termdock 1.4.240 → 1.4.242

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 (316) hide show
  1. package/dist/client/assets/App-CVuPbhP4.js +155 -0
  2. package/dist/client/assets/App-CVuPbhP4.js.br +0 -0
  3. package/dist/client/assets/App-CVuPbhP4.js.gz +0 -0
  4. package/dist/client/assets/{ChangeWalkthroughPanel-9whVVXTr.js → ChangeWalkthroughPanel-4kynRLRs.js} +1 -1
  5. package/dist/client/assets/ChangeWalkthroughPanel-4kynRLRs.js.br +0 -0
  6. package/dist/client/assets/ChangeWalkthroughPanel-4kynRLRs.js.gz +0 -0
  7. package/dist/client/assets/{DagPlayground-y80OTTQj.js → DagPlayground-Yx7XBwmM.js} +1 -1
  8. package/dist/client/assets/DagPlayground-Yx7XBwmM.js.br +0 -0
  9. package/dist/client/assets/DagPlayground-Yx7XBwmM.js.gz +0 -0
  10. package/dist/client/assets/{DiffLab-BY2wbRtg.js → DiffLab-Cn1f9iHY.js} +1 -1
  11. package/dist/client/assets/DiffLab-Cn1f9iHY.js.br +0 -0
  12. package/dist/client/assets/DiffLab-Cn1f9iHY.js.gz +0 -0
  13. package/dist/client/assets/{DiffReview-DLlDJbK1.js → DiffReview-BJQ92hBr.js} +1 -1
  14. package/dist/client/assets/DiffReview-BJQ92hBr.js.br +0 -0
  15. package/dist/client/assets/DiffReview-BJQ92hBr.js.gz +0 -0
  16. package/dist/client/assets/{DiffReviewLab-CEpa_B8I.js → DiffReviewLab-CN3a3LhH.js} +1 -1
  17. package/dist/client/assets/DiffReviewLab-CN3a3LhH.js.br +0 -0
  18. package/dist/client/assets/DiffReviewLab-CN3a3LhH.js.gz +0 -0
  19. package/dist/client/assets/{DiffViewer-GLkd1zMQ.js → DiffViewer-BFn2Gz8v.js} +1 -1
  20. package/dist/client/assets/DiffViewer-BFn2Gz8v.js.br +0 -0
  21. package/dist/client/assets/DiffViewer-BFn2Gz8v.js.gz +0 -0
  22. package/dist/client/assets/{ModelPreview-DB8tw45f.js → ModelPreview-CC8Uf4et.js} +1 -1
  23. package/dist/client/assets/ModelPreview-CC8Uf4et.js.br +0 -0
  24. package/dist/client/assets/ModelPreview-CC8Uf4et.js.gz +0 -0
  25. package/dist/client/assets/{RightSidebar-aoJjOQGX.js → RightSidebar-Bz9BkzCR.js} +4 -4
  26. package/dist/client/assets/RightSidebar-Bz9BkzCR.js.br +0 -0
  27. package/dist/client/assets/RightSidebar-Bz9BkzCR.js.gz +0 -0
  28. package/dist/client/assets/{abnfDiagram-VCTEODGH-RBGYciHa.js → abnfDiagram-VCTEODGH-hQSzKoeJ.js} +1 -1
  29. package/dist/client/assets/abnfDiagram-VCTEODGH-hQSzKoeJ.js.br +0 -0
  30. package/dist/client/assets/abnfDiagram-VCTEODGH-hQSzKoeJ.js.gz +0 -0
  31. package/dist/client/assets/{app-Ctrh4Bku.js → app-CgwJz96Y.js} +9 -9
  32. package/dist/client/assets/app-CgwJz96Y.js.br +0 -0
  33. package/dist/client/assets/app-CgwJz96Y.js.gz +0 -0
  34. package/dist/client/assets/{arc-CzQsNCup.js → arc-DNdtsFHs.js} +1 -1
  35. package/dist/client/assets/arc-DNdtsFHs.js.br +0 -0
  36. package/dist/client/assets/arc-DNdtsFHs.js.gz +0 -0
  37. package/dist/client/assets/{architectureDiagram-5GKGNRK7-sDp6hSiy.js → architectureDiagram-5GKGNRK7-ClYN-ZWK.js} +1 -1
  38. package/dist/client/assets/architectureDiagram-5GKGNRK7-ClYN-ZWK.js.br +0 -0
  39. package/dist/client/assets/architectureDiagram-5GKGNRK7-ClYN-ZWK.js.gz +0 -0
  40. package/dist/client/assets/{blockDiagram-I7D4REHJ-C-AHqZPo.js → blockDiagram-I7D4REHJ-ybw8N2u6.js} +1 -1
  41. package/dist/client/assets/blockDiagram-I7D4REHJ-ybw8N2u6.js.br +0 -0
  42. package/dist/client/assets/blockDiagram-I7D4REHJ-ybw8N2u6.js.gz +0 -0
  43. package/dist/client/assets/{c4Diagram-7LVT6UL2-B8VGhLwN.js → c4Diagram-7LVT6UL2-BUySB1D8.js} +1 -1
  44. package/dist/client/assets/c4Diagram-7LVT6UL2-BUySB1D8.js.br +0 -0
  45. package/dist/client/assets/c4Diagram-7LVT6UL2-BUySB1D8.js.gz +0 -0
  46. package/dist/client/assets/channel-C6y0-VyK.js +1 -0
  47. package/dist/client/assets/{chunk-2Q5K7J3B-D56jCJTr.js → chunk-2Q5K7J3B-DEG-dAIQ.js} +1 -1
  48. package/dist/client/assets/{chunk-5VM5RSS4-cga3WKIM.js → chunk-5VM5RSS4-DkNem54n.js} +1 -1
  49. package/dist/client/assets/{chunk-F27PBJKO-BNOR_7WA.js → chunk-F27PBJKO-D32jqKl9.js} +1 -1
  50. package/dist/client/assets/chunk-F27PBJKO-D32jqKl9.js.br +0 -0
  51. package/dist/client/assets/chunk-F27PBJKO-D32jqKl9.js.gz +0 -0
  52. package/dist/client/assets/{chunk-IMKFNOWR-Dk12DKtC.js → chunk-IMKFNOWR-JxJHaym5.js} +1 -1
  53. package/dist/client/assets/chunk-IMKFNOWR-JxJHaym5.js.br +0 -0
  54. package/dist/client/assets/chunk-IMKFNOWR-JxJHaym5.js.gz +0 -0
  55. package/dist/client/assets/{chunk-JWPE2WC7-CVqdLg0d.js → chunk-JWPE2WC7-CS7uV1GH.js} +1 -1
  56. package/dist/client/assets/{chunk-POPQ4Y6H-Y6gEzK15.js → chunk-POPQ4Y6H-B02kbaJZ.js} +1 -1
  57. package/dist/client/assets/{chunk-SVP7TREG-BIJtdFBL.js → chunk-SVP7TREG-Bc9XpKmH.js} +1 -1
  58. package/dist/client/assets/chunk-SVP7TREG-Bc9XpKmH.js.br +0 -0
  59. package/dist/client/assets/chunk-SVP7TREG-Bc9XpKmH.js.gz +0 -0
  60. package/dist/client/assets/{chunk-TICWLB2K-CS3jsxv7.js → chunk-TICWLB2K-DW69sulY.js} +1 -1
  61. package/dist/client/assets/chunk-TICWLB2K-DW69sulY.js.br +0 -0
  62. package/dist/client/assets/chunk-TICWLB2K-DW69sulY.js.gz +0 -0
  63. package/dist/client/assets/{chunk-XXDRQBXY-BYgvxPrj.js → chunk-XXDRQBXY-CqHkJ6cA.js} +1 -1
  64. package/dist/client/assets/classDiagram-ZZMXUADV-zxEN3eAk.js +1 -0
  65. package/dist/client/assets/classDiagram-v2-VYDZK3BY-zxEN3eAk.js +1 -0
  66. package/dist/client/assets/{cose-bilkent-JH36ORCC-9udJiW7h.js → cose-bilkent-JH36ORCC-DJAx_fGd.js} +1 -1
  67. package/dist/client/assets/cose-bilkent-JH36ORCC-DJAx_fGd.js.br +0 -0
  68. package/dist/client/assets/cose-bilkent-JH36ORCC-DJAx_fGd.js.gz +0 -0
  69. package/dist/client/assets/{cynefin-OW5HDTMX-D-6q-6N2.js → cynefin-OW5HDTMX-BJmu05nC.js} +1 -1
  70. package/dist/client/assets/cynefin-OW5HDTMX-BJmu05nC.js.br +0 -0
  71. package/dist/client/assets/{cynefin-OW5HDTMX-D-6q-6N2.js.gz → cynefin-OW5HDTMX-BJmu05nC.js.gz} +0 -0
  72. package/dist/client/assets/{cynefinDiagram-5FMLGOSQ-B5c37uFA.js → cynefinDiagram-5FMLGOSQ-B0m0YIa6.js} +1 -1
  73. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-B0m0YIa6.js.br +0 -0
  74. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-B0m0YIa6.js.gz +0 -0
  75. package/dist/client/assets/{dagre-GXQ25YYZ-DoFMIka4.js → dagre-GXQ25YYZ-Cbs-u5oy.js} +1 -1
  76. package/dist/client/assets/dagre-GXQ25YYZ-Cbs-u5oy.js.br +0 -0
  77. package/dist/client/assets/dagre-GXQ25YYZ-Cbs-u5oy.js.gz +0 -0
  78. package/dist/client/assets/{diagram-S7CK7UJ4-DrAwxGx7.js → diagram-S7CK7UJ4-DnFgNCva.js} +1 -1
  79. package/dist/client/assets/diagram-S7CK7UJ4-DnFgNCva.js.br +0 -0
  80. package/dist/client/assets/diagram-S7CK7UJ4-DnFgNCva.js.gz +0 -0
  81. package/dist/client/assets/{diagram-UQ7AKVKN-DbWfEzKd.js → diagram-UQ7AKVKN-CRbBEuHO.js} +1 -1
  82. package/dist/client/assets/diagram-UQ7AKVKN-CRbBEuHO.js.br +0 -0
  83. package/dist/client/assets/diagram-UQ7AKVKN-CRbBEuHO.js.gz +0 -0
  84. package/dist/client/assets/{diagram-VSXAHHWV-zKcVacRq.js → diagram-VSXAHHWV-CIPivMwW.js} +1 -1
  85. package/dist/client/assets/diagram-VSXAHHWV-CIPivMwW.js.br +0 -0
  86. package/dist/client/assets/diagram-VSXAHHWV-CIPivMwW.js.gz +0 -0
  87. package/dist/client/assets/{diagram-VX7I27RA-BNAI-5sG.js → diagram-VX7I27RA-CY8G867I.js} +1 -1
  88. package/dist/client/assets/diagram-VX7I27RA-CY8G867I.js.br +0 -0
  89. package/dist/client/assets/diagram-VX7I27RA-CY8G867I.js.gz +0 -0
  90. package/dist/client/assets/{diagram-Z3DM3KII-ChB9ZeuK.js → diagram-Z3DM3KII-owVjuxom.js} +1 -1
  91. package/dist/client/assets/diagram-Z3DM3KII-owVjuxom.js.br +0 -0
  92. package/dist/client/assets/diagram-Z3DM3KII-owVjuxom.js.gz +0 -0
  93. package/dist/client/assets/{ebnfDiagram-PWID7BFC-Fe8VFmWJ.js → ebnfDiagram-PWID7BFC-DMoOEDnf.js} +1 -1
  94. package/dist/client/assets/ebnfDiagram-PWID7BFC-DMoOEDnf.js.br +0 -0
  95. package/dist/client/assets/ebnfDiagram-PWID7BFC-DMoOEDnf.js.gz +0 -0
  96. package/dist/client/assets/{erDiagram-RLTQ6QDP-CC7DagoX.js → erDiagram-RLTQ6QDP-DuEHUYT0.js} +1 -1
  97. package/dist/client/assets/erDiagram-RLTQ6QDP-DuEHUYT0.js.br +0 -0
  98. package/dist/client/assets/erDiagram-RLTQ6QDP-DuEHUYT0.js.gz +0 -0
  99. package/dist/client/assets/{flowDiagram-HODETNUW-BBIgixMV.js → flowDiagram-HODETNUW-Duys8g5v.js} +1 -1
  100. package/dist/client/assets/flowDiagram-HODETNUW-Duys8g5v.js.br +0 -0
  101. package/dist/client/assets/flowDiagram-HODETNUW-Duys8g5v.js.gz +0 -0
  102. package/dist/client/assets/{ganttDiagram-EL5Y4UJY-CHRaIQ9P.js → ganttDiagram-EL5Y4UJY-4uNGC3eO.js} +1 -1
  103. package/dist/client/assets/ganttDiagram-EL5Y4UJY-4uNGC3eO.js.br +0 -0
  104. package/dist/client/assets/ganttDiagram-EL5Y4UJY-4uNGC3eO.js.gz +0 -0
  105. package/dist/client/assets/{gestureArbiter-5c1oGojb.js → gestureArbiter-CTk63JTf.js} +1 -1
  106. package/dist/client/assets/gestureArbiter-CTk63JTf.js.br +0 -0
  107. package/dist/client/assets/gestureArbiter-CTk63JTf.js.gz +0 -0
  108. package/dist/client/assets/{gitGraphDiagram-WWUBYQGX-iJPivC9C.js → gitGraphDiagram-WWUBYQGX-CoNcYxET.js} +1 -1
  109. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-CoNcYxET.js.br +0 -0
  110. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-CoNcYxET.js.gz +0 -0
  111. package/dist/client/assets/{index-BzglvLj5.css → index-QFRD5OND.css} +1 -1
  112. package/dist/client/assets/index-QFRD5OND.css.br +0 -0
  113. package/dist/client/assets/{index-BzglvLj5.css.gz → index-QFRD5OND.css.gz} +0 -0
  114. package/dist/client/assets/{infoDiagram-27XIBGKW-CWjxPUb1.js → infoDiagram-27XIBGKW-D1APvjL0.js} +1 -1
  115. package/dist/client/assets/{ishikawaDiagram-5VMMS53U-2dN_H6WK.js → ishikawaDiagram-5VMMS53U-B0CGmgD9.js} +1 -1
  116. package/dist/client/assets/ishikawaDiagram-5VMMS53U-B0CGmgD9.js.br +0 -0
  117. package/dist/client/assets/ishikawaDiagram-5VMMS53U-B0CGmgD9.js.gz +0 -0
  118. package/dist/client/assets/{journeyDiagram-3NMN7TZE-BqY-OLE2.js → journeyDiagram-3NMN7TZE-BIcr4OmP.js} +1 -1
  119. package/dist/client/assets/journeyDiagram-3NMN7TZE-BIcr4OmP.js.br +0 -0
  120. package/dist/client/assets/journeyDiagram-3NMN7TZE-BIcr4OmP.js.gz +0 -0
  121. package/dist/client/assets/{kanban-definition-UXKFOSKX-CSOXhjNh.js → kanban-definition-UXKFOSKX-BGY-UCFp.js} +1 -1
  122. package/dist/client/assets/kanban-definition-UXKFOSKX-BGY-UCFp.js.br +0 -0
  123. package/dist/client/assets/kanban-definition-UXKFOSKX-BGY-UCFp.js.gz +0 -0
  124. package/dist/client/assets/{layout-BxIcRRf7.js → layout-Dy-XBjcQ.js} +1 -1
  125. package/dist/client/assets/layout-Dy-XBjcQ.js.br +0 -0
  126. package/dist/client/assets/layout-Dy-XBjcQ.js.gz +0 -0
  127. package/dist/client/assets/{linear-BYWiw-Yd.js → linear-DGdoGGqI.js} +1 -1
  128. package/dist/client/assets/linear-DGdoGGqI.js.br +0 -0
  129. package/dist/client/assets/linear-DGdoGGqI.js.gz +0 -0
  130. package/dist/client/assets/{mermaid.core-DhRpdkKn.js → mermaid.core-uUtQ6Zvd.js} +5 -5
  131. package/dist/client/assets/mermaid.core-uUtQ6Zvd.js.br +0 -0
  132. package/dist/client/assets/mermaid.core-uUtQ6Zvd.js.gz +0 -0
  133. package/dist/client/assets/{mindmap-definition-YA3MSWOX-DwBcGwTF.js → mindmap-definition-YA3MSWOX-BBMP8prO.js} +1 -1
  134. package/dist/client/assets/mindmap-definition-YA3MSWOX-BBMP8prO.js.br +0 -0
  135. package/dist/client/assets/mindmap-definition-YA3MSWOX-BBMP8prO.js.gz +0 -0
  136. package/dist/client/assets/{passwordBootstrap-BkAa-DO2.js → passwordBootstrap-CazWrYzP.js} +1 -1
  137. package/dist/client/assets/{passwordBootstrap-BkAa-DO2.js.br → passwordBootstrap-CazWrYzP.js.br} +0 -0
  138. package/dist/client/assets/{passwordBootstrap-BkAa-DO2.js.gz → passwordBootstrap-CazWrYzP.js.gz} +0 -0
  139. package/dist/client/assets/{pegDiagram-XKGWAZYB-D_04AQMs.js → pegDiagram-XKGWAZYB-BvxAwgS8.js} +1 -1
  140. package/dist/client/assets/pegDiagram-XKGWAZYB-BvxAwgS8.js.br +0 -0
  141. package/dist/client/assets/pegDiagram-XKGWAZYB-BvxAwgS8.js.gz +0 -0
  142. package/dist/client/assets/{pieDiagram-E7YTZNPT-DgHIGdDc.js → pieDiagram-E7YTZNPT-DZ4F26FA.js} +1 -1
  143. package/dist/client/assets/pieDiagram-E7YTZNPT-DZ4F26FA.js.br +0 -0
  144. package/dist/client/assets/pieDiagram-E7YTZNPT-DZ4F26FA.js.gz +0 -0
  145. package/dist/client/assets/{quadrantDiagram-AXDQQJYC-BrxP_uCp.js → quadrantDiagram-AXDQQJYC-FJGBvmNp.js} +1 -1
  146. package/dist/client/assets/quadrantDiagram-AXDQQJYC-FJGBvmNp.js.br +0 -0
  147. package/dist/client/assets/quadrantDiagram-AXDQQJYC-FJGBvmNp.js.gz +0 -0
  148. package/dist/client/assets/{railroadDiagram-O6MQD6OU-Bj8aV8et.js → railroadDiagram-O6MQD6OU-B4f16qlN.js} +1 -1
  149. package/dist/client/assets/railroadDiagram-O6MQD6OU-B4f16qlN.js.br +0 -0
  150. package/dist/client/assets/railroadDiagram-O6MQD6OU-B4f16qlN.js.gz +0 -0
  151. package/dist/client/assets/{referenceLongPress-CG4k8F2W.js → referenceLongPress-4ydKrZtC.js} +1 -1
  152. package/dist/client/assets/referenceLongPress-4ydKrZtC.js.br +0 -0
  153. package/dist/client/assets/referenceLongPress-4ydKrZtC.js.gz +0 -0
  154. package/dist/client/assets/{requirementDiagram-BXWQKSXE-DHOBnmaH.js → requirementDiagram-BXWQKSXE-DDEDP28y.js} +1 -1
  155. package/dist/client/assets/requirementDiagram-BXWQKSXE-DDEDP28y.js.br +0 -0
  156. package/dist/client/assets/requirementDiagram-BXWQKSXE-DDEDP28y.js.gz +0 -0
  157. package/dist/client/assets/{sankeyDiagram-P5KCCOFB-B46rNwzQ.js → sankeyDiagram-P5KCCOFB-eZbHgAJ2.js} +1 -1
  158. package/dist/client/assets/sankeyDiagram-P5KCCOFB-eZbHgAJ2.js.br +0 -0
  159. package/dist/client/assets/sankeyDiagram-P5KCCOFB-eZbHgAJ2.js.gz +0 -0
  160. package/dist/client/assets/{sequenceDiagram-WJ2MYXX4-D8PnDgC6.js → sequenceDiagram-WJ2MYXX4-C26sID_J.js} +1 -1
  161. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-C26sID_J.js.br +0 -0
  162. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-C26sID_J.js.gz +0 -0
  163. package/dist/client/assets/{sizeCapture-INFHLROL-CjofpSnZ.js → sizeCapture-INFHLROL-CunqRjZH.js} +1 -1
  164. package/dist/client/assets/sizeCapture-INFHLROL-CunqRjZH.js.br +0 -0
  165. package/dist/client/assets/sizeCapture-INFHLROL-CunqRjZH.js.gz +0 -0
  166. package/dist/client/assets/{sparkles-Zi8g0TMb.js → sparkles-Cs8KAbL4.js} +1 -1
  167. package/dist/client/assets/{stateDiagram-D77RDMKH-BX_StFJV.js → stateDiagram-D77RDMKH-BDCgrd2K.js} +1 -1
  168. package/dist/client/assets/stateDiagram-D77RDMKH-BDCgrd2K.js.br +0 -0
  169. package/dist/client/assets/stateDiagram-D77RDMKH-BDCgrd2K.js.gz +0 -0
  170. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-JBMsRqan.js +1 -0
  171. package/dist/client/assets/{swimlanes-42K2YHIH-bxGulCYh.js → swimlanes-42K2YHIH-ClJ98iVo.js} +1 -1
  172. package/dist/client/assets/swimlanes-42K2YHIH-ClJ98iVo.js.br +0 -0
  173. package/dist/client/assets/swimlanes-42K2YHIH-ClJ98iVo.js.gz +0 -0
  174. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-BvtpepbK.js +8 -0
  175. package/dist/client/assets/{timeline-definition-24CTP7MA-DcHYPI0d.js → timeline-definition-24CTP7MA-CDCDunzZ.js} +1 -1
  176. package/dist/client/assets/timeline-definition-24CTP7MA-CDCDunzZ.js.br +0 -0
  177. package/dist/client/assets/{timeline-definition-24CTP7MA-DcHYPI0d.js.gz → timeline-definition-24CTP7MA-CDCDunzZ.js.gz} +0 -0
  178. package/dist/client/assets/{triangle-alert-BXXcxTk8.js → triangle-alert-B0gXRJJm.js} +1 -1
  179. package/dist/client/assets/{vennDiagram-4TSXK5OY-CjIGwkZf.js → vennDiagram-4TSXK5OY-BBqRUM5-.js} +1 -1
  180. package/dist/client/assets/{vennDiagram-4TSXK5OY-CjIGwkZf.js.br → vennDiagram-4TSXK5OY-BBqRUM5-.js.br} +0 -0
  181. package/dist/client/assets/vennDiagram-4TSXK5OY-BBqRUM5-.js.gz +0 -0
  182. package/dist/client/assets/{wardleyDiagram-VM6X3IG4-B-WK3Fil.js → wardleyDiagram-VM6X3IG4-DKpVgjww.js} +1 -1
  183. package/dist/client/assets/wardleyDiagram-VM6X3IG4-DKpVgjww.js.br +0 -0
  184. package/dist/client/assets/wardleyDiagram-VM6X3IG4-DKpVgjww.js.gz +0 -0
  185. package/dist/client/assets/{xychartDiagram-S5SC5T6Z-4RzKQfNK.js → xychartDiagram-S5SC5T6Z-CHwA2dfA.js} +1 -1
  186. package/dist/client/assets/xychartDiagram-S5SC5T6Z-CHwA2dfA.js.br +0 -0
  187. package/dist/client/assets/{xychartDiagram-S5SC5T6Z-4RzKQfNK.js.gz → xychartDiagram-S5SC5T6Z-CHwA2dfA.js.gz} +0 -0
  188. package/dist/client/index.html +2 -2
  189. package/dist/client/index.html.br +0 -0
  190. package/dist/client/index.html.gz +0 -0
  191. package/dist/client/sw.js +1 -1
  192. package/dist/client/sw.js.br +0 -0
  193. package/dist/client/sw.js.gz +0 -0
  194. package/dist/server/cli.js +56 -42
  195. package/dist/server/entry.js +24 -2
  196. package/dist/server/federation/relay.js +3 -0
  197. package/dist/server/federation/routeAccess.js +39 -2
  198. package/dist/server/federation/runtime.js +5 -0
  199. package/dist/server/federation/selfRelay.js +182 -0
  200. package/package.json +1 -1
  201. package/runtime-manifest.json +3 -3
  202. package/dist/client/assets/App-CmlGDKDj.js +0 -155
  203. package/dist/client/assets/App-CmlGDKDj.js.br +0 -0
  204. package/dist/client/assets/App-CmlGDKDj.js.gz +0 -0
  205. package/dist/client/assets/ChangeWalkthroughPanel-9whVVXTr.js.br +0 -0
  206. package/dist/client/assets/ChangeWalkthroughPanel-9whVVXTr.js.gz +0 -0
  207. package/dist/client/assets/DagPlayground-y80OTTQj.js.br +0 -0
  208. package/dist/client/assets/DagPlayground-y80OTTQj.js.gz +0 -0
  209. package/dist/client/assets/DiffLab-BY2wbRtg.js.br +0 -0
  210. package/dist/client/assets/DiffLab-BY2wbRtg.js.gz +0 -0
  211. package/dist/client/assets/DiffReview-DLlDJbK1.js.br +0 -0
  212. package/dist/client/assets/DiffReview-DLlDJbK1.js.gz +0 -0
  213. package/dist/client/assets/DiffReviewLab-CEpa_B8I.js.br +0 -0
  214. package/dist/client/assets/DiffReviewLab-CEpa_B8I.js.gz +0 -0
  215. package/dist/client/assets/DiffViewer-GLkd1zMQ.js.br +0 -0
  216. package/dist/client/assets/DiffViewer-GLkd1zMQ.js.gz +0 -0
  217. package/dist/client/assets/ModelPreview-DB8tw45f.js.br +0 -0
  218. package/dist/client/assets/ModelPreview-DB8tw45f.js.gz +0 -0
  219. package/dist/client/assets/RightSidebar-aoJjOQGX.js.br +0 -0
  220. package/dist/client/assets/RightSidebar-aoJjOQGX.js.gz +0 -0
  221. package/dist/client/assets/abnfDiagram-VCTEODGH-RBGYciHa.js.br +0 -0
  222. package/dist/client/assets/abnfDiagram-VCTEODGH-RBGYciHa.js.gz +0 -0
  223. package/dist/client/assets/app-Ctrh4Bku.js.br +0 -0
  224. package/dist/client/assets/app-Ctrh4Bku.js.gz +0 -0
  225. package/dist/client/assets/arc-CzQsNCup.js.br +0 -0
  226. package/dist/client/assets/arc-CzQsNCup.js.gz +0 -0
  227. package/dist/client/assets/architectureDiagram-5GKGNRK7-sDp6hSiy.js.br +0 -0
  228. package/dist/client/assets/architectureDiagram-5GKGNRK7-sDp6hSiy.js.gz +0 -0
  229. package/dist/client/assets/blockDiagram-I7D4REHJ-C-AHqZPo.js.br +0 -0
  230. package/dist/client/assets/blockDiagram-I7D4REHJ-C-AHqZPo.js.gz +0 -0
  231. package/dist/client/assets/c4Diagram-7LVT6UL2-B8VGhLwN.js.br +0 -0
  232. package/dist/client/assets/c4Diagram-7LVT6UL2-B8VGhLwN.js.gz +0 -0
  233. package/dist/client/assets/channel-zK78er-R.js +0 -1
  234. package/dist/client/assets/chunk-F27PBJKO-BNOR_7WA.js.br +0 -0
  235. package/dist/client/assets/chunk-F27PBJKO-BNOR_7WA.js.gz +0 -0
  236. package/dist/client/assets/chunk-IMKFNOWR-Dk12DKtC.js.br +0 -0
  237. package/dist/client/assets/chunk-IMKFNOWR-Dk12DKtC.js.gz +0 -0
  238. package/dist/client/assets/chunk-SVP7TREG-BIJtdFBL.js.br +0 -0
  239. package/dist/client/assets/chunk-SVP7TREG-BIJtdFBL.js.gz +0 -0
  240. package/dist/client/assets/chunk-TICWLB2K-CS3jsxv7.js.br +0 -0
  241. package/dist/client/assets/chunk-TICWLB2K-CS3jsxv7.js.gz +0 -0
  242. package/dist/client/assets/classDiagram-ZZMXUADV-BMh5Sak3.js +0 -1
  243. package/dist/client/assets/classDiagram-v2-VYDZK3BY-BMh5Sak3.js +0 -1
  244. package/dist/client/assets/cose-bilkent-JH36ORCC-9udJiW7h.js.br +0 -0
  245. package/dist/client/assets/cose-bilkent-JH36ORCC-9udJiW7h.js.gz +0 -0
  246. package/dist/client/assets/cynefin-OW5HDTMX-D-6q-6N2.js.br +0 -0
  247. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-B5c37uFA.js.br +0 -0
  248. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-B5c37uFA.js.gz +0 -0
  249. package/dist/client/assets/dagre-GXQ25YYZ-DoFMIka4.js.br +0 -0
  250. package/dist/client/assets/dagre-GXQ25YYZ-DoFMIka4.js.gz +0 -0
  251. package/dist/client/assets/diagram-S7CK7UJ4-DrAwxGx7.js.br +0 -0
  252. package/dist/client/assets/diagram-S7CK7UJ4-DrAwxGx7.js.gz +0 -0
  253. package/dist/client/assets/diagram-UQ7AKVKN-DbWfEzKd.js.br +0 -0
  254. package/dist/client/assets/diagram-UQ7AKVKN-DbWfEzKd.js.gz +0 -0
  255. package/dist/client/assets/diagram-VSXAHHWV-zKcVacRq.js.br +0 -0
  256. package/dist/client/assets/diagram-VSXAHHWV-zKcVacRq.js.gz +0 -0
  257. package/dist/client/assets/diagram-VX7I27RA-BNAI-5sG.js.br +0 -0
  258. package/dist/client/assets/diagram-VX7I27RA-BNAI-5sG.js.gz +0 -0
  259. package/dist/client/assets/diagram-Z3DM3KII-ChB9ZeuK.js.br +0 -0
  260. package/dist/client/assets/diagram-Z3DM3KII-ChB9ZeuK.js.gz +0 -0
  261. package/dist/client/assets/ebnfDiagram-PWID7BFC-Fe8VFmWJ.js.br +0 -0
  262. package/dist/client/assets/ebnfDiagram-PWID7BFC-Fe8VFmWJ.js.gz +0 -0
  263. package/dist/client/assets/erDiagram-RLTQ6QDP-CC7DagoX.js.br +0 -0
  264. package/dist/client/assets/erDiagram-RLTQ6QDP-CC7DagoX.js.gz +0 -0
  265. package/dist/client/assets/flowDiagram-HODETNUW-BBIgixMV.js.br +0 -0
  266. package/dist/client/assets/flowDiagram-HODETNUW-BBIgixMV.js.gz +0 -0
  267. package/dist/client/assets/ganttDiagram-EL5Y4UJY-CHRaIQ9P.js.br +0 -0
  268. package/dist/client/assets/ganttDiagram-EL5Y4UJY-CHRaIQ9P.js.gz +0 -0
  269. package/dist/client/assets/gestureArbiter-5c1oGojb.js.br +0 -0
  270. package/dist/client/assets/gestureArbiter-5c1oGojb.js.gz +0 -0
  271. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-iJPivC9C.js.br +0 -0
  272. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-iJPivC9C.js.gz +0 -0
  273. package/dist/client/assets/index-BzglvLj5.css.br +0 -0
  274. package/dist/client/assets/ishikawaDiagram-5VMMS53U-2dN_H6WK.js.br +0 -0
  275. package/dist/client/assets/ishikawaDiagram-5VMMS53U-2dN_H6WK.js.gz +0 -0
  276. package/dist/client/assets/journeyDiagram-3NMN7TZE-BqY-OLE2.js.br +0 -0
  277. package/dist/client/assets/journeyDiagram-3NMN7TZE-BqY-OLE2.js.gz +0 -0
  278. package/dist/client/assets/kanban-definition-UXKFOSKX-CSOXhjNh.js.br +0 -0
  279. package/dist/client/assets/kanban-definition-UXKFOSKX-CSOXhjNh.js.gz +0 -0
  280. package/dist/client/assets/layout-BxIcRRf7.js.br +0 -0
  281. package/dist/client/assets/layout-BxIcRRf7.js.gz +0 -0
  282. package/dist/client/assets/linear-BYWiw-Yd.js.br +0 -0
  283. package/dist/client/assets/linear-BYWiw-Yd.js.gz +0 -0
  284. package/dist/client/assets/mermaid.core-DhRpdkKn.js.br +0 -0
  285. package/dist/client/assets/mermaid.core-DhRpdkKn.js.gz +0 -0
  286. package/dist/client/assets/mindmap-definition-YA3MSWOX-DwBcGwTF.js.br +0 -0
  287. package/dist/client/assets/mindmap-definition-YA3MSWOX-DwBcGwTF.js.gz +0 -0
  288. package/dist/client/assets/pegDiagram-XKGWAZYB-D_04AQMs.js.br +0 -0
  289. package/dist/client/assets/pegDiagram-XKGWAZYB-D_04AQMs.js.gz +0 -0
  290. package/dist/client/assets/pieDiagram-E7YTZNPT-DgHIGdDc.js.br +0 -0
  291. package/dist/client/assets/pieDiagram-E7YTZNPT-DgHIGdDc.js.gz +0 -0
  292. package/dist/client/assets/quadrantDiagram-AXDQQJYC-BrxP_uCp.js.br +0 -0
  293. package/dist/client/assets/quadrantDiagram-AXDQQJYC-BrxP_uCp.js.gz +0 -0
  294. package/dist/client/assets/railroadDiagram-O6MQD6OU-Bj8aV8et.js.br +0 -0
  295. package/dist/client/assets/railroadDiagram-O6MQD6OU-Bj8aV8et.js.gz +0 -0
  296. package/dist/client/assets/referenceLongPress-CG4k8F2W.js.br +0 -0
  297. package/dist/client/assets/referenceLongPress-CG4k8F2W.js.gz +0 -0
  298. package/dist/client/assets/requirementDiagram-BXWQKSXE-DHOBnmaH.js.br +0 -0
  299. package/dist/client/assets/requirementDiagram-BXWQKSXE-DHOBnmaH.js.gz +0 -0
  300. package/dist/client/assets/sankeyDiagram-P5KCCOFB-B46rNwzQ.js.br +0 -0
  301. package/dist/client/assets/sankeyDiagram-P5KCCOFB-B46rNwzQ.js.gz +0 -0
  302. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-D8PnDgC6.js.br +0 -0
  303. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-D8PnDgC6.js.gz +0 -0
  304. package/dist/client/assets/sizeCapture-INFHLROL-CjofpSnZ.js.br +0 -0
  305. package/dist/client/assets/sizeCapture-INFHLROL-CjofpSnZ.js.gz +0 -0
  306. package/dist/client/assets/stateDiagram-D77RDMKH-BX_StFJV.js.br +0 -0
  307. package/dist/client/assets/stateDiagram-D77RDMKH-BX_StFJV.js.gz +0 -0
  308. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-CMG96YGj.js +0 -1
  309. package/dist/client/assets/swimlanes-42K2YHIH-bxGulCYh.js.br +0 -0
  310. package/dist/client/assets/swimlanes-42K2YHIH-bxGulCYh.js.gz +0 -0
  311. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-sPKOywKp.js +0 -8
  312. package/dist/client/assets/timeline-definition-24CTP7MA-DcHYPI0d.js.br +0 -0
  313. package/dist/client/assets/vennDiagram-4TSXK5OY-CjIGwkZf.js.gz +0 -0
  314. package/dist/client/assets/wardleyDiagram-VM6X3IG4-B-WK3Fil.js.br +0 -0
  315. package/dist/client/assets/wardleyDiagram-VM6X3IG4-B-WK3Fil.js.gz +0 -0
  316. package/dist/client/assets/xychartDiagram-S5SC5T6Z-4RzKQfNK.js.br +0 -0
@@ -1,12 +1,12 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/passwordBootstrap-BkAa-DO2.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/App-CmlGDKDj.js","assets/gestureArbiter-5c1oGojb.js","assets/gestureArbiter-C2J0D0kV.css","assets/triangle-alert-BXXcxTk8.js","assets/referenceLongPress-CG4k8F2W.js","assets/DagPlayground-y80OTTQj.js","assets/ChangeWalkthroughPanel-9whVVXTr.js","assets/sparkles-Zi8g0TMb.js","assets/DiffLab-BY2wbRtg.js","assets/DiffViewer-GLkd1zMQ.js","assets/DiffViewer-T3uj2-aP.css","assets/DiffReviewLab-CEpa_B8I.js","assets/DiffReview-DLlDJbK1.js"])))=>i.map(i=>d[i]);
2
- import{r as Rc,a as mm,g as bf}from"./react-XDCjal2T.js";import{b as _,R as ze,r as Tc}from"./dnd-BCFAPC0L.js";import{L as wm,l as ym}from"./terminal-C7X98Amf.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const i of s.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(o){if(o.ep)return;o.ep=!0;const s=n(o);fetch(o.href,s)}})();const bm="modulepreload",vm=function(t){return"/"+t},jl={},Gt=function(e,n,r){let o=Promise.resolve();if(n&&n.length>0){let c=function(l){return Promise.all(l.map(d=>Promise.resolve(d).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),a=i?.nonce||i?.getAttribute("nonce");o=c(n.map(l=>{if(l=vm(l),l in jl)return;jl[l]=!0;const d=l.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${u}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":bm,d||(f.as="script"),f.crossOrigin="",f.href=l,a&&f.setAttribute("nonce",a),document.head.appendChild(f),d)return new Promise((h,g)=>{f.addEventListener("load",h),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${l}`)))})}))}function s(i){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=i,window.dispatchEvent(a),!a.defaultPrevented)throw i}return o.then(i=>{for(const a of i||[])a.status==="rejected"&&s(a.reason);return e().catch(s)})};var wi={exports:{}},xr={};var Ul;function Sm(){if(Ul)return xr;Ul=1;var t=Rc(),e=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function i(a,c,l){var d,u={},f=null,h=null;l!==void 0&&(f=""+l),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(h=c.ref);for(d in c)r.call(c,d)&&!s.hasOwnProperty(d)&&(u[d]=c[d]);if(a&&a.defaultProps)for(d in c=a.defaultProps,c)u[d]===void 0&&(u[d]=c[d]);return{$$typeof:e,type:a,key:f,ref:h,props:u,_owner:o.current}}return xr.Fragment=n,xr.jsx=i,xr.jsxs=i,xr}var $l;function xm(){return $l||($l=1,wi.exports=Sm()),wi.exports}var p=xm();const pn="termdock-secure-target-v1",Pc="termdock-secure-entry-v1",Em=new Set([pn,Pc,"termdock-color-theme","termdock:locale","termdock.federation.connections.v1"]),xo=typeof Storage>"u"?void 0:Storage.prototype.getItem,yi=typeof Storage>"u"?void 0:Storage.prototype.setItem,Hl="termdock-secure-legacy-owner",Ms=typeof window<"u"&&window.parent!==window&&location.pathname==="/workspace.html";function Am(){if(typeof window>"u")return null;try{if(Ms){const e=new URLSearchParams(location.search).get("termdock-workspace"),n=JSON.parse(localStorage.getItem("termdock.federation.connections.v1")||"[]"),r=Array.isArray(n)?n.find(o=>o?.targetPeerId===e):void 0;return r&&typeof r.url=="string"&&typeof r.targetPeerId=="string"?{...r,serviceName:r.label||r.serviceName}:null}const t=JSON.parse(sessionStorage.getItem(pn)??localStorage.getItem(pn)??"null");return t&&typeof t.url=="string"&&typeof t.targetPeerId=="string"?t:null}catch{return null}}let js=Am();const Kn=js?.targetPeerId??"unpaired";function Nc(){return js}function vf(t){if(js=t,Ms)return;const e=JSON.stringify(t);sessionStorage.setItem(pn,e),localStorage.setItem(pn,e)}function km(){js=null,!Ms&&(localStorage.removeItem(pn),sessionStorage.removeItem(pn),localStorage.removeItem(Pc))}function zr(t,e=Kn){return Em.has(t)||t.startsWith("termdock-secure-")?t:`termdock-service:${e}:${t}`}function Cm(t){if(!(!xo||!yi))try{if(xo.call(localStorage,Hl))return;yi.call(localStorage,Hl,t);for(const n of[localStorage,sessionStorage]){const r=Array.from({length:n.length},(o,s)=>n.key(s)).filter(o=>!!o);for(const o of r){if(o.startsWith("termdock-service:")||zr(o,t)===o)continue;const s=zr(o,t),i=xo.call(n,o);i!==null&&xo.call(n,s)===null&&yi.call(n,s,i)}}}catch{}}let ql=!1;function Im(){if(ql||typeof Storage>"u")return;ql=!0;const t=Storage.prototype.getItem,e=Storage.prototype.setItem,n=Storage.prototype.removeItem;Storage.prototype.getItem=function(r){return t.call(this,zr(String(r)))},Storage.prototype.setItem=function(r,o){e.call(this,zr(String(r)),o)},Storage.prototype.removeItem=function(r){n.call(this,zr(String(r)))}}Im();const Us="termdock.federation.connections.v1",ka="termdock:services-changed",Lc="termdock-secure-removed-services",is=t=>[t.id,t.targetPeerId,t.serviceOrigin||t.url].filter(e=>!!e);function Bc(){try{const t=JSON.parse(localStorage.getItem(Lc)||"[]");return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}catch{return[]}}function Oe(t){const e=t.trim();if(!e)throw new Error("请输入服务地址。");const n=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(e)?e:`https://${e}`);n.protocol==="wss:"&&(n.protocol="https:"),n.protocol==="ws:"&&(n.protocol="http:");const r=["localhost","127.0.0.1","[::1]"].includes(n.hostname);if(!["https:","http:"].includes(n.protocol)||n.protocol==="http:"&&!r)throw new Error("请使用 HTTPS 服务地址。");if(n.username||n.password||n.search||n.hash||!["/","/api/federation/secure"].includes(n.pathname))throw new Error("请输入服务首页地址,不要包含账号或额外参数。");return n.origin}function $s(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.url=="string")try{const n=Oe(e.url),r=typeof e.targetPeerId=="string"&&e.targetPeerId?e.targetPeerId:void 0,o=(typeof e.label=="string"?e.label:typeof e.serviceName=="string"?e.serviceName:"").trim().slice(0,120)||new URL(n).host;return{id:typeof e.id=="string"&&e.id?e.id:r||n,url:n,label:o,...r?{targetPeerId:r}:{},...typeof e.serviceOrigin=="string"?{serviceOrigin:Oe(e.serviceOrigin)}:{},...typeof e.entryServiceId=="string"&&e.entryServiceId?{entryServiceId:e.entryServiceId}:{},...Array.isArray(e.routes)?{routes:e.routes.slice(0,4).flatMap(s=>{try{return s&&typeof s.targetPeerId=="string"&&s.targetPeerId?[{url:Oe(s.url),targetPeerId:s.targetPeerId}]:[]}catch{return[]}})}:{}}}catch{return}}function St(t,e){return t.targetPeerId&&e.targetPeerId?t.targetPeerId===e.targetPeerId:(t.serviceOrigin||t.url)===(e.serviceOrigin||e.url)}function Sf(t){const e=[];for(const n of t){const r=e.findIndex(o=>St(o,n));r<0?e.push(n):e[r]={...e[r],...n,id:e[r].id}}return e}function fo(){return typeof window>"u"?void 0:window.termdockDesktop}function gn(){try{const t=JSON.parse(localStorage.getItem(Us)||"[]");return Array.isArray(t)?Sf(t.map($s).filter(e=>!!e)):[]}catch{return[]}}function xf(t){localStorage.setItem(Us,JSON.stringify(t.map(e=>({...e,serviceName:e.label})))),window.dispatchEvent(new Event(ka))}let Er;async function He(){const t=fo();if(!t?.serviceConnections||!t.saveServiceConnection)return gn();if(Er)return Er;Er=(async()=>{let e=await t.serviceConnections();const n=gn();for(const r of n)e.some(o=>St(o,r))||(e=await(t.importServiceConnection||t.saveServiceConnection)(r));return n.length&&localStorage.removeItem(Us),e})();try{return await Er}finally{Er=void 0}}async function Ct(t){const e=$s(t);if(!e)throw new Error("服务地址无效。");const n=fo();if(n?.saveServiceConnection)return n.saveServiceConnection(e);const r=gn(),o=r.find(a=>a.id===e.id||St(a,e)),s=new Set([...is(e),...o?is(o):[]]);localStorage.setItem(Lc,JSON.stringify(Bc().filter(a=>!s.has(a))));const i=Sf([...r.filter(a=>a!==o),{...o,...e,id:o?.id||e.id}]);return xf(i),i}async function Rm(t){const e=$s(t);if(!e)throw new Error("服务地址无效。");const n=fo();if(n?.importServiceConnection)return n.importServiceConnection(e);if(n?.serviceConnections){const r=await n.serviceConnections();return r.some(o=>St(o,e))?Ct(e):r}return is(e).some(r=>Bc().includes(r))?gn():Ct(e)}async function Tm(t){const e=fo();if(e?.removeServiceConnection)return e.removeServiceConnection(t);const n=gn(),r=n.find(s=>s.id===t);r&&localStorage.setItem(Lc,JSON.stringify([...new Set([...Bc(),...is(r)])].slice(-768)));const o=n.filter(s=>s.id!==t);return xf(o),o}function Hs(t){const e=r=>{(r.key===Us||r.key===null)&&t()};window.addEventListener(ka,t),window.addEventListener("storage",e);const n=fo()?.onServiceConnections?.(t);return()=>{window.removeEventListener(ka,t),window.removeEventListener("storage",e),n?.()}}class Pm extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}let Nm=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},ot=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};class Ef extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class Af extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}}class Lm extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class Bm extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class qs extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}const kf=Symbol.for("@libp2p/peer-id");function _m(t){return typeof t?.handleEvent=="function"}function Om(t){return t===!0||t===!1}function Dm(t){return Om(t)?t:t?.capture??!1}function Ca(t){const e={capture:Dm(t),once:!!t?.once};return t?.passive!=null&&(e.passive=t?.passive),t?.signal!=null&&(e.signal=t?.signal),e}function Kl(t,e){return Ca(t).capture===Ca(e).capture}class Fm extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const n=this.#e.get(e);return n==null?0:n.length}addEventListener(e,n,r){const o=Ca(r);if(o?.signal?.aborted===!0)return;const s=l=>{o.once&&this.removeEventListener(e,n,o),_m(n)?n.handleEvent(l):n(l)};let i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(l=>l.callback!==n?!1:Kl(l.options,o)))return;super.addEventListener(e,s,o);const c=()=>{this.removeEventListener(e,n,o)};o.signal?.addEventListener("abort",c),i.push({callback:n,wrapper:s,options:o,onAbort:c})}removeEventListener(e,n,r){const o=this.#e.get(e);if(o==null){super.removeEventListener(e,n??null,r);return}this.#e.set(e,o.filter(s=>s.callback===n&&Kl(s.options,r)?(super.removeEventListener(e,s.wrapper,r),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,n={}){return this.dispatchEvent(new CustomEvent(e,n))}}const Mm=Symbol.for("@libp2p/service-capabilities");function jm(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let n=0;n<t.byteLength;n++)if(t[n]!==e[n])return!1;return!0}function Ks(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function Um(t){return new TextEncoder().encode(t)}function $m(t){return new TextDecoder().decode(t)}function Hm(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(n[i]!==255)throw new TypeError(s+" is ambiguous");n[i]=o}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var m=0,b=0,w=0,I=g.length;w!==I&&g[w]===0;)w++,m++;for(var y=(I-w)*d+1>>>0,v=new Uint8Array(y);w!==I;){for(var L=g[w],C=0,T=y-1;(L!==0||C<b)&&T!==-1;T--,C++)L+=256*v[T]>>>0,v[T]=L%a>>>0,L=L/a>>>0;if(L!==0)throw new Error("Non-zero carry");b=C,w++}for(var E=y-b;E!==y&&v[E]===0;)E++;for(var S=c.repeat(m);E<y;++E)S+=t.charAt(v[E]);return S}function f(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var m=0;if(g[m]!==" "){for(var b=0,w=0;g[m]===c;)b++,m++;for(var I=(g.length-m)*l+1>>>0,y=new Uint8Array(I);g[m];){var v=n[g.charCodeAt(m)];if(v===255)return;for(var L=0,C=I-1;(v!==0||L<w)&&C!==-1;C--,L++)v+=a*y[C]>>>0,y[C]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");w=L,m++}if(g[m]!==" "){for(var T=I-w;T!==I&&y[T]===0;)T++;for(var E=new Uint8Array(b+(I-T)),S=b;T!==I;)E[S++]=y[T++];return E}}}function h(g){var m=f(g);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:h}}var qm=Hm,Km=qm;class zm{name;prefix;baseEncode;constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Wm{name;prefix;baseDecode;prefixCodePoint;constructor(e,n,r){this.name=e,this.prefix=n;const o=n.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Cf(this,e)}}class Vm{decoders;constructor(e){this.decoders=e}or(e){return Cf(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r!=null)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function Cf(t,e){return new Vm({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class Gm{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,n,r,o){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=o,this.encoder=new zm(e,n,r),this.decoder=new Wm(e,n,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function zs({name:t,prefix:e,encode:n,decode:r}){return new Gm(t,e,n,r)}function ho({name:t,prefix:e,alphabet:n}){const{encode:r,decode:o}=Km(n,t);return zs({prefix:e,name:t,encode:r,decode:s=>Ks(o(s))})}function Xm(t,e,n,r){let o=t.length;for(;t[o-1]==="=";)--o;const s=new Uint8Array(o*n/8|0);let i=0,a=0,c=0;for(let l=0;l<o;++l){const d=e[t[l]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<n|d,i+=n,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=n||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Ym(t,e,n){const r=e[e.length-1]==="=",o=(1<<n)-1;let s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>n;)i-=n,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<n-i]),r)for(;(s.length*n&7)!==0;)s+="=";return s}function Zm(t){const e={};for(let n=0;n<t.length;++n)e[t[n]]=n;return e}function Ce({name:t,prefix:e,bitsPerChar:n,alphabet:r}){const o=Zm(r);return zs({prefix:e,name:t,encode(s){return Ym(s,r,n)},decode(s){return Xm(s,o,n,t)}})}const Be=ho({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Jm=ho({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Qm=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Be,base58flickr:Jm},Symbol.toStringTag,{value:"Module"})),Wr=Ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ew=Ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),tw=Ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),nw=Ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),rw=Ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ow=Ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),sw=Ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),iw=Ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),aw=Ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),cw=Object.freeze(Object.defineProperty({__proto__:null,base32:Wr,base32hex:rw,base32hexpad:sw,base32hexpadupper:iw,base32hexupper:ow,base32pad:tw,base32padupper:nw,base32upper:ew,base32z:aw},Symbol.toStringTag,{value:"Module"})),Vo=ho({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),lw=ho({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),dw=Object.freeze(Object.defineProperty({__proto__:null,base36:Vo,base36upper:lw},Symbol.toStringTag,{value:"Module"}));var uw=If,zl=128,fw=-128,hw=Math.pow(2,31);function If(t,e,n){e=e||[],n=n||0;for(var r=n;t>=hw;)e[n++]=t&255|zl,t/=128;for(;t&fw;)e[n++]=t&255|zl,t>>>=7;return e[n]=t|0,If.bytes=n-r+1,e}var pw=Ia,gw=128,Wl=127;function Ia(t,r){var n=0,r=r||0,o=0,s=r,i,a=t.length;do{if(s>=a)throw Ia.bytes=0,new RangeError("Could not decode varint");i=t[s++],n+=o<28?(i&Wl)<<o:(i&Wl)*Math.pow(2,o),o+=7}while(i>=gw);return Ia.bytes=s-r,n}var mw=Math.pow(2,7),ww=Math.pow(2,14),yw=Math.pow(2,21),bw=Math.pow(2,28),vw=Math.pow(2,35),Sw=Math.pow(2,42),xw=Math.pow(2,49),Ew=Math.pow(2,56),Aw=Math.pow(2,63),kw=function(t){return t<mw?1:t<ww?2:t<yw?3:t<bw?4:t<vw?5:t<Sw?6:t<xw?7:t<Ew?8:t<Aw?9:10},Cw={encode:uw,decode:pw,encodingLength:kw},as=Cw;function Ra(t,e=0){return[as.decode(t,e),as.decode.bytes]}function cs(t,e,n=0){return as.encode(t,e,n),e}function ls(t){return as.encodingLength(t)}function po(t,e){const n=e.byteLength,r=ls(t),o=r+ls(n),s=new Uint8Array(o+n);return cs(t,s,0),cs(n,s,r),s.set(e,o),new _c(t,n,e,s)}function Rf(t){const e=Ks(t),[n,r]=Ra(e),[o,s]=Ra(e.subarray(r)),i=e.subarray(r+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new _c(n,o,i,e)}function Iw(t,e){if(t===e)return!0;{const n=e;return t.code===n.code&&t.size===n.size&&n.bytes instanceof Uint8Array&&jm(t.bytes,n.bytes)}}class _c{code;size;digest;bytes;constructor(e,n,r,o){this.code=e,this.size=n,this.digest=r,this.bytes=o}}function Vl(t,e){const{bytes:n,version:r}=t;return r===0?Tw(n,Ta(t),e??Be.encoder):Pw(n,Ta(t),e??Wr.encoder)}const Gl=new WeakMap;function Ta(t){const e=Gl.get(t);if(e==null){const n=new Map;return Gl.set(t,n),n}return e}class le{code;version;multihash;bytes;"/";constructor(e,n,r,o){this.code=n,this.version=e,this.multihash=r,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:e,multihash:n}=this;if(e!==Ar)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==Nw)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return le.createV0(n)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:e,digest:n}=this.multihash,r=po(e,n);return le.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return le.equals(this,e)}static equals(e,n){const r=n;return r!=null&&e.code===r.code&&e.version===r.version&&Iw(e.multihash,r.multihash)}toString(e){return Vl(this,e)}toJSON(){return{"/":Vl(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;const n=e;if(n instanceof le)return n;if(n["/"]!=null&&n["/"]===n.bytes||n.asCID===n){const{version:r,code:o,multihash:s,bytes:i}=n;return new le(r,o,s,i??Xl(r,o,s.bytes))}else if(n[Lw]===!0){const{version:r,multihash:o,code:s}=n,i=Rf(o);return le.create(r,s,i)}else return null}static create(e,n,r){if(typeof n!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(n!==Ar)throw new Error(`Version 0 CID must use dag-pb (code: ${Ar}) block encoding`);return new le(e,n,r,r.bytes)}case 1:{const o=Xl(e,n,r.bytes);return new le(e,n,r,o)}default:throw new Error("Invalid version")}}static createV0(e){return le.create(0,Ar,e)}static createV1(e,n){return le.create(1,e,n)}static decode(e){const[n,r]=le.decodeFirst(e);if(r.length!==0)throw new Error("Incorrect length");return n}static decodeFirst(e){const n=le.inspectBytes(e),r=n.size-n.multihashSize,o=Ks(e.subarray(r,r+n.multihashSize));if(o.byteLength!==n.multihashSize)throw new Error("Incorrect length");const s=o.subarray(n.multihashSize-n.digestSize),i=new _c(n.multihashCode,n.digestSize,s,o);return[n.version===0?le.createV0(i):le.createV1(n.codec,i),e.subarray(n.size)]}static inspectBytes(e){let n=0;const r=()=>{const[u,f]=Ra(e.subarray(n));return n+=f,u};let o=r(),s=Ar;if(o===18?(o=0,n=0):s=r(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);const i=n,a=r(),c=r(),l=n+c,d=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:l}}static parse(e,n){const[r,o]=Rw(e,n),s=le.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ta(s).set(r,e),s}}function Rw(t,e){switch(t[0]){case"Q":{const n=e??Be;return[Be.prefix,n.decode(`${Be.prefix}${t}`)]}case Be.prefix:{const n=e??Be;return[Be.prefix,n.decode(t)]}case Wr.prefix:{const n=e??Wr;return[Wr.prefix,n.decode(t)]}case Vo.prefix:{const n=e??Vo;return[Vo.prefix,n.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function Tw(t,e,n){const{prefix:r}=n;if(r!==Be.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);const o=e.get(r);if(o==null){const s=n.encode(t).slice(1);return e.set(r,s),s}else return o}function Pw(t,e,n){const{prefix:r}=n,o=e.get(r);if(o==null){const s=n.encode(t);return e.set(r,s),s}else return o}const Ar=112,Nw=18;function Xl(t,e,n){const r=ls(t),o=r+ls(e),s=new Uint8Array(o+n.byteLength);return cs(t,s,0),cs(e,s,r),s.set(n,o),s}const Lw=Symbol.for("@ipld/js-cid/CID"),Tf=0,Bw="identity",Pf=Ks;function _w(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return po(Tf,Pf(t))}const go={code:Tf,name:Bw,encode:Pf,digest:_w};function st(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let n=0;n<t.byteLength;n++)if(t[n]!==e[n])return!1;return!0}function Ue(t=0){return new Uint8Array(t)}function It(t=0){return new Uint8Array(t)}function Pa(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));const n=It(e);let r=0;for(const o of t)n.set(o,r),r+=o.length;return n}const Nf=Symbol.for("@achingbrain/uint8arraylist");function Yl(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let n=0;for(const r of t){const o=n+r.byteLength;if(e<o)return{buf:r,index:e-n};n=o}throw new RangeError("index is out of bounds")}function Eo(t){return!!t?.[Nf]}class se{bufs;length;[Nf]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let n=0;for(const r of e)if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.push(r);else if(Eo(r)){n+=r.byteLength;for(const o of r.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=n}prepend(...e){this.prependAll(e)}prependAll(e){let n=0;for(const r of e.reverse())if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.unshift(r);else if(Eo(r))n+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=n}get(e){const n=Yl(this.bufs,e);return n.buf[n.index]}set(e,n){const r=Yl(this.bufs,e);r.buf[r.index]=n}write(e,n=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(n+r,e[r]);else if(Eo(e))for(let r=0;r<e.length;r++)this.set(n+r,e.get(r));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,n){const{bufs:r,length:o}=this._subList(e,n);return Pa(r,o)}subarray(e,n){const{bufs:r,length:o}=this._subList(e,n);return r.length===1?r[0]:Pa(r,o)}sublist(e,n){const{bufs:r,length:o}=this._subList(e,n),s=new se;return s.length=o,s.bufs=r,s}_subList(e,n){if(e=e??0,n=n??this.length,e<0&&(e=this.length+e),n<0&&(n=this.length+n),e<0||n>this.length)throw new RangeError("index is out of bounds");if(e===n)return{bufs:[],length:0};if(e===0&&n===this.length)return{bufs:[...this.bufs],length:this.length};const r=[];let o=0;for(let s=0;s<this.bufs.length;s++){const i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;const l=e>=a&&e<c,d=n>a&&n<=c;if(l&&d){if(e===a&&n===c){r.push(i);break}const u=e-a;r.push(i.subarray(u,u+(n-e)));break}if(l){if(e===0){r.push(i);continue}r.push(i.subarray(e-a));continue}if(d){if(n===c){r.push(i);break}r.push(i.subarray(0,n-a));break}r.push(i)}return{bufs:r,length:n-e}}indexOf(e,n=0){if(!Eo(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(n=Number(n??0),isNaN(n)&&(n=0),n<0&&(n=this.length+n),n<0&&(n=0),e.length===0)return n>this.length?this.length:n;const o=r.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");const s=256,i=new Int32Array(s);for(let u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[r[u]]=u;const a=i,c=this.byteLength-r.byteLength,l=r.byteLength-1;let d;for(let u=n;u<=c;u+=d){d=0;for(let f=l;f>=0;f--){const h=this.get(u+f);if(r[f]!==h){d=Math.max(1,f-a[h]);break}}if(d===0)return u}return-1}getInt8(e){const n=this.subarray(e,e+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt8(0)}setInt8(e,n){const r=It(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,n),this.write(r,e)}getInt16(e,n){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,n)}setInt16(e,n,r){const o=Ue(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,n,r),this.write(o,e)}getInt32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,n)}setInt32(e,n,r){const o=Ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,n,r),this.write(o,e)}getBigInt64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,n)}setBigInt64(e,n,r){const o=Ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,n,r),this.write(o,e)}getUint8(e){const n=this.subarray(e,e+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint8(0)}setUint8(e,n){const r=It(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,n),this.write(r,e)}getUint16(e,n){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,n)}setUint16(e,n,r){const o=Ue(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,n,r),this.write(o,e)}getUint32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,n)}setUint32(e,n,r){const o=Ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,n,r),this.write(o,e)}getBigUint64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,n)}setBigUint64(e,n,r){const o=Ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,n,r),this.write(o,e)}getFloat32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,n)}setFloat32(e,n,r){const o=Ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,n,r),this.write(o,e)}getFloat64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,n)}setFloat64(e,n,r){const o=Ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,n,r),this.write(o,e)}equals(e){if(e==null||!(e instanceof se)||e.bufs.length!==this.bufs.length)return!1;for(let n=0;n<this.bufs.length;n++)if(!st(this.bufs[n],e.bufs[n]))return!1;return!0}static fromUint8Arrays(e,n){const r=new se;return r.bufs=e,n==null&&(n=e.reduce((o,s)=>o+s.byteLength,0)),r.length=n,r}}const Ow=ho({prefix:"9",name:"base10",alphabet:"0123456789"}),Dw=Object.freeze(Object.defineProperty({__proto__:null,base10:Ow},Symbol.toStringTag,{value:"Module"})),Fw=Ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Mw=Ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),jw=Object.freeze(Object.defineProperty({__proto__:null,base16:Fw,base16upper:Mw},Symbol.toStringTag,{value:"Module"})),Uw=Ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),$w=Object.freeze(Object.defineProperty({__proto__:null,base2:Uw},Symbol.toStringTag,{value:"Module"})),Lf=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Hw=Lf.reduce((t,e,n)=>(t[n]=e,t),[]),qw=Lf.reduce((t,e,n)=>{const r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return t[r]=n,t},[]);function Kw(t){return t.reduce((e,n)=>(e+=Hw[n],e),"")}function zw(t){const e=[];for(const n of t){const r=n.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${n}`);const o=qw[r];if(o==null)throw new Error(`Non-base256emoji character: ${n}`);e.push(o)}return new Uint8Array(e)}const Ww=zs({prefix:"🚀",name:"base256emoji",encode:Kw,decode:zw}),Vw=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:Ww},Symbol.toStringTag,{value:"Module"})),Gw=Ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Xw=Ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Yw=Ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Zw=Ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Jw=Object.freeze(Object.defineProperty({__proto__:null,base64:Gw,base64pad:Xw,base64url:Yw,base64urlpad:Zw},Symbol.toStringTag,{value:"Module"})),Qw=Ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),ey=Object.freeze(Object.defineProperty({__proto__:null,base8:Qw},Symbol.toStringTag,{value:"Module"})),ty=zs({prefix:"\0",name:"identity",encode:t=>$m(t),decode:t=>Um(t)}),ny=Object.freeze(Object.defineProperty({__proto__:null,identity:ty},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const ry=20;function oy({name:t,code:e,encode:n,minDigestLength:r,maxDigestLength:o}){return new sy(t,e,n,r,o)}class sy{name;code;encode;minDigestLength;maxDigestLength;constructor(e,n,r,o,s){this.name=e,this.code=n,this.encode=r,this.minDigestLength=o??ry,this.maxDigestLength=s}digest(e,n){if(n?.truncate!=null){if(n.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&n.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Zl(r,this.code,n?.truncate):r.then(o=>Zl(o,this.code,n?.truncate))}else throw Error("Unknown type, must be binary type")}}function Zl(t,e,n){if(n!=null&&n!==t.byteLength){if(n>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,n)}return po(e,t)}function iy(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}const Oc=oy({name:"sha2-256",code:18,encode:iy("SHA-256")}),Jl={...ny,...$w,...ey,...Dw,...jw,...cw,...dw,...Qm,...Jw,...Vw};function Bf(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const Ql=Bf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),bi=Bf("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=It(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),_f={utf8:Ql,"utf-8":Ql,hex:Jl.base16,latin1:bi,ascii:bi,binary:bi,...Jl};function we(t,e="utf8"){const n=_f[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.decoder.decode(`${n.prefix}${t}`)}function ee(t,e="utf8"){const n=_f[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.encoder.encode(t).substring(1)}const ay=parseInt("11111",2),Na=parseInt("10000000",2),cy=parseInt("01111111",2),ed={0:kr,1:kr,2:ly,3:fy,4:hy,5:uy,6:dy,16:kr,22:kr,48:kr};function gr(t,e={offset:0}){const n=t[e.offset]&ay;if(e.offset++,ed[n]!=null)return ed[n](t,e);throw new Error("No decoder for tag "+n)}function mo(t,e){let n=0;if((t[e.offset]&Na)===Na){const r=t[e.offset]&cy;let o="0x";e.offset++;for(let s=0;s<r;s++,e.offset++)o+=t[e.offset].toString(16).padStart(2,"0");n=parseInt(o,16)}else n=t[e.offset],e.offset++;return n}function kr(t,e){mo(t,e);const n=[];for(;!(e.offset>=t.byteLength);){const r=gr(t,e);if(r===null)break;n.push(r)}return n}function ly(t,e){const n=mo(t,e),r=e.offset,o=e.offset+n,s=[];for(let i=r;i<o;i++)i===r&&t[i]===0||s.push(t[i]);return e.offset+=n,Uint8Array.from(s)}function dy(t,e){const n=mo(t,e),r=e.offset+n,o=t[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<r;){const l=t[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let d=0;for(let u=0;u<c.length;u++)d+=c[u]<<u*7;a+=`.${d}`,c=[]}}return a}function uy(t,e){return e.offset++,null}function fy(t,e){const n=mo(t,e),r=t[e.offset];e.offset++;const o=t.subarray(e.offset,e.offset+n-1);if(e.offset+=n,r!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function hy(t,e){const n=mo(t,e),r=t.subarray(e.offset,e.offset+n);return e.offset+=n,r}function py(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);const n=new se;for(let r=0;r<e.length;r+=2)n.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return n}function Ws(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);const e=py(t.byteLength);return new se(Uint8Array.from([e.byteLength|Na]),e)}function Ke(t){const e=new se,n=128;return(t.subarray()[0]&n)===n&&e.append(Uint8Array.from([0])),e.append(t),new se(Uint8Array.from([2]),Ws(e),e)}function Dc(t){const e=Uint8Array.from([0]),n=new se(e,t);return new se(Uint8Array.from([3]),Ws(n),n)}function gy(t){return new se(Uint8Array.from([4]),Ws(t),t)}function kt(t,e=48){const n=new se;for(const r of t)n.append(r);return new se(Uint8Array.from([e]),Ws(n),n)}async function my(t,e,n){const r=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["sign"]);n?.signal?.throwIfAborted();const o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function wy(t,e,n,r){const o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();const s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,n.subarray());return r?.signal?.throwIfAborted(),s}const yy=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),by=Uint8Array.from([6,5,43,129,4,0,34]),vy=Uint8Array.from([6,5,43,129,4,0,35]),Of={ext:!0,kty:"EC",crv:"P-256"},Df={ext:!0,kty:"EC",crv:"P-384"},Ff={ext:!0,kty:"EC",crv:"P-521"},zn=32,Wn=48,Vn=66;function Sy(t){const e=gr(t);return xy(e)}function xy(t){const e=t[1],n=ee(e,"base64url"),r=t[2][1][0],o=1;let s,i;if(e.byteLength===zn)return s=ee(r.subarray(o,o+zn),"base64url"),i=ee(r.subarray(o+zn),"base64url"),new vi({...Of,key_ops:["sign"],d:n,x:s,y:i});if(e.byteLength===Wn)return s=ee(r.subarray(o,o+Wn),"base64url"),i=ee(r.subarray(o+Wn),"base64url"),new vi({...Df,key_ops:["sign"],d:n,x:s,y:i});if(e.byteLength===Vn)return s=ee(r.subarray(o,o+Vn),"base64url"),i=ee(r.subarray(o+Vn),"base64url"),new vi({...Ff,key_ops:["sign"],d:n,x:s,y:i});throw new ot(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function Mf(t){const e=gr(t);return Ey(e)}function Ey(t){const e=t[1][1][0],n=1;let r,o;if(e.byteLength===zn*2+1)return r=ee(e.subarray(n,n+zn),"base64url"),o=ee(e.subarray(n+zn),"base64url"),new Go({...Of,key_ops:["verify"],x:r,y:o});if(e.byteLength===Wn*2+1)return r=ee(e.subarray(n,n+Wn),"base64url"),o=ee(e.subarray(n+Wn),"base64url"),new Go({...Df,key_ops:["verify"],x:r,y:o});if(e.byteLength===Vn*2+1)return r=ee(e.subarray(n,n+Vn),"base64url"),o=ee(e.subarray(n+Vn),"base64url"),new Go({...Ff,key_ops:["verify"],x:r,y:o});throw new ot(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Ay(t){return kt([Ke(Uint8Array.from([1])),gy(we(t.d??"","base64url")),kt([jf(t.crv)],160),kt([Dc(new se(Uint8Array.from([4]),we(t.x??"","base64url"),we(t.y??"","base64url")))],161)]).subarray()}function ky(t){return kt([Ke(Uint8Array.from([1])),kt([jf(t.crv)],160),kt([Dc(new se(Uint8Array.from([4]),we(t.x??"","base64url"),we(t.y??"","base64url")))],161)]).subarray()}function jf(t){if(t==="P-256")return yy;if(t==="P-384")return by;if(t==="P-521")return vy;throw new ot(`Invalid curve ${t}`)}class Go{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=ky(this.jwk)),this._raw}toMultihash(){return go.digest(Js(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return Be.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:st(this.raw,e.raw)}async verify(e,n,r){return wy(this.jwk,n,e,r)}}class vi{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Go({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=Ay(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:st(this.raw,e.raw)}async sign(e,n){return my(this.jwk,e,n)}}const Nn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function wo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function La(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Sn(t,...e){if(!wo(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Uf(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");La(t.outputLen),La(t.blockLen)}function ds(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Cy(t,e){Sn(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function ir(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Si(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function it(t,e){return t<<32-e|t>>>e}const $f=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Iy=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function dn(t){if(Sn(t),$f)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Iy[t[n]];return e}const gt={_0:48,_9:57,A:65,F:70,a:97,f:102};function td(t){if(t>=gt._0&&t<=gt._9)return t-gt._0;if(t>=gt.A&&t<=gt.F)return t-(gt.A-10);if(t>=gt.a&&t<=gt.f)return t-(gt.a-10)}function us(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if($f)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){const i=td(t.charCodeAt(s)),a=td(t.charCodeAt(s+1));if(i===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a}return r}function Ry(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Fc(t){return typeof t=="string"&&(t=Ry(t)),Sn(t),t}function lt(...t){let e=0;for(let r=0;r<t.length;r++){const o=t[r];Sn(o),e+=o.length}const n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){const s=t[r];n.set(s,o),o+=s.length}return n}class Hf{}function qf(t){const e=r=>t().update(Fc(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Mc(t=32){if(Nn&&typeof Nn.getRandomValues=="function")return Nn.getRandomValues(new Uint8Array(t));if(Nn&&typeof Nn.randomBytes=="function")return Uint8Array.from(Nn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function Ty(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const o=BigInt(32),s=BigInt(4294967295),i=Number(n>>o&s),a=Number(n&s),c=r?4:0,l=r?0:4;t.setUint32(e+c,i,r),t.setUint32(e+l,a,r)}function Py(t,e,n){return t&e^~t&n}function Ny(t,e,n){return t&e^t&n^e&n}let Kf=class extends Hf{constructor(e,n,r,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Si(this.buffer)}update(e){ds(this),e=Fc(e),Sn(e);const{view:n,buffer:r,blockLen:o}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(o-this.pos,s-i);if(a===o){const c=Si(e);for(;o<=s-i;i+=o)this.process(c,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ds(this),Cy(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:o,isLE:s}=this;let{pos:i}=this;n[i++]=128,ir(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(r,0),i=0);for(let u=i;u<o;u++)n[u]=0;Ty(r,o-8,BigInt(this.length*8),s),this.process(r,0);const a=Si(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};const Nt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Re=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Ao=BigInt(2**32-1),nd=BigInt(32);function Ly(t,e=!1){return e?{h:Number(t&Ao),l:Number(t>>nd&Ao)}:{h:Number(t>>nd&Ao)|0,l:Number(t&Ao)|0}}function By(t,e=!1){const n=t.length;let r=new Uint32Array(n),o=new Uint32Array(n);for(let s=0;s<n;s++){const{h:i,l:a}=Ly(t[s],e);[r[s],o[s]]=[i,a]}return[r,o]}const rd=(t,e,n)=>t>>>n,od=(t,e,n)=>t<<32-n|e>>>n,Ln=(t,e,n)=>t>>>n|e<<32-n,Bn=(t,e,n)=>t<<32-n|e>>>n,ko=(t,e,n)=>t<<64-n|e>>>n-32,Co=(t,e,n)=>t>>>n-32|e<<64-n;function mt(t,e,n,r){const o=(e>>>0)+(r>>>0);return{h:t+n+(o/2**32|0)|0,l:o|0}}const _y=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Oy=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Dy=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Fy=(t,e,n,r,o)=>e+n+r+o+(t/2**32|0)|0,My=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),jy=(t,e,n,r,o,s)=>e+n+r+o+s+(t/2**32|0)|0,Uy=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Lt=new Uint32Array(64);class $y extends Kf{constructor(e=32){super(64,e,8,!1),this.A=Nt[0]|0,this.B=Nt[1]|0,this.C=Nt[2]|0,this.D=Nt[3]|0,this.E=Nt[4]|0,this.F=Nt[5]|0,this.G=Nt[6]|0,this.H=Nt[7]|0}get(){const{A:e,B:n,C:r,D:o,E:s,F:i,G:a,H:c}=this;return[e,n,r,o,s,i,a,c]}set(e,n,r,o,s,i,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,n){for(let u=0;u<16;u++,n+=4)Lt[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const f=Lt[u-15],h=Lt[u-2],g=it(f,7)^it(f,18)^f>>>3,m=it(h,17)^it(h,19)^h>>>10;Lt[u]=m+Lt[u-7]+g+Lt[u-16]|0}let{A:r,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=it(a,6)^it(a,11)^it(a,25),h=d+f+Py(a,c,l)+Uy[u]+Lt[u]|0,m=(it(r,2)^it(r,13)^it(r,22))+Ny(r,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=r,r=h+m|0}r=r+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,s,i,a,c,l,d)}roundClean(){ir(Lt)}destroy(){this.set(0,0,0,0,0,0,0,0),ir(this.buffer)}}const zf=By(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Hy=zf[0],qy=zf[1],Bt=new Uint32Array(80),_t=new Uint32Array(80);class Ky extends Kf{constructor(e=64){super(128,e,16,!1),this.Ah=Re[0]|0,this.Al=Re[1]|0,this.Bh=Re[2]|0,this.Bl=Re[3]|0,this.Ch=Re[4]|0,this.Cl=Re[5]|0,this.Dh=Re[6]|0,this.Dl=Re[7]|0,this.Eh=Re[8]|0,this.El=Re[9]|0,this.Fh=Re[10]|0,this.Fl=Re[11]|0,this.Gh=Re[12]|0,this.Gl=Re[13]|0,this.Hh=Re[14]|0,this.Hl=Re[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:f,Gh:h,Gl:g,Hh:m,Hl:b}=this;return[e,n,r,o,s,i,a,c,l,d,u,f,h,g,m,b]}set(e,n,r,o,s,i,a,c,l,d,u,f,h,g,m,b){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=d|0,this.Fh=u|0,this.Fl=f|0,this.Gh=h|0,this.Gl=g|0,this.Hh=m|0,this.Hl=b|0}process(e,n){for(let y=0;y<16;y++,n+=4)Bt[y]=e.getUint32(n),_t[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){const v=Bt[y-15]|0,L=_t[y-15]|0,C=Ln(v,L,1)^Ln(v,L,8)^rd(v,L,7),T=Bn(v,L,1)^Bn(v,L,8)^od(v,L,7),E=Bt[y-2]|0,S=_t[y-2]|0,k=Ln(E,S,19)^ko(E,S,61)^rd(E,S,6),N=Bn(E,S,19)^Co(E,S,61)^od(E,S,6),D=Dy(T,N,_t[y-7],_t[y-16]),A=Fy(D,C,k,Bt[y-7],Bt[y-16]);Bt[y]=A|0,_t[y]=D|0}let{Ah:r,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:f,Fh:h,Fl:g,Gh:m,Gl:b,Hh:w,Hl:I}=this;for(let y=0;y<80;y++){const v=Ln(u,f,14)^Ln(u,f,18)^ko(u,f,41),L=Bn(u,f,14)^Bn(u,f,18)^Co(u,f,41),C=u&h^~u&m,T=f&g^~f&b,E=My(I,L,T,qy[y],_t[y]),S=jy(E,w,v,C,Hy[y],Bt[y]),k=E|0,N=Ln(r,o,28)^ko(r,o,34)^ko(r,o,39),D=Bn(r,o,28)^Co(r,o,34)^Co(r,o,39),A=r&s^r&a^s&a,x=o&i^o&c^i&c;w=m|0,I=b|0,m=h|0,b=g|0,h=u|0,g=f|0,{h:u,l:f}=mt(l|0,d|0,S|0,k|0),l=a|0,d=c|0,a=s|0,c=i|0,s=r|0,i=o|0;const P=_y(k,D,x);r=Oy(P,S,N,A),o=P|0}({h:r,l:o}=mt(this.Ah|0,this.Al|0,r|0,o|0)),{h:s,l:i}=mt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=mt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=mt(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:f}=mt(this.Eh|0,this.El|0,u|0,f|0),{h,l:g}=mt(this.Fh|0,this.Fl|0,h|0,g|0),{h:m,l:b}=mt(this.Gh|0,this.Gl|0,m|0,b|0),{h:w,l:I}=mt(this.Hh|0,this.Hl|0,w|0,I|0),this.set(r,o,s,i,a,c,l,d,u,f,h,g,m,b,w,I)}roundClean(){ir(Bt,_t)}destroy(){ir(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Wf=qf(()=>new $y),zy=qf(()=>new Ky);const jc=BigInt(0),Ba=BigInt(1);function mn(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function rt(t,e,n=""){const r=wo(t),o=t?.length,s=e!==void 0;if(!r||s&&o!==e){const i=n&&`"${n}" `,a=s?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function Io(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Vf(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?jc:BigInt("0x"+t)}function Vs(t){return Vf(dn(t))}function to(t){return Sn(t),Vf(dn(Uint8Array.from(t).reverse()))}function Uc(t,e){return us(t.toString(16).padStart(e*2,"0"))}function Gf(t,e){return Uc(t,e).reverse()}function he(t,e,n){let r;if(typeof e=="string")try{r=us(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(wo(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const o=r.length;if(typeof n=="number"&&o!==n)throw new Error(t+" of length "+n+" expected, got "+o);return r}function sd(t){return Uint8Array.from(t)}const xi=t=>typeof t=="bigint"&&jc<=t;function Wy(t,e,n){return xi(t)&&xi(e)&&xi(n)&&e<=t&&t<n}function _a(t,e,n,r){if(!Wy(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Xf(t){let e;for(e=0;t>jc;t>>=Ba,e+=1);return e}const yo=t=>(Ba<<BigInt(t))-Ba;function Vy(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=h=>new Uint8Array(h),o=h=>Uint8Array.of(h);let s=r(t),i=r(t),a=0;const c=()=>{s.fill(1),i.fill(0),a=0},l=(...h)=>n(i,s,...h),d=(h=r(0))=>{i=l(o(0),h),s=l(),h.length!==0&&(i=l(o(1),h),s=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const g=[];for(;h<e;){s=l();const m=s.slice();g.push(m),h+=s.length}return lt(...g)};return(h,g)=>{c(),d(h);let m;for(;!(m=g(u()));)d();return c(),m}}function bo(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(o,s,i){const a=t[o];if(i&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([o,s])=>r(o,s,!1)),Object.entries(n).forEach(([o,s])=>r(o,s,!0))}function fs(t){const e=new WeakMap;return(n,...r)=>{const o=e.get(n);if(o!==void 0)return o;const s=t(n,...r);return e.set(n,s),s}}const $e=BigInt(0),ke=BigInt(1),rn=BigInt(2),Yf=BigInt(3),Zf=BigInt(4),Jf=BigInt(5),Gy=BigInt(7),Qf=BigInt(8),Xy=BigInt(9),eh=BigInt(16);function ye(t,e){const n=t%e;return n>=$e?n:e+n}function fe(t,e,n){let r=t;for(;e-- >$e;)r*=r,r%=n;return r}function id(t,e){if(t===$e)throw new Error("invert: expected non-zero number");if(e<=$e)throw new Error("invert: expected positive modulus, got "+e);let n=ye(t,e),r=e,o=$e,s=ke;for(;n!==$e;){const a=r/n,c=r%n,l=o-s*a;r=n,n=c,o=s,s=l}if(r!==ke)throw new Error("invert: does not exist");return ye(o,e)}function $c(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function th(t,e){const n=(t.ORDER+ke)/Zf,r=t.pow(e,n);return $c(t,r,e),r}function Yy(t,e){const n=(t.ORDER-Jf)/Qf,r=t.mul(e,rn),o=t.pow(r,n),s=t.mul(e,o),i=t.mul(t.mul(s,rn),o),a=t.mul(s,t.sub(i,t.ONE));return $c(t,a,e),a}function Zy(t){const e=xn(t),n=nh(t),r=n(e,e.neg(e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+Gy)/eh;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,r);const u=a.mul(l,o),f=a.mul(l,s),h=a.eql(a.sqr(d),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,d,h),d=a.cmov(f,u,g);const m=a.eql(a.sqr(d),c),b=a.cmov(l,d,m);return $c(a,b,c),b}}function nh(t){if(t<Yf)throw new Error("sqrt is not defined for small field");let e=t-ke,n=0;for(;e%rn===$e;)e/=rn,n++;let r=rn;const o=xn(t);for(;ad(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return th;let s=o.pow(r,e);const i=(e+ke)/rn;return function(c,l){if(c.is0(l))return l;if(ad(c,l)!==1)throw new Error("Cannot find square root");let d=n,u=c.mul(c.ONE,s),f=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let g=1,m=c.sqr(f);for(;!c.eql(m,c.ONE);)if(g++,m=c.sqr(m),g===d)throw new Error("Cannot find square root");const b=ke<<BigInt(d-g-1),w=c.pow(u,b);d=g,u=c.sqr(w),f=c.mul(f,u),h=c.mul(h,w)}return h}}function Jy(t){return t%Zf===Yf?th:t%Qf===Jf?Yy:t%eh===Xy?Zy(t):nh(t)}const Qy=(t,e)=>(ye(t,e)&ke)===ke,eb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function tb(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=eb.reduce((r,o)=>(r[o]="function",r),e);return bo(t,n),t}function nb(t,e,n){if(n<$e)throw new Error("invalid exponent, negatives unsupported");if(n===$e)return t.ONE;if(n===ke)return e;let r=t.ONE,o=e;for(;n>$e;)n&ke&&(r=t.mul(r,o)),o=t.sqr(o),n>>=ke;return r}function rh(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),o=e.reduce((i,a,c)=>t.is0(a)?i:(r[c]=i,t.mul(i,a)),t.ONE),s=t.inv(o);return e.reduceRight((i,a,c)=>t.is0(a)?i:(r[c]=t.mul(i,r[c]),t.mul(i,a)),s),r}function ad(t,e){const n=(t.ORDER-ke)/rn,r=t.pow(e,n),o=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),i=t.eql(r,t.neg(t.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function oh(t,e){e!==void 0&&La(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function xn(t,e,n=!1,r={}){if(t<=$e)throw new Error("invalid field: expected ORDER > 0, got "+t);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const f=e;f.BITS&&(o=f.BITS),f.sqrt&&(s=f.sqrt),typeof f.isLE=="boolean"&&(n=f.isLE),typeof f.modFromBytes=="boolean"&&(i=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(o=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:l}=oh(t,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:l,MASK:yo(c),ZERO:$e,ONE:ke,allowedLengths:a,create:f=>ye(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return $e<=f&&f<t},is0:f=>f===$e,isValidNot0:f=>!u.is0(f)&&u.isValid(f),isOdd:f=>(f&ke)===ke,neg:f=>ye(-f,t),eql:(f,h)=>f===h,sqr:f=>ye(f*f,t),add:(f,h)=>ye(f+h,t),sub:(f,h)=>ye(f-h,t),mul:(f,h)=>ye(f*h,t),pow:(f,h)=>nb(u,f,h),div:(f,h)=>ye(f*id(h,t),t),sqrN:f=>f*f,addN:(f,h)=>f+h,subN:(f,h)=>f-h,mulN:(f,h)=>f*h,inv:f=>id(f,t),sqrt:s||(f=>(d||(d=Jy(t)),d(u,f))),toBytes:f=>n?Gf(f,l):Uc(f,l),fromBytes:(f,h=!0)=>{if(a){if(!a.includes(f.length)||f.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);const m=new Uint8Array(l);m.set(f,n?0:m.length-f.length),f=m}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let g=n?to(f):Vs(f);if(i&&(g=ye(g,t)),!h&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:f=>rh(u,f),cmov:(f,h,g)=>g?h:f});return Object.freeze(u)}function sh(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function ih(t){const e=sh(t);return e+Math.ceil(e/2)}function rb(t,e,n=!1){const r=t.length,o=sh(e),s=ih(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const i=n?to(t):Vs(t),a=ye(i,e-ke)+ke;return n?Gf(a,o):Uc(a,o)}const ar=BigInt(0),on=BigInt(1);function hs(t,e){const n=e.negate();return t?n:e}function sn(t,e){const n=rh(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function ah(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ei(t,e){ah(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,s=yo(t),i=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function cd(t,e,n){const{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n;let a=Number(t&o),c=t>>i;a>r&&(a-=s,c+=on);const l=e*r,d=l+Math.abs(a)-1,u=a===0,f=a<0,h=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:f,isNegF:h,offsetF:l}}function ob(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function sb(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const Ai=new WeakMap,ch=new WeakMap;function ki(t){return ch.get(t)||1}function ld(t){if(t!==ar)throw new Error("invalid wNAF")}class lh{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>ar;)n&on&&(r=r.add(o)),o=o.double(),n>>=on;return r}precomputeWindow(e,n){const{windows:r,windowSize:o}=Ei(n,this.bits),s=[];let i=e,a=i;for(let c=0;c<r;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE;const i=Ei(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:f,offsetF:h}=cd(r,a,i);r=c,d?s=s.add(hs(f,n[h])):o=o.add(hs(u,n[l]))}return ld(r),{p:o,f:s}}wNAFUnsafe(e,n,r,o=this.ZERO){const s=Ei(e,this.bits);for(let i=0;i<s.windows&&r!==ar;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=cd(r,i,s);if(r=a,!l){const u=n[c];o=o.add(d?u.negate():u)}}return ld(r),o}getPrecomputes(e,n,r){let o=Ai.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Ai.set(n,o))),o}cached(e,n,r){const o=ki(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){const s=ki(e);return s===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,o)}createCache(e,n){ah(n,this.bits),ch.set(e,n),Ai.delete(e)}hasCache(e){return ki(e)!==1}}function ib(t,e,n,r){let o=e,s=t.ZERO,i=t.ZERO;for(;n>ar||r>ar;)n&on&&(s=s.add(o)),r&on&&(i=i.add(o)),o=o.double(),n>>=on,r>>=on;return{p1:s,p2:i}}function dh(t,e,n,r){ob(n,t),sb(r,e);const o=n.length,s=r.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,a=Xf(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=yo(c),d=new Array(Number(l)+1).fill(i),u=Math.floor((e.BITS-1)/c)*c;let f=i;for(let h=u;h>=0;h-=c){d.fill(i);for(let m=0;m<s;m++){const b=r[m],w=Number(b>>BigInt(h)&l);d[w]=d[w].add(n[m])}let g=i;for(let m=d.length-1,b=i;m>0;m--)b=b.add(d[m]),g=g.add(b);if(f=f.add(g),h!==0)for(let m=0;m<c;m++)f=f.double()}return f}function dd(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return tb(e),e}else return xn(t,{isLE:n})}function uh(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>ar))throw new Error(`CURVE.${c} must be positive bigint`)}const o=dd(e.p,n.Fp,r),s=dd(e.n,n.Fn,r),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}const Ot=BigInt(0),be=BigInt(1),Ci=BigInt(2),ab=BigInt(8);function cb(t,e,n,r){const o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function lb(t,e={}){const n=uh("edwards",t,e,e.FpFnLE),{Fp:r,Fn:o}=n;let s=n.CURVE;const{h:i}=s;bo(e,{},{uvRatio:"function"});const a=Ci<<BigInt(o.BYTES*8)-be,c=b=>r.create(b),l=e.uvRatio||((b,w)=>{try{return{isValid:!0,value:r.sqrt(r.div(b,w))}}catch{return{isValid:!1,value:Ot}}});if(!cb(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(b,w,I=!1){const y=I?be:Ot;return _a("coordinate "+b,w,y,a),w}function u(b){if(!(b instanceof g))throw new Error("ExtendedPoint expected")}const f=fs((b,w)=>{const{X:I,Y:y,Z:v}=b,L=b.is0();w==null&&(w=L?ab:r.inv(v));const C=c(I*w),T=c(y*w),E=r.mul(v,w);if(L)return{x:Ot,y:be};if(E!==be)throw new Error("invZ was invalid");return{x:C,y:T}}),h=fs(b=>{const{a:w,d:I}=s;if(b.is0())throw new Error("bad point: ZERO");const{X:y,Y:v,Z:L,T:C}=b,T=c(y*y),E=c(v*v),S=c(L*L),k=c(S*S),N=c(T*w),D=c(S*c(N+E)),A=c(k+c(I*c(T*E)));if(D!==A)throw new Error("bad point: equation left != right (1)");const x=c(y*v),P=c(L*C);if(x!==P)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(w,I,y,v){this.X=d("x",w),this.Y=d("y",I),this.Z=d("z",y,!0),this.T=d("t",v),Object.freeze(this)}static CURVE(){return s}static fromAffine(w){if(w instanceof g)throw new Error("extended point not allowed");const{x:I,y}=w||{};return d("x",I),d("y",y),new g(I,y,be,c(I*y))}static fromBytes(w,I=!1){const y=r.BYTES,{a:v,d:L}=s;w=sd(rt(w,y,"point")),mn(I,"zip215");const C=sd(w),T=w[y-1];C[y-1]=T&-129;const E=to(C),S=I?a:r.ORDER;_a("point.y",E,Ot,S);const k=c(E*E),N=c(k-be),D=c(L*k-v);let{isValid:A,value:x}=l(N,D);if(!A)throw new Error("bad point: invalid y coordinate");const P=(x&be)===be,R=(T&128)!==0;if(!I&&x===Ot&&R)throw new Error("bad point: x=0 and x_0=1");return R!==P&&(x=c(-x)),g.fromAffine({x,y:E})}static fromHex(w,I=!1){return g.fromBytes(he("point",w),I)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,I=!0){return m.createCache(this,w),I||this.multiply(Ci),this}assertValidity(){h(this)}equals(w){u(w);const{X:I,Y:y,Z:v}=this,{X:L,Y:C,Z:T}=w,E=c(I*T),S=c(L*v),k=c(y*T),N=c(C*v);return E===S&&k===N}is0(){return this.equals(g.ZERO)}negate(){return new g(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:w}=s,{X:I,Y:y,Z:v}=this,L=c(I*I),C=c(y*y),T=c(Ci*c(v*v)),E=c(w*L),S=I+y,k=c(c(S*S)-L-C),N=E+C,D=N-T,A=E-C,x=c(k*D),P=c(N*A),R=c(k*A),O=c(D*N);return new g(x,P,O,R)}add(w){u(w);const{a:I,d:y}=s,{X:v,Y:L,Z:C,T}=this,{X:E,Y:S,Z:k,T:N}=w,D=c(v*E),A=c(L*S),x=c(T*y*N),P=c(C*k),R=c((v+L)*(E+S)-D-A),O=P-x,j=P+x,M=c(A-I*D),B=c(R*O),F=c(j*M),U=c(R*M),H=c(O*j);return new g(B,F,H,U)}subtract(w){return this.add(w.negate())}multiply(w){if(!o.isValidNot0(w))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:I,f:y}=m.cached(this,w,v=>sn(g,v));return sn(g,[I,y])[0]}multiplyUnsafe(w,I=g.ZERO){if(!o.isValid(w))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return w===Ot?g.ZERO:this.is0()||w===be?this:m.unsafe(this,w,y=>sn(g,y),I)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(w){return f(this,w)}clearCofactor(){return i===be?this:this.multiplyUnsafe(i)}toBytes(){const{x:w,y:I}=this.toAffine(),y=r.toBytes(I);return y[y.length-1]|=w&be?128:0,y}toHex(){return dn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(w){return sn(g,w)}static msm(w,I){return dh(g,o,w,I)}_setWindowSize(w){this.precompute(w)}toRawBytes(){return this.toBytes()}}g.BASE=new g(s.Gx,s.Gy,be,c(s.Gx*s.Gy)),g.ZERO=new g(Ot,be,be,Ot),g.Fp=r,g.Fn=o;const m=new lh(g,o.BITS);return g.BASE.precompute(8),g}function db(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is required');bo(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:o,Fp:s,Fn:i}=t,a=n.randomBytes||Mc,c=n.adjustScalarBytes||(S=>S),l=n.domain||((S,k,N)=>{if(mn(N,"phflag"),k.length||N)throw new Error("Contexts/pre-hash are not supported");return S});function d(S){return i.create(to(S))}function u(S){const k=y.secretKey;S=he("private key",S,k);const N=he("hashed private key",e(S),2*k),D=c(N.slice(0,k)),A=N.slice(k,2*k),x=d(D);return{head:D,prefix:A,scalar:x}}function f(S){const{head:k,prefix:N,scalar:D}=u(S),A=o.multiply(D),x=A.toBytes();return{head:k,prefix:N,scalar:D,point:A,pointBytes:x}}function h(S){return f(S).pointBytes}function g(S=Uint8Array.of(),...k){const N=lt(...k);return d(e(l(N,he("context",S),!!r)))}function m(S,k,N={}){S=he("message",S),r&&(S=r(S));const{prefix:D,scalar:A,pointBytes:x}=f(k),P=g(N.context,D,S),R=o.multiply(P).toBytes(),O=g(N.context,R,x,S),j=i.create(P+O*A);if(!i.isValid(j))throw new Error("sign failed: invalid s");const M=lt(R,i.toBytes(j));return rt(M,y.signature,"result")}const b={zip215:!0};function w(S,k,N,D=b){const{context:A,zip215:x}=D,P=y.signature;S=he("signature",S,P),k=he("message",k),N=he("publicKey",N,y.publicKey),x!==void 0&&mn(x,"zip215"),r&&(k=r(k));const R=P/2,O=S.subarray(0,R),j=to(S.subarray(R,P));let M,B,F;try{M=t.fromBytes(N,x),B=t.fromBytes(O,x),F=o.multiplyUnsafe(j)}catch{return!1}if(!x&&M.isSmallOrder())return!1;const U=g(A,B.toBytes(),M.toBytes(),k);return B.add(M.multiplyUnsafe(U)).subtract(F).clearCofactor().is0()}const I=s.BYTES,y={secretKey:I,publicKey:I,signature:2*I,seed:I};function v(S=a(y.seed)){return rt(S,y.seed,"seed")}function L(S){const k=E.randomSecretKey(S);return{secretKey:k,publicKey:h(k)}}function C(S){return wo(S)&&S.length===i.BYTES}function T(S,k){try{return!!t.fromBytes(S,k)}catch{return!1}}const E={getExtendedPublicKey:f,randomSecretKey:v,isValidSecretKey:C,isValidPublicKey:T,toMontgomery(S){const{y:k}=t.fromBytes(S),N=y.publicKey,D=N===32;if(!D&&N!==57)throw new Error("only defined for 25519 and 448");const A=D?s.div(be+k,be-k):s.div(k-be,k+be);return s.toBytes(A)},toMontgomerySecret(S){const k=y.secretKey;rt(S,k);const N=e(S.subarray(0,k));return c(N).subarray(0,k)},randomPrivateKey:v,precompute(S=8,k=t.BASE){return k.precompute(S,!1)}};return Object.freeze({keygen:L,getPublicKey:h,sign:m,verify:w,utils:E,Point:t,lengths:y})}function ub(t){const e={a:t.a,d:t.d,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp,r=xn(e.n,t.nBitLength,!0),o={Fp:n,Fn:r,uvRatio:t.uvRatio},s={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:o,hash:t.hash,eddsaOpts:s}}function fb(t,e){const n=e.Point;return Object.assign({},e,{ExtendedPoint:n,CURVE:t,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function hb(t){const{CURVE:e,curveOpts:n,hash:r,eddsaOpts:o}=ub(t),s=lb(e,n),i=db(s,r,o);return fb(t,i)}const pb=BigInt(1),ud=BigInt(2);BigInt(3);const gb=BigInt(5),mb=BigInt(8),Hc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),fh={p:Hc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:mb,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function wb(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=Hc,a=t*t%s*t%s,c=fe(a,ud,s)*a%s,l=fe(c,pb,s)*t%s,d=fe(l,gb,s)*l%s,u=fe(d,e,s)*d%s,f=fe(u,n,s)*u%s,h=fe(f,r,s)*f%s,g=fe(h,o,s)*h%s,m=fe(g,o,s)*h%s,b=fe(m,e,s)*d%s;return{pow_p_5_8:fe(b,ud,s)*t%s,b2:a}}function yb(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const fd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function bb(t,e){const n=Hc,r=ye(e*e*e,n),o=ye(r*r*e,n),s=wb(t*o).pow_p_5_8;let i=ye(t*r*s,n);const a=ye(e*i*i,n),c=i,l=ye(i*fd,n),d=a===t,u=a===ye(-t,n),f=a===ye(-t*fd,n);return d&&(i=c),(u||f)&&(i=l),Qy(i,n)&&(i=ye(-i,n)),{isValid:d||u,value:i}}const vb=xn(fh.p,{isLE:!0}),Sb={...fh,Fp:vb,hash:zy,adjustScalarBytes:yb,uvRatio:bb},ps=hb(Sb);class hd extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}}class pd extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class xb extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}const Rt={get(t=globalThis){const e=t.crypto;if(e?.subtle==null)throw new xb("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}},gs=32,yt=64,Oa=32;let Gn;const hh=(async()=>{try{return await Rt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Eb(){const t=ps.utils.randomPrivateKey(),e=ps.getPublicKey(t);return{privateKey:Pb(t,e),publicKey:e}}async function Ab(t,e){let n;t.length===yt?n=t.subarray(0,32):n=t;const r={crv:"Ed25519",kty:"OKP",x:ee(t.subarray(32),"base64url"),d:ee(n,"base64url"),ext:!0,key_ops:["sign"]},o=await Rt.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),s=await Rt.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function kb(t,e){const n=t.subarray(0,Oa);return ps.sign(e instanceof Uint8Array?e:e.subarray(),n)}async function Cb(t,e){return Gn==null&&(Gn=await hh),Gn?Ab(t,e):kb(t,e)}async function Ib(t,e,n){if(t.buffer instanceof ArrayBuffer){const r=await Rt.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await Rt.get().subtle.verify({name:"Ed25519"},r,e,n instanceof Uint8Array?n:n.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Rb(t,e,n){return ps.verify(e,n instanceof Uint8Array?n:n.subarray(),t)}async function Tb(t,e,n){return Gn==null&&(Gn=await hh),Gn?Ib(t,e,n):Rb(t,e,n)}function Pb(t,e){const n=new Uint8Array(yt);for(let r=0;r<Oa;r++)n[r]=t[r],n[Oa+r]=e[r];return n}function Gs(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}class ph{type="Ed25519";raw;constructor(e){this.raw=no(e,gs)}toMultihash(){return go.digest(Js(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return Be.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:st(this.raw,e.raw)}verify(e,n,r){r?.signal?.throwIfAborted();const o=Tb(this.raw,n,e);return Gs(o)?o.then(s=>(r?.signal?.throwIfAborted(),s)):o}}class Da{type="Ed25519";raw;publicKey;constructor(e,n){this.raw=no(e,yt),this.publicKey=new ph(n)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:st(this.raw,e.raw)}sign(e,n){n?.signal?.throwIfAborted();const r=Cb(this.raw,e);return Gs(r)?r.then(o=>(n?.signal?.throwIfAborted(),o)):(n?.signal?.throwIfAborted(),r)}}function Nb(t){if(t.length>yt){t=no(t,yt+gs);const r=t.subarray(0,yt),o=t.subarray(yt,t.length);return new Da(r,o)}t=no(t,yt);const e=t.subarray(0,yt),n=t.subarray(gs);return new Da(e,n)}function gh(t){return t=no(t,gs),new ph(t)}async function Lb(){const{privateKey:t,publicKey:e}=Eb();return new Da(t,e)}function no(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new ot(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}const Bb=Math.pow(2,7),_b=Math.pow(2,14),Ob=Math.pow(2,21),qc=Math.pow(2,28),Kc=Math.pow(2,35),zc=Math.pow(2,42),Wc=Math.pow(2,49),oe=128,Te=127;function En(t){if(t<Bb)return 1;if(t<_b)return 2;if(t<Ob)return 3;if(t<qc)return 4;if(t<Kc)return 5;if(t<zc)return 6;if(t<Wc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function mh(t,e,n=0){switch(En(t)){case 8:e[n++]=t&255|oe,t/=128;case 7:e[n++]=t&255|oe,t/=128;case 6:e[n++]=t&255|oe,t/=128;case 5:e[n++]=t&255|oe,t/=128;case 4:e[n++]=t&255|oe,t>>>=7;case 3:e[n++]=t&255|oe,t>>>=7;case 2:e[n++]=t&255|oe,t>>>=7;case 1:{e[n++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Db(t,e,n=0){switch(En(t)){case 8:e.set(n++,t&255|oe),t/=128;case 7:e.set(n++,t&255|oe),t/=128;case 6:e.set(n++,t&255|oe),t/=128;case 5:e.set(n++,t&255|oe),t/=128;case 4:e.set(n++,t&255|oe),t>>>=7;case 3:e.set(n++,t&255|oe),t>>>=7;case 2:e.set(n++,t&255|oe),t>>>=7;case 1:{e.set(n++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function wh(t,e){let n=t[e],r=0;if(r+=n&Te,n<oe||(n=t[e+1],r+=(n&Te)<<7,n<oe)||(n=t[e+2],r+=(n&Te)<<14,n<oe)||(n=t[e+3],r+=(n&Te)<<21,n<oe)||(n=t[e+4],r+=(n&Te)*qc,n<oe)||(n=t[e+5],r+=(n&Te)*Kc,n<oe)||(n=t[e+6],r+=(n&Te)*zc,n<oe)||(n=t[e+7],r+=(n&Te)*Wc,n<oe))return r;throw new RangeError("Could not decode varint")}function Fb(t,e){let n=t.get(e),r=0;if(r+=n&Te,n<oe||(n=t.get(e+1),r+=(n&Te)<<7,n<oe)||(n=t.get(e+2),r+=(n&Te)<<14,n<oe)||(n=t.get(e+3),r+=(n&Te)<<21,n<oe)||(n=t.get(e+4),r+=(n&Te)*qc,n<oe)||(n=t.get(e+5),r+=(n&Te)*Kc,n<oe)||(n=t.get(e+6),r+=(n&Te)*zc,n<oe)||(n=t.get(e+7),r+=(n&Te)*Wc,n<oe))return r;throw new RangeError("Could not decode varint")}function Mb(t,e,n=0){return e==null&&(e=It(En(t))),e instanceof Uint8Array?mh(t,e,n):Db(t,e,n)}function yh(t,e=0){return t instanceof Uint8Array?wh(t,e):Fb(t,e)}const Vc=new Float32Array([-0]),Kt=new Uint8Array(Vc.buffer);function jb(t,e,n){Vc[0]=t,e[n]=Kt[0],e[n+1]=Kt[1],e[n+2]=Kt[2],e[n+3]=Kt[3]}function Ub(t,e){return Kt[0]=t[e],Kt[1]=t[e+1],Kt[2]=t[e+2],Kt[3]=t[e+3],Vc[0]}const Gc=new Float64Array([-0]),Pe=new Uint8Array(Gc.buffer);function $b(t,e,n){Gc[0]=t,e[n]=Pe[0],e[n+1]=Pe[1],e[n+2]=Pe[2],e[n+3]=Pe[3],e[n+4]=Pe[4],e[n+5]=Pe[5],e[n+6]=Pe[6],e[n+7]=Pe[7]}function Hb(t,e){return Pe[0]=t[e],Pe[1]=t[e+1],Pe[2]=t[e+2],Pe[3]=t[e+3],Pe[4]=t[e+4],Pe[5]=t[e+5],Pe[6]=t[e+6],Pe[7]=t[e+7],Gc[0]}const qb=BigInt(Number.MAX_SAFE_INTEGER),Kb=BigInt(Number.MIN_SAFE_INTEGER);class Ne{lo;hi;constructor(e,n){this.lo=e|0,this.hi=n|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){const n=~this.lo+1>>>0;let r=~this.hi>>>0;return n===0&&(r=r+1>>>0),-(n+r*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){const n=~this.lo+1>>>0;let r=~this.hi>>>0;return n===0&&(r=r+1>>>0),-(BigInt(n)+(BigInt(r)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,n=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?n===0?e<16384?e<128?1:2:e<2097152?3:4:n<16384?n<128?5:6:n<2097152?7:8:r<128?9:10}static fromBigInt(e){if(e===0n)return un;if(e<qb&&e>Kb)return this.fromNumber(Number(e));const n=e<0n;n&&(e=-e);let r=e>>32n,o=e-(r<<32n);return n&&(r=~r|0n,o=~o|0n,++o>gd&&(o=0n,++r>gd&&(r=0n))),new Ne(Number(o),Number(r))}static fromNumber(e){if(e===0)return un;const n=e<0;n&&(e=-e);let r=e>>>0,o=(e-r)/4294967296>>>0;return n&&(o=~o>>>0,r=~r>>>0,++r>4294967295&&(r=0,++o>4294967295&&(o=0))),new Ne(r,o)}static from(e){return typeof e=="number"?Ne.fromNumber(e):typeof e=="bigint"?Ne.fromBigInt(e):typeof e=="string"?Ne.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new Ne(e.low>>>0,e.high>>>0):un}}const un=new Ne(0,0);un.toBigInt=function(){return 0n};un.zzEncode=un.zzDecode=function(){return this};un.length=function(){return 1};const gd=4294967296n;function zb(t){let e=0,n=0;for(let r=0;r<t.length;++r)n=t.charCodeAt(r),n<128?e+=1:n<2048?e+=2:(n&64512)===55296&&(t.charCodeAt(r+1)&64512)===56320?(++r,e+=4):e+=3;return e}function Wb(t,e,n){if(n-e<1)return"";let o;const s=[];let i=0,a;for(;e<n;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function bh(t,e,n){const r=n;let o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[n++]=o:o<2048?(e[n++]=o>>6|192,e[n++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[n++]=o>>18|240,e[n++]=o>>12&63|128,e[n++]=o>>6&63|128,e[n++]=o&63|128):(e[n++]=o>>12|224,e[n++]=o>>6&63|128,e[n++]=o&63|128);return n-r}function tt(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function Ro(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}class Vb{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,tt(this,10);return e}int32(){return this.uint32()|0}sint32(){const e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw tt(this,4);return Ro(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw tt(this,4);return Ro(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw tt(this,4);const e=Ub(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw tt(this,4);const e=Hb(this.buf,this.pos);return this.pos+=8,e}bytes(){const e=this.uint32(),n=this.pos,r=this.pos+e;if(r>this.len)throw tt(this,e);return this.pos+=e,n===r?new Uint8Array(0):this.buf.subarray(n,r)}string(){const e=this.bytes();return Wb(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw tt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw tt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new Ne(0,0);let n=0;if(this.len-this.pos>4){for(;n<4;++n)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<n*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;n=0}else{for(;n<3;++n){if(this.pos>=this.len)throw tt(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<n*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<n*7)>>>0,e}if(this.len-this.pos>4){for(;n<5;++n)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<n*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;n<5;++n){if(this.pos>=this.len)throw tt(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<n*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw tt(this,8);const e=Ro(this.buf,this.pos+=4),n=Ro(this.buf,this.pos+=4);return new Ne(e,n)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=wh(this.buf,this.pos);return this.pos+=En(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function Gb(t){return new Vb(t instanceof Uint8Array?t:t.subarray())}function Xs(t,e,n){const r=Gb(t);return e.decode(r,void 0,n)}function Xb(t){let r,o=8192;return function(i){if(i<1||i>4096)return It(i);o+i>8192&&(r=It(8192),o=0);const a=r.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}class Ur{fn;len;next;val;constructor(e,n,r){this.fn=e,this.len=n,this.next=void 0,this.val=r}}function Ii(){}class Yb{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const Zb=Xb();function Jb(t){return globalThis.Buffer!=null?It(t):Zb(t)}class Fa{len;head;tail;states;constructor(){this.len=0,this.head=new Ur(Ii,0,0),this.tail=this.head,this.states=null}_push(e,n,r){return this.tail=this.tail.next=new Ur(e,n,r),this.len+=n,this}uint32(e){return this.len+=(this.tail=this.tail.next=new e0((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(To,10,Ne.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const n=Ne.fromBigInt(e);return this._push(To,n.length(),n)}uint64Number(e){return this._push(mh,En(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const n=Ne.fromBigInt(e).zzEncode();return this._push(To,n.length(),n)}sint64Number(e){const n=Ne.fromNumber(e).zzEncode();return this._push(To,n.length(),n)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ri,1,e?1:0)}fixed32(e){return this._push(Cr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const n=Ne.fromBigInt(e);return this._push(Cr,4,n.lo)._push(Cr,4,n.hi)}fixed64Number(e){const n=Ne.fromNumber(e);return this._push(Cr,4,n.lo)._push(Cr,4,n.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(jb,4,e)}double(e){return this._push($b,8,e)}bytes(e){const n=e.length>>>0;return n===0?this._push(Ri,1,0):this.uint32(n)._push(t0,n,e)}string(e){const n=zb(e);return n!==0?this.uint32(n)._push(bh,n,e):this._push(Ri,1,0)}fork(){return this.states=new Yb(this),this.head=this.tail=new Ur(Ii,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Ur(Ii,0,0),this.len=0),this}ldelim(){const e=this.head,n=this.tail,r=this.len;return this.reset().uint32(r),r!==0&&(this.tail.next=e.next,this.tail=n,this.len+=r),this}finish(){let e=this.head.next;const n=Jb(this.len);let r=0;for(;e!=null;)e.fn(e.val,n,r),r+=e.len,e=e.next;return n}}function Ri(t,e,n){e[n]=t&255}function Qb(t,e,n){for(;t>127;)e[n++]=t&127|128,t>>>=7;e[n]=t}class e0 extends Ur{next;constructor(e,n){super(Qb,e,n),this.next=void 0}}function To(t,e,n){for(;t.hi!==0;)e[n++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[n++]=t.lo&127|128,t.lo=t.lo>>>7;e[n++]=t.lo}function Cr(t,e,n){e[n]=t&255,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}function t0(t,e,n){e.set(t,n)}globalThis.Buffer!=null&&(Fa.prototype.bytes=function(t){const e=t.length>>>0;return this.uint32(e),e>0&&this._push(n0,e,t),this},Fa.prototype.string=function(t){const e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(r0,e,t),this});function n0(t,e,n){e.set(t,n)}function r0(t,e,n){t.length<40?bh(t,e,n):e.utf8Write!=null?e.utf8Write(t,n):e.set(we(t),n)}function o0(){return new Fa}function Ys(t,e){const n=o0();return e.encode(t,n,{lengthDelimited:!1}),n.finish()}var ms;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(ms||(ms={}));function vh(t,e,n,r){return{name:t,type:e,encode:n,decode:r}}function s0(t){function e(o){if(t[o.toString()]==null)throw new Error("Invalid enum value");return t[o]}const n=function(s,i){const a=e(s);i.int32(a)},r=function(s){const i=s.int32();return e(i)};return vh("enum",ms.VARINT,n,r)}function Zs(t,e){return vh("message",ms.LENGTH_DELIMITED,t,e)}class md extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var de;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(de||(de={}));var Ma;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(Ma||(Ma={}));(function(t){t.codec=()=>s0(Ma)})(de||(de={}));var wn;(function(t){let e;t.codec=()=>(e==null&&(e=Zs((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),de.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{s.Type=de.codec().decode(n);break}case 2:{s.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>Ys(n,t.codec()),t.decode=(n,r)=>Xs(n,t.codec(),r)})(wn||(wn={}));var ws;(function(t){let e;t.codec=()=>(e==null&&(e=Zs((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),de.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{s.Type=de.codec().decode(n);break}case 2:{s.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>Ys(n,t.codec()),t.decode=(n,r)=>Xs(n,t.codec(),r)})(ws||(ws={}));const Sh=Wf;class xh{type="RSA";jwk;_raw;_multihash;constructor(e,n){this.jwk=e,this._multihash=n}get raw(){return this._raw==null&&(this._raw=Ah(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return le.createV1(114,this._multihash)}toString(){return Be.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:st(this.raw,e.raw)}verify(e,n,r){return v0(this.jwk,n,e,r)}}class i0{type="RSA";jwk;_raw;publicKey;constructor(e,n){this.jwk=e,this.publicKey=n}get raw(){return this._raw==null&&(this._raw=u0(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:st(this.raw,e.raw)}sign(e,n){return b0(this.jwk,e,n)}}const a0=8192,Eh=18,c0=1062,l0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function d0(t){return{n:ee(t[1],"base64url"),e:ee(t[2],"base64url"),d:ee(t[3],"base64url"),p:ee(t[4],"base64url"),q:ee(t[5],"base64url"),dp:ee(t[6],"base64url"),dq:ee(t[7],"base64url"),qi:ee(t[8],"base64url"),kty:"RSA"}}function u0(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new ot("JWK was missing components");return kt([Ke(Uint8Array.from([0])),Ke(we(t.n,"base64url")),Ke(we(t.e,"base64url")),Ke(we(t.d,"base64url")),Ke(we(t.p,"base64url")),Ke(we(t.q,"base64url")),Ke(we(t.dp,"base64url")),Ke(we(t.dq,"base64url")),Ke(we(t.qi,"base64url"))]).subarray()}function f0(t){const e=gr(t[1],{offset:0});return{kty:"RSA",n:ee(e[0],"base64url"),e:ee(e[1],"base64url")}}function Ah(t){if(t.n==null||t.e==null)throw new ot("JWK was missing components");return kt([l0,Dc(kt([Ke(we(t.n,"base64url")),Ke(we(t.e,"base64url"))]))]).subarray()}function h0(t){const e=gr(t);return p0(e)}function p0(t){const e=d0(t);return w0(e)}function g0(t,e){if(t.byteLength>=c0)throw new Ef("Key size is too large");const n=gr(t,{offset:0});return m0(n,t,e)}function m0(t,e,n){const r=f0(t);if(n==null){const o=Sh(wn.encode({Type:de.RSA,Data:e}));n=po(Eh,o)}return new xh(r,n)}function w0(t){if(S0(t)>a0)throw new ot("Key size is too large");const e=y0(t),n=Sh(wn.encode({Type:de.RSA,Data:Ah(e.publicKey)})),r=po(Eh,n);return new i0(e.privateKey,new xh(e.publicKey,r))}function y0(t){if(t==null)throw new ot("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function b0(t,e,n){const r=await Rt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);n?.signal?.throwIfAborted();const o=await Rt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function v0(t,e,n,r){const o=await Rt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const s=await Rt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,n instanceof Uint8Array?n:n.subarray());return r?.signal?.throwIfAborted(),s}function S0(t){if(t.kty!=="RSA")throw new ot("invalid key type");if(t.n==null)throw new ot("invalid key modulus");return we(t.n,"base64url").length*8}class kh extends Hf{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,Uf(e);const r=Fc(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const o=this.blockLen,s=new Uint8Array(o);s.set(r.length>o?e.create().update(r).digest():r);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),ir(s)}update(e){return ds(this),this.iHash.update(e),this}digestInto(e){ds(this),Sn(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ch=(t,e,n)=>new kh(t,e).update(n).digest();Ch.create=(t,e)=>new kh(t,e);const wd=(t,e)=>(t+(t>=0?e:-e)/Ih)/e;function x0(t,e,n){const[[r,o],[s,i]]=e,a=wd(i*t,n),c=wd(-o*t,n);let l=t-a*r-c*s,d=-a*o-c*i;const u=l<xt,f=d<xt;u&&(l=-l),f&&(d=-d);const h=yo(Math.ceil(Xf(n)/2))+Xn;if(l<xt||l>=h||d<xt||d>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:f,k2:d}}function ja(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Ti(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return mn(n.lowS,"lowS"),mn(n.prehash,"prehash"),n.format!==void 0&&ja(n.format),n}class E0 extends Error{constructor(e=""){super(e)}}const bt={Err:E0,_tlv:{encode:(t,e)=>{const{Err:n}=bt;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,o=Io(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Io(o.length/2|128):"";return Io(t)+s+o+e},decode(t,e){const{Err:n}=bt;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const o=e[r++],s=!!(o&128);let i=0;if(!s)i=o;else{const c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(r+=c,i<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+i);if(a.length!==i)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+i)}}},_int:{encode(t){const{Err:e}=bt;if(t<xt)throw new e("integer: negative integers are not allowed");let n=Io(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=bt;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Vs(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=bt,o=he("signature",t),{v:s,l:i}=r.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:l,l:d}=r.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){const{_tlv:e,_int:n}=bt,r=e.encode(2,n.encode(t.r)),o=e.encode(2,n.encode(t.s)),s=r+o;return e.encode(48,s)}},xt=BigInt(0),Xn=BigInt(1),Ih=BigInt(2),Po=BigInt(3),A0=BigInt(4);function $n(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let o=he("private key",e);try{r=t.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function k0(t,e={}){const n=uh("weierstrass",t,e),{Fp:r,Fn:o}=n;let s=n.CURVE;const{h:i,n:a}=s;bo(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Th(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(D,A,x){const{x:P,y:R}=A.toAffine(),O=r.toBytes(P);if(mn(x,"isCompressed"),x){d();const j=!r.isOdd(R);return lt(Rh(j),O)}else return lt(Uint8Array.of(4),O,r.toBytes(R))}function f(D){rt(D,void 0,"Point");const{publicKey:A,publicKeyUncompressed:x}=l,P=D.length,R=D[0],O=D.subarray(1);if(P===A&&(R===2||R===3)){const j=r.fromBytes(O);if(!r.isValid(j))throw new Error("bad point: is not on curve, wrong x");const M=m(j);let B;try{B=r.sqrt(M)}catch(H){const q=H instanceof Error?": "+H.message:"";throw new Error("bad point: is not on curve, sqrt error"+q)}d();const F=r.isOdd(B);return(R&1)===1!==F&&(B=r.neg(B)),{x:j,y:B}}else if(P===x&&R===4){const j=r.BYTES,M=r.fromBytes(O.subarray(0,j)),B=r.fromBytes(O.subarray(j,j*2));if(!b(M,B))throw new Error("bad point: is not on curve");return{x:M,y:B}}else throw new Error(`bad point: got length ${P}, expected compressed=${A} or uncompressed=${x}`)}const h=e.toBytes||u,g=e.fromBytes||f;function m(D){const A=r.sqr(D),x=r.mul(A,D);return r.add(r.add(x,r.mul(D,s.a)),s.b)}function b(D,A){const x=r.sqr(A),P=m(D);return r.eql(x,P)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const w=r.mul(r.pow(s.a,Po),A0),I=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(w,I)))throw new Error("bad curve params: a or b");function y(D,A,x=!1){if(!r.isValid(A)||x&&r.is0(A))throw new Error(`bad point coordinate ${D}`);return A}function v(D){if(!(D instanceof S))throw new Error("ProjectivePoint expected")}function L(D){if(!c||!c.basises)throw new Error("no endo");return x0(D,c.basises,o.ORDER)}const C=fs((D,A)=>{const{X:x,Y:P,Z:R}=D;if(r.eql(R,r.ONE))return{x,y:P};const O=D.is0();A==null&&(A=O?r.ONE:r.inv(R));const j=r.mul(x,A),M=r.mul(P,A),B=r.mul(R,A);if(O)return{x:r.ZERO,y:r.ZERO};if(!r.eql(B,r.ONE))throw new Error("invZ was invalid");return{x:j,y:M}}),T=fs(D=>{if(D.is0()){if(e.allowInfinityPoint&&!r.is0(D.Y))return;throw new Error("bad point: ZERO")}const{x:A,y:x}=D.toAffine();if(!r.isValid(A)||!r.isValid(x))throw new Error("bad point: x or y not field elements");if(!b(A,x))throw new Error("bad point: equation left != right");if(!D.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function E(D,A,x,P,R){return x=new S(r.mul(x.X,D),x.Y,x.Z),A=hs(P,A),x=hs(R,x),A.add(x)}class S{constructor(A,x,P){this.X=y("x",A),this.Y=y("y",x,!0),this.Z=y("z",P),Object.freeze(this)}static CURVE(){return s}static fromAffine(A){const{x,y:P}=A||{};if(!A||!r.isValid(x)||!r.isValid(P))throw new Error("invalid affine point");if(A instanceof S)throw new Error("projective point not allowed");return r.is0(x)&&r.is0(P)?S.ZERO:new S(x,P,r.ONE)}static fromBytes(A){const x=S.fromAffine(g(rt(A,void 0,"point")));return x.assertValidity(),x}static fromHex(A){return S.fromBytes(he("pointHex",A))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(A=8,x=!0){return N.createCache(this,A),x||this.multiply(Po),this}assertValidity(){T(this)}hasEvenY(){const{y:A}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(A)}equals(A){v(A);const{X:x,Y:P,Z:R}=this,{X:O,Y:j,Z:M}=A,B=r.eql(r.mul(x,M),r.mul(O,R)),F=r.eql(r.mul(P,M),r.mul(j,R));return B&&F}negate(){return new S(this.X,r.neg(this.Y),this.Z)}double(){const{a:A,b:x}=s,P=r.mul(x,Po),{X:R,Y:O,Z:j}=this;let M=r.ZERO,B=r.ZERO,F=r.ZERO,U=r.mul(R,R),H=r.mul(O,O),q=r.mul(j,j),K=r.mul(R,O);return K=r.add(K,K),F=r.mul(R,j),F=r.add(F,F),M=r.mul(A,F),B=r.mul(P,q),B=r.add(M,B),M=r.sub(H,B),B=r.add(H,B),B=r.mul(M,B),M=r.mul(K,M),F=r.mul(P,F),q=r.mul(A,q),K=r.sub(U,q),K=r.mul(A,K),K=r.add(K,F),F=r.add(U,U),U=r.add(F,U),U=r.add(U,q),U=r.mul(U,K),B=r.add(B,U),q=r.mul(O,j),q=r.add(q,q),U=r.mul(q,K),M=r.sub(M,U),F=r.mul(q,H),F=r.add(F,F),F=r.add(F,F),new S(M,B,F)}add(A){v(A);const{X:x,Y:P,Z:R}=this,{X:O,Y:j,Z:M}=A;let B=r.ZERO,F=r.ZERO,U=r.ZERO;const H=s.a,q=r.mul(s.b,Po);let K=r.mul(x,O),W=r.mul(P,j),V=r.mul(R,M),G=r.add(x,P),X=r.add(O,j);G=r.mul(G,X),X=r.add(K,W),G=r.sub(G,X),X=r.add(x,R);let Z=r.add(O,M);return X=r.mul(X,Z),Z=r.add(K,V),X=r.sub(X,Z),Z=r.add(P,R),B=r.add(j,M),Z=r.mul(Z,B),B=r.add(W,V),Z=r.sub(Z,B),U=r.mul(H,X),B=r.mul(q,V),U=r.add(B,U),B=r.sub(W,U),U=r.add(W,U),F=r.mul(B,U),W=r.add(K,K),W=r.add(W,K),V=r.mul(H,V),X=r.mul(q,X),W=r.add(W,V),V=r.sub(K,V),V=r.mul(H,V),X=r.add(X,V),K=r.mul(W,X),F=r.add(F,K),K=r.mul(Z,X),B=r.mul(G,B),B=r.sub(B,K),K=r.mul(G,W),U=r.mul(Z,U),U=r.add(U,K),new S(B,F,U)}subtract(A){return this.add(A.negate())}is0(){return this.equals(S.ZERO)}multiply(A){const{endo:x}=e;if(!o.isValidNot0(A))throw new Error("invalid scalar: out of range");let P,R;const O=j=>N.cached(this,j,M=>sn(S,M));if(x){const{k1neg:j,k1:M,k2neg:B,k2:F}=L(A),{p:U,f:H}=O(M),{p:q,f:K}=O(F);R=H.add(K),P=E(x.beta,U,q,j,B)}else{const{p:j,f:M}=O(A);P=j,R=M}return sn(S,[P,R])[0]}multiplyUnsafe(A){const{endo:x}=e,P=this;if(!o.isValid(A))throw new Error("invalid scalar: out of range");if(A===xt||P.is0())return S.ZERO;if(A===Xn)return P;if(N.hasCache(this))return this.multiply(A);if(x){const{k1neg:R,k1:O,k2neg:j,k2:M}=L(A),{p1:B,p2:F}=ib(S,P,O,M);return E(x.beta,B,F,R,j)}else return N.unsafe(P,A)}multiplyAndAddUnsafe(A,x,P){const R=this.multiplyUnsafe(x).add(A.multiplyUnsafe(P));return R.is0()?void 0:R}toAffine(A){return C(this,A)}isTorsionFree(){const{isTorsionFree:A}=e;return i===Xn?!0:A?A(S,this):N.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:A}=e;return i===Xn?this:A?A(S,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(A=!0){return mn(A,"isCompressed"),this.assertValidity(),h(S,this,A)}toHex(A=!0){return dn(this.toBytes(A))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(A=!0){return this.toBytes(A)}_setWindowSize(A){this.precompute(A)}static normalizeZ(A){return sn(S,A)}static msm(A,x){return dh(S,o,A,x)}static fromPrivateKey(A){return S.BASE.multiply($n(o,A))}}S.BASE=new S(s.Gx,s.Gy,r.ONE),S.ZERO=new S(r.ZERO,r.ONE,r.ZERO),S.Fp=r,S.Fn=o;const k=o.BITS,N=new lh(S,e.endo?Math.ceil(k/2):k);return S.BASE.precompute(8),S}function Rh(t){return Uint8Array.of(t?2:3)}function Th(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function C0(t,e={}){const{Fn:n}=t,r=e.randomBytes||Mc,o=Object.assign(Th(t.Fp,n),{seed:ih(n.ORDER)});function s(h){try{return!!$n(n,h)}catch{return!1}}function i(h,g){const{publicKey:m,publicKeyUncompressed:b}=o;try{const w=h.length;return g===!0&&w!==m||g===!1&&w!==b?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=r(o.seed)){return rb(rt(h,o.seed,"seed"),n.ORDER)}function c(h,g=!0){return t.BASE.multiply($n(n,h)).toBytes(g)}function l(h){const g=a(h);return{secretKey:g,publicKey:c(g)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:g,publicKey:m,publicKeyUncompressed:b}=o;if(n.allowedLengths||g===m)return;const w=he("key",h).length;return w===m||w===b}function u(h,g,m=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(g)===!1)throw new Error("second arg must be public key");const b=$n(n,h);return t.fromHex(g).multiply(b).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>$n(n,h),precompute(h=8,g=t.BASE){return g.precompute(h,!1)}},lengths:o})}function I0(t,e,n={}){Uf(e),bo(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Mc,o=n.hmac||((x,...P)=>Ch(e,x,lt(...P))),{Fp:s,Fn:i}=t,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h}=C0(t,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function b(x){const P=a>>Xn;return x>P}function w(x,P){if(!i.isValidNot0(P))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return P}function I(x,P){ja(P);const R=h.signature,O=P==="compact"?R:P==="recovered"?R+1:void 0;return rt(x,O,`${P} signature`)}class y{constructor(P,R,O){this.r=w("r",P),this.s=w("s",R),O!=null&&(this.recovery=O),Object.freeze(this)}static fromBytes(P,R=m){I(P,R);let O;if(R==="der"){const{r:F,s:U}=bt.toSig(rt(P));return new y(F,U)}R==="recovered"&&(O=P[0],R="compact",P=P.subarray(1));const j=i.BYTES,M=P.subarray(0,j),B=P.subarray(j,j*2);return new y(i.fromBytes(M),i.fromBytes(B),O)}static fromHex(P,R){return this.fromBytes(us(P),R)}addRecoveryBit(P){return new y(this.r,this.s,P)}recoverPublicKey(P){const R=s.ORDER,{r:O,s:j,recovery:M}=this;if(M==null||![0,1,2,3].includes(M))throw new Error("recovery id invalid");if(a*Ih<R&&M>1)throw new Error("recovery id is ambiguous for h>1 curve");const F=M===2||M===3?O+a:O;if(!s.isValid(F))throw new Error("recovery id 2 or 3 invalid");const U=s.toBytes(F),H=t.fromBytes(lt(Rh((M&1)===0),U)),q=i.inv(F),K=L(he("msgHash",P)),W=i.create(-K*q),V=i.create(j*q),G=t.BASE.multiplyUnsafe(W).add(H.multiplyUnsafe(V));if(G.is0())throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return b(this.s)}toBytes(P=m){if(ja(P),P==="der")return us(bt.hexFromSig(this));const R=i.toBytes(this.r),O=i.toBytes(this.s);if(P==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return lt(Uint8Array.of(this.recovery),R,O)}return lt(R,O)}toHex(P){return dn(this.toBytes(P))}assertValidity(){}static fromCompact(P){return y.fromBytes(he("sig",P),"compact")}static fromDER(P){return y.fromBytes(he("sig",P),"der")}normalizeS(){return this.hasHighS()?new y(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return dn(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return dn(this.toBytes("compact"))}}const v=n.bits2int||function(P){if(P.length>8192)throw new Error("input is too large");const R=Vs(P),O=P.length*8-c;return O>0?R>>BigInt(O):R},L=n.bits2int_modN||function(P){return i.create(v(P))},C=yo(c);function T(x){return _a("num < 2^"+c,x,xt,C),i.toBytes(x)}function E(x,P){return rt(x,void 0,"message"),P?rt(e(x),void 0,"prehashed message"):x}function S(x,P,R){if(["recovered","canonical"].some(W=>W in R))throw new Error("sign() legacy options not supported");const{lowS:O,prehash:j,extraEntropy:M}=Ti(R,g);x=E(x,j);const B=L(x),F=$n(i,P),U=[T(F),T(B)];if(M!=null&&M!==!1){const W=M===!0?r(h.secretKey):M;U.push(he("extraEntropy",W))}const H=lt(...U),q=B;function K(W){const V=v(W);if(!i.isValidNot0(V))return;const G=i.inv(V),X=t.BASE.multiply(V).toAffine(),Z=i.create(X.x);if(Z===xt)return;const ce=i.create(G*i.create(q+Z*F));if(ce===xt)return;let Ie=(X.x===Z?0:2)|Number(X.y&Xn),Me=ce;return O&&b(ce)&&(Me=i.neg(ce),Ie^=1),new y(Z,Me,Ie)}return{seed:H,k2sig:K}}function k(x,P,R={}){x=he("message",x);const{seed:O,k2sig:j}=S(x,P,R);return Vy(e.outputLen,i.BYTES,o)(O,j)}function N(x){let P;const R=typeof x=="string"||wo(x),O=!R&&x!==null&&typeof x=="object"&&typeof x.r=="bigint"&&typeof x.s=="bigint";if(!R&&!O)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(O)P=new y(x.r,x.s);else if(R){try{P=y.fromBytes(he("sig",x),"der")}catch(j){if(!(j instanceof bt.Err))throw j}if(!P)try{P=y.fromBytes(he("sig",x),"compact")}catch{return!1}}return P||!1}function D(x,P,R,O={}){const{lowS:j,prehash:M,format:B}=Ti(O,g);if(R=he("publicKey",R),P=E(he("message",P),M),"strict"in O)throw new Error("options.strict was renamed to lowS");const F=B===void 0?N(x):y.fromBytes(he("sig",x),B);if(F===!1)return!1;try{const U=t.fromBytes(R);if(j&&F.hasHighS())return!1;const{r:H,s:q}=F,K=L(P),W=i.inv(q),V=i.create(K*W),G=i.create(H*W),X=t.BASE.multiplyUnsafe(V).add(U.multiplyUnsafe(G));return X.is0()?!1:i.create(X.x)===H}catch{return!1}}function A(x,P,R={}){const{prehash:O}=Ti(R,g);return P=E(P,O),y.fromBytes(x,"recovered").recoverPublicKey(P).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h,Point:t,sign:k,verify:D,recoverPublicKey:A,Signature:y,hash:e})}function R0(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp;let r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0;const o=xn(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),s={Fp:n,Fn:o,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function T0(t){const{CURVE:e,curveOpts:n}=R0(t),r={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,hash:t.hash,ecdsaOpts:r}}function P0(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,oh(n.Fn.ORDER,n.Fn.BITS))})}function N0(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:o}=T0(t),s=k0(e,n),i=I0(s,r,o);return P0(t,i)}function L0(t,e){const n=r=>N0({...t,hash:r});return{...n(e),create:n}}const Xc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},B0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},yd=BigInt(2);function _0(t){const e=Xc.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,u=fe(d,n,e)*d%e,f=fe(u,n,e)*d%e,h=fe(f,yd,e)*l%e,g=fe(h,o,e)*h%e,m=fe(g,s,e)*g%e,b=fe(m,a,e)*m%e,w=fe(b,c,e)*b%e,I=fe(w,a,e)*m%e,y=fe(I,n,e)*d%e,v=fe(y,i,e)*g%e,L=fe(v,r,e)*l%e,C=fe(L,yd,e);if(!Ua.eql(Ua.sqr(C),t))throw new Error("Cannot find square root");return C}const Ua=xn(Xc.p,{sqrt:_0}),Wt=L0({...Xc,Fp:Ua,lowS:!0,endo:B0},Wf);function O0(t,e,n){const r=Oc.digest(e instanceof Uint8Array?e:e.subarray());if(Gs(r))return r.then(({digest:o})=>(n?.signal?.throwIfAborted(),Wt.sign(o,t).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new hd(String(o))});try{return Wt.sign(r.digest,t).toDERRawBytes()}catch(o){throw new hd(String(o))}}function D0(t,e,n,r){const o=Oc.digest(n instanceof Uint8Array?n:n.subarray());if(Gs(o))return o.then(({digest:s})=>(r?.signal?.throwIfAborted(),Wt.verify(e,s,t))).catch(s=>{throw s.name==="AbortError"?s:new pd(String(s))});try{return r?.signal?.throwIfAborted(),Wt.verify(e,o.digest,t)}catch(s){throw new pd(String(s))}}class Ph{type="secp256k1";raw;_key;constructor(e){this._key=$0(e),this.raw=j0(this._key)}toMultihash(){return go.digest(Js(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return Be.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:st(this.raw,e.raw)}verify(e,n,r){return D0(this._key,n,e,r)}}class F0{type="secp256k1";raw;publicKey;constructor(e,n){this.raw=U0(e),this.publicKey=new Ph(n??H0(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:st(this.raw,e.raw)}sign(e,n){return O0(this.raw,e,n)}}function M0(t){return new F0(t)}function Nh(t){return new Ph(t)}function j0(t){return Wt.ProjectivePoint.fromHex(t).toRawBytes(!0)}function U0(t){try{return Wt.getPublicKey(t,!0),t}catch(e){throw new Af(String(e))}}function $0(t){try{return Wt.ProjectivePoint.fromHex(t),t}catch(e){throw new Ef(String(e))}}function H0(t){try{return Wt.getPublicKey(t,!0)}catch(e){throw new Af(String(e))}}async function q0(t,e){return Lb()}function $a(t,e){const{Type:n,Data:r}=wn.decode(t),o=r??new Uint8Array;switch(n){case de.RSA:return g0(o,e);case de.Ed25519:return gh(o);case de.secp256k1:return Nh(o);case de.ECDSA:return Mf(o);default:throw new qs}}function K0(t){const{Type:e,Data:n}=wn.decode(t.digest),r=n??new Uint8Array;switch(e){case de.Ed25519:return gh(r);case de.secp256k1:return Nh(r);case de.ECDSA:return Mf(r);default:throw new qs}}function Js(t){return wn.encode({Type:de[t.type],Data:t.raw})}function z0(t){const e=ws.decode(t),n=e.Data??new Uint8Array;switch(e.Type){case de.RSA:return h0(n);case de.Ed25519:return Nb(n);case de.secp256k1:return M0(n);case de.ECDSA:return Sy(n);default:throw new qs}}function W0(t){return ws.encode({Type:de[t.type],Data:t.raw})}const Lh=Symbol.for("nodejs.util.inspect.custom"),V0=114;class Yc{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[kf]=!0;toString(){return this.string==null&&(this.string=Be.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return le.createV1(V0,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return st(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return st(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Lh](){return`PeerId(${this.toString()})`}}class Bh extends Yc{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class _h extends Yc{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class Oh extends Yc{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}const G0=2336;class Dh{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=go.digest(we(this.url))}[Lh](){return`PeerId(${this.url})`}[kf]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return le.createV1(G0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=ee(e)),e.toString()===this.toString())}}const X0=114,bd=2336;function Y0(t,e){let n;if(t.charAt(0)==="1"||t.charAt(0)==="Q")n=Rf(Be.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return Z0(le.parse(t));throw new ot('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return Fh(n)}function cr(t){if(t.type==="Ed25519")return new _h({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new Oh({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new Bh({multihash:t.toCID().multihash,publicKey:t});throw new qs}function Fh(t){if(Q0(t))return new Bh({multihash:t});if(J0(t))try{const e=K0(t);if(e.type==="Ed25519")return new _h({multihash:t,publicKey:e});if(e.type==="secp256k1")return new Oh({multihash:t,publicKey:e})}catch{const n=ee(t.digest);return new Dh(new URL(n))}throw new Bm("Supplied PeerID Multihash is invalid")}function Z0(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==X0&&t.code!==bd)throw new Lm("Supplied PeerID CID is invalid");if(t.code===bd){const e=ee(t.multihash.digest);return new Dh(new URL(e))}return Fh(t.multihash)}function J0(t){return t.code===go.code}function Q0(t){return t.code===Oc.code}class Mh extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class ev extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class Ir extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class vd extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}}class tv extends Event{data;constructor(e,n){super("message",n),this.data=e}}class Zc extends Event{error;local;constructor(e,n,r){super("close",r),this.error=n,this.local=e}}class nv extends Zc{constructor(e,n){super(!0,e,n)}}class rv extends Zc{constructor(e,n){super(!1,e,n)}}const ov=t=>t/2**32|0,sv=t=>t>>>0;function iv(t,e,n,r){const o=ov(n),s=sv(n);t.setUint32(e,r?s:o,r),t.setUint32(e+4,r?o:s,r)}function Ha(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const qa=t=>t?`"${t}" `:"";function Tt(t,e=""){if(typeof t!="number")throw new TypeError(qa(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(qa(e)+"expected integer >= 0, got "+t);return t}function Pt(t,e,n=""){if(Ha(t)&&(e===void 0||t.length===e))return t;e!==void 0&&Tt(e,"length");const r=Ha(t),o=e!==void 0?` of length ${e}`:"",s=r?`length=${t.length}`:`type=${typeof t}`,i=qa(n)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}function Jc(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Tt(t.outputLen),Tt(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}const av=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)},Sd=(t,e)=>{av(t,e);const n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function ys(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function jh(t,e){Pt(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function HI(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function fn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Pi(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function at(t,e){return t<<32-e|t>>>e}function qI(t,e){return t<<e|t>>>32-e>>>0}const cv=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function lv(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function dv(t){for(let e=0;e<t.length;e++)t[e]=lv(t[e]);return t}const KI=cv?t=>t:dv,Uh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",uv=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Qc(t){if(Pt(t),Uh)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=uv[t[n]];return e}function xd(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function $h(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Uh)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}const e=t.length,n=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){const i=xd(t.charCodeAt(s)),a=xd(t.charCodeAt(s+1));if(i===void 0||a===void 0){const c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a}return r}function fv(t){const e=globalThis;if(typeof e.scheduler?.yield=="function"){const n=e.scheduler.yield();return t&&n.catch(t),n}return new Promise(n=>e.setTimeout(n,0))}async function zI(t,e,n,r){if(Tt(t,"iters"),Tt(e,"tick"),typeof n!="function")throw new TypeError("callback must be a function");let o=Date.now();for(let s=0;s<t;s++){n(s);const i=Date.now()-o;i>=0&&i<e||(await fv(r),o=Date.now())}}function hv(t){if(typeof t!="string")throw new TypeError("string expected");const e=new TextEncoder().encode(t);try{return new Uint8Array(e)}finally{fn(e)}}function WI(t,e=""){return typeof t=="string"?hv(t):Pt(t,void 0,e)}function pv(t,e,n="opts"){return Sd(t,"defaults"),e!==void 0&&Sd(e,n),Object.assign(Object.create(null),t,e)}function gv(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=pv({},e,"info");const n=(o,s)=>t(s).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function mv(t=32){Tt(t,"bytesLength");const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}const wv=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function yv(t,e,n){return t&e^~t&n}function bv(t,e,n){return t&e^t&n^e&n}class vv{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,n,r,o){this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Pi(this.buffer)}update(e){ys(this),Pt(e);const{view:n,buffer:r,blockLen:o}=this,s=e.length;let i=!1;for(let a=0;a<s;){const c=Math.min(o-this.pos,s-a);if(c===o){const l=Pi(e);for(;o<=s-a;a+=o)this.process(l,a);i=!0;continue}r.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(n,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){ys(this),jh(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:o,isLE:s}=this;let{pos:i}=this;n[i++]=128,n.fill(0,i),this.padOffset>o-i&&(this.process(r,0),n.fill(0)),iv(r,o-8,this.length*8,s),this.process(r,0),this.roundClean();const a=e===n?r:Pi(e),c=this.outputLen,l=c/4,d=this.get();if(c%4||l>d.length)throw new Error("invalid outputLen");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneIntoMeta(e){const{buffer:n,length:r,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=r,e.pos=i,i&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Sv=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),xv=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Dt=new Uint32Array(64);class Ev extends vv{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,n){super(64,e,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){const{A:e,B:n,C:r,D:o,E:s,F:i,G:a,H:c}=this;return[e,n,r,o,s,i,a,c]}set(e,n,r,o,s,i,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,n){for(let u=0;u<16;u++,n+=4)Dt[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const f=Dt[u-15],h=Dt[u-2],g=at(f,7)^at(f,18)^f>>>3,m=at(h,17)^at(h,19)^h>>>10;Dt[u]=m+Dt[u-7]+g+Dt[u-16]|0}let{A:r,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=at(a,6)^at(a,11)^at(a,25),h=d+f+yv(a,c,l)+xv[u]+Dt[u]|0,m=(at(r,2)^at(r,13)^at(r,22))+bv(r,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=r,r=h+m|0}r=r+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,s,i,a,c,l,d)}roundClean(){fn(Dt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),fn(this.buffer)}}class Av extends Ev{constructor(){super(32,Sv)}}const Ni=gv(()=>new Av,wv(1));function Hh(t,e,n=()=>{}){if(!Array.isArray(t))throw new TypeError(`"${e}" expected array, got type=${typeof t}`);for(let r=0;r<t.length;r++)n(t[r],`${e}[${r}]`);return t}const Yn=(t,e,n)=>Pt(t,e,n),qh=Tt;function Zn(t,e="object"){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`);return t}function Vr(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}const kv=Qc,Cv=t=>$h(t),Kh=Ha,zh=t=>mv(t),bs=BigInt(0),Ed=BigInt(1),Iv=t=>t?`"${t}" `:"";function Qs(t,e=""){if(typeof t!="boolean")throw new TypeError(Iv(e)+"expected boolean, got type="+typeof t);return t}function Rv(t){if(typeof t=="bigint"){if(!hn(t))throw new RangeError("positive bigint expected, got "+t)}else qh(t);return t}function Ka(t,e=""){if(typeof t!="number"){const n=e&&`"${e}" `;throw new TypeError(n+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){const n=e&&`"${e}" `;throw new RangeError(n+"expected safe integer, got "+t)}}function Wh(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?bs:BigInt("0x"+t)}function Vh(t){return Wh(Qc(t))}function vs(t){return Wh(Qc(ro(Pt(t)).reverse()))}function Gh(t,e){if(Tt(e),e===0)throw new Error("zero output length is invalid");t=Rv(t);const n=e*2,r=t.toString(16);if(r.length>n)throw new RangeError("number is too large");return $h(r.padStart(n,"0"))}function Xh(t,e){return Gh(t,e).reverse()}function ro(t){return Uint8Array.from(Yn(t))}function hn(t){return typeof t=="bigint"&&bs<=t}function Yh(t,e,n){return hn(t)&&hn(e)&&hn(n)&&e<=t&&t<n}function Gr(t,e,n,r){if(!Yh(e,n,r))throw new RangeError("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Tv(t){if(t<bs)throw new Error("expected non-negative bigint, got "+t);return t===bs?0:t.toString(2).length}const Pv=t=>(Ka(t,"n"),(Ed<<BigInt(t))-Ed);function Ss(t,e={},n={},r="object"){Zn(t,r),Zn(e,"fields"),Zn(n,"optFields");function o(i,a,c){const l=r==="object"?`param "${String(i)}"`:`"${r}.${String(i)}"`,d=t[i];if(!Object.hasOwn(t,i)&&(c?d!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&d===void 0)return;const u=typeof d;if(u!==a||d===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${u}`)}const s=(i,a)=>Object.entries(i).forEach(([c,l])=>o(c,l,a));s(e,!1),s(n,!0)}const Se=BigInt(0),ae=BigInt(1),an=BigInt(2),Zh=BigInt(3),el=BigInt(4),Jh=BigInt(5),Nv=BigInt(7),Qh=BigInt(8),Lv=BigInt(9),Bv=BigInt(15),ep=BigInt(16),_v=BigInt("0x10000000000000000");function ie(t,e){if(e<=Se)throw new Error("mod: expected positive modulus, got "+e);const n=t%e;return n>=Se?n:e+n}function Ov(t,e,n){if(n<=ae)throw new Error("pow: expected modulus > 1, got "+n);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<Se)throw new Error("invalid exponent, negatives unsupported");if(e===Se)return ae;if(e===ae)return t;let r=t%n;if(r<Se&&(r+=n),e<_v){let a=ae;for(;e>Se;)e&ae&&(a=a*r%n),r=r*r%n,e>>=ae;return a}const o=[];for(;e>Se;)o.push(Number(e&Bv)),e>>=el;const s=new Array(16);s[0]=ae,s[1]=r;for(let a=2;a<16;a++)s[a]=s[a-1]*r%n;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%n,i=i*i%n,i=i*i%n,i=i*i%n;const c=o[a];c!==0&&(i=i*s[c]%n)}return i}function nt(t,e,n){if(n<=ae)throw new Error("pow2: expected modulus > 1, got "+n);if(e<Se)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >Se;)r*=r,r%=n;return r}function Ad(t,e){if(t===Se)throw new Error("invert: expected non-zero number");if(e<=ae)throw new Error("invert: expected modulus > 1, got "+e);let n=ie(t,e),r=e,o=Se,s=ae;for(;n!==Se;){const a=r/n,c=r-n*a,l=o-s*a;r=n,n=c,o=s,s=l}if(r!==ae)throw new Error("invert: does not exist");return ie(o,e)}function tl(t,e,n){const r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function nl(t,e){if((t&ae)===Se)throw new Error(e+": expected odd modulus, got "+t)}function tp(t,e){const n=t,r=(n.ORDER+ae)/el,o=n.pow(e,r);return tl(n,o,e),o}function Dv(t,e){const n=t,r=(n.ORDER-Jh)/Qh,o=n.mul(e,an),s=n.pow(o,r),i=n.mul(e,s),a=n.mul(n.mul(i,an),s),c=n.mul(i,n.sub(a,n.ONE));return tl(n,c,e),c}function Fv(t){const e=rl(t),n=np(t),r=n(e,e.neg(e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+Nv)/ep;return((a,c)=>{const l=a;let d=l.pow(c,i),u=l.mul(d,r);const f=l.mul(d,o),h=l.mul(d,s),g=l.eql(l.sqr(u),c),m=l.eql(l.sqr(f),c);d=l.cmov(d,u,g),u=l.cmov(h,f,m);const b=l.eql(l.sqr(u),c),w=l.cmov(d,u,b);return tl(l,w,c),w})}function np(t){if(t<Zh)throw new Error("sqrt is not defined for small field");nl(t,"tonelliShanks");let e=t-ae,n=0;for(;e%an===Se;)e/=an,n++;let r=an;const o=rl(t);for(;xs(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return tp;let s=o.pow(r,e);const i=(e+ae)/an;return function(c,l){const d=c;if(d.is0(l))return l;if(xs(d,l)!==1)throw new Error("Cannot find square root");let u=n,f=d.mul(d.ONE,s),h=d.pow(l,e),g=d.pow(l,i);for(;!d.eql(h,d.ONE);){if(d.is0(h))throw new Error("Cannot find square root: probably non-prime P");let m=1,b=d.sqr(h);for(;!d.eql(b,d.ONE);)if(m++,b=d.sqr(b),m===u)throw new Error("Cannot find square root");const w=ae<<BigInt(u-m-1),I=d.pow(f,w);u=m,f=d.sqr(I),h=d.mul(h,f),g=d.mul(g,I)}return g}}function Mv(t){return nl(t,"Fp.sqrt"),t%el===Zh?tp:t%Qh===Jh?Dv:t%ep===Lv?Fv(t):np(t)}const jv=(t,e)=>(ie(t,e)&ae)===ae,Uv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function oo(t){if(Zn(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);Ka(t.BYTES,"BYTES"),Ka(t.BITS,"BITS");for(const e of Uv)Vr(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=ae)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function rp(t,e,n=!1){oo(t),Hh(e,"nums"),Qs(n,"passZero");const r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),s=e.reduce((a,c,l)=>r.is0(c)?a:(o[l]=a,r.mul(a,c)),r.ONE),i=r.inv(s);return e.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),i),o}function xs(t,e){oo(t);const n=t;nl(n.ORDER,"FpLegendre");const r=(n.ORDER-ae)/an,o=n.pow(e,r),s=n.eql(o,n.ONE),i=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function $v(t,e){if(e!==void 0&&qh(e),t<=Se)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);const n=Tv(t);if(e!==void 0&&e<n)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${n})`);const r=e!==void 0?e:n,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}const kd=new WeakMap;class Cd{ORDER;BITS;BYTES;isLE;ZERO=Se;ONE=ae;_lengths;_mod;constructor(e,n={}){if(e<=ae)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:!0}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));const{nBitLength:o,nByteLength:s}=$v(e,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return ie(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Se<=e&&e<this.ORDER}is0(e){return e===Se}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ae)===ae}neg(e){return ie(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return ie(e*e,this.ORDER)}add(e,n){return ie(e+n,this.ORDER)}sub(e,n){return ie(e-n,this.ORDER)}mul(e,n){return ie(e*n,this.ORDER)}pow(e,n){return Ov(e,n,this.ORDER)}div(e,n){return ie(e*Ad(n,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return Ad(e,this.ORDER)}sqrt(e){let n=kd.get(this);return n||kd.set(this,n=Mv(this.ORDER)),n(this,e)}toBytes(e){return this.isLE?Xh(e,this.BYTES):Gh(e,this.BYTES)}fromBytes(e,n=!1){Yn(e);const{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);const l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?vs(e):Vh(e);if(a&&(c=ie(c,i)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return rp(this,e,!0)}cmov(e,n,r){return Qs(r,"condition"),r?n:e}}function rl(t,e={}){return Object.freeze(Cd.prototype),new Cd(t,e)}const ol=BigInt(0),so=BigInt(1),Hv=BigInt(4),Li=16,Id=128,qv=5,Rd=2**31;function sl(t){const e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);Vr(e.fromAffine,"Point.fromAffine"),Vr(e.fromBytes,"Point.fromBytes"),Vr(e.fromHex,"Point.fromHex"),Zn(e.BASE,"Point.BASE"),Zn(e.ZERO,"Point.ZERO"),oo(e.Fp),oo(e.Fn)}function Kv(t,e){sl(t),op(e,t);const n=rp(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function zv(t,e,n=1){if(!Number.isSafeInteger(t)||t<n||t>e)throw new Error("invalid window size, expected ["+n+".."+e+"], got W="+t)}function Wv(t,e){const n=t*(4*e+128);if(n>Rd)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+Rd/2**20+" MiB")}function Vv(t,e){if(t!==void 0){Vr(t,"randomBytes");try{const n=t(e);if(!Kh(n)||n.length!==e)return}catch{return}return t}}function op(t,e){Hh(t,"points"),t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function Gv(t,e,n){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,o)=>{if(!(n===void 0?e.isValid(r):hn(r)&&r<n))throw new Error("invalid scalar at index "+o)})}const sp=new WeakMap;function Bi(t){return sp.get(t)||1}function Xv(t,e){const n=t.double(),r=[t];for(let o=1;o<e;o++)r.push(r[o-1].add(n));return r}function Yv(t,e){const n=2**e,r=n/2,o=BigInt(n-1),s=[];for(;t>ol;){let i=0;t&so&&(i=Number(t&o),i>=r&&(i-=n),t-=BigInt(i)),s.push(i),t>>=so}return s}function Zv(t,e,n){const r=2**e,o=r/2,s=BigInt(r-1),i=BigInt(e),a=[];for(let c=0;c<n;c++){let l=Number(t&s);t>>=i,l>o&&(l-=r,t+=so),a.push(l)}if(t!==ol)throw new Error("invalid wnaf");return a}function Jv(t,e,n){let r=0;for(const s of n)r=Math.max(r,s.length);let o=t;for(let s=r-1;s>=0;s--){s!==r-1&&(o=o.double());for(let i=0;i<n.length;i++){const a=n[i][s];if(a){const c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}class Qv{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,n){sl(e),this.randomBytes=Vv(n,Li),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,n,r){const o=Math.ceil(r/n)+1,s=2**(n-1),i=[];let a=e;for(let c=0;c<o;c++){let l=a;for(let d=0;d<s;d++)i.push(l),l=l.add(a);a=i[i.length-1].double()}return{W:n,bits:r,windows:o,comp:i}}wnafCachedCT(e,n){const{W:r,windows:o,comp:s}=e,i=2**(r-1),a=Zv(n,r,o);let c=this.ZERO,l=this.BASE;for(let d=0;d<o;d++){const u=a[d],f=d*i,h=Math.abs(u)-1;let g=s[f];for(let b=1;b<i;b++)g=b===h?s[f+b]:g;const m=g.negate();u===0?l=l.add(s[f]):c=c.add(u<0?m:g)}return{p:c,f:l}}getWnafPrecomputes(e,n,r,o){let s=this.wnafPrecomputes.get(n),i=s?.find(a=>a.W===e&&a.bits===r);return i||(i=this.buildWnafTable(n,e,r),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(n,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,n){if(this.assertPoint(e),!Yh(n,so,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,n,r,o){const s=Bi(e);return s===1?this.fixedWindowCT(e,n,r):this.wnafCachedCT(this.getWnafPrecomputes(s,e,r,o),n)}mulCT(e,n,r){return this.validateMulInput(e,n),this.runCT(e,n,this.bits,r)}mulCTBlinded(e,n,r){if(this.validateMulInput(e,n),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");const o=this.Point.Fn.BITS+Id,s=this.randomBytes(Li);if(!Kh(s)||s.length!==Li)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;const i=n+Vh(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,r)}fixedWindowCT(e,n,r){const o=qv,s=1<<o,i=Pv(o),a=new Array(s);a[0]=this.ZERO;for(let d=1;d<s;d++)a[d]=a[d-1].add(e);const c=Math.ceil(r/o);let l=this.ZERO;for(let d=c-1;d>=0;d--){if(d!==c-1)for(let h=0;h<o;h++)l=l.double();const u=Number(n>>BigInt(d*o)&i);let f=a[0];for(let h=1;h<s;h++)f=h===u?a[h]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(e,n){return this.randomBytes===void 0?!1:n===so?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,n,r,o){return this.shouldBlind(e,r)?this.mulCTBlinded(e,n,o):this.mulCT(e,n,o)}mulUnsafe(e,n,r){if(this.assertPoint(e),!hn(n))throw new Error("invalid scalar");const o=Bi(e);if(o===1||n>=this.Point.Fn.ORDER)return eS(this.Point,[e],[n],!0);const s=this.getWnafPrecomputes(o,e,this.bits,r);return this.wnafCachedCT(s,n).p}setWindowSize(e,n){this.assertPoint(e),zv(n,this.bits);const r=Math.ceil((this.bits+Id)/n)+1;Wv(r*2**(n-1),this.Point.Fp.BYTES),sp.set(e,n),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Bi(e)!==1}}function eS(t,e,n,r=!1){if(sl(t),op(e,t),Qs(r,"allowOversized"),Gv(n,t.Fn,r?t.Fn.ORDER**Hv:void 0),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const o=e.map(i=>Xv(i,4)),s=n.map(i=>Yv(i,4));return Jv(t.ZERO,o,s)}function Td(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return oo(e),e}else return rl(t,{isLE:n})}function tS(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);Ss(n);for(const c of["p","n","h"]){const l=e[c];if(!(hn(l)&&l!==ol))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Td(e.p,n.Fp,r),s=Td(e.n,n.Fn,r),a=["Gx","Gy","a","d"];for(const c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function nS(t,e){return function(r){const o=t(r);return{secretKey:o,publicKey:e(o)}}}const No=BigInt(0),Lo=BigInt(1),Bo=BigInt(2),rS=BigInt(4),Pd=BigInt(8);function oS(t,e,n,r){const o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function sS(t,e={}){Ss(e,{},{},"extraOpts");const n=e,r=tS("edwards",t,n,n.FpFnLE),{Fp:o,Fn:s}=r;let i=r.CURVE;const{h:a}=i;if(xs(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(xs(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Ss(n,{},{uvRatio:"function",randomBytes:"function"});const c=n.randomBytes===void 0?zh:n.randomBytes,l=Bo<<BigInt(o.BYTES*8)-Lo;function d(I){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(I)}const u=n.uvRatio===void 0?(I,y)=>{try{return{isValid:!0,value:o.sqrt(o.div(I,y))}}catch{return{isValid:!1,value:No}}}:n.uvRatio;if(!oS(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");const f=o.eql(i.a,o.neg(o.ONE))?I=>o.neg(I):o.eql(i.a,o.ONE)?I=>I:I=>o.mul(i.a,I);function h(I,y,v=!1){const L=v?Lo:No;return Gr("coordinate "+I,y,L,l),y}function g(I){if(!(I instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.Gy));static ZERO=new m(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(y,v,L,C){this.X=h("x",y),this.Y=h("y",v),this.Z=h("z",L,!0),this.T=h("t",C),Object.freeze(this)}static CURVE(){return i}static fromAffine(y){if(y instanceof m)throw new Error("extended point not allowed");const{x:v,y:L}=y||{};return h("x",v),h("y",L),new m(v,L,o.ONE,o.mul(v,L))}static fromBytes(y,v=!1){const L=o.BYTES,{a:C,d:T}=i;y=ro(Yn(y,L,"point")),Qs(v,"zip215");const E=ro(y),S=y[L-1];E[L-1]=S&-129;const k=vs(E),N=v?l:o.ORDER;Gr("point.y",k,No,N);const D=o.sqr(k),A=o.sub(D,o.ONE),x=o.sub(o.mulN(T,D),C);let{isValid:P,value:R}=u(A,x);if(!P)throw new Error("bad point: invalid y coordinate");const O=d(R),j=(S&128)!==0;if(!v&&o.is0(R)&&j)throw new Error("bad point: x=0 and x_0=1");return j!==O&&(R=o.neg(R)),m.fromAffine({x:R,y:k})}static fromHex(y,v=!1){return m.fromBytes(Cv(y),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=6,v=!0){return w.setWindowSize(this,y),v||this.multiply(Bo),this}assertValidity(){const y=this,{a:v,d:L}=i;if(y.is0())throw new Error("bad point: ZERO");const{X:C,Y:T,Z:E,T:S}=y,k=o.sqr(C),N=o.sqr(T),D=o.sqr(E),A=o.sqr(D),x=o.mul(k,v),P=o.mul(o.add(x,N),D),R=o.add(A,o.mul(L,o.mul(k,N)));if(!o.eql(P,R))throw new Error("bad point: equation left != right (1)");const O=o.mul(C,T),j=o.mul(E,S);if(!o.eql(O,j))throw new Error("bad point: equation left != right (2)")}equals(y){g(y);const{X:v,Y:L,Z:C}=this,{X:T,Y:E,Z:S}=y,k=o.mul(v,S),N=o.mul(T,C),D=o.mul(L,S),A=o.mul(E,C);return o.eql(k,N)&&o.eql(D,A)}is0(){return this.equals(m.ZERO)}negate(){return new m(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){const{X:y,Y:v,Z:L}=this,C=o.sqr(y),T=o.sqr(v),E=o.mul(o.sqr(L),Bo),S=f(C),k=o.addN(y,v),N=o.sub(o.subN(o.sqr(k),C),T),D=o.addN(S,T),A=o.subN(D,E),x=o.subN(S,T),P=o.mul(N,A),R=o.mul(D,x),O=o.mul(N,x),j=o.mul(A,D);return new m(P,R,j,O)}add(y){g(y);const{d:v}=i,{X:L,Y:C,Z:T,T:E}=this,{X:S,Y:k,Z:N,T:D}=y,A=o.mul(L,S),x=o.mul(C,k),P=o.mul(o.mulN(E,v),D),R=o.mul(T,N),O=o.sub(o.subN(o.mulN(o.addN(L,C),o.addN(S,k)),A),x),j=o.subN(R,P),M=o.addN(R,P),B=o.sub(x,f(A)),F=o.mul(O,j),U=o.mul(M,B),H=o.mul(O,B),q=o.mul(j,M);return new m(F,U,q,H)}subtract(y){return g(y),this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");const{p:v,f:L}=w.mulSecret(this,y,a,b);return b([v,L])[0]}multiplyUnsafe(y){if(!s.isValid(y))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return y===No?m.ZERO:this.is0()||y===Lo?this:w.mulUnsafe(this,y,b)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.mulUnsafe(this,i.n).is0()}toAffine(y){const v=this;let L=y;if(L!=null&&typeof L!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof L);const{X:C,Y:T,Z:E}=v,S=v.is0();L==null&&(L=S?o.create(Pd):o.inv(E));const k=o.mul(C,L),N=o.mul(T,L),D=o.mul(E,L);if(S)return{x:o.ZERO,y:o.ONE};if(!o.eql(D,o.ONE))throw new Error("invZ was invalid");return{x:k,y:N}}clearCofactor(){return a===Lo?this:a===Bo?this.double():a===rS?this.double().double():a===Pd?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){const{x:y,y:v}=this.toAffine(),L=o.toBytes(v);return L[L.length-1]|=d(y)?128:0,L}toHex(){return kv(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const b=I=>Kv(m,I),w=new Qv(m,c);return w.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}const en=BigInt(0),Xe=BigInt(1),_o=BigInt(2);function Nd(t,e){return t+e-(e>>Xe<<Xe)}function iS(t){const e=BigInt(6)*t;return(n,r,o)=>{const s=r+o,a=((e+o-r)*n+r)%t;return{x_2:a,x_3:s-a}}}function aS(t){return Ss(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...t})}function cS(t){const e=aS(t),{P:n,type:r,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=e.scalarMultBase,c=r==="x25519";if(!c&&r!=="x448")throw new Error("invalid type");const l=i===void 0?zh:i,d=c?255:448,u=iS(n),f=c?32:56,h=BigInt(c?9:5),g=BigInt(c?121665:39081),m=c?_o**BigInt(254):_o**BigInt(447),b=c?BigInt(8)*(_o**BigInt(251)-Xe):BigInt(4)*(_o**BigInt(445)-Xe),w=m+b+Xe,I=R=>ie(R,n),y=v(h);function v(R){return Xh(I(R),f)}function L(R){const O=ro(Yn(R,f,"uCoordinate"));return c&&(O[31]&=127),I(vs(O))}function C(R){return vs(o(ro(Yn(R,f,"scalar"))))}const T=new Set(c?[en,Xe,n-Xe,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[en,Xe,n-Xe]);function E(R,O){const j=L(O);if(T.has(j))throw new Error("invalid private or public key received");const M=D(j,C(R));if(M===en)throw new Error("invalid private or public key received");return v(M)}function S(R){if(a===void 0)return E(R,y);const O=C(R);Gr("scalar",O,m,w);const j=I(a(O));if(j===en)throw new Error("invalid private or public key received");return v(j)}const k=S,N=E;function D(R,O){Gr("u",R,en,n),Gr("scalar",O,m,w);const j=O,M=R;let B=Xe,F=en,U=R,H=Xe;const q=j^j>>Xe;for(let V=BigInt(d-1);V>=en;V--){const G=Nd(n,q>>V);({x_2:B,x_3:U}=u(G,B,U)),{x_2:F,x_3:H}=u(G,F,H);const X=B+F,Z=I(X*X),ce=B-F,Ie=I(ce*ce),Me=Z-Ie,ne=U+H,Ve=U-H,Yt=I(Ve*X),Zt=I(ne*ce),je=Yt+Zt,Jt=Yt-Zt;U=I(je*je),H=I(M*I(Jt*Jt)),B=I(Z*Ie),F=I(Me*(Z+I(g*Me)))}const K=Nd(n,j);({x_2:B,x_3:U}=u(K,B,U)),{x_2:F,x_3:H}=u(K,F,H);const W=s(F);return I(B*W)}const A={secretKey:f,publicKey:f,seed:f},x=R=>(R=R===void 0?l(f):R,Yn(R,A.seed,"seed"),R),P={randomSecretKey:x};return Object.freeze(A),Object.freeze(P),Object.freeze({keygen:nS(x,k),getSharedSecret:N,getPublicKey:k,scalarMult:E,scalarMultBase:S,utils:P,GuBytes:y.slice(),lengths:A})}const Ld=BigInt(0),lS=BigInt(1),Bd=BigInt(2),dS=BigInt(3),uS=BigInt(5),fS=BigInt(8),ei=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),hS={p:ei,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:fS,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ip(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=ei,a=t*t%s*t%s,c=nt(a,Bd,s)*a%s,l=nt(c,lS,s)*t%s,d=nt(l,uS,s)*l%s,u=nt(d,e,s)*d%s,f=nt(u,n,s)*u%s,h=nt(f,r,s)*f%s,g=nt(h,o,s)*h%s,m=nt(g,o,s)*h%s,b=nt(m,e,s)*d%s;return{pow_p_5_8:nt(b,Bd,s)*t%s,b2:a}}function pS(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const _d=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function gS(t,e){const n=ei,r=ie(e*e*e,n),o=ie(r*r*e,n),s=ip(t*o).pow_p_5_8;let i=ie(t*r*s,n);const a=ie(e*i*i,n),c=i,l=ie(i*_d,n),d=a===t,u=a===ie(-t,n),f=a===ie(-t*_d,n);return d&&(i=c),(u||f)&&(i=l),jv(i,n)&&(i=ie(-i,n)),{isValid:d||u,value:i}}const Od=sS(hS,{uvRatio:gS}),Oo=(()=>{const t=ei,e=n=>{const{pow_p_5_8:r,b2:o}=ip(n);return ie(nt(r,dS,t)*o,t)};return cS({P:t,type:"x25519",powPminus2:e,adjustScalarBytes:pS,scalarMultBase:n=>{const r=ie(n,Od.Fn.ORDER);if(r===Ld)return Ld;const o=Od.BASE.multiply(r);return ie((o.Z+o.Y)*e(ie(o.Z-o.Y,t)),t)}})})();class Dd{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,n){if(Jc(e),Pt(n,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?e.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),fn(o)}update(e){return ys(this),this.iHash.update(e),this}digestInto(e){ys(this),jh(e,this),this.finished=!0;const n=e.subarray(0,this.outputLen);this.iHash.digestInto(n),this.oHash.update(n),this.oHash.digestInto(n),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});const{oHash:n,iHash:r,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ap=(()=>{const t=((e,n,r)=>new Dd(e,n).update(r).digest());return t.create=(e,n)=>new Dd(e,n),t})();function Fd(){const t={};return t.promise=new Promise((e,n)=>{t.resolve=e,t.reject=n}),t}class Md{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}}class _i{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Md(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const n=this.head;this.head=n.next=new Md(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){const n=this.tail.next;this.tail.next=null,this.tail=n,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}class mS extends Error{type;code;constructor(e,n){super(e??"The operation was aborted"),this.type="aborted",this.code=n??"ABORT_ERR"}}function wS(t={}){return yS(n=>{const r=n.shift();if(r==null)return{done:!0};if(r.error!=null)throw r.error;return{done:r.done===!0,value:r.value}},t)}function yS(t,e){e=e??{};let n=e.onEnd,r=new _i,o,s,i,a=Fd();const c=async()=>{try{return r.isEmpty()?i?{done:!0}:await new Promise((b,w)=>{s=I=>{s=null,r.push(I);try{b(t(r))}catch(y){w(y)}return o}}):t(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Fd()})}},l=b=>s!=null?s(b):(r.push(b),o),d=b=>(r=new _i,s!=null?s({error:b}):(r.push({error:b}),o)),u=b=>{if(i)return o;if(e?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:b})},f=b=>i?o:(i=!0,b!=null?d(b):l({done:!0})),h=()=>(r=new _i,f(),{done:!0}),g=b=>(f(b),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:g,push:u,end:f,get readableLength(){return r.size},onEmpty:async b=>{const w=b?.signal;if(w?.throwIfAborted(),r.isEmpty())return;let I,y;w!=null&&(I=new Promise((v,L)=>{y=()=>{L(new mS)},w.addEventListener("abort",y)}));try{await Promise.race([a.promise,I])}finally{y!=null&&w!=null&&w?.removeEventListener("abort",y)}}},n==null)return o;const m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(b){return m.throw(b),n!=null&&(n(b),n=void 0),{done:!0}},return(){return m.return(),n!=null&&(n(),n=void 0),{done:!0}},push:u,end(b){return m.end(b),n!=null&&(n(b),n=void 0),o},get readableLength(){return m.readableLength},onEmpty:b=>m.onEmpty(b)},o}class il extends Error{name="TimeoutError";constructor(e,n){super(e,n),Error.captureStackTrace?.(this,il)}}const jd=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function bS(t,e){const{milliseconds:n,fallback:r,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e;let a,c;const d=new Promise((u,f)=>{if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(i?.aborted){f(jd(i));return}if(i&&(c=()=>{f(jd(i))},i.addEventListener("abort",c,{once:!0})),t.then(u,f),n===Number.POSITIVE_INFINITY)return;const h=new il;a=s.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){f(g)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?u():o instanceof Error?f(o):(h.message=o??`Promise timed out after ${n} milliseconds`,f(h))},n)}).finally(()=>{d.clear(),c&&i&&i.removeEventListener("abort",c)});return d.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},d}const vS=t=>{const e=t.addEventListener||t.on||t.addListener,n=t.removeEventListener||t.off||t.removeListener;if(!e||!n)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:n.bind(t)}};function SS(t,e,n){let r;const o=new Promise((s,i)=>{if(n={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...n},!(n.count>=0&&(n.count===Number.POSITIVE_INFINITY||Number.isInteger(n.count))))throw new TypeError("The `count` option should be at least 0 or more");n.signal?.throwIfAborted();const a=[e].flat(),c=[],{addListener:l,removeListener:d}=vS(t),u=async(...h)=>{const g=n.multiArgs?h:h[0];if(n.filter)try{if(!await n.filter(g))return}catch(m){r(),i(m);return}c.push(g),n.count===c.length&&(r(),s(c))},f=(...h)=>{r(),i(n.rejectionMultiArgs?h:h[0])};r=()=>{for(const h of a)d(h,u);for(const h of n.rejectionEvents)a.includes(h)||d(h,f)};for(const h of a)l(h,u);for(const h of n.rejectionEvents)a.includes(h)||l(h,f);n.signal&&n.signal.addEventListener("abort",()=>{f(n.signal.reason)},{once:!0}),n.resolveImmediately&&s(c)});if(o.cancel=r,typeof n.timeout=="number"){const s=bS(o,{milliseconds:n.timeout});return s.cancel=()=>{r(),s.clear()},s}return o}function xS(t,e,n){typeof n=="function"&&(n={filter:n}),n={...n,count:1,resolveImmediately:!1};const r=SS(t,e,n),o=r.then(s=>s[0]);return o.cancel=r.cancel,o}class Es extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class ES extends Error{static name="StreamClosedError";name="StreamClosedError"}function AS(t){return t.reason}function cp(t,e,n){if(e==null||t==null)return t;const r=AS;if(e.aborted)return t.catch(()=>{}),Promise.reject(r(e));let o;return Promise.race([t,new Promise((s,i)=>{o=()=>{i(r(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}const kS=Math.pow(2,20)*4;class lp extends Fm{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??kS,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new se,this.writeBuffer=new se,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);const n=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",n);const r=o=>{this.onDrainPromise?.reject(o.error??new ES)};this.addEventListener("close",r)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),cp(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;const e=wS(),n=s=>{e.push(s.data)};this.addEventListener("message",n);const r=s=>{e.end(s.error)};this.addEventListener("close",r);const o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",n),this.removeEventListener("close",r),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Ir(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(n){this.log("failed to send reset to remote - %e",n)}this.dispatchEvent(new nv(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Ir("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Ir("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Ir(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Ir(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");const e=new ev;this.dispatchEvent(new rv(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new Zc))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0;const n=this.writeBuffer.byteLength;let r=0;for(;this.writeBuffer.byteLength>0;){const o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}const s=this.writeBuffer.sublist(0,o),i=new se(s);this.writeBuffer.consume(s.byteLength);const a=this.sendData(s);if(e=a.canSendMore,r+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",r,n,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}const e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new tv(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new vd(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new vd(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}}const CS=4194304;class Ud extends Error{static name="UnwrappedError";name="UnwrappedError"}class dp extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class IS extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class RS extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function TS(t){return typeof t?.closeRead=="function"}function PS(t){return typeof t?.close=="function"}function Oi(t){return TS(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:PS(t)?t.status!=="open":!1}function NS(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function LS(t,e){const n=e?.maxBufferSize??CS,r=new se;let o,s=!1;if(!NS(t))throw new Mh("Argument should be a Stream or a Multiaddr");const i=d=>{if(r.append(d.data),r.byteLength>n){const u=r.byteLength;r.consume(r.byteLength),o?.reject(new Error(`Read buffer overflow - ${u} > ${n}`))}o?.resolve()};t.addEventListener("message",i);const a=d=>{d.error!=null?o?.reject(d.error):o?.resolve()};t.addEventListener("close",a);const c=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",c);const l={readBuffer:r,async read(d){if(s===!0)throw new Ud("Stream was unwrapped");if(Oi(t)){if(d?.bytes==null)return null;if(r.byteLength<d.bytes)throw t.log.error("closed after reading %d/%d bytes",r.byteLength,d.bytes),new Es(`Unexpected EOF - stream closed after reading ${r.byteLength}/${d.bytes} bytes`)}const u=d?.bytes??1;for(o=Promise.withResolvers();;){if(r.byteLength>=u){o.resolve();break}if(await cp(o.promise,d?.signal),Oi(t)){if(r.byteLength===0&&d?.bytes==null)return null;break}o=Promise.withResolvers()}const f=d?.bytes??r.byteLength;if(r.byteLength<f){if(Oi(t))throw t.log.error("closed while reading %d/%d bytes",r.byteLength,f),new Es(`Unexpected EOF - stream closed while reading ${r.byteLength}/${f} bytes`);return l.read(d)}const h=r.sublist(0,f);return r.consume(f),h},async write(d,u){if(s===!0)throw new Ud("Stream was unwrapped");t.send(d)||await xS(t,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",i),t.removeEventListener("close",a),t.removeEventListener("remoteCloseWrite",c),r.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",r.byteLength),t.push(r))),t}};return l}function $d(t,e={}){const n=LS(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=En(e.maxDataLength));const r=e?.lengthDecoder??yh,o=e?.lengthEncoder??Mb;return{async read(i){let a=-1;const c=new se;for(;;){const d=await n.read({...i,bytes:1});if(d==null)break;c.append(d);try{a=r(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new dp("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new RS(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new IS(`Message length too long - ${a} > ${e.maxDataLength}`);const l=await n.read({...i,bytes:a});if(l==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new Es(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw t.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Es(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await n.write(new se(o(i.byteLength),i),a)},async writeV(i,a){const c=new se(...i.flatMap(l=>[o(l.byteLength),l]));await n.write(c,a)},unwrap(){return n.unwrap()}}}const BS=1024*1024*4,_S=1024*1024*4;class OS{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new se,this.maxBufferSize=e.maxBufferSize??BS,this.maxDataLength=e.maxDataLength??_S,this.lengthDecoder=e.lengthDecoder??yh,this.encodingLength=e.encodingLength??En}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new Mh(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let n;try{n=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(n<0||n>this.maxDataLength)throw new dp("Invalid message length");const r=this.encodingLength(n),o=r+n;if(this.buffer.byteLength>=o){const s=this.buffer.sublist(r,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}}var DS={};const io=65535,Hd=io-16,vo=!!DS?.DUMP_SESSION_KEYS,qd=16;function za(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const As=t=>t?`"${t}" `:"";function Wa(t,e=""){if(typeof t!="boolean")throw new TypeError(As(e)+"expected boolean, got type="+typeof t);return t}function Jn(t,e=""){if(typeof t!="number")throw new TypeError(As(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(As(e)+"expected integer >= 0, got "+t);return t}function ve(t,e,n=""){if(za(t)&&(e===void 0||t.length===e))return t;e!==void 0&&Jn(e,"length");const r=za(t),o=e!==void 0?` of length ${e}`:"",s=r?`length=${t.length}`:`type=${typeof t}`,i=As(n)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}const Kd=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`)};function zd(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function FS(t,e){ve(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function Et(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function zt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function MS(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const Qn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function jS(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function US(t){for(let e=0;e<t.length;e++)t[e]=jS(t[e]);return t}const cn=Qn?t=>t:US;function $S(t,e){return!t.byteLength||!e.byteLength?!1:t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function HS(t,e){if($S(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function qS(t,e){return Kd(t,"defaults"),Kd(e,"opts"),Object.assign(t,e)}function KS(t,e){if(t=ve(t),e=ve(e),t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}function zS(t,e,n){const r=e,o=(()=>[]),s=(a,c)=>r(c,...o(a)).update(a).digest(),i=r(new Uint8Array(t),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>r(a,...c),s}const WS=(t,e)=>{function n(r,...o){if(ve(r,void 0,"key"),t.nonceLength!==void 0){const u=o[0];ve(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}const s=t.tagLength,i=t.nonceLength!==void 0?1:0;if(!t.withAAD){for(let u=i;u<o.length;u++)if(za(o[u]))throw new Error("AAD not supported")}t.withAAD&&o[i]!==void 0&&ve(o[i],void 0,"AAD");const a=e(r,...o),c=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");ve(f,void 0,"output")}};let l=!1;return{encrypt(u,f){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,ve(u,void 0,"data"),c(a.encrypt.length,f),a.encrypt(u,f)},decrypt(u,f){if(ve(u,void 0,"data"),s&&u.length<s)throw new Error('"ciphertext" expected length >= tagLength='+s);return c(a.decrypt.length,f),a.decrypt(u,f)}}}return Object.assign(n,t),n};function Va(t,e,n=!0){if(e===void 0)return new Uint8Array(t);if(ve(e,t,"output"),n&&!ks(e))throw new Error("invalid output, must be aligned");return e}function VS(t,e,n){Jn(t),Jn(e),Wa(n);const r=new Uint8Array(16),o=MS(r);return o.setBigUint64(0,BigInt(e),n),o.setBigUint64(8,BigInt(t),n),r}function ks(t){return t.byteOffset%4===0}function Cs(t){return Uint8Array.from(ve(t))}const up=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),GS=cn(Et(up("expand 16-byte k"))),XS=cn(Et(up("expand 32-byte k")));function te(t,e){return t<<e|t>>>32-e}const Rr=64,YS=16,Ga=2**32-1,Wd=Uint32Array.of();function ZS(t,e,n,r,o,s,i,a){const c=o.length,l=new Uint8Array(Rr),d=Et(l),u=Qn&&ks(o)&&ks(s),f=u?Et(o):Wd,h=u?Et(s):Wd;if(!Qn){for(let g=0;g<c;i++){if(t(e,n,r,d,i,a),cn(d),i>=Ga)throw new Error("arx: counter overflow");const m=Math.min(Rr,c-g);for(let b=0,w;b<m;b++)w=g+b,s[w]=o[w]^l[b];g+=m}return}for(let g=0;g<c;i++){if(t(e,n,r,d,i,a),i>=Ga)throw new Error("arx: counter overflow");const m=Math.min(Rr,c-g);if(u&&m===Rr){const b=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,I;w<YS;w++)I=b+w,h[I]=f[I]^d[w];g+=Rr;continue}for(let b=0,w;b<m;b++)w=g+b,s[w]=o[w]^l[b];g+=m}}function JS(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:s,rounds:i}=qS({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Jn(o),Jn(i),Wa(s),Wa(n),(a,c,l,d,u=0)=>{ve(a,void 0,"key"),ve(c,void 0,"nonce"),ve(l,void 0,"data");const f=l.length,h=d!==void 0;if(d=Va(f,d,!1),h&&HS(l,d),Jn(u),u<0||u>=Ga)throw new Error("arx: counter overflow");const g=[];let m=a.length,b,w;if(m===32)g.push(b=Cs(a)),w=XS;else if(m===16&&n)b=new Uint8Array(32),b.set(a),b.set(a,16),w=GS,g.push(b);else throw ve(a,32,"arx key"),new Error("invalid key size");(!Qn||!ks(c))&&g.push(c=Cs(c));let I=Et(b);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");const L=c.subarray(0,16);if(Qn)r(w,I,Et(L),I);else{const C=cn(Uint32Array.from(w));r(C,I,Et(L),I),zt(C),cn(I)}c=c.subarray(16)}else Qn||cn(I);const y=16-o;if(y!==c.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){const L=new Uint8Array(12);L.set(c,s?0:12-c.length),c=L,g.push(c)}const v=cn(Et(c));try{return ZS(t,w,I,v,l,d,u,i),d}finally{zt(...g)}}}function Ee(t,e){return t[e++]&255|(t[e++]&255)<<8}class QS{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=Cs(ve(e,32,"key"));const n=Ee(e,0),r=Ee(e,2),o=Ee(e,4),s=Ee(e,6),i=Ee(e,8),a=Ee(e,10),c=Ee(e,12),l=Ee(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let d=0;d<8;d++)this.pad[d]=Ee(e,16+2*d)}process(e,n,r=!1){const o=r?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],d=i[3],u=i[4],f=i[5],h=i[6],g=i[7],m=i[8],b=i[9],w=Ee(e,n+0),I=Ee(e,n+2),y=Ee(e,n+4),v=Ee(e,n+6),L=Ee(e,n+8),C=Ee(e,n+10),T=Ee(e,n+12),E=Ee(e,n+14);let S=s[0]+(w&8191),k=s[1]+((w>>>13|I<<3)&8191),N=s[2]+((I>>>10|y<<6)&8191),D=s[3]+((y>>>7|v<<9)&8191),A=s[4]+((v>>>4|L<<12)&8191),x=s[5]+(L>>>1&8191),P=s[6]+((L>>>14|C<<2)&8191),R=s[7]+((C>>>11|T<<5)&8191),O=s[8]+((T>>>8|E<<8)&8191),j=s[9]+(E>>>5|o),M=0,B=M+S*a+k*(5*b)+N*(5*m)+D*(5*g)+A*(5*h);M=B>>>13,B&=8191,B+=x*(5*f)+P*(5*u)+R*(5*d)+O*(5*l)+j*(5*c),M+=B>>>13,B&=8191;let F=M+S*c+k*a+N*(5*b)+D*(5*m)+A*(5*g);M=F>>>13,F&=8191,F+=x*(5*h)+P*(5*f)+R*(5*u)+O*(5*d)+j*(5*l),M+=F>>>13,F&=8191;let U=M+S*l+k*c+N*a+D*(5*b)+A*(5*m);M=U>>>13,U&=8191,U+=x*(5*g)+P*(5*h)+R*(5*f)+O*(5*u)+j*(5*d),M+=U>>>13,U&=8191;let H=M+S*d+k*l+N*c+D*a+A*(5*b);M=H>>>13,H&=8191,H+=x*(5*m)+P*(5*g)+R*(5*h)+O*(5*f)+j*(5*u),M+=H>>>13,H&=8191;let q=M+S*u+k*d+N*l+D*c+A*a;M=q>>>13,q&=8191,q+=x*(5*b)+P*(5*m)+R*(5*g)+O*(5*h)+j*(5*f),M+=q>>>13,q&=8191;let K=M+S*f+k*u+N*d+D*l+A*c;M=K>>>13,K&=8191,K+=x*a+P*(5*b)+R*(5*m)+O*(5*g)+j*(5*h),M+=K>>>13,K&=8191;let W=M+S*h+k*f+N*u+D*d+A*l;M=W>>>13,W&=8191,W+=x*c+P*a+R*(5*b)+O*(5*m)+j*(5*g),M+=W>>>13,W&=8191;let V=M+S*g+k*h+N*f+D*u+A*d;M=V>>>13,V&=8191,V+=x*l+P*c+R*a+O*(5*b)+j*(5*m),M+=V>>>13,V&=8191;let G=M+S*m+k*g+N*h+D*f+A*u;M=G>>>13,G&=8191,G+=x*d+P*l+R*c+O*a+j*(5*b),M+=G>>>13,G&=8191;let X=M+S*b+k*m+N*g+D*h+A*f;M=X>>>13,X&=8191,X+=x*u+P*d+R*l+O*c+j*a,M+=X>>>13,X&=8191,M=(M<<2)+M|0,M=M+B|0,B=M&8191,M=M>>>13,F+=M,s[0]=B,s[1]=F,s[2]=U,s[3]=H,s[4]=q,s[5]=K,s[6]=W,s[7]=V,s[8]=G,s[9]=X}finalize(){const{h:e,pad:n}=this,r=new Uint16Array(10);let o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+o,o=r[a]>>>13,r[a]&=8191;r[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)r[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+n[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+n[a]|0)+(i>>>16)|0,e[a]=i&65535;zt(r)}update(e){zd(this),ve(e),e=Cs(e);const{buffer:n,blockLen:r}=this,o=e.length;for(let s=0;s<o;){const i=Math.min(r-this.pos,o-s);if(i===r){for(;r<=o-s;s+=r)this.process(e,s);continue}n.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,zt(this.h,this.r,this.buffer,this.pad)}digestInto(e){zd(this),FS(e,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:o}=this;if(o){for(n[o++]=1;o<16;o++)n[o]=0;this.process(n,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=r[i]>>>0,e[s++]=r[i]>>>8}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}}const ex=zS(32,t=>new QS(t));function tx(t,e,n,r,o,s=20){let i=t[0],a=t[1],c=t[2],l=t[3],d=e[0],u=e[1],f=e[2],h=e[3],g=e[4],m=e[5],b=e[6],w=e[7],I=o,y=n[0],v=n[1],L=n[2],C=i,T=a,E=c,S=l,k=d,N=u,D=f,A=h,x=g,P=m,R=b,O=w,j=I,M=y,B=v,F=L;for(let H=0;H<s;H+=2)C=C+k|0,j=te(j^C,16),x=x+j|0,k=te(k^x,12),C=C+k|0,j=te(j^C,8),x=x+j|0,k=te(k^x,7),T=T+N|0,M=te(M^T,16),P=P+M|0,N=te(N^P,12),T=T+N|0,M=te(M^T,8),P=P+M|0,N=te(N^P,7),E=E+D|0,B=te(B^E,16),R=R+B|0,D=te(D^R,12),E=E+D|0,B=te(B^E,8),R=R+B|0,D=te(D^R,7),S=S+A|0,F=te(F^S,16),O=O+F|0,A=te(A^O,12),S=S+A|0,F=te(F^S,8),O=O+F|0,A=te(A^O,7),C=C+N|0,F=te(F^C,16),R=R+F|0,N=te(N^R,12),C=C+N|0,F=te(F^C,8),R=R+F|0,N=te(N^R,7),T=T+D|0,j=te(j^T,16),O=O+j|0,D=te(D^O,12),T=T+D|0,j=te(j^T,8),O=O+j|0,D=te(D^O,7),E=E+A|0,M=te(M^E,16),x=x+M|0,A=te(A^x,12),E=E+A|0,M=te(M^E,8),x=x+M|0,A=te(A^x,7),S=S+k|0,B=te(B^S,16),P=P+B|0,k=te(k^P,12),S=S+k|0,B=te(B^S,8),P=P+B|0,k=te(k^P,7);let U=0;r[U++]=i+C|0,r[U++]=a+T|0,r[U++]=c+E|0,r[U++]=l+S|0,r[U++]=d+k|0,r[U++]=u+N|0,r[U++]=f+D|0,r[U++]=h+A|0,r[U++]=g+x|0,r[U++]=m+P|0,r[U++]=b+R|0,r[U++]=w+O|0,r[U++]=I+j|0,r[U++]=y+M|0,r[U++]=v+B|0,r[U++]=L+F|0}const nx=JS(tx,{counterRight:!1,counterLength:4,allowShortKeys:!1}),rx=new Uint8Array(16),Vd=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(rx.subarray(n))},ox=new Uint8Array(32);function Gd(t,e,n,r,o){o!==void 0&&ve(o,void 0,"AAD");const s=t(e,n,ox),i=VS(r.length,o?o.length:0,!0),a=ex.create(s);o&&Vd(a,o),Vd(a,r),a.update(i);const c=a.digest();return zt(s,i),c}const sx=t=>(e,n,r)=>({encrypt(s,i){const a=s.length;i=Va(a+16,i,!1),i.set(s);const c=i.subarray(0,-16);t(e,n,c,c,1);const l=Gd(t,e,n,c,r);return i.set(l,a),zt(l),i},decrypt(s,i){i=Va(s.length-16,i,!1);const a=s.subarray(0,-16),c=s.subarray(-16),l=Gd(t,e,n,a,r);if(!KS(c,l))throw zt(l),new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,n,i,i,1),zt(l),i}}),Xd=WS({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},sx(nx));function ix(t,e,n){return Jc(t),n===void 0&&(n=new Uint8Array(t.outputLen)),ap(t,n,e)}const Tr=Uint8Array.of(0),ax=Uint8Array.of();function cx(t,e,n,r=32,o){Jc(t),Tt(r,"length"),Pt(e,void 0,"prk");const s=t.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(r>255*s)throw new Error("Length must be <= 255*HashLen");const i=Math.ceil(r/s);if(n===void 0?n=ax:Pt(n,void 0,"info"),!i)return new Uint8Array;const a=new Uint8Array(i*s),{iHash:c,oHash:l}=ap.create(t,e),d=new Uint8Array(s),u=i>1?t.create():void 0;for(let h=0;h<i-1;h++){Tr[0]=h+1;const g=c._cloneInto(u);h&&g.update(d),g.update(n).update(Tr).digestInto(d),l._cloneInto(u).update(d).digestInto(d),a.set(d,s*h)}if(Tr[0]=i,i>1&&c.update(d),c.update(n).update(Tr).digestInto(d),l.update(d).digestInto(d),a.set(d,s*(i-1)),c.destroy(),l.destroy(),u?.destroy(),d!==a&&fn(d),fn(Tr),r===a.length)return a;const f=a.slice(0,r);return fn(a),f}const fp={hashSHA256(t){return Ni(t.subarray())},getHKDF(t,e){const n=ix(Ni,e,t),o=cx(Ni,n,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){const t=Oo.utils.randomSecretKey();return{publicKey:Oo.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:Oo.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return Oo.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,n,r){return Xd(r,e,n).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,n,r,o){return Xd(r,e,n).decrypt(t.subarray(),o)}},lx=fp;function dx(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,n)=>t.generateX25519SharedKey(e.privateKey,n).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}const Is=t=>{const e=It(2);return e[0]=t>>8,e[1]=t,e};Is.bytes=2;const Rs=t=>{if(t.length<2)throw RangeError("Could not decode int16BE");if(t instanceof Uint8Array){let e=0;return e+=t[0]<<8,e+=t[1],e}return t.getUint16(0)};Rs.bytes=2;function ux(t){return{xxHandshakeSuccesses:t.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:t.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:t.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:t.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:t.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function hp(t,e){!e.enabled||!vo||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${ee(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${ee(t.privateKey,"hex")}`)):e("Missing local static keys."))}function pp(t,e){!e.enabled||!vo||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${ee(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${ee(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function fx(t,e){!e.enabled||!vo||e(t?`REMOTE_STATIC_PUBLIC_KEY ${ee(t.subarray(),"hex")}`:"Missing remote static public key.")}function gp(t,e){!e.enabled||!vo||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${ee(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function mp(t,e,n){!n.enabled||!vo||(n(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&ee(t.k,"hex")}`),n(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&ee(e.k,"hex")}`))}class Xr extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=Xr.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}const hx=0,px=4294967295,gx="Cipherstate has reached maximum n, a new handshake must be performed";class mx{n;bytes;view;constructor(e=hx){this.n=e,this.bytes=Ue(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>px)throw new Error(gx)}}const er=Ue(0);class Do{k;n;crypto;constructor(e,n=void 0,r=0){this.crypto=e,this.k=n,this.n=new mx(r)}hasKey(){return!!this.k}encryptWithAd(e,n){if(!this.hasKey())return n;this.n.assertValue();const r=this.crypto.encrypt(n,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,n,r){if(!this.hasKey())return n;this.n.assertValue();const o=this.crypto.decrypt(n,this.n.getBytes(),e,this.k,r);return this.n.increment(),o}}class wx{cs;ck;h;crypto;constructor(e,n){this.crypto=e;const r=we(n,"utf-8");this.h=bx(e,r),this.ck=this.h,this.cs=new Do(e)}mixKey(e){const[n,r]=this.crypto.hkdf(this.ck,e);this.ck=n,this.cs=new Do(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new se(this.h,e))}encryptAndHash(e){const n=this.cs.encryptWithAd(this.h,e);return this.mixHash(n),n}decryptAndHash(e){const n=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),n}split(){const[e,n]=this.crypto.hkdf(this.ck,er);return[new Do(this.crypto,e),new Do(this.crypto,n)]}}class yx{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:n,protocolName:r,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=n,this.ss=new wx(n,r),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,n=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<n+32)throw new Error("message is not long enough");this.re=e.sublist(n,n+32),this.ss.mixHash(this.re)}readS(e,n=0){if(this.rs)throw new Error("remote static public key is already set");const r=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<n+r)throw new Error("message is not long enough");const o=e.sublist(n,n+r);return this.rs=this.ss.decryptAndHash(o),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class wp extends yx{writeMessageA(e){return new se(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const n=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new se(n,r,this.ss.encryptAndHash(e))}writeMessageC(e){const n=this.writeS();return this.writeSE(),new se(n,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(n){throw new Xr(`handshake stage 0 validation fail: ${n.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();const n=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+n))}catch(n){throw new Xr(`handshake stage 1 validation fail: ${n.message}`)}}readMessageC(e){try{const n=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(n))}catch(n){throw new Xr(`handshake stage 2 validation fail: ${n.message}`)}}}function bx(t,e){if(e.length<=32){const n=Ue(32);return n.set(e),n}else return t.hash(e)}var Ts;(function(t){let e;t.codec=()=>(e==null&&(e=Zs((n,r,o={})=>{if(o.lengthDelimited!==!1&&r.fork(),n.webtransportCerthashes!=null)for(const s of n.webtransportCerthashes)r.uint32(10),r.bytes(s);if(n.streamMuxers!=null)for(const s of n.streamMuxers)r.uint32(18),r.string(s);o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={webtransportCerthashes:[],streamMuxers:[]},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new md('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(n.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new md('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(n.string());break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>Ys(n,t.codec()),t.decode=(n,r)=>Xs(n,t.codec(),r)})(Ts||(Ts={}));var Ps;(function(t){let e;t.codec=()=>(e==null&&(e=Zs((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.identityKey!=null&&n.identityKey.byteLength>0&&(r.uint32(10),r.bytes(n.identityKey)),n.identitySig!=null&&n.identitySig.byteLength>0&&(r.uint32(18),r.bytes(n.identitySig)),n.extensions!=null&&(r.uint32(34),Ts.codec().encode(n.extensions,r)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={identityKey:Ue(0),identitySig:Ue(0)},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{s.identityKey=n.bytes();break}case 2:{s.identitySig=n.bytes();break}case 4:{s.extensions=Ts.codec().decode(n,n.uint32(),{limits:o.limits?.extensions});break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>Ys(n,t.codec()),t.decode=(n,r)=>Xs(n,t.codec(),r)})(Ps||(Ps={}));async function yp(t,e,n){const r=await t.sign(vp(e));return Ps.encode({identityKey:Js(t.publicKey),identitySig:r,extensions:n})}async function bp(t,e,n){try{const r=Ps.decode(t),o=$a(r.identityKey);if(n?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${n}`);if(!e)throw new Error("Remote static does not exist");const s=vp(e);if(!await o.verify(s,r.identitySig))throw new Error("Invalid payload signature");return r}catch(r){throw new Pm(r.message)}}function vp(t){const e=we("noise-libp2p-static-key:");return t instanceof Uint8Array?Pa([e,t],e.length+t.length):(t.prepend(e),t)}class vx extends lp{stream;handshake;metrics;decoder;constructor(e,n,r){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=n,this.metrics=r,this.decoder=new OS({lengthDecoder:Rs,maxBufferSize:16*1024*1024,encodingLength:()=>2});const o=c=>{try{for(const l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);const s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);const i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);const a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){const n=new se;for(let r=0;r<e.byteLength;r+=Hd){let o=r+Hd;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(r,o)):s=this.handshake.encrypt(e.sublist(r,o)),this.metrics?.encryptedPackets.increment(),n.append(Is(s.byteLength)),n.append(s)}return n}decrypt(e){const n=new se;for(let r=0;r<e.byteLength;r+=io){let o=r+io;if(o>e.byteLength&&(o=e.byteLength),o-qd<r)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(r,o):s=e.sublist(r,o);const i=e.subarray(r,o-qd);try{const a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),n.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return n}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}}function Yd(t,e,n){return new vx(t,e,n)}async function Sx(t,e){const{log:n,connection:r,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await yp(s,a.publicKey,l),u=new wp({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});hp(u.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(u.writeMessageA(er),e),n.trace("Stage 0 - Initiator finished sending first message."),pp(u.e,n),n.trace("Stage 1 - Initiator waiting to receive first message from responder...");const f=u.readMessageB(await r.read(e));n.trace("Stage 1 - Initiator received the message."),gp(u.re,n),fx(u.rs,n),n.trace("Initiator going to check remote's signature...");const h=await bp(f,u.rs,c);n.trace("All good with the signature!"),n.trace("Stage 2 - Initiator sending third handshake message."),await r.write(u.writeMessageC(d),e),n.trace("Stage 2 - Initiator sent message with signed payload.");const[g,m]=u.ss.split();return mp(g,m,n),{payload:h,encrypt:b=>g.encryptWithAd(er,b),decrypt:(b,w)=>m.decryptWithAd(er,b,w)}}async function xx(t,e){const{log:n,connection:r,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await yp(s,a.publicKey,l),u=new wp({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});hp(u.s,n),n.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await r.read(e)),n.trace("Stage 0 - Responder received first message."),gp(u.re,n),n.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await r.write(u.writeMessageB(d),e),n.trace("Stage 1 - Responder sent the second handshake message with signed payload."),pp(u.e,n),n.trace("Stage 2 - Responder waiting for third handshake message...");const f=u.readMessageC(await r.read(e));n.trace("Stage 2 - Responder received the message, finished handshake.");const h=await bp(f,u.rs,c),[g,m]=u.ss.split();return mp(g,m,n),{payload:h,encrypt:b=>m.encryptWithAd(er,b),decrypt:(b,w)=>g.decryptWithAd(er,b,w)}}class Ex{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,n={}){const{staticNoiseKey:r,extensions:o,crypto:s,prologueBytes:i}=n,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");const c=s??lx;this.crypto=dx(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?ux(a):void 0,r?this.staticKey=c.generateX25519KeyPairFromSeed(r):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??Ue(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Mm]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,n){const r=e.log?.newScope("noise")??this.log,o=$d(e,{lengthEncoder:Is,lengthDecoder:Rs,maxDataLength:io}),s=await this.performHandshakeInitiator(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=$a(s.payload.identityKey);return{connection:Yd(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:cr(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;const n=this.components.upgrader.getStreamMuxers();if(n!=null)for(const r of e){const o=n.get(r);if(o!=null)return o}if(e.length)throw new Nm("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,n){const r=e.log?.newScope("noise")??this.log,o=$d(e,{lengthEncoder:Is,lengthDecoder:Rs,maxDataLength:io}),s=await this.performHandshakeResponder(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=$a(s.payload.identityKey);return{connection:Yd(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:cr(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,n,r,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Sx({connection:e,privateKey:n,remoteIdentityKey:o,log:r.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,n,r,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await xx({connection:e,privateKey:n,remoteIdentityKey:o,log:r.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}}function Ax(t={}){return e=>new Ex(e,t)}const kx="termdock-e2ee-v1",Xa=3600*1e3,Zd=512*1024*1024,Ya=4*1024*1024,Xo=()=>{},ti=Object.assign(Xo,{enabled:!1,error:Xo,trace:Xo,newScope:()=>ti});Object.freeze(ti);async function Sp(){const t=await q0();return{privateKey:t,peerId:cr(t.publicKey).toString()}}function Cx(t){return btoa(String.fromCharCode(...W0(t.privateKey)))}function Jd(t){if(t.length>512||!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Invalid identity encoding");const e=z0(Uint8Array.from(atob(t),n=>n.charCodeAt(0)));if(e.type!=="Ed25519")throw new Error("Only Ed25519 device identities are supported");return{privateKey:e,peerId:cr(e.publicKey).toString()}}class xp{constructor(e=Xo){this.consumed=e}consumed;chunks=[];size=0;ended=!1;error;wake;push(e){if(this.ended)throw this.error??new Error("Byte stream closed");if(this.size+e.byteLength>Ya)throw new Error("Secure stream buffer limit exceeded");this.chunks.push(e.slice()),this.size+=e.byteLength,this.wake?.()}end(e){this.ended=!0,this.error??=e,this.wake?.()}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const e=this.chunks.shift();if(e)this.size-=e.byteLength,yield e,this.consumed();else{if(this.ended)return;await new Promise(n=>{this.wake=n})}}}}class Ix extends lp{constructor(e,n){super({log:ti,direction:n?"outbound":"inbound",maxReadBufferLength:Ya,maxWriteBufferLength:Ya}),this.duplex=e,this.finished=e.sink(this.outgoing).catch(r=>{this.abort(lr(r))}),this.readTransport()}duplex;outgoing=new xp(()=>this.onMuxerDrain());finished;async readTransport(){try{for await(const e of this.duplex.source)this.onData(e.slice());this.onTransportClosed()}catch(e){this.onTransportClosed(lr(e))}}sendData(e){return this.outgoing.push(e.subarray()),{sentBytes:e.byteLength,canSendMore:!1}}sendReset(e){this.outgoing.end(e),this.duplex.close?.(e)}sendPause(){}sendResume(){}async close(){this.outgoing.end(),this.duplex.close?.(),this.onTransportClosed(),await this.finished}}function lr(t){return t instanceof Error?t:new Error("Secure transport failed")}class Rx extends Error{code="E2EE_REHANDSHAKE_REQUIRED";constructor(){super("Encrypted connection lifetime reached; establish a new handshake without replaying pending input")}}function Tx(t){const e=t?.maxAgeMs??Xa,n=t?.maxBytesPerDirection??Zd;if(!Number.isSafeInteger(e)||e<=0||e>Xa||!Number.isSafeInteger(n)||n<=0||n>Zd)throw new Error("Encrypted connection limits cannot exceed the production maximum");return{maxAgeMs:e,maxBytesPerDirection:n}}async function Px(t){const{identity:e,duplex:n,initiator:r,targetPinnedPeerId:o,signal:s}=t,i=Tx(t.limits);if(typeof Reflect.get(Promise,"withResolvers")!="function"||typeof globalThis.crypto?.getRandomValues!="function")throw new Error("End-to-end encryption requires Node.js 22+ or a modern browser with Promise.withResolvers and secure random support");if(r&&!o)throw new Error("A pinned target identity is required");const a=o?Y0(o):void 0;if(a&&a.type!=="Ed25519")throw new Error("Only Ed25519 target identities are supported");if(e.peerId!==cr(e.privateKey.publicKey).toString())throw new Error("Local identity mismatch");if(s?.aborted)throw s.reason??new Error("Connection aborted");const c=new Ix(n,r),l=new AbortController,d=setTimeout(()=>{const h=new Error("Encrypted handshake timed out");l.abort(h),c.abort(h)},15e3),u=()=>{l.abort(s?.reason),c.abort(lr(s?.reason))};s?.addEventListener("abort",u,{once:!0}),c.addEventListener("close",()=>s?.removeEventListener("abort",u),{once:!0});const f=Ax({crypto:fp,prologueBytes:new TextEncoder().encode(kx)})({privateKey:e.privateKey,peerId:cr(e.privateKey.publicKey),logger:{forComponent:()=>ti},upgrader:{getStreamMuxers:()=>new Map}});try{const h=await(r?f.secureOutbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}):f.secureInbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}));if(h.remotePeer.type!=="Ed25519")throw new Error("Unsupported remote identity");return{authenticatedPeerId:h.remotePeer.toString(),duplex:Nx(h.connection,i)}}catch(h){throw c.abort(lr(h)),h}finally{clearTimeout(d),s?.removeEventListener("abort",u)}}function Nx(t,e){const n=new xp,r=performance.now(),o=Date.now();let s=0,i=0,a;const c=()=>(a??=new Rx,n.end(a),t.abort(a),a),l=setTimeout(c,e.maxAgeMs);typeof l=="object"&&l.unref?.();const d=(f,h)=>{if(a)throw a;if(Math.max(performance.now()-r,Date.now()-o)>=e.maxAgeMs||f+h>=e.maxBytesPerDirection)throw c()};t.addEventListener("message",f=>{try{d(i,f.data.byteLength),i+=f.data.byteLength,n.push(f.data.subarray())}catch(h){t.abort(lr(h))}}),t.addEventListener("close",f=>{clearTimeout(l),n.end(f.error)},{once:!0});let u=!1;return{source:n,async sink(f){if(u)throw new Error("Secure sink already consumed");u=!0;try{for await(const h of f)d(s,h.byteLength),s+=h.byteLength,t.send(h)||await t.onDrain()}catch(h){throw t.abort(lr(h)),h}},close(f){f?t.abort(f):t.close()}}}const Ep=1012,Ap="Encrypted transport renewed";class al{constructor(e=64){this.limit=e}limit;items=[];wake;ended=!1;error;push(e){if(this.ended)throw new Error("Channel closed");if(this.items.length>=this.limit)throw this.end(new Error("Channel queue exceeded")),this.error;this.items.push(e),this.wake?.()}end(e){this.ended=!0,this.error??=e,this.wake?.()}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const e=this.items.shift();if(e!==void 0){yield e;continue}if(this.ended)return;await new Promise(n=>{this.wake=n}),this.wake=void 0}}}const Di=2*1024*1024,Lx=new TextEncoder,Bx=new TextDecoder("utf-8",{fatal:!0});class _x{constructor(e){this.duplex=e;const n=this;this.done=e.sink((async function*(){for await(const r of n.outgoing)try{yield r}finally{n.outgoingBytes-=r.byteLength}})()),this.done.catch(r=>this.close(r instanceof Error?r:new Error("Transport failed")))}duplex;outgoing=new al(256);outgoingBytes=0;get hasPendingWrites(){return this.outgoingBytes>0}done;send(e){const n=Lx.encode(JSON.stringify(e));if(n.length>Di)throw new Error("Record too large");const r=new Uint8Array(n.length+4);if(new DataView(r.buffer).setUint32(0,n.length),r.set(n,4),this.outgoingBytes+r.byteLength>4*1024*1024)throw new Error("Record queue byte budget exceeded");this.outgoingBytes+=r.byteLength;try{this.outgoing.push(r)}catch(o){throw this.outgoingBytes-=r.byteLength,o}}close(e){this.outgoing.end(e),this.duplex.close?.(e)}async*read(){let e=new Uint8Array(0);for await(const n of this.duplex.source){if(e.length+n.length>Di*2+8)throw new Error("Record buffer exceeded");const r=new Uint8Array(e.length+n.length);for(r.set(e),r.set(n,e.length),e=r;e.length>=4;){const o=new DataView(e.buffer,e.byteOffset,4).getUint32(0);if(o>Di||o===0)throw new Error("Invalid record size");if(e.length<o+4)break;const s=JSON.parse(Bx.decode(e.subarray(4,o+4)));if(!s||typeof s!="object"||typeof s.id!="string"||typeof s.type!="string")throw new Error("Invalid record");yield s,e=e.slice(o+4)}}if(e.length)throw new Error("Truncated record")}}function kp(t){let e="";for(let n=0;n<t.length;n+=8192)e+=String.fromCharCode(...t.subarray(n,n+8192));return btoa(e)}function Cp(t){const e=atob(t);return Uint8Array.from(e,n=>n.charCodeAt(0))}function Ox(t){const e=new al(64);t.binaryType="arraybuffer";const n=r=>{e.end(r),t.close(1e3)};return t.addEventListener("message",r=>{try{if(!(r.data instanceof ArrayBuffer)||r.data.byteLength>1024*1024)throw new Error("Invalid encrypted frame");e.push(new Uint8Array(r.data))}catch{n(new Error("Encrypted transport rejected frame"))}}),t.addEventListener("close",()=>e.end()),t.addEventListener("error",()=>e.end(new Error("Encrypted transport disconnected"))),{source:e,close:n,async sink(r){try{for await(const o of r)for(let s=0;s<o.length;s+=64*1024){const i=Date.now();for(;t.bufferedAmount>256*1024;){if(t.readyState!==1||Date.now()-i>15e3)throw new Error("Encrypted transport congested");await new Promise(a=>setTimeout(a,10))}if(t.readyState!==1)throw new Error("Encrypted transport closed");t.send(o.subarray(s,s+64*1024))}}catch(o){throw n(o instanceof Error?o:new Error("Encrypted transport failed")),o}}}}const Ip=8,Rp=128,Dx=5*1024*1024,Fx=Rp+Ip+8,Mx=256,Fo=3e4,Pr=64*1024;function $t(t){return t instanceof Error?t:new Error(String(t??"Secure connection closed"))}function Qd(t){if(!t.startsWith("/")||t.startsWith("//")||t.includes("#"))throw new Error("A local API path is required");return t}class Tp extends EventTarget{constructor(e,n,r){super(),this.url=e,this.transmit=n,this.disconnect=r}url;transmit;disconnect;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;binaryType="arraybuffer";bufferedAmount=0;protocol="termdock-e2ee-v1";extensions="";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;send(e){if(this.readyState!==1)throw new Error("Secure socket is not open");if(typeof e!="string"||new TextEncoder().encode(e).length>1024*1024)throw new Error("Unsupported socket payload");this.transmit(e)}close(e=1e3,n=""){this.readyState!==3&&(this.disconnect(),this.finish(e,n))}accept(e){if(this.readyState!==3)if(e.type==="ws-ready"){this.readyState=1;const n=new Event("open");this.dispatchEvent(n),this.onopen?.(n)}else if(e.type==="ws-data"&&typeof e.data=="string"){const n=new MessageEvent("message",{data:e.data});this.dispatchEvent(n),this.onmessage?.(n)}else e.type==="ws-close"?this.finish(typeof e.code=="number"?e.code:1e3,typeof e.reason=="string"?e.reason:""):e.type==="error"&&this.fail($t(e.error))}fail(e){if(this.readyState===3)return;const n=new Event("error");this.dispatchEvent(n),this.onerror?.(n),this.finish(1006,e.message)}finish(e,n){if(this.readyState===3)return;this.readyState=3;const r=new CloseEvent("close",{code:e,reason:n,wasClean:e===1e3});this.dispatchEvent(r),this.onclose?.(r)}}class jx{constructor(e,n,r){this.channel=e,this.identity=n,this.targetPeerId=r,this.read().catch(o=>this.close($t(o))),e.done.catch(o=>this.close($t(o)))}channel;identity;targetPeerId;establishedAt=performance.now();establishedWallTime=Date.now();lastInputAt=-1/0;pending=new Map;waiting=[];stopped=!1;closeReason;get canSwitchTransport(){return!this.channel.hasPendingWrites&&performance.now()-this.lastInputAt>=2e3&&![...this.pending.values()].some(e=>e.kind!=="socket")&&!this.waiting.some(e=>e.kind!=="socket")}get renewalDue(){return!this.stopped&&Math.max(performance.now()-this.establishedAt,Date.now()-this.establishedWallTime)>=Xa-5*6e4}get closed(){return this.stopped}hasCapacity(e){if(this.pending.size>=Fx)return!1;const n=[...this.pending.values()].filter(r=>r.kind===e).length;return e==="http"?n<Ip:e==="socket"?n<Rp:!0}allocate(e){if(this.stopped)throw this.closeReason??new Error("Secure connection closed");const n=crypto.randomUUID(),r=new al(4);return this.pending.set(n,{queue:r,kind:e}),{id:n,queue:r}}reserve(e,n){return n?.aborted?Promise.reject(n.reason):this.stopped?Promise.reject(this.closeReason??new Error("Secure connection closed")):this.hasCapacity(e)?Promise.resolve(this.allocate(e)):this.waiting.length>=Mx?Promise.reject(new Error("连接繁忙,请稍后重试。")):new Promise((r,o)=>{const s=l=>{this.waiting=this.waiting.filter(d=>d!==c),c.cleanup(),o(l)},i=()=>s(n?.reason??new Error("Request aborted")),a=setTimeout(()=>s(new Error("连接等待超时,请重试。")),Fo),c={kind:e,resolve:r,reject:o,cleanup:()=>{clearTimeout(a),n?.removeEventListener("abort",i)}};this.waiting.push(c),n?.addEventListener("abort",i,{once:!0})})}dispatchWaiting(){if(!this.stopped)for(let e=0;e<this.waiting.length;){const n=this.waiting[e];if(!this.hasCapacity(n.kind)){e++;continue}this.waiting.splice(e,1),n.cleanup(),n.resolve(this.allocate(n.kind))}}async read(){try{for await(const e of this.channel.read()){const n=this.pending.get(e.id);n&&(n.socket?(n.socket.accept(e),(e.type==="ws-close"||e.type==="error")&&this.release(e.id)):(n.queue.push(e),(e.type==="end"||e.type==="error")&&(n.cancelUpload?.(),this.release(e.id))))}}finally{this.close(new Error("Secure connection closed"))}}release(e){this.pending.get(e)?.queue.end(),this.pending.delete(e),this.dispatchWaiting()}async request(e,n){const{id:r,queue:o}=await this.reserve("request"),s=setTimeout(()=>this.close(new Error("Secure connection timed out")),Math.max(1e3,Math.min(Fo,n?.timeoutMs??Fo)));try{if(this.stopped)throw this.closeReason;this.channel.send({...e,id:r});const i=(await o[Symbol.asyncIterator]().next()).value;if(!i)throw new Error("Secure request closed");if(i.type==="error")throw $t(i.error);return i}finally{clearTimeout(s),this.release(r)}}openSocket(e){Qd(e);let n;const r=new AbortController,o=new Tp(e,s=>{if(n){try{JSON.parse(s)?.type==="input"&&(this.lastInputAt=performance.now())}catch{}this.channel.send({id:n,type:"ws-data",data:s})}},()=>{if(r.abort(),n)try{this.channel.send({id:n,type:"ws-close"})}finally{this.release(n)}});return this.reserve("socket",r.signal).then(s=>{if(n=s.id,o.readyState===3){this.release(n);return}const i=this.pending.get(n);if(!i)throw new Error("Secure connection closed");i.socket=o,this.channel.send({id:n,type:"ws-open",path:e})}).catch(s=>{n&&this.release(n),o.fail($t(s))}),o}async fetch(e,n){const r=typeof location>"u"?"https://termdock.invalid":location.origin,o=e instanceof Request?e:null,s=new URL(o?.url??String(e),r);if(s.origin!==r)throw new Error("Only current-service API requests are supported");const i=new Request(s,o?new Request(o,n):n),a=i.method.toUpperCase(),c=Qd(s.pathname+s.search),l=s.pathname==="/api/terminal/fs/upload"?110*1024*1024:Dx;if(i.signal.aborted)throw i.signal.reason;const d={};i.headers.forEach((v,L)=>{["cookie","authorization","host","connection","content-length"].includes(L)||(d[L]=v)});const{id:u,queue:f}=await this.reserve("http",i.signal),h=f[Symbol.asyncIterator]();let g;const m=()=>{g?.cancel().catch(()=>{})},b=this.pending.get(u);if(!b)throw new Error("Secure connection closed");b.cancelUpload=m;const w=()=>{m();try{this.channel.send({id:u,type:"cancel"})}catch{}f.end($t(i.signal.reason??"Request aborted")),this.release(u)};i.signal.addEventListener("abort",w,{once:!0});const I=()=>{i.signal.removeEventListener("abort",w),this.release(u)},y=async()=>{let v;try{const L=(await Promise.race([h.next(),new Promise((C,T)=>{v=setTimeout(()=>T(new Error("服务响应超时,请重试。")),Fo)})])).value;if(!L)throw new Error("Secure response ended unexpectedly");if(L.type==="error")throw $t(L.error);return L}finally{clearTimeout(v)}};try{if(i.signal.aborted)throw i.signal.reason;if(this.channel.send({id:u,type:"http",method:a,path:c,headers:d}),i.body){const E=i.body.getReader();g=E;let S=0,k=0;try{for(;;){const{done:N,value:D}=await E.read();if(N)break;if(S+=D.byteLength,S>l)throw new Error("Request body exceeds upload limit");for(let A=0;A<D.byteLength;A+=Pr){if(this.channel.send({id:u,type:"upload",data:kp(D.subarray(A,A+Pr))}),(await y()).type!=="upload-ack")throw new Error("Invalid upload acknowledgement");k+=Math.min(Pr,D.byteLength-A),n?.onUploadProgress?.(k)}}}catch(N){throw await E.cancel(N).catch(()=>{}),N}finally{g=void 0,E.releaseLock()}}if(i.signal.aborted||this.stopped)throw new Error("Request aborted");this.channel.send({id:u,type:"upload-end"});const v=await y();if(v.type!=="head"||typeof v.status!="number")throw new Error("Invalid response header");const L=new Headers(v.headers);if(a==="HEAD"||[204,205,304].includes(v.status)){if((await y()).type!=="end")throw new Error("Unexpected response body");return I(),new Response(null,{status:v.status,headers:L})}let C=!1;const T=new ReadableStream({pull:async E=>{try{C&&(this.channel.send({id:u,type:"ack"}),C=!1);const S=await y();if(S.type==="end"){E.close(),I();return}if(S.type!=="chunk"||typeof S.data!="string")throw new Error("Invalid response chunk");const k=Cp(S.data);if(k.length>Pr)throw new Error("Response chunk exceeds budget");E.enqueue(k),C=!0}catch(S){E.error(S),w(),I()}},cancel:()=>{w(),I()}},{highWaterMark:Pr,size:E=>E.byteLength});return new Response(T,{status:v.status,headers:L})}catch(v){throw w(),I(),v}}retire(){for(const e of this.pending.values())e.socket?.accept({id:"",type:"ws-close",code:Ep,reason:Ap});this.close()}close(e=new Error("Secure connection closed")){if(!this.stopped){this.stopped=!0,this.closeReason=e;for(const n of this.waiting.splice(0))n.cleanup(),n.reject(e);for(const n of this.pending.values())n.queue.end(e),n.cancelUpload?.(),n.socket?.fail(e);this.pending.clear(),this.channel.close(e)}}}async function yn(t){const e=new URL(t.url);if(!["wss:","ws:"].includes(e.protocol))throw new Error("A WebSocket endpoint is required");if(e.protocol==="ws:"&&!["127.0.0.1","localhost","[::1]"].includes(e.hostname))throw new Error("Remote secure channels require WSS");const n=t.identity??await Sp(),r=(t.socketFactory??(c=>new WebSocket(c)))(e.href),o=Ox(r),s=new AbortController,i=setTimeout(()=>s.abort(new Error("Secure handshake timed out")),2e4),a=t.signal?AbortSignal.any([t.signal,s.signal]):s.signal;try{await new Promise((d,u)=>{if(a.aborted){u(a.reason);return}const f=()=>{a.removeEventListener("abort",m),r.removeEventListener("open",h),r.removeEventListener("error",g),r.removeEventListener("close",g)},h=()=>{f(),d()},g=()=>{f(),u(new Error("Secure transport unavailable"))},m=()=>{f(),u(a.reason)};a.addEventListener("abort",m,{once:!0}),r.addEventListener("open",h),r.addEventListener("error",g),r.addEventListener("close",g),r.readyState===1&&h()});const c=await Px({identity:n,duplex:o,initiator:!0,targetPinnedPeerId:t.targetPeerId,signal:a}),l=new jx(new _x(c.duplex),n,c.authenticatedPeerId);if(t.pairingCode)try{await l.request({type:"pair",code:t.pairingCode})}catch(d){throw l.close($t(d)),d}return l}catch(c){throw r.close(),c}finally{clearTimeout(i)}}const eu=256*1024,Ux=1024*1024;class $x extends EventTarget{constructor(e,n,r=o=>new WebSocket(o)){if(super(),this.url=e,!/^[a-zA-Z0-9_.:-]{1,160}$/.test(n))throw new Error("Invalid target identity");this.upstream=r(e),this.deadline=setTimeout(()=>this.fail("Relay connection timed out"),2e4),this.upstream.addEventListener("message",o=>{if(this.readyState!==3)try{if(typeof o.data!="string"||new TextEncoder().encode(o.data).length>eu)throw new Error("Invalid relay envelope");const s=JSON.parse(o.data);if(s.type==="ready"&&!this.requested){this.requested=!0,this.transmit({type:"open",streamId:this.streamId,serviceId:n});return}if(s.streamId!==this.streamId)return;if(s.type==="opened"&&this.readyState===0){clearTimeout(this.deadline),this.readyState=1;const l=new Event("open");this.dispatchEvent(l),this.onopen?.(l);return}if(s.type==="close"){this.finish(1001,"Relay route closed"),this.upstream.close();return}if(s.type!=="data"||this.readyState!==1||s.encoding!=="base64"||typeof s.payload!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(s.payload))throw new Error("Invalid ciphertext relay frame");const i=Cp(s.payload),a=this.binaryType==="blob"?new Blob([i]):i.buffer,c=new MessageEvent("message",{data:a});this.dispatchEvent(c),this.onmessage?.(c)}catch{this.fail("Relay protocol rejected frame")}}),this.upstream.addEventListener("close",o=>this.finish(o.code||1006,"Relay disconnected")),this.upstream.addEventListener("error",()=>this.fail("Relay transport unavailable"))}url;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;protocol="";extensions="";binaryType="arraybuffer";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;upstream;streamId=crypto.randomUUID();requested=!1;deadline;get bufferedAmount(){return this.upstream.bufferedAmount}transmit(e){const n=JSON.stringify(e);if(this.upstream.readyState!==1||this.upstream.bufferedAmount+n.length>Ux||n.length>eu)throw new Error("Relay unavailable or congested");this.upstream.send(n)}send(e){if(this.readyState!==1)throw new Error("Relay socket is not open");let n;if(ArrayBuffer.isView(e))n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof ArrayBuffer)n=new Uint8Array(e);else throw new Error("Relay secure transport requires binary bytes");try{this.transmit({type:"data",streamId:this.streamId,encoding:"base64",payload:kp(n)})}catch(r){throw this.fail("Relay transport congested"),r}}close(e=1e3,n=""){if(this.readyState!==3){try{this.requested&&this.transmit({type:"close",streamId:this.streamId})}catch{}this.finish(e,n),this.upstream.close()}}fail(e){if(this.readyState===3)return;const n=new Event("error");this.dispatchEvent(n),this.onerror?.(n),this.finish(1006,e),this.upstream.close()}finish(e,n){if(this.readyState===3)return;clearTimeout(this.deadline),this.readyState=3;const r=new CloseEvent("close",{code:e,reason:n,wasClean:e===1e3});this.dispatchEvent(r),this.onclose?.(r)}}function Pp(t){return e=>new $x(e,t)}function Hx(t){if(typeof t!="string"||!t.startsWith("/api/")||/[\\\x00-\x20\x7f#]/.test(t))return null;const e=t.split("?")[0];if(e.includes("//"))return null;try{const r=e.split("/").map((o,s)=>{if(s===0||o===""&&s===e.split("/").length-1)return o;const i=decodeURIComponent(o);if(!i||i==="."||i===".."||/[\\/\x00-\x1f\x7f]/.test(i)||/%[a-f0-9]{2}/i.test(i))throw new Error("Ambiguous API path");return i}).join("/");return r.endsWith("/")&&!r.startsWith("/api/terminal/fs/preview/")?null:r}catch{return null}}function qx(t){if(!("serviceWorker"in navigator))return()=>{};const e=new Set,n=r=>{if(r.source!==navigator.serviceWorker.controller||r.data?.type!=="termdock-secure-fetch"||r.ports.length!==1)return;const o=r.ports[0],{path:s,method:i,headers:a,body:c,expectedTargetPeerId:l,previewPrefix:d}=r.data;let u;try{u=new URL(s,location.origin)}catch{o.close();return}if(u.origin!==location.origin||!u.pathname.startsWith("/api/")||e.size>=32||typeof i!="string"||c!==void 0&&(!(c instanceof ArrayBuffer)||c.byteLength>5*1024*1024)){o.postMessage({type:"error"}),o.close();return}if(d!==void 0&&(typeof d!="string"||!d.endsWith("/")||!/^\/api\/terminal\/fs\/preview\/[a-f0-9]{32}\//.test(d)||!["GET","HEAD"].includes(i)||!Hx(u.pathname)?.startsWith(d))){o.postMessage({type:"error"}),o.close();return}const f=new AbortController;let h,g,m=!1,b=!1;const w=()=>{b||(b=!0,e.delete(w),f.abort(),h?.cancel().catch(()=>{}),o.close())};e.add(w),o.onmessage=I=>{if(I.data?.type==="cancel"){w();return}I.data?.type!=="pull"||m||b||(m=!0,(async()=>{if(!h){o.postMessage({type:"end"}),w();return}if(!g?.length){const v=await h.read();if(v.done){o.postMessage({type:"end"}),w();return}g=v.value}const y=g.slice(0,64*1024);g=g.subarray(y.length),o.postMessage({type:"chunk",data:y.buffer},[y.buffer])})().catch(()=>{o.postMessage({type:"error"}),w()}).finally(()=>{m=!1}))},o.onmessageerror=w,o.start(),(async()=>{const I=await t();if(b)return;if(l&&l!==I.targetPeerId)throw new Error("Preview target changed");const y=await I.fetch(u.pathname+u.search,{method:i,headers:a,body:["GET","HEAD"].includes(i)?void 0:c,signal:f.signal});if(b){await y.body?.cancel();return}h=y.body?.getReader();const v={};y.headers.forEach((L,C)=>{v[C]=L}),o.postMessage({type:"head",status:y.status,headers:v,bodyless:!h,targetPeerId:I.targetPeerId})})().catch(()=>{b||(o.postMessage({type:"error"}),w())})};return navigator.serviceWorker.addEventListener("message",n),()=>{navigator.serviceWorker.removeEventListener("message",n);for(const r of[...e])r()}}class Je extends Error{constructor(){super("Device authorization expired or revoked")}}const Mo=new WeakMap;function mr(t,e={}){const n=Mo.get(t);if(!t.closed&&n&&(!n.settled||Date.now()-n.at<(e.maxAgeMs??1e3)))return n.pending;const r={at:Date.now(),settled:!1,pending:void 0},o=Kx(t,e.timeoutMs??5e3).then(s=>(r.at=Date.now(),r.settled=!0,s),s=>{throw Mo.get(t)===r&&Mo.delete(t),s});return r.pending=o,Mo.set(t,r),o}async function Kx(t,e){const n=await t.request({type:"permissions"},{timeoutMs:e});if(n.type!=="result"||typeof n.fullService!="boolean"||!Array.isArray(n.grants))throw new Error("Invalid permission response");const r=n.grants,o=n.fullService===!0;if(!o&&r.length===0)throw new Je;return{fullService:o,grants:r,canManage:o&&r.length>0||r.some(s=>s.actions.includes("authorization.manage"))}}const Np="termdock-secure-last-path:",zx=10*6e4;function Lp(t){try{const e=JSON.parse(sessionStorage.getItem(Np+t)||"null");return e&&typeof e.key=="string"&&Date.now()-e.at<zx?e.key:void 0}catch{return}}function Za(t,e){try{sessionStorage.setItem(Np+t,JSON.stringify({key:e,at:Date.now()}))}catch{}}function Bp(t,e,n=!1){return new Promise((r,o)=>{let s=0,i=0,a=!1,c,l;const d=new Set,u=()=>{clearTimeout(l);for(const h of d)h.abort();d.clear()},f=()=>{if(a)return;if(s>=t.length){i||(a=!0,u(),o(c||new Error("没有可用的连接路线。")));return}if(i>=(n?1:2))return;const h=t[s++],g=performance.now(),m=w=>{performance.getEntriesByName("termdock:connection-path").length>64&&performance.clearMeasures("termdock:connection-path"),performance.measure("termdock:connection-path",{start:g,end:performance.now(),detail:{path:h.key.startsWith("relay:")?"relay":"direct",ok:w}})},b=new AbortController;d.add(b),i++,h.run(b.signal).then(w=>{if(m(!0),d.delete(b),a){e(w);return}a=!0,u(),r({value:w,key:h.key})},w=>{if(m(!1),d.delete(b),i--,!a){if(c=w,w instanceof Je){a=!0,u(),o(w);return}f()}}),clearTimeout(l),!n&&s<t.length&&(l=setTimeout(f,400))};f()})}const Wx=3,Vx=1/0,Gx=10,_p="termdock-secure-workspace-limit";function Op(t){return t===1/0||Number.isInteger(t)&&t>=3&&t<=Gx}function Xx(){try{const t=localStorage.getItem(_p),e=t==="unlimited"?1/0:Number(t);if(Op(e))return e}catch{}return navigator.maxTouchPoints>0?Wx:Vx}function Yx(t,e,n,r){if(t.length<=r)return t;const o=new Set(["root",e,...n?[n]:[]]),s=[...t].reverse().sort((i,a)=>a.touchedAt-i.touchedAt);for(const i of s){if(o.size>=r)break;o.add(i.key)}return t.filter(i=>o.has(i.key))}const Dp="termdock-workspace",ao="termdock:workspace-visibility",Ja="termdock:workspace-activate";function ni(){return window.parent!==window&&location.pathname==="/workspace.html"&&new URLSearchParams(location.search).get(Dp)||"root"}let tu,nu;function ut(){try{if(window.parent===window)return window.__termdockWorkspaceHost;const t=window.parent.__termdockWorkspaceHost;return t&&t!==tu&&(tu=t,nu={...t,subscribe(e){const n=t.subscribe(e,ni()),r=o=>{o.persisted||n()};return window.addEventListener("pagehide",r),()=>{n(),window.removeEventListener("pagehide",r)}}}),t?nu:void 0}catch{return}}function Yo(){const t=ut();return!t||t.snapshot().activeKey===ni()}function Ns(t,e=!0){return ut()?.activate(t,e)??!1}function Mn(t){ut()?.report(ni(),t)}const Qa="termdock-secure-workspace-session:",Fp="termdock-secure-last-workspace";function Zx(){for(const t of["sessionStorage","localStorage"])try{const e=window[t].getItem(Fp);if(e)return e}catch{}return null}function Jx(t){for(const e of["sessionStorage","localStorage"])try{window[e].setItem(Fp,t)}catch{}}function VI(t){if(t)try{const e=JSON.parse(localStorage.getItem(Qa+t)||"null");return localStorage.removeItem(Qa+t),e&&typeof e.sessionId=="string"&&Date.now()-e.at<6e4?e.sessionId:void 0}catch{return}}function Qx(t){if(window.parent!==window||window.termdockDesktop)return;if(window.__termdockWorkspaceHost)return window.__termdockWorkspaceHost;let e={activeKey:"root",items:[{key:"root",service:t,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]};try{const u=Zx(),f=t&&u!==t.targetPeerId?gn().find(h=>h.targetPeerId===u):void 0;f?.targetPeerId&&(e={activeKey:f.targetPeerId,items:[...e.items,{key:f.targetPeerId,service:f,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]})}catch{}let n=Xx(),r=e.activeKey==="root"?"root":null;const o=new Map,s=new Map([["root",window]]),i=new Set,a=()=>{for(const u of[...o.keys()])u()},c=()=>{const u=Yx(e.items,e.activeKey,r,n),f=new Set(u.map(h=>h.key));e={...e,items:u};for(const[h,g]of o)g&&!f.has(g)&&o.delete(h);for(const h of s.keys())f.has(h)||s.delete(h);for(const h of i)f.has(h)||i.delete(h)},l=(u,f)=>{try{const h=f.document.createEvent("CustomEvent");if(h.initCustomEvent(ao,!1,!1,{active:e.activeKey===u}),f.dispatchEvent(h),e.activeKey===u){const g=f.document.createEvent("Event");if(g.initEvent("resize",!1,!1),f.dispatchEvent(g),i.delete(u)){const m=f.document.createEvent("Event");m.initEvent(Ja,!1,!1),f.dispatchEvent(m)}}else f.document.activeElement?.blur?.()}catch{}},d={snapshot:()=>e,subscribe:(u,f)=>(o.set(u,f),()=>{o.delete(u)}),present(u){r=u},retentionLimit:()=>n,setRetentionLimit(u){if(Op(u)){n=u;try{localStorage.setItem(_p,u===1/0?"unlimited":String(u))}catch{}c(),a()}},activate(u,f=!0){const h=$s(u);if(!h?.targetPeerId)return!1;const g=e.items.find(w=>w.service?.targetPeerId===h.targetPeerId),m=g?.key||h.targetPeerId,b=g?{...g,service:h,touchedAt:Date.now()}:{key:m,service:h,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()};e={activeKey:m,items:g?e.items.map(w=>w===g?b:w):[...e.items,b]},c(),Jx(h.targetPeerId),f&&i.add(m),a();for(const[w,I]of s)l(w,I);return!0},report(u,f){const h=e.items.find(m=>m.key===u);if(!h||f.service&&h.service?.targetPeerId&&f.service.targetPeerId!==h.service.targetPeerId)return;const g={...h,...f};JSON.stringify(g)!==JSON.stringify(h)&&(e={...e,items:e.items.map(m=>m===h?g:m)},a())},attach(u,f){f&&e.items.some(h=>h.key===u)?(s.set(u,f),l(u,f)):s.delete(u)},focusSession(u,f){const h=gn().find(m=>m.targetPeerId===u);if(!h)return!1;try{localStorage.setItem(Qa+u,JSON.stringify({sessionId:f,at:Date.now()}))}catch{return!1}d.activate(h,!1);const g=s.get(e.activeKey);if(g){const m=g.document.createEvent("CustomEvent");m.initCustomEvent("termdock:workspace-session",!1,!1,null),g.dispatchEvent(m)}return!0}};return window.__termdockWorkspaceHost=d,d}let Fi;async function Qe(){return Fi||(Fi=(async()=>{const t=await new Promise((e,n)=>{const r=indexedDB.open("termdock-device-identity",1);r.onupgradeneeded=()=>r.result.createObjectStore("keys"),r.onsuccess=()=>e(r.result),r.onerror=()=>n(r.error)});try{const e=await new Promise((o,s)=>{const i=t.transaction("keys").objectStore("keys").get("identity");i.onsuccess=()=>o(i.result),i.onerror=()=>s(i.error)});if(e)return Jd(e);const n=await Sp();let r=n;return await new Promise((o,s)=>{const i=t.transaction("keys","readwrite"),a=i.objectStore("keys"),c=a.get("identity");c.onsuccess=()=>{typeof c.result=="string"?r=Jd(c.result):a.put(Cx(n),"identity")},i.oncomplete=()=>o(),i.onerror=()=>s(i.error)}),r}finally{t.close()}})()),Fi}const Ye="termdock:secure-state";let J,jn,_e,dr="direct",Zo=!1,ru=0,Jo=!1,ou=-1/0;const ur=globalThis.fetch.bind(globalThis);function re(){return Nc()}function nn(){return J}function eE(){return _e}function Mp(){J?.close(),_e?.close(),J=void 0,_e=void 0}async function jp(){const t=await ur("/api/auth/status",{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error("Failed to query auth status");return t.json()}async function tE(){if(re()){await dt();return}if((await jp()).enabled)return;const t=await ur("/api/auth/open/parameters",{cache:"no-store"});if(!t.ok)throw new Error("Open service unavailable");const{serviceIdentity:e}=await t.json();if(typeof e!="string"||!e)throw new Error("Invalid service identity");await Ze({url:location.origin,targetPeerId:e,serviceName:location.hostname})}async function nE(t,e){const{startPasswordBootstrap:n,finishPasswordBootstrap:r}=await Gt(async()=>{const{startPasswordBootstrap:l,finishPasswordBootstrap:d}=await import("./passwordBootstrap-BkAa-DO2.js");return{startPasswordBootstrap:l,finishPasswordBootstrap:d}},__vite__mapDeps([0,1,2,3])),o=l=>t===location.origin?l:new URL(l,t).href,s=async(l,d)=>{const u=await ur(o(l),{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(15e3),...d?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}:{}});if(!u.ok)throw new Error(u.status===429?"尝试次数较多,请稍后再试。":u.status===401?"密码不正确,请重新输入。":"暂时无法登录这台服务,请稍后重试。");return u.json()},{saltHex:i}=await s("/api/auth/password/parameters"),a=await Qe(),c=await n(e,i);try{const l=await s("/api/auth/password/start",{startLoginRequest:c.startLoginRequest,clientIdentity:a.peerId});let d;try{d=await r(c,l,{clientIdentity:a.peerId,origin:location.origin})}catch{throw new Error("密码不正确,或服务身份无法验证。请检查后重试。")}return await s("/api/auth/password/finish",{attemptId:d.attemptId,finishLoginRequest:d.finishLoginRequest}),{url:t,targetPeerId:d.serverIdentity,serviceName:new URL(t).host,serviceOrigin:t}}finally{c.passwordKey=""}}async function cl(t,e){const n=re();if(n&&(n.serviceOrigin||n.url)===t)return await ec(n,e),n;try{return await nE(t,e)}catch(r){if(!(r instanceof TypeError)&&!(r instanceof DOMException))throw r;const o=(await He()).find(i=>i.targetPeerId&&(i.serviceOrigin||i.url)===t);if(!o?.targetPeerId)throw new Error("暂时连不上这台服务,请检查地址和网络。");const s={...o,targetPeerId:o.targetPeerId,serviceName:o.label};return await ec(s,e),s}}async function ec(t,e){const n=await ll(t),{startPasswordBootstrap:r,finishPasswordBootstrap:o}=await Gt(async()=>{const{startPasswordBootstrap:i,finishPasswordBootstrap:a}=await import("./passwordBootstrap-BkAa-DO2.js");return{startPasswordBootstrap:i,finishPasswordBootstrap:a}},__vite__mapDeps([0,1,2,3]));let s;try{const i=await n.request({type:"password-parameters"},{timeoutMs:5e3});s=await r(e,String(i.saltHex));const a=await n.request({type:"password-start",startLoginRequest:s.startLoginRequest,origin:location.origin}),c=await o(s,a,{clientIdentity:(await Qe()).peerId,origin:location.origin});if(c.serverIdentity!==t.targetPeerId)throw new Error("服务身份发生变化。");await n.request({type:"password-finish",attemptId:c.attemptId,finishLoginRequest:c.finishLoginRequest})}catch{throw new Error("暂时无法登录,请检查目标服务密码与入口授权后重试。")}finally{s&&(s.passwordKey=""),n.close()}}async function rE(t){try{const e=re(),n=e?.serviceOrigin||location.origin,r=await cl(n,t);return await Ze({...r,routes:e?.routes,serviceName:e?.serviceName||r.serviceName}),Response.json({ok:!0})}catch(e){return Response.json({error:e instanceof Error?e.message:"暂时无法登录,请重试。",code:"INVALID_PASSWORD"},{status:401})}}async function su(t,e){const n=Oe(t),r=(await He()).find(i=>(i.serviceOrigin||i.url)===n&&i.targetPeerId);if(e===void 0&&r?.targetPeerId)try{return await Ze({...r,targetPeerId:r.targetPeerId,serviceName:r.label}),{}}catch(i){if(!(i instanceof Je))throw i}if(e!==void 0){const i=await cl(n,e);if(r?.targetPeerId&&r.targetPeerId!==i.targetPeerId)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await Ze({...i,routes:r?.routes,serviceName:r?.label||i.serviceName}),{}}const o=await ur(new URL("/api/auth/open/parameters",n).href,{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(1e4)}).catch(()=>{throw new Error("暂时连不上这台服务,请检查地址和网络后重试。")});if(o.status===403)return{passwordRequired:!0};if(!o.ok)throw new Error("这台服务暂时不可用,请稍后重试。");const{serviceIdentity:s}=await o.json();if(typeof s!="string"||!s)throw new Error("这不是可连接的 Termdock 服务。");if(r?.targetPeerId&&r.targetPeerId!==s)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await Ze({url:n,targetPeerId:s,serviceName:r?.label||new URL(n).host,serviceOrigin:n}),{}}function Vt(t){const e=[...t.routes||[]];if(t.entryServiceId&&t.entryServiceId!==t.targetPeerId&&e.unshift({url:t.url,targetPeerId:t.entryServiceId}),!e.length&&t.routes===void 0)try{const n=JSON.parse(localStorage.getItem(Pc)||"null");n&&n.targetPeerId!==t.targetPeerId&&new URL(n.url).host===new URL(t.url).host&&e.push(n)}catch{}return e.flatMap((n,r)=>{try{return n.targetPeerId&&n.targetPeerId!==t.targetPeerId&&e.findIndex(o=>o.targetPeerId===n.targetPeerId)===r?[{url:Oe(n.url),targetPeerId:n.targetPeerId}]:[]}catch{return[]}}).slice(0,4)}function wr(t){const e=Vt(t),n=[t.serviceOrigin||t.url,...(t.routes||[]).slice(0,4).filter(o=>o.targetPeerId===t.targetPeerId).map(o=>o.url)],r=new Set;for(const o of n)try{const s=Oe(o);e.some(i=>i.url===s)||r.add(s)}catch{}return[...r]}function bn(t){const e=new URL("/api/federation/secure",Oe(t));return e.protocol=e.protocol==="https:"?"wss:":"ws:",e.href}async function Xt(t,e){return yn({url:bn(t.url),targetPeerId:t.targetPeerId,identity:await Qe(),signal:e?AbortSignal.any([e,AbortSignal.timeout(5e3)]):AbortSignal.timeout(5e3)})}async function ll(t,e){const n=await Qe(),r=wr(t).map(i=>({key:`direct:${i}`,run:a=>yn({url:bn(i),targetPeerId:t.targetPeerId,identity:n,signal:AbortSignal.any([a,AbortSignal.timeout(8e3),...e?[e]:[]])})}));for(const i of Vt(t))r.push({key:`relay:${i.targetPeerId}:${i.url}`,run:async a=>{e&&(a=AbortSignal.any([a,e]));const c=[J,_e].find(d=>d&&!d.closed&&d.targetPeerId===i.targetPeerId),l=c||await Xt(i,a);try{if(a.aborted)throw a.reason;const d=await l.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(a.aborted)throw a.reason;if(typeof d.routeToken!="string")throw new Error("入口未允许此设备连接该服务。");const u=new URL(bn(i.url));return u.pathname="/api/federation/relay",u.searchParams.set("routeToken",d.routeToken),await yn({url:u.href,targetPeerId:t.targetPeerId,identity:n,socketFactory:Pp(t.targetPeerId),signal:AbortSignal.any([a,AbortSignal.timeout(8e3)])})}finally{c||l.close()}}});const o=Lp(t.targetPeerId);r.sort((i,a)=>+(a.key===o)-+(i.key===o));const s=await Bp(r,i=>i.close());return Za(t.targetPeerId,s.key),s.value}async function oE(t,e){const n=await ll(t,e);try{const o=(await n.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node;if(o?.serviceId!==t.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");return{...o,serviceId:t.targetPeerId}}finally{n.close()}}async function sE(t,e){const n=await ll(t,e),r=()=>n.close();e.addEventListener("abort",r,{once:!0});try{if(e.aborted||(await mr(n,{timeoutMs:3e3}),e.aborted))throw e.reason;return n}catch(o){throw n.close(),o}finally{e.removeEventListener("abort",r)}}async function Ze(t,e={}){const n=J,r=_e,o=await Qe(),s=Oe(t.serviceOrigin||t.url),i=(await He()).find(w=>w.targetPeerId===t.targetPeerId),a={...t,routes:t.routes??i?.routes},c=Vt(a),l=wr(a);let d,u,f=t.pairingCode,h="direct";const g=new Set,m=new Map,b=async(w,I)=>{if(n&&!n.closed&&n.targetPeerId===w.targetPeerId)return n;if(r&&!r.closed&&r.targetPeerId===w.targetPeerId)return r;const y=m.get(w.targetPeerId);if(y&&!y.closed)return y;const v=await Xt(w,I);return g.add(v),m.set(w.targetPeerId,v),v};try{if(t.routeCode&&t.entryServiceId){const E=c.find(N=>N.targetPeerId===t.entryServiceId);if(!E)throw new Error("邀请缺少入口信息。");if((await(await b(E)).request({type:"route-pair",code:t.routeCode})).serviceId!==t.targetPeerId)throw new Error("邀请的目标服务不一致。");t.routeOnly&&await Ct({id:t.targetPeerId,url:s,label:t.serviceName||new URL(s).host,targetPeerId:t.targetPeerId,serviceOrigin:s,routes:c})}const w=[],I=async(E,S)=>{const k=()=>E.close();S.addEventListener("abort",k,{once:!0});try{if(S.aborted||(await mr(E),S.aborted))throw S.reason}catch(N){throw E.close(),N}finally{S.removeEventListener("abort",k)}};for(const E of l)w.push({key:`direct:${E}`,run:async S=>{const k=await yn({url:bn(E),targetPeerId:t.targetPeerId,pairingCode:f,identity:o,signal:AbortSignal.any([S,AbortSignal.timeout(8e3)])});return f=void 0,await I(k,S),{client:k,path:"direct"}}});for(const E of c)w.push({key:`relay:${E.targetPeerId}:${E.url}`,run:async S=>{let k,N;try{if(k=await b(E,S),S.aborted)throw S.reason;const D=await k.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(S.aborted)throw S.reason;if(typeof D.routeToken!="string"||!D.routeToken)throw new Error("入口未允许此设备连接该服务。");const A=new URL(bn(E.url));return A.pathname="/api/federation/relay",A.searchParams.set("routeToken",D.routeToken),N=await yn({url:A.href,targetPeerId:t.targetPeerId,pairingCode:f,identity:o,socketFactory:Pp(t.targetPeerId),signal:AbortSignal.any([S,AbortSignal.timeout(8e3)])}),f=void 0,await I(N,S),{client:N,entry:k,path:"relay"}}catch(D){throw N?.close(),k&&k!==r&&k!==n&&k.close(),D}}});const y=Lp(t.targetPeerId);w.sort((E,S)=>+(S.key===y)-+(E.key===y));const v=await Bp(w,E=>{E.client.close(),E.entry&&E.entry!==n&&E.entry!==r&&E.entry.close()},!!f);if(d=v.value.client,u=v.value.entry,h=v.value.path,e.renewIfCurrent){if(J!==e.renewIfCurrent||n!==e.renewIfCurrent||n.closed||!n.canSwitchTransport||re()?.targetPeerId!==t.targetPeerId){d.close();for(const E of g)E!==_e&&E!==J&&E.close();return J??n}J=d,dr=h,_e=u,Za(t.targetPeerId,v.key),n.retire();for(const E of new Set([r,...g]))E&&E!==n&&E!==d&&E!==u&&E.close();return window.dispatchEvent(new Event(Ye)),d}if(Za(t.targetPeerId,v.key),J!==n&&J&&!J.closed&&J.targetPeerId===t.targetPeerId){d.close();for(const E of g)E!==_e&&E.close();return J}h==="direct"&&new URL(s).host===location.host&&Cm(t.targetPeerId);const L=(await He()).find(E=>E.targetPeerId===t.targetPeerId||!E.targetPeerId&&(E.serviceOrigin||E.url)===s),C=L?.label||t.serviceName||new URL(s).host,T={url:s,targetPeerId:t.targetPeerId,serviceName:C,serviceOrigin:s,routes:a.routes??c};if(await(e.rememberOnly?Rm:Ct)({id:L?.id||t.targetPeerId,...T,label:C}),Kn!=="unpaired"&&Kn!==t.targetPeerId&&ut()&&Ns({id:L?.id||t.targetPeerId,...T,label:C})){d.close();for(const E of g)E!==n&&E!==r&&E.close();return n||d}vf(T),J=d,dr=h,_e=u;for(const E of new Set([n,r,...g]))E&&E!==d&&E!==u&&E.close();return Kn!==t.targetPeerId?(location.reload(),new Promise(()=>{})):(window.dispatchEvent(new Event(Ye)),d)}catch(w){d?.close();for(const I of g)I!==r&&I.close();throw w}}async function iE(){const t=J,e=re();if(!(Jo||Zo||jn||!t?.renewalDue||!t.canSwitchTransport||!e||performance.now()-ou<3e4)){ou=performance.now(),Jo=!0;try{await Ze(e,{renewIfCurrent:t})}catch(n){console.debug("[connection] renewal deferred",{reason:n instanceof Error?n.message:"unknown"})}finally{Jo=!1}}}async function aE(){const t=J,e=re();if(Date.now()-ru<6e4||Jo||Zo||dr!=="relay"||!t||t.closed||!t.canSwitchTransport||!e?.serviceOrigin)return;Zo=!0,ru=Date.now();let n;try{for(const o of wr(e))try{n=await yn({url:bn(o),targetPeerId:e.targetPeerId,identity:await Qe(),signal:AbortSignal.timeout(3e3)}),await mr(n);break}catch(s){if(n?.close(),n=void 0,s instanceof Je)throw s}if(!n||J!==t||!t.canSwitchTransport)return;const r=_e;J=n,n=void 0,_e=void 0,dr="direct",t.close(),r?.close(),window.dispatchEvent(new Event(Ye))}catch(r){r instanceof Je&&J===t&&(Mp(),window.dispatchEvent(new Event("auth:unauthorized")))}finally{n?.close(),Zo=!1}}function cE(){return dr}async function lE(t){return t?(t.throwIfAborted(),new Promise((e,n)=>{const r=()=>n(t.reason);t.addEventListener("abort",r,{once:!0}),dt().then(o=>{t.removeEventListener("abort",r),t.aborted?n(t.reason):e(o)},o=>{t.removeEventListener("abort",r),n(o)})})):dt()}async function dt(){if(J&&!J.closed){const e=J;return iE(),e}if(J=void 0,jn)return jn;const t=re();if(!t)throw new Error("DEVICE_PAIRING_REQUIRED");return jn=Ze(t,{rememberOnly:!0}).catch(e=>{if(J&&!J.closed&&J.targetPeerId===t.targetPeerId)return J;throw e}).finally(()=>{jn=void 0}),jn}function Up(t){const e=new URL(t,location.href);if(J&&!J.closed)return J.openSocket(e.pathname+e.search);let n;const r=new Tp(t,o=>n?.send(o),()=>n?.close());return dt().then(o=>{r.readyState!==3&&(n=o.openSocket(e.pathname+e.search),n.onopen=()=>r.accept({type:"ws-ready",id:""}),n.onmessage=s=>r.accept({type:"ws-data",id:"",data:s.data}),n.onclose=s=>r.accept({type:"ws-close",id:"",code:s.code,reason:s.reason}),n.onerror=()=>r.fail(new Error("Encrypted connection unavailable")))}).catch(o=>r.fail(o)),r}function dE(){qx(dt),window.fetch=async(t,e)=>{const n=new URL(t instanceof Request?t.url:String(t),location.href);if(!n.pathname.startsWith("/api/"))return ur(t,e);if(n.origin!==location.origin)throw new Error("Remote business API requires a paired encrypted service");if(n.pathname==="/api/meta")return ur(t,e);if(n.pathname==="/api/auth/status"){if(!re()){const s=await jp();return Response.json({enabled:s.enabled,authenticated:!1})}try{const s=await mr(await dt());return Response.json({enabled:s.grants.length>0,authenticated:!0})}catch(s){if(s instanceof Je)return Response.json({enabled:!0,authenticated:!1});throw s}}if(n.pathname==="/api/auth/login"){const i=await new Request(t instanceof Request?t:n.href,e).json();return rE(typeof i.password=="string"?i.password:"")}if(n.pathname==="/api/csrf-token")return Response.json({csrfToken:"encrypted-device-channel"});if(n.pathname==="/api/auth/logout")return J&&!J.closed&&await J.request({type:"logout"}),J?.close(),_e?.close(),J=void 0,_e=void 0,km(),location.reload(),Response.json({ok:!0});const r=e?.signal!==void 0?e.signal:t instanceof Request?t.signal:void 0,o=await lE(r);return t instanceof Request?o.fetch(t,e):o.fetch(n.pathname+n.search,e)}}async function uE(t){if(!t.targetPeerId)throw new Error("请先连接这台服务,再查看可中转的服务。");for(const e of wr({...t,targetPeerId:t.targetPeerId})){let n;const r={url:e,targetPeerId:t.targetPeerId};try{n=await Xt(r)}catch{continue}try{const o=await n.request({type:"route-targets"},{timeoutMs:5e3});if(!Array.isArray(o.items))throw new Error("入口服务需要更新后才能查看中转列表。");return{route:r,canManage:o.canManage===!0,items:o.items}}catch(o){throw o instanceof Error&&/UNKNOWN|UNSUPPORTED/i.test(o.message)?new Error("入口服务需要更新后才能查看中转列表。"):o}finally{n.close()}}throw new Error("暂时连不上中转入口,请检查地址和网络后重试。")}async function fE(t,e){const n=await Xt(t);try{const r=await n.request({type:"route-targets"},{timeoutMs:5e3}),o=(Array.isArray(r.items)?r.items:[]).find(c=>c.serviceId===e);if(!o)throw new Error("该服务已不可见,请刷新列表或请入口管理员授权。");if(!o.available)throw new Error("入口暂时无法中转到这台服务,请稍后重试。");const s=(await He()).find(c=>c.targetPeerId===o.serviceId),i=[t,...(s?.routes||[]).filter(c=>c.targetPeerId!==t.targetPeerId)];if(i.length>4)throw new Error("这台服务已保存 4 个备用连接,请先移除一个后重试。");if(!o.authorized){if(!r.canManage)throw new Error("请先让入口管理员授权此设备。");await n.request({type:"route-grant",serviceId:o.serviceId,subjectId:(await Qe()).peerId})}const a=s?.serviceOrigin||s?.url||o.url||t.url;return{url:a,serviceOrigin:a,targetPeerId:o.serviceId,serviceName:s?.label||o.label||(o.url?new URL(o.url).host:`中转服务 ${o.serviceId.slice(0,8)}`),routes:i}}finally{n.close()}}async function hE(t,e){const n=await Xt(t);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),o=(await Qe()).peerId;return{canManage:r.canManage===!0,grants:(Array.isArray(r.grants)?r.grants:[]).filter(s=>s.subjectId===o&&s.targetServiceId===e)}}finally{n.close()}}async function pE(t,e,n){if(n!==void 0&&(await cl(Oe(e.url),n)).targetPeerId!==e.targetPeerId)throw new Error("入口服务的身份已改变,请重新连接并确认。");const r=await Xt(e);try{await r.request({type:"route-grant",serviceId:t.targetPeerId,subjectId:(await Qe()).peerId,url:Oe(t.serviceOrigin||t.url)})}finally{r.close()}}async function gE(t,e){const n=await Xt(e);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),o=(await Qe()).peerId,s=(Array.isArray(r.grants)?r.grants:[]).filter(i=>i.subjectId===o&&i.targetServiceId===t&&i.active);for(const i of s)await n.request({type:"route-revoke",grantId:i.id})}finally{n.close()}}async function $p(t,e){const n=await Xt(e);try{const r=await n.request({type:"route-invite-create",serviceId:t.targetPeerId});if(typeof r.routeCode!="string"||typeof r.expiresAt!="number")throw new Error("暂时无法生成备用连接邀请。");return{routeCode:r.routeCode,expiresAt:r.expiresAt}}finally{n.close()}}async function Qo(t,e){const n=(await He()).find(o=>o.id===t.id||t.targetPeerId&&o.targetPeerId===t.targetPeerId)||t;await Ct({...n,url:n.serviceOrigin||n.url,entryServiceId:void 0,routes:e});const r=re();r&&r.targetPeerId===t.targetPeerId&&vf({...r,url:r.serviceOrigin||r.url,entryServiceId:void 0,routes:e})}async function mE(t,e){const n=t.targetPeerId;if(!n)throw new Error("请先连接这台服务,再添加备用地址。");let r;try{r=Oe(e)}catch{throw new Error("请输入有效的 HTTPS 地址,例如 https://电脑地址:9834。")}const o=async()=>(await He()).find(a=>a.targetPeerId===n)||t,s=a=>{const c=a.routes??Vt({...a,targetPeerId:n});if(Oe(a.serviceOrigin||a.url)===r||c.some(l=>Oe(l.url)===r))throw new Error("这个地址已经在连接列表中。");if(c.length>=4)throw new Error("最多保存 4 个备用地址或入口,请先移除不再使用的连接。");return[...c,{url:r,targetPeerId:n}]};s(await o());let i;try{try{i=await yn({url:bn(r),targetPeerId:n,identity:await Qe(),signal:AbortSignal.timeout(5e3)}),await mr(i)}catch(l){throw l instanceof Je?new Error("这台服务尚未授权当前设备,请先恢复设备授权。"):new Error("无法验证这个地址。请确认能访问该地址、HTTPS 证书受信任,且运行的是同一台 Termdock 服务。")}const a=await o(),c=s(a);if(await Qo(a,c),re()?.targetPeerId===n&&Kn===n&&(!J||J.closed)){const l=J,d=_e;J=i,i=void 0,_e=void 0,dr="direct",l?.close(),d?.close(),window.dispatchEvent(new Event(Ye))}return c}finally{i?.close()}}async function iu(t,e){await ec(t,e),await Ze({...t,pairingCode:void 0,routeCode:void 0})}function wE(){let t=!1,e=!1,n=!1,r;const o=new Map,s=new Map,i=async(u,f,h)=>{const g=JSON.stringify(h);if(o.get(f.serviceId)===g)return;const m=AbortSignal.timeout(1e4),b=await u.fetch("/api/csrf-token",{signal:m});if(!b.ok)throw new Error("CONNECTION_AUTHORIZATION_REQUIRED");const w=await b.json();if(typeof w.csrfToken!="string")throw new Error("INVALID_CSRF_TOKEN");const I=await u.fetch("/api/terminal/operations/collaboration-connections",{method:"POST",signal:m,headers:{"Content-Type":"application/json","X-XSRF-TOKEN":w.csrfToken},body:JSON.stringify({origin:f.origin,nodes:h})});if(!I.ok){const y=await I.json().catch(()=>({}));throw new Error(y.error||`HTTP_${I.status}`)}o.set(f.serviceId,g)},a=async()=>{if(t){n=!0;return}const u=re(),f=nn();if(!(e||!u||!f||f.closed)){t=!0,n=!1;try{let h;const g=await Promise.race([He(),new Promise((v,L)=>{h=setTimeout(()=>L(new Error("SERVICE_DIRECTORY_TIMEOUT")),8e3)})]).finally(()=>clearTimeout(h));g.some(v=>v.targetPeerId===u.targetPeerId)||g.push({...u,id:u.targetPeerId,label:u.serviceName||u.url});const m=[...new Map(g.filter(v=>!!v.targetPeerId).map(v=>[v.targetPeerId,v])).values()].slice(0,64);if(m.length<2)return;const b=[];for(const v of m)try{const L=`${v.targetPeerId}:${v.serviceOrigin||v.url}`;let C=s.get(L);if(!C){const T=v.targetPeerId===u.targetPeerId?(await f.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node:await oE({...v,targetPeerId:v.targetPeerId},AbortSignal.timeout(8e3));if(T?.serviceId!==v.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");const E=T.origin||v.serviceOrigin||v.url,S=new URL(E);if(S.protocol!=="https:"||S.origin!==E)throw new Error("INVALID_SERVICE_ORIGIN");C={serviceId:T.serviceId,origin:E,...T.caFingerprint256?{caFingerprint256:T.caFingerprint256}:{}},s.set(L,C)}b.push({service:v,node:C})}catch{}if(e||nn()!==f||re()?.targetPeerId!==u.targetPeerId)return;const w=b.find(v=>v.node.serviceId===u.targetPeerId);if(!w||b.length<2){c(3e4);return}const I=b.map(v=>v.node).sort((v,L)=>v.serviceId.localeCompare(L.serviceId));await i(f,w.node,I);let y=b.length<m.length;for(const v of b){if(v===w||o.get(v.node.serviceId)===JSON.stringify(I))continue;let L;try{L=await sE({...v.service,targetPeerId:v.node.serviceId},AbortSignal.timeout(8e3)),await i(L,v.node,I)}catch{y=!0}finally{L?.close()}}window.dispatchEvent(new CustomEvent("termdock:collaboration-enrollment",{detail:{ok:!0}})),y&&c(3e4)}catch(h){window.dispatchEvent(new CustomEvent("termdock:collaboration-enrollment",{detail:{ok:!1,error:h instanceof Error?h.message:"CONNECTION_ENROLLMENT_FAILED"}})),c(3e4)}finally{t=!1,n&&c(100)}}};function c(u=100){e||(clearTimeout(r),r=setTimeout(()=>{a()},u))}const l=()=>{c()},d=Hs(l);window.addEventListener(Ye,l),window.addEventListener("termdock:collaboration-enroll",l),window.addEventListener("online",l),window.addEventListener("pageshow",l),window.addEventListener("pagehide",u=>{u.persisted||(e=!0,clearTimeout(r),d(),window.removeEventListener("termdock:collaboration-enroll",l),window.removeEventListener(Ye,l),window.removeEventListener("online",l),window.removeEventListener("pageshow",l))}),c()}var jo={},au;function yE(){if(au)return jo;au=1;var t=mm();return jo.createRoot=t.createRoot,jo.hydrateRoot=t.hydrateRoot,jo}var bE=yE();const vE=bf(bE);const Hp=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim();const SE=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const xE=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,r)=>r?r.toUpperCase():n.toLowerCase());const cu=t=>{const e=xE(t);return e.charAt(0).toUpperCase()+e.slice(1)};var Mi={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const EE=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1},AE=_.createContext({}),kE=()=>_.useContext(AE),CE=_.forwardRef(({color:t,size:e,strokeWidth:n,absoluteStrokeWidth:r,className:o="",children:s,iconNode:i,...a},c)=>{const{size:l=24,strokeWidth:d=2,absoluteStrokeWidth:u=!1,color:f="currentColor",className:h=""}=kE()??{},g=r??u?Number(n??d)*24/Number(e??l):n??d;return _.createElement("svg",{ref:c,...Mi,width:e??l??Mi.width,height:e??l??Mi.height,stroke:t??f,strokeWidth:g,className:Hp("lucide",h,o),...!s&&!EE(a)&&{"aria-hidden":"true"},...a},[...i.map(([m,b])=>_.createElement(m,b)),...Array.isArray(s)?s:[s]])});const xe=(t,e)=>{const n=_.forwardRef(({className:r,...o},s)=>_.createElement(CE,{ref:s,iconNode:e,className:Hp(`lucide-${SE(cu(t))}`,`lucide-${t}`,r),...o}));return n.displayName=cu(t),n};const IE=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],qp=xe("arrow-left",IE);const RE=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],TE=xe("arrow-right",RE);const PE=[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]],NE=xe("arrow-up-right",PE);const LE=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M11.68 2.009A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673c-.824-.85-1.678-1.731-2.21-3.348",key:"xaq59h"}],["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}]],Kp=xe("bell-dot",LE);const BE=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],dl=xe("check",BE);const _E=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],zp=xe("chevron-down",_E);const OE=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],vn=xe("chevron-right",OE);const DE=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],FE=xe("chevron-up",DE);const ME=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Wp=xe("copy",ME);const jE=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],Vp=xe("ellipsis",jE);const UE=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],De=xe("loader-circle",UE);const $E=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],HE=xe("monitor",$E);const qE=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],KE=xe("pencil",qE);const zE=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Gp=xe("plus",zE);const WE=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],ri=xe("server",WE);const VE=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],Xp=xe("smartphone",VE);const GE=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],XE=xe("terminal",GE);const YE=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Yp=xe("x",YE),ZE={},lu=t=>{let e;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(e):d;if(!Object.is(f,e)){const h=e;e=u??(typeof f!="object"||f===null)?f:Object.assign({},e,f),n.forEach(g=>g(e,h))}},o=()=>e,c={setState:r,getState:o,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(ZE?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},l=e=t(r,o,c);return c},JE=t=>t?lu(t):lu;var ji={exports:{}},Ui={},$i={exports:{}},Hi={};var du;function QE(){if(du)return Hi;du=1;var t=Rc();function e(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var n=typeof Object.is=="function"?Object.is:e,r=t.useState,o=t.useEffect,s=t.useLayoutEffect,i=t.useDebugValue;function a(u,f){var h=f(),g=r({inst:{value:h,getSnapshot:f}}),m=g[0].inst,b=g[1];return s(function(){m.value=h,m.getSnapshot=f,c(m)&&b({inst:m})},[u,h,f]),o(function(){return c(m)&&b({inst:m}),u(function(){c(m)&&b({inst:m})})},[u]),i(h),h}function c(u){var f=u.getSnapshot;u=u.value;try{var h=f();return!n(u,h)}catch{return!0}}function l(u,f){return f()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?l:a;return Hi.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:d,Hi}var uu;function e1(){return uu||(uu=1,$i.exports=QE()),$i.exports}var fu;function t1(){if(fu)return Ui;fu=1;var t=Rc(),e=e1();function n(l,d){return l===d&&(l!==0||1/l===1/d)||l!==l&&d!==d}var r=typeof Object.is=="function"?Object.is:n,o=e.useSyncExternalStore,s=t.useRef,i=t.useEffect,a=t.useMemo,c=t.useDebugValue;return Ui.useSyncExternalStoreWithSelector=function(l,d,u,f,h){var g=s(null);if(g.current===null){var m={hasValue:!1,value:null};g.current=m}else m=g.current;g=a(function(){function w(C){if(!I){if(I=!0,y=C,C=f(C),h!==void 0&&m.hasValue){var T=m.value;if(h(T,C))return v=T}return v=C}if(T=v,r(y,C))return T;var E=f(C);return h!==void 0&&h(T,E)?(y=C,T):(y=C,v=E)}var I=!1,y,v,L=u===void 0?null:u;return[function(){return w(d())},L===null?void 0:function(){return w(L())}]},[d,u,f,h]);var b=o(l,g[0],g[1]);return i(function(){m.hasValue=!0,m.value=b},[b]),c(b),b},Ui}var hu;function n1(){return hu||(hu=1,ji.exports=t1()),ji.exports}var r1=n1();const o1=bf(r1),Zp={},{useDebugValue:s1}=ze,{useSyncExternalStoreWithSelector:i1}=o1;let pu=!1;const a1=t=>t;function c1(t,e=a1,n){(Zp?"production":void 0)!=="production"&&n&&!pu&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),pu=!0);const r=i1(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,n);return s1(r),r}const gu=t=>{(Zp?"production":void 0)!=="production"&&typeof t!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof t=="function"?JE(t):t,n=(r,o)=>c1(e,r,o);return Object.assign(n,e),n},oi=t=>t?gu(t):gu,ul=t=>`@collaboration:${t}`,Jp=oi(t=>({activePaneId:null,setActivePane:e=>t({activePaneId:e}),docks:{},hosts:{},setDock:(e,n)=>t(r=>{const o={...r.docks};return n?o[e]=n:delete o[e],{docks:o,...!n&&r.activePaneId===ul(e)?{activePaneId:r.docks[e]?.sessionId??null}:{}}}),setHost:(e,n)=>t(r=>{const o={...r.hosts};return n?o[e]=n:delete o[e],{hosts:o}})})),ln=new Map;let Yr;function Qp(){const t=Jp.getState().activePaneId;for(const[n,r]of ln)if(r.requiresFocus&&t===ul(n))return r.receive;const e=ln.get(Yr??"");return e&&!e.requiresFocus?e.receive:void 0}function GI(t){const e=ln.get(t);e&&(e.requiresFocus?Jp.getState().setActivePane(ul(t)):Yr=t)}function l1(t){const e=Qp();return!e||!t?!1:(e(t),!0)}function XI(t,e="default",n=!1){ln.set(e,{receive:t,requiresFocus:n}),n||(Yr=e);const r=o=>{const{text:s,nonce:i}=o.detail??{};!s||Qp()!==t||(t(s),o.stopImmediatePropagation(),i&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:i,ok:!0}})))};return window.addEventListener("termdock-insert-reference",r,!0),()=>{ln.get(e)?.receive===t&&(ln.delete(e),Yr===e&&(Yr=[...ln.keys()].at(-1))),window.removeEventListener("termdock-insert-reference",r,!0)}}const d1=/^[A-Za-z0-9_@%+=:,./-]$/;function u1(t){return Array.from(t,e=>(e.codePointAt(0)??0)>127||d1.test(e)?e:`\\${e}`).join("")}function f1(t,e){if(!e)return!1;try{const n=new URL(e.serviceOrigin||e.url);return n.origin===t&&/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})$/.test(n.hostname)&&!(e.routes??[]).some(r=>r.targetPeerId!==e.targetPeerId)}catch{return!1}}function h1(t){const e=s=>s.target instanceof Element?s.target.closest("[data-termdock-terminal-dropzone]"):null,n=()=>!f1(location.origin,Nc()),r=s=>{const i=e(s);!i||!n()||!s.dataTransfer?.types.includes("Files")||(s.preventDefault(),s.stopImmediatePropagation(),s.dataTransfer.dropEffect="copy",i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="remote")},o=s=>{const i=e(s),a=Array.from(s.dataTransfer?.files??[]);if(!i||!a.length||!n())return;s.preventDefault(),s.stopImmediatePropagation();const c=i.dataset.termdockTerminalDropzone??"";i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="uploading",Gt(async()=>{const{uploadFiles:l}=await Promise.resolve().then(()=>E2);return{uploadFiles:l}},void 0).then(({uploadFiles:l})=>l("/tmp",a)).then(l=>{if(l.files.length!==a.length||l.files.some(d=>!d.path))throw new Error("Upload did not return every file path");delete i.dataset.nativeFileDrag,delete i.dataset.nativeFileDropState,t({sessionKey:c,paths:l.files.map(d=>d.path)})}).catch(l=>{i.dataset.nativeFileDropState="error",i.dispatchEvent(new CustomEvent("termdock:file-drop-error",{bubbles:!0,detail:l instanceof Error?l.message:"File upload failed"})),window.setTimeout(()=>{i.dataset.nativeFileDropState==="error"&&(delete i.dataset.nativeFileDrag,delete i.dataset.nativeFileDropState)},3e3)})};return window.addEventListener("dragover",r,!0),window.addEventListener("drop",o,!0),()=>{window.removeEventListener("dragover",r,!0),window.removeEventListener("drop",o,!0)}}function et(){return typeof window>"u"?null:window.termdockDesktop??null}const qi=new Set;let mu=!1;function YI(t){const e=et();if(!e)return()=>{};if(qi.add(t),!mu){const n=r=>{if(!l1(r.paths.map(u1).join(" ")+" "))for(const o of qi)o(r)};h1(n),e.onNativeFileDrop(n),mu=!0}return()=>{qi.delete(t)}}function eg(t=navigator.userAgent,e=navigator.maxTouchPoints){const n=/iPad/.test(t)||/Macintosh/.test(t)&&e>1?"iPad":/iPhone/.test(t)?"iPhone":/Android/.test(t)?"Android":/Windows/.test(t)?"Windows":/Macintosh|Mac OS X/.test(t)?"Mac":/Linux/.test(t)?"Linux":"设备",r=/Electron/.test(t)?"Termdock":/Edg\//.test(t)?"Edge":/Firefox|FxiOS/.test(t)?"Firefox":/Chrome|CriOS/.test(t)?"Chrome":/Safari/.test(t)?"Safari":"浏览器";return`${n} · ${r}`}let p1;function g1(){return p1??=(async()=>{const t=navigator.userAgent,[e,n]=eg().split(" · "),r=/(?:Edg|Firefox|FxiOS|Chrome|CriOS|Version)\/([\d.]+)/g,o=[...t.matchAll(r)],s=/(?:CPU (?:iPhone )?OS |Mac OS X |Android )([\d._]+)/.exec(t)?.[1]?.replaceAll("_","."),i={system:`${e}${s?` ${s}`:""}`,client:`${n}${o.length?` ${o.at(-1)[1]}`:""}`,mode:matchMedia("(display-mode: standalone)").matches||navigator.standalone?"已安装的网页应用":"网页"},a=et();if(a){i.mode="桌面客户端";const l=/Electron\/([\d.]+)/.exec(t)?.[1];i.client=l?`Termdock(Electron ${l})`:"Termdock";try{Object.assign(i,await a.deviceInfo?.())}catch{}return i}const c=navigator.userAgentData;try{const l=await c?.getHighEntropyValues(["model","architecture","bitness","platformVersion"]);typeof l?.model=="string"&&l.model&&(i.model=l.model),typeof l?.architecture=="string"&&l.architecture&&(i.arch=`${l.architecture}${l.bitness?` ${l.bitness} 位`:""}`)}catch{}return i})()}function m1({service:t,onBusyChange:e,onConnect:n,onConnectWithPassword:r}){const[o,s]=_.useState(),[i,a]=_.useState(!0),[c,l]=_.useState(!1),[d,u]=_.useState(""),[f,h]=_.useState(0),[g,m]=_.useState(),[b,w]=_.useState("");_.useEffect(()=>{let v=!1;return a(!0),u(""),s(void 0),uE(t).then(L=>{v||s(L)}).catch(L=>{v||u(L instanceof Error?L.message:"暂时无法读取中转列表,请重试。")}).finally(()=>{v||a(!1)}),()=>{v=!0}},[t.id,t.url,f]);const I=async v=>{if(!c){l(!0),e(!0),u("");try{await v()}catch(L){u(L instanceof Error?L.message:"暂时无法连接,请重试。")}finally{l(!1),e(!1)}}},y=async v=>{const L=await fE(o.route,v.serviceId);try{await n(L)}catch(C){if(!(C instanceof Je))throw C;m(L)}};return p.jsxs("div",{className:"service-form",children:[g?p.jsxs("form",{className:"service-form",onSubmit:v=>{v.preventDefault(),I(async()=>{try{await r?.(g,b)}finally{w("")}})},children:[p.jsxs("p",{className:"service-help",children:["已通过“",t.label,"”连接到“",g.serviceName,"”。请登录目标服务,完成此设备的访问授权。"]}),r?p.jsxs(p.Fragment,{children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"目标服务密码"}),p.jsx("input",{type:"password",autoFocus:!0,required:!0,autoComplete:"current-password",value:b,disabled:c,onChange:v=>w(v.target.value)})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:c||!b,children:c?"正在登录…":"登录并连接"})]}):p.jsx("p",{className:"service-help",children:"请让目标服务管理员邀请此设备后再连接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>{m(void 0),w(""),u(""),h(v=>v+1)},children:"返回中转列表"})]}):p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["通过“",t.label,"”连接下方服务。",o?.canManage?"选择未授权的服务会授权此设备使用该中转。":"这里只显示已授权给此设备的中转。","目标服务会单独验证访问权限。"]}),i?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(De,{size:16,className:"service-spinning"}),"正在读取可中转的服务…"]}):o&&p.jsxs("div",{className:"service-list",children:[o.items.map(v=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:c||!v.available,onClick:()=>{I(()=>y(v))},children:[p.jsx("span",{className:"service-icon",children:p.jsx(ri,{size:19})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:v.label||(v.url?new URL(v.url).host:`中转服务 ${v.serviceId.slice(0,8)}`)}),p.jsx("span",{className:"service-description",children:v.available?v.authorized?"已获中转授权 · 连接":"授权此设备并连接":"中转暂不可用"})]}),p.jsx(vn,{size:16})]},v.serviceId)),o.items.length===0&&p.jsx("p",{className:"service-empty",children:o.canManage?"暂无可中转的服务。可在本机 Mac 客户端连接目标服务,或在目标服务的“备用连接”中启用本入口。":"暂无已授权的中转服务,请让入口管理员分享备用连接邀请。"})]}),c&&p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(De,{size:16,className:"service-spinning"}),"正在授权并连接目标服务…"]}),!i&&p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>h(v=>v+1),children:"刷新列表"})]}),d&&p.jsx("p",{className:"service-error",role:"alert",children:d})]})}const tc="#termdock-invite=";function tg(t){const e=new URL(t.entryUrl);e.hash="",e.search="",e.pathname="/";const n=new TextEncoder().encode(JSON.stringify(t));return e.hash=tc.slice(1)+btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.href}function Ls(t){const e=new URL(t);if(!["https:","http:"].includes(e.protocol)||!e.hash.startsWith(tc))throw new Error("这不是有效的 Termdock 邀请链接");const n=e.hash.slice(tc.length);if(n.length>8192)throw new Error("邀请链接过长");let r;try{const i=n.replace(/-/g,"+").replace(/_/g,"/");r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(atob(i),a=>a.charCodeAt(0))))}catch{throw new Error("邀请链接不完整,请重新复制")}if(r.v!==1||typeof r.serviceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(r.serviceId)||r.routeOnly!==!0&&(typeof r.code!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(r.code)))throw new Error("邀请信息无效或版本不兼容");const o=new URL(r.entryUrl);if(o.origin!==e.origin||o.username||o.password||!["https:","http:"].includes(o.protocol))throw new Error("邀请地址与服务不一致");if(o.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(o.hostname))throw new Error("远程邀请需要 HTTPS");if(r.entryServiceId!==void 0&&(typeof r.entryServiceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(r.entryServiceId)))throw new Error("邀请入口身份无效");if(r.routeCode!==void 0&&(typeof r.routeCode!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(r.routeCode)||!r.entryServiceId))throw new Error("邀请入口权限无效");if(r.routeOnly===!0&&(!r.entryServiceId||!r.routeCode||r.code!==void 0))throw new Error("备用连接邀请不完整");let s=o.origin;if(r.serviceUrl!==void 0){const i=new URL(r.serviceUrl);if(!["https:","http:"].includes(i.protocol)||i.username||i.password)throw new Error("目标服务地址无效");s=r.entryServiceId&&r.entryServiceId!==r.serviceId?i.origin:o.origin}return{url:o.origin,targetPeerId:r.serviceId,pairingCode:r.code,...r.routeOnly===!0?{routeOnly:!0}:{},serviceOrigin:s,serviceName:typeof r.name=="string"?r.name.slice(0,120):void 0,entryServiceId:r.entryServiceId,routeCode:r.routeCode}}function w1({service:t,onBusyChange:e}){const n={...t,targetPeerId:t.targetPeerId,serviceName:t.label},[r,o]=_.useState(()=>t.routes??Vt(n)),[s,i]=_.useState([]),[a,c]=_.useState(!0),[l,d]=_.useState(!1),[u,f]=_.useState(""),h=B=>{d(B),e(B)},[g,m]=_.useState(),[b,w]=_.useState(""),[I,y]=_.useState(""),[v,L]=_.useState(""),[C,T]=_.useState(!1),[E,S]=_.useState(),[k,N]=_.useState(),[D,A]=_.useState(!1);_.useEffect(()=>{let B=!1;return He().then(F=>{B||i(F.filter(U=>U.targetPeerId&&U.targetPeerId!==t.targetPeerId))}).catch(()=>{B||f("暂时无法读取可用服务。")}).finally(()=>{B||c(!1)}),()=>{B=!0}},[t.targetPeerId]);const x=B=>s.find(F=>F.targetPeerId===B.targetPeerId)?.label||new URL(B.url).host,P=async B=>{h(!0),f(""),L("");try{await B()}catch(F){const U=F instanceof Error?F.message:"";f(/AUTHORIZATION|DENIED/.test(U)?"当前设备没有入口管理权限。请让管理员分享备用连接邀请,或使用入口密码授权。":"暂时无法完成。请确认入口能连接目标服务,且目标地址、证书和授权有效。")}finally{h(!1)}},R=async(B,F)=>{const U={url:B.serviceOrigin||B.url,targetPeerId:B.targetPeerId};await P(async()=>{const H=await hE(U,n.targetPeerId);if(!H.grants.some(K=>K.active)){if(!H.canManage&&F===void 0){m(B);return}await pE(n,U,F)}const q=[...r.filter(K=>K.targetPeerId!==U.targetPeerId),U];await Qo(t,q),o(q),m(void 0),w("")})};if(k)return p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["把链接发给需要使用此备用连接的人。它只允许通过入口连接“",t.label,"”,对方仍需获得目标服务的访问权限。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用连接邀请"}),p.jsx("input",{readOnly:!0,value:k,onFocus:B=>B.target.select()})]}),p.jsxs("button",{type:"button",className:"service-button service-primary",onClick:()=>{navigator.clipboard.writeText(k).then(()=>A(!0)).catch(()=>f("无法自动复制,请长按链接复制。"))},children:[p.jsx(Wp,{size:16}),D?"已复制":"复制邀请链接"]}),p.jsx("button",{type:"button",className:"service-button service-secondary",onClick:()=>{N(void 0),A(!1)},children:"返回备用连接"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});if(g)return p.jsxs("form",{className:"service-form",onSubmit:B=>{B.preventDefault(),R(g,b).finally(()=>w(""))},children:[p.jsxs("p",{className:"service-help",children:["需要“",g.label,"”的管理员授权。若这是你的服务,可以使用它的密码;否则请管理员分享备用连接邀请。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"入口服务密码"}),p.jsx("input",{type:"password",required:!0,value:b,onChange:B=>w(B.target.value),autoComplete:"current-password",disabled:l,autoFocus:!0})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||!b,children:l?"正在授权…":"授权并启用"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{m(void 0),w("")},children:"取消"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});const O=r.filter(B=>B.targetPeerId===n.targetPeerId),j=r.filter(B=>B.targetPeerId!==n.targetPeerId),M=async()=>{if(!l){h(!0),T(!0),f(""),L("");try{o(await mE({...t,routes:r},I)),y(""),L("备用地址已验证并保存。")}catch(B){f(B instanceof Error?B.message:"暂时无法添加地址,请重试。")}finally{h(!1),T(!1)}}};return p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"电脑换了网络?添加它在新网络下的地址,原地址连不上时会自动尝试。只接受同一台服务。"}),p.jsxs("form",{className:"service-form",onSubmit:B=>{B.preventDefault(),M()},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用地址"}),p.jsx("input",{value:I,onChange:B=>{y(B.target.value),f(""),L("")},required:!0,disabled:l||r.length>=4,inputMode:"url",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:192.168.10.20:9834"})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||r.length>=4||!I.trim(),children:C?p.jsxs(p.Fragment,{children:[p.jsx(De,{size:16,className:"service-spinning"}),"正在验证…"]}):"验证并添加"})]}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u}),v&&p.jsx("p",{role:"status",className:"service-help",children:v}),r.length>=4&&p.jsx("p",{className:"service-help",children:"已保存 4 个备用连接。移除不再使用的地址或入口后,可以继续添加。"}),p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"首选地址"}),p.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url})]}),O.length>0&&p.jsx("div",{className:"service-list",children:O.map(B=>p.jsxs("div",{className:"service-route-item",children:[p.jsxs("div",{className:"service-route-line",children:[p.jsx("span",{className:"service-address service-route-address",children:B.url}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`移除地址 ${B.url}`,disabled:l,onClick:()=>S(B),children:"移除"})]}),E?.targetPeerId===B.targetPeerId&&E.url===B.url&&p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"从备用连接中移除此地址?不会停止正在运行的终端。"}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>S(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{P(async()=>{const F=r.filter(U=>U.targetPeerId!==B.targetPeerId||U.url!==B.url);await Qo(t,F),o(F),S(void 0)})},children:"确认移除"})]})]})]},B.url))}),p.jsxs("details",{className:"service-relay-options",children:[p.jsxs("summary",{children:["通过其他服务中转",j.length?`(${j.length})`:""]}),p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"所有直连地址都不可用时,尝试下方已授权入口;直连恢复后自动切回。"}),j.length>0&&p.jsx("div",{className:"service-list",children:j.map(B=>p.jsxs("div",{className:"service-route-item",children:[p.jsxs("div",{className:"service-route-line",children:[p.jsx("span",{className:"service-icon",children:p.jsx(ri,{size:18})}),p.jsx("span",{className:"service-name",children:x(B)}),p.jsx(dl,{size:16,className:"service-selected"})]}),E?.targetPeerId===B.targetPeerId?p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["撤销此设备经“",x(B),"”连接目标的权限?如当前无法直连,目标服务将断开。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>S(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{P(async()=>{await gE(n.targetPeerId,B);const F=r.filter(U=>U.targetPeerId!==B.targetPeerId);await Qo(t,F),o(F),S(void 0)})},children:"确认撤销"})]})]}):p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{P(async()=>{const F=await $p(n,B);N(tg({v:1,routeOnly:!0,serviceId:n.targetPeerId,name:t.label,serviceUrl:t.serviceOrigin||t.url,entryUrl:B.url,entryServiceId:B.targetPeerId,routeCode:F.routeCode}))})},children:"分享备用连接"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>S(B),children:"撤销授权"})]})]},B.targetPeerId))}),a?p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(De,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"添加中转入口"}),s.filter(B=>!r.some(F=>F.targetPeerId===B.targetPeerId)).map(B=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:l||r.length>=4,onClick:()=>{R(B)},children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:B.label}),p.jsx("span",{className:"service-description",children:"验证并授权后启用"})]}),p.jsx(vn,{size:16})]},B.id)),s.length===0&&p.jsx("p",{className:"service-empty",children:"添加并登录另一台服务后,可以将它设为中转入口。"})]})]})]}),l&&!C&&p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(De,{size:16,className:"service-spinning"}),"正在验证连接与授权…"]})]})}function y1({current:t,renderRoutes:e,renderRelayServices:n,onOpen:r,onAdd:o,onInvite:s,hideHeader:i,onNavigation:a,onBusyChange:c,initiallyAdding:l=!1}){const[d,u]=_.useState([]),[f,h]=_.useState(!0),[g,m]=_.useState(l?{kind:"add"}:{kind:"list"}),[b,w]=_.useState(!1),I=_.useCallback(A=>{w(A),c?.(A)},[c]),[y,v]=_.useState(""),L=_.useCallback(()=>{m(A=>A.kind==="routes"||A.kind==="relay-services"?{kind:"edit",service:A.service}:{kind:"list"}),v("")},[]),C=g.kind==="add"?"添加服务":g.kind==="edit"?"服务设置":g.kind==="routes"?"备用连接":g.kind==="relay-services"?"可中转的服务":void 0;_.useEffect(()=>{a?.({title:C,...C?{back:L}:{}})},[C,L,a]),_.useEffect(()=>{let A=!1,x=0;const P=async()=>{const O=++x;try{const j=await He();!A&&x===O&&(u(j),v(""))}catch{!A&&x===O&&v("暂时无法读取服务列表,请重试。")}finally{!A&&x===O&&h(!1)}};P();const R=Hs(()=>{P()});return()=>{A=!0,R()}},[]);const T=async A=>{if(!b){I(!0),v("");try{await A()}catch(x){v(x instanceof Error?x.message:"暂时无法完成,请重试。")}finally{I(!1)}}},E=g.kind==="edit"||g.kind==="routes"||g.kind==="relay-services"?d.find(A=>St(A,g.service))||g.service:void 0,S=t?d.find(A=>St(A,t))||t:void 0,k=d.filter(A=>!t||!St(A,t)),N=S?[S,...k]:k,D=p.jsxs(p.Fragment,{children:[f?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(De,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{className:"service-list",children:[N.map(A=>{const x=!!t&&St(A,t);return p.jsxs("div",{className:"service-row",children:[p.jsxs("button",{type:"button",className:"service-row-open",disabled:b||x,onClick:()=>{T(async()=>{(await r(A))?.passwordRequired&&m({kind:"add",input:A.serviceOrigin||A.url,passwordRequired:!0})})},"aria-label":x?`当前服务 ${A.label}`:`打开 ${A.label}`,children:[p.jsx("span",{className:"service-icon",children:p.jsx(ri,{size:20})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:A.label}),p.jsx("span",{className:"service-description",children:x?"当前服务":new URL(A.serviceOrigin||A.url).host})]}),x?p.jsx(dl,{size:17,className:"service-selected"}):p.jsx(vn,{size:16,className:"service-muted"})]}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`管理 ${A.label}`,disabled:b,onClick:()=>{m({kind:"edit",service:A}),v("")},children:p.jsx(Vp,{size:19})})]},A.id)}),N.length===0&&p.jsx("p",{className:"service-empty",children:"还没有添加服务。连接你的电脑,或粘贴收到的邀请链接。"})]}),p.jsxs("div",{className:`service-actions${s?" service-actions-pair":""}`,children:[p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:b,onClick:()=>{m({kind:"add"}),v("")},children:[p.jsx(Gp,{size:16}),"添加服务"]}),s&&p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:b,onClick:s,children:[p.jsx(Xp,{size:16}),"邀请设备"]})]})]});return p.jsxs("div",{className:"service-manager",children:[!i&&p.jsxs("div",{className:"service-heading",children:[C&&p.jsx("button",{type:"button",className:"service-icon-button","aria-label":"返回服务",disabled:b,onClick:L,children:p.jsx(qp,{size:20})}),p.jsx("h2",{children:C||"服务"})]}),g.kind==="relay-services"?n?.(E,I):g.kind==="routes"?e?.(E,I):g.kind==="list"?D:g.kind==="add"?p.jsx(b1,{onSave:A=>T(async()=>{const x=Oe(A);u(await Ct({id:x,url:x,label:new URL(x).host})),L()}),initialInput:g.input,passwordRequired:g.passwordRequired,busy:b,onSubmit:async(A,x)=>{let P;return await T(async()=>{P=await o(A,x),P?.passwordRequired||L()}),P}}):p.jsx(v1,{onRelayServices:n&&g.service.targetPeerId?()=>m({kind:"relay-services",service:g.service}):void 0,onRoutes:e&&g.service.targetPeerId?()=>m({kind:"routes",service:g.service}):void 0,service:E,busy:b,canRemove:!t||!St(g.service,t),onSave:A=>{T(async()=>{u(await Ct({...E,label:A})),L()})},onRemove:()=>{T(async()=>{u(await Tm(g.service.id)),L()})}}),y&&p.jsx("p",{className:"service-error",role:"alert",children:y})]})}function b1({busy:t,onSubmit:e,onSave:n,initialInput:r="",passwordRequired:o=!1}){const[s,i]=_.useState(r),[a,c]=_.useState(""),[l,d]=_.useState(o);return p.jsxs("form",{className:"service-form",onSubmit:async u=>{u.preventDefault(),(await e(s.trim(),l?a:void 0))?.passwordRequired&&d(!0),c("")},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务地址或邀请链接"}),p.jsx("input",{value:s,onChange:u=>{i(u.target.value),d(!1),c("")},disabled:t,required:!0,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:电脑地址:9834 或 https://…"})]}),l?p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务密码"}),p.jsx("input",{type:"password",value:a,onChange:u=>c(u.target.value),disabled:t,required:!0,autoFocus:!0,autoComplete:"current-password",placeholder:"输入这台服务的密码"})]}):p.jsx("p",{className:"service-help",children:"连接自己的服务,输入地址即可;收到邀请时,粘贴完整链接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:t||!s.trim()||s.includes("#termdock-invite="),onClick:()=>{n(s.trim())},children:"仅保存,不连接"}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:t||!s.trim()||l&&!a,children:t?p.jsxs(p.Fragment,{children:[p.jsx(De,{size:16,className:"service-spinning"}),"正在连接…"]}):l?"登录并连接":"继续"})]})}function v1({service:t,busy:e,canRemove:n,onSave:r,onRemove:o,onRoutes:s,onRelayServices:i}){const[a,c]=_.useState(t.label),[l,d]=_.useState(!1);return p.jsxs("form",{className:"service-form",onSubmit:u=>{u.preventDefault(),r(a.trim())},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务名称"}),p.jsx("input",{value:a,onChange:u=>c(u.target.value),disabled:e,required:!0,maxLength:120,placeholder:"例如:办公室电脑"})]}),p.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:e||!a.trim(),children:"保存名称"}),i&&p.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:i,children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:"可中转的服务"}),p.jsx("span",{className:"service-description",children:"通过这台服务连接其他电脑"})]}),p.jsx(vn,{size:16})]}),s&&p.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:s,children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:"备用连接"}),p.jsx("span",{className:"service-description",children:"添加其他网络地址或授权入口"})]}),p.jsx(vn,{size:16})]}),n&&p.jsx("div",{className:"service-remove",children:l?p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["从列表移除“",t.label,"”?不会停止服务或删除终端。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:e,onClick:()=>d(!1),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:o,children:"确认移除"})]})]}):p.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:()=>d(!0),children:"移除服务"})})]})}var _n={},Ki,wu;function S1(){return wu||(wu=1,Ki=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Ki}var zi={},Ft={},yu;function An(){if(yu)return Ft;yu=1;let t;const e=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Ft.getSymbolSize=function(r){if(!r)throw new Error('"version" cannot be null or undefined');if(r<1||r>40)throw new Error('"version" should be in range from 1 to 40');return r*4+17},Ft.getSymbolTotalCodewords=function(r){return e[r]},Ft.getBCHDigit=function(n){let r=0;for(;n!==0;)r++,n>>>=1;return r},Ft.setToSJISFunction=function(r){if(typeof r!="function")throw new Error('"toSJISFunc" is not a valid function.');t=r},Ft.isKanjiModeEnabled=function(){return typeof t<"u"},Ft.toSJIS=function(r){return t(r)},Ft}var Wi={},bu;function fl(){return bu||(bu=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+n)}}t.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},t.from=function(r,o){if(t.isValid(r))return r;try{return e(r)}catch{return o}}})(Wi)),Wi}var Vi,vu;function x1(){if(vu)return Vi;vu=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(e){const n=Math.floor(e/8);return(this.buffer[n]>>>7-e%8&1)===1},put:function(e,n){for(let r=0;r<n;r++)this.putBit((e>>>n-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const n=Math.floor(this.length/8);this.buffer.length<=n&&this.buffer.push(0),e&&(this.buffer[n]|=128>>>this.length%8),this.length++}},Vi=t,Vi}var Gi,Su;function E1(){if(Su)return Gi;Su=1;function t(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return t.prototype.set=function(e,n,r,o){const s=e*this.size+n;this.data[s]=r,o&&(this.reservedBit[s]=!0)},t.prototype.get=function(e,n){return this.data[e*this.size+n]},t.prototype.xor=function(e,n,r){this.data[e*this.size+n]^=r},t.prototype.isReserved=function(e,n){return this.reservedBit[e*this.size+n]},Gi=t,Gi}var Xi={},xu;function A1(){return xu||(xu=1,(function(t){const e=An().getSymbolSize;t.getRowColCoords=function(r){if(r===1)return[];const o=Math.floor(r/7)+2,s=e(r),i=s===145?26:Math.ceil((s-13)/(2*o-2))*2,a=[s-7];for(let c=1;c<o-1;c++)a[c]=a[c-1]-i;return a.push(6),a.reverse()},t.getPositions=function(r){const o=[],s=t.getRowColCoords(r),i=s.length;for(let a=0;a<i;a++)for(let c=0;c<i;c++)a===0&&c===0||a===0&&c===i-1||a===i-1&&c===0||o.push([s[a],s[c]]);return o}})(Xi)),Xi}var Yi={},Eu;function k1(){if(Eu)return Yi;Eu=1;const t=An().getSymbolSize,e=7;return Yi.getPositions=function(r){const o=t(r);return[[0,0],[o-e,0],[0,o-e]]},Yi}var Zi={},Au;function C1(){return Au||(Au=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},t.from=function(o){return t.isValid(o)?parseInt(o,10):void 0},t.getPenaltyN1=function(o){const s=o.size;let i=0,a=0,c=0,l=null,d=null;for(let u=0;u<s;u++){a=c=0,l=d=null;for(let f=0;f<s;f++){let h=o.get(u,f);h===l?a++:(a>=5&&(i+=e.N1+(a-5)),l=h,a=1),h=o.get(f,u),h===d?c++:(c>=5&&(i+=e.N1+(c-5)),d=h,c=1)}a>=5&&(i+=e.N1+(a-5)),c>=5&&(i+=e.N1+(c-5))}return i},t.getPenaltyN2=function(o){const s=o.size;let i=0;for(let a=0;a<s-1;a++)for(let c=0;c<s-1;c++){const l=o.get(a,c)+o.get(a,c+1)+o.get(a+1,c)+o.get(a+1,c+1);(l===4||l===0)&&i++}return i*e.N2},t.getPenaltyN3=function(o){const s=o.size;let i=0,a=0,c=0;for(let l=0;l<s;l++){a=c=0;for(let d=0;d<s;d++)a=a<<1&2047|o.get(l,d),d>=10&&(a===1488||a===93)&&i++,c=c<<1&2047|o.get(d,l),d>=10&&(c===1488||c===93)&&i++}return i*e.N3},t.getPenaltyN4=function(o){let s=0;const i=o.data.length;for(let c=0;c<i;c++)s+=o.data[c];return Math.abs(Math.ceil(s*100/i/5)-10)*e.N4};function n(r,o,s){switch(r){case t.Patterns.PATTERN000:return(o+s)%2===0;case t.Patterns.PATTERN001:return o%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(o+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return o*s%2+o*s%3===0;case t.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case t.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}t.applyMask=function(o,s){const i=s.size;for(let a=0;a<i;a++)for(let c=0;c<i;c++)s.isReserved(c,a)||s.xor(c,a,n(o,c,a))},t.getBestMask=function(o,s){const i=Object.keys(t.Patterns).length;let a=0,c=1/0;for(let l=0;l<i;l++){s(l),t.applyMask(l,o);const d=t.getPenaltyN1(o)+t.getPenaltyN2(o)+t.getPenaltyN3(o)+t.getPenaltyN4(o);t.applyMask(l,o),d<c&&(c=d,a=l)}return a}})(Zi)),Zi}var Uo={},ku;function ng(){if(ku)return Uo;ku=1;const t=fl(),e=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],n=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return Uo.getBlocksCount=function(o,s){switch(s){case t.L:return e[(o-1)*4+0];case t.M:return e[(o-1)*4+1];case t.Q:return e[(o-1)*4+2];case t.H:return e[(o-1)*4+3];default:return}},Uo.getTotalCodewordsCount=function(o,s){switch(s){case t.L:return n[(o-1)*4+0];case t.M:return n[(o-1)*4+1];case t.Q:return n[(o-1)*4+2];case t.H:return n[(o-1)*4+3];default:return}},Uo}var Ji={},Nr={},Cu;function I1(){if(Cu)return Nr;Cu=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let r=1;for(let o=0;o<255;o++)t[o]=r,e[r]=o,r<<=1,r&256&&(r^=285);for(let o=255;o<512;o++)t[o]=t[o-255]})(),Nr.log=function(r){if(r<1)throw new Error("log("+r+")");return e[r]},Nr.exp=function(r){return t[r]},Nr.mul=function(r,o){return r===0||o===0?0:t[e[r]+e[o]]},Nr}var Iu;function R1(){return Iu||(Iu=1,(function(t){const e=I1();t.mul=function(r,o){const s=new Uint8Array(r.length+o.length-1);for(let i=0;i<r.length;i++)for(let a=0;a<o.length;a++)s[i+a]^=e.mul(r[i],o[a]);return s},t.mod=function(r,o){let s=new Uint8Array(r);for(;s.length-o.length>=0;){const i=s[0];for(let c=0;c<o.length;c++)s[c]^=e.mul(o[c],i);let a=0;for(;a<s.length&&s[a]===0;)a++;s=s.slice(a)}return s},t.generateECPolynomial=function(r){let o=new Uint8Array([1]);for(let s=0;s<r;s++)o=t.mul(o,new Uint8Array([1,e.exp(s)]));return o}})(Ji)),Ji}var Qi,Ru;function T1(){if(Ru)return Qi;Ru=1;const t=R1();function e(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(r){this.degree=r,this.genPoly=t.generateECPolynomial(this.degree)},e.prototype.encode=function(r){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(r.length+this.degree);o.set(r);const s=t.mod(o,this.genPoly),i=this.degree-s.length;if(i>0){const a=new Uint8Array(this.degree);return a.set(s,i),a}return s},Qi=e,Qi}var ea={},ta={},na={},Tu;function rg(){return Tu||(Tu=1,na.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),na}var ct={},Pu;function og(){if(Pu)return ct;Pu=1;const t="[0-9]+",e="[A-Z $%*+\\-./:]+";let n="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";n=n.replace(/u/g,"\\u");const r="(?:(?![A-Z0-9 $%*+\\-./:]|"+n+`)(?:.|[\r
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/passwordBootstrap-CazWrYzP.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/App-CVuPbhP4.js","assets/gestureArbiter-CTk63JTf.js","assets/gestureArbiter-C2J0D0kV.css","assets/triangle-alert-B0gXRJJm.js","assets/referenceLongPress-4ydKrZtC.js","assets/DagPlayground-Yx7XBwmM.js","assets/ChangeWalkthroughPanel-4kynRLRs.js","assets/sparkles-Cs8KAbL4.js","assets/DiffLab-Cn1f9iHY.js","assets/DiffViewer-BFn2Gz8v.js","assets/DiffViewer-T3uj2-aP.css","assets/DiffReviewLab-CN3a3LhH.js","assets/DiffReview-BJQ92hBr.js"])))=>i.map(i=>d[i]);
2
+ import{r as Rc,a as mm,g as bf}from"./react-XDCjal2T.js";import{b as _,R as ze,r as Tc}from"./dnd-BCFAPC0L.js";import{L as wm,l as ym}from"./terminal-C7X98Amf.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const i of s.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(o){if(o.ep)return;o.ep=!0;const s=n(o);fetch(o.href,s)}})();const bm="modulepreload",vm=function(t){return"/"+t},jl={},Gt=function(e,n,r){let o=Promise.resolve();if(n&&n.length>0){let c=function(l){return Promise.all(l.map(d=>Promise.resolve(d).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),a=i?.nonce||i?.getAttribute("nonce");o=c(n.map(l=>{if(l=vm(l),l in jl)return;jl[l]=!0;const d=l.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${u}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":bm,d||(f.as="script"),f.crossOrigin="",f.href=l,a&&f.setAttribute("nonce",a),document.head.appendChild(f),d)return new Promise((h,g)=>{f.addEventListener("load",h),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${l}`)))})}))}function s(i){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=i,window.dispatchEvent(a),!a.defaultPrevented)throw i}return o.then(i=>{for(const a of i||[])a.status==="rejected"&&s(a.reason);return e().catch(s)})};var wi={exports:{}},xr={};var Ul;function Sm(){if(Ul)return xr;Ul=1;var t=Rc(),e=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function i(a,c,l){var d,u={},f=null,h=null;l!==void 0&&(f=""+l),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(h=c.ref);for(d in c)r.call(c,d)&&!s.hasOwnProperty(d)&&(u[d]=c[d]);if(a&&a.defaultProps)for(d in c=a.defaultProps,c)u[d]===void 0&&(u[d]=c[d]);return{$$typeof:e,type:a,key:f,ref:h,props:u,_owner:o.current}}return xr.Fragment=n,xr.jsx=i,xr.jsxs=i,xr}var $l;function xm(){return $l||($l=1,wi.exports=Sm()),wi.exports}var p=xm();const pn="termdock-secure-target-v1",Pc="termdock-secure-entry-v1",Em=new Set([pn,Pc,"termdock-color-theme","termdock:locale","termdock.federation.connections.v1"]),xo=typeof Storage>"u"?void 0:Storage.prototype.getItem,yi=typeof Storage>"u"?void 0:Storage.prototype.setItem,Hl="termdock-secure-legacy-owner",Ms=typeof window<"u"&&window.parent!==window&&location.pathname==="/workspace.html";function Am(){if(typeof window>"u")return null;try{if(Ms){const e=new URLSearchParams(location.search).get("termdock-workspace"),n=JSON.parse(localStorage.getItem("termdock.federation.connections.v1")||"[]"),r=Array.isArray(n)?n.find(o=>o?.targetPeerId===e):void 0;return r&&typeof r.url=="string"&&typeof r.targetPeerId=="string"?{...r,serviceName:r.label||r.serviceName}:null}const t=JSON.parse(sessionStorage.getItem(pn)??localStorage.getItem(pn)??"null");return t&&typeof t.url=="string"&&typeof t.targetPeerId=="string"?t:null}catch{return null}}let js=Am();const Kn=js?.targetPeerId??"unpaired";function Nc(){return js}function vf(t){if(js=t,Ms)return;const e=JSON.stringify(t);sessionStorage.setItem(pn,e),localStorage.setItem(pn,e)}function km(){js=null,!Ms&&(localStorage.removeItem(pn),sessionStorage.removeItem(pn),localStorage.removeItem(Pc))}function zr(t,e=Kn){return Em.has(t)||t.startsWith("termdock-secure-")?t:`termdock-service:${e}:${t}`}function Cm(t){if(!(!xo||!yi))try{if(xo.call(localStorage,Hl))return;yi.call(localStorage,Hl,t);for(const n of[localStorage,sessionStorage]){const r=Array.from({length:n.length},(o,s)=>n.key(s)).filter(o=>!!o);for(const o of r){if(o.startsWith("termdock-service:")||zr(o,t)===o)continue;const s=zr(o,t),i=xo.call(n,o);i!==null&&xo.call(n,s)===null&&yi.call(n,s,i)}}}catch{}}let ql=!1;function Im(){if(ql||typeof Storage>"u")return;ql=!0;const t=Storage.prototype.getItem,e=Storage.prototype.setItem,n=Storage.prototype.removeItem;Storage.prototype.getItem=function(r){return t.call(this,zr(String(r)))},Storage.prototype.setItem=function(r,o){e.call(this,zr(String(r)),o)},Storage.prototype.removeItem=function(r){n.call(this,zr(String(r)))}}Im();const Us="termdock.federation.connections.v1",ka="termdock:services-changed",Lc="termdock-secure-removed-services",is=t=>[t.id,t.targetPeerId,t.serviceOrigin||t.url].filter(e=>!!e);function Bc(){try{const t=JSON.parse(localStorage.getItem(Lc)||"[]");return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}catch{return[]}}function Oe(t){const e=t.trim();if(!e)throw new Error("请输入服务地址。");const n=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(e)?e:`https://${e}`);n.protocol==="wss:"&&(n.protocol="https:"),n.protocol==="ws:"&&(n.protocol="http:");const r=["localhost","127.0.0.1","[::1]"].includes(n.hostname);if(!["https:","http:"].includes(n.protocol)||n.protocol==="http:"&&!r)throw new Error("请使用 HTTPS 服务地址。");if(n.username||n.password||n.search||n.hash||!["/","/api/federation/secure"].includes(n.pathname))throw new Error("请输入服务首页地址,不要包含账号或额外参数。");return n.origin}function $s(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.url=="string")try{const n=Oe(e.url),r=typeof e.targetPeerId=="string"&&e.targetPeerId?e.targetPeerId:void 0,o=(typeof e.label=="string"?e.label:typeof e.serviceName=="string"?e.serviceName:"").trim().slice(0,120)||new URL(n).host;return{id:typeof e.id=="string"&&e.id?e.id:r||n,url:n,label:o,...r?{targetPeerId:r}:{},...typeof e.serviceOrigin=="string"?{serviceOrigin:Oe(e.serviceOrigin)}:{},...typeof e.entryServiceId=="string"&&e.entryServiceId?{entryServiceId:e.entryServiceId}:{},...Array.isArray(e.routes)?{routes:e.routes.slice(0,4).flatMap(s=>{try{return s&&typeof s.targetPeerId=="string"&&s.targetPeerId?[{url:Oe(s.url),targetPeerId:s.targetPeerId}]:[]}catch{return[]}})}:{}}}catch{return}}function St(t,e){return t.targetPeerId&&e.targetPeerId?t.targetPeerId===e.targetPeerId:(t.serviceOrigin||t.url)===(e.serviceOrigin||e.url)}function Sf(t){const e=[];for(const n of t){const r=e.findIndex(o=>St(o,n));r<0?e.push(n):e[r]={...e[r],...n,id:e[r].id}}return e}function fo(){return typeof window>"u"?void 0:window.termdockDesktop}function gn(){try{const t=JSON.parse(localStorage.getItem(Us)||"[]");return Array.isArray(t)?Sf(t.map($s).filter(e=>!!e)):[]}catch{return[]}}function xf(t){localStorage.setItem(Us,JSON.stringify(t.map(e=>({...e,serviceName:e.label})))),window.dispatchEvent(new Event(ka))}let Er;async function He(){const t=fo();if(!t?.serviceConnections||!t.saveServiceConnection)return gn();if(Er)return Er;Er=(async()=>{let e=await t.serviceConnections();const n=gn();for(const r of n)e.some(o=>St(o,r))||(e=await(t.importServiceConnection||t.saveServiceConnection)(r));return n.length&&localStorage.removeItem(Us),e})();try{return await Er}finally{Er=void 0}}async function Ct(t){const e=$s(t);if(!e)throw new Error("服务地址无效。");const n=fo();if(n?.saveServiceConnection)return n.saveServiceConnection(e);const r=gn(),o=r.find(a=>a.id===e.id||St(a,e)),s=new Set([...is(e),...o?is(o):[]]);localStorage.setItem(Lc,JSON.stringify(Bc().filter(a=>!s.has(a))));const i=Sf([...r.filter(a=>a!==o),{...o,...e,id:o?.id||e.id}]);return xf(i),i}async function Rm(t){const e=$s(t);if(!e)throw new Error("服务地址无效。");const n=fo();if(n?.importServiceConnection)return n.importServiceConnection(e);if(n?.serviceConnections){const r=await n.serviceConnections();return r.some(o=>St(o,e))?Ct(e):r}return is(e).some(r=>Bc().includes(r))?gn():Ct(e)}async function Tm(t){const e=fo();if(e?.removeServiceConnection)return e.removeServiceConnection(t);const n=gn(),r=n.find(s=>s.id===t);r&&localStorage.setItem(Lc,JSON.stringify([...new Set([...Bc(),...is(r)])].slice(-768)));const o=n.filter(s=>s.id!==t);return xf(o),o}function Hs(t){const e=r=>{(r.key===Us||r.key===null)&&t()};window.addEventListener(ka,t),window.addEventListener("storage",e);const n=fo()?.onServiceConnections?.(t);return()=>{window.removeEventListener(ka,t),window.removeEventListener("storage",e),n?.()}}class Pm extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}let Nm=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},ot=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};class Ef extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class Af extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}}class Lm extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class Bm extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class qs extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}const kf=Symbol.for("@libp2p/peer-id");function _m(t){return typeof t?.handleEvent=="function"}function Om(t){return t===!0||t===!1}function Dm(t){return Om(t)?t:t?.capture??!1}function Ca(t){const e={capture:Dm(t),once:!!t?.once};return t?.passive!=null&&(e.passive=t?.passive),t?.signal!=null&&(e.signal=t?.signal),e}function Kl(t,e){return Ca(t).capture===Ca(e).capture}class Fm extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const n=this.#e.get(e);return n==null?0:n.length}addEventListener(e,n,r){const o=Ca(r);if(o?.signal?.aborted===!0)return;const s=l=>{o.once&&this.removeEventListener(e,n,o),_m(n)?n.handleEvent(l):n(l)};let i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(l=>l.callback!==n?!1:Kl(l.options,o)))return;super.addEventListener(e,s,o);const c=()=>{this.removeEventListener(e,n,o)};o.signal?.addEventListener("abort",c),i.push({callback:n,wrapper:s,options:o,onAbort:c})}removeEventListener(e,n,r){const o=this.#e.get(e);if(o==null){super.removeEventListener(e,n??null,r);return}this.#e.set(e,o.filter(s=>s.callback===n&&Kl(s.options,r)?(super.removeEventListener(e,s.wrapper,r),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,n={}){return this.dispatchEvent(new CustomEvent(e,n))}}const Mm=Symbol.for("@libp2p/service-capabilities");function jm(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let n=0;n<t.byteLength;n++)if(t[n]!==e[n])return!1;return!0}function Ks(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function Um(t){return new TextEncoder().encode(t)}function $m(t){return new TextDecoder().decode(t)}function Hm(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(n[i]!==255)throw new TypeError(s+" is ambiguous");n[i]=o}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var m=0,b=0,w=0,I=g.length;w!==I&&g[w]===0;)w++,m++;for(var y=(I-w)*d+1>>>0,v=new Uint8Array(y);w!==I;){for(var L=g[w],k=0,T=y-1;(L!==0||k<b)&&T!==-1;T--,k++)L+=256*v[T]>>>0,v[T]=L%a>>>0,L=L/a>>>0;if(L!==0)throw new Error("Non-zero carry");b=k,w++}for(var E=y-b;E!==y&&v[E]===0;)E++;for(var S=c.repeat(m);E<y;++E)S+=t.charAt(v[E]);return S}function f(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var m=0;if(g[m]!==" "){for(var b=0,w=0;g[m]===c;)b++,m++;for(var I=(g.length-m)*l+1>>>0,y=new Uint8Array(I);g[m];){var v=n[g.charCodeAt(m)];if(v===255)return;for(var L=0,k=I-1;(v!==0||L<w)&&k!==-1;k--,L++)v+=a*y[k]>>>0,y[k]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");w=L,m++}if(g[m]!==" "){for(var T=I-w;T!==I&&y[T]===0;)T++;for(var E=new Uint8Array(b+(I-T)),S=b;T!==I;)E[S++]=y[T++];return E}}}function h(g){var m=f(g);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:h}}var qm=Hm,Km=qm;class zm{name;prefix;baseEncode;constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Wm{name;prefix;baseDecode;prefixCodePoint;constructor(e,n,r){this.name=e,this.prefix=n;const o=n.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Cf(this,e)}}class Vm{decoders;constructor(e){this.decoders=e}or(e){return Cf(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r!=null)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function Cf(t,e){return new Vm({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class Gm{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,n,r,o){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=o,this.encoder=new zm(e,n,r),this.decoder=new Wm(e,n,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function zs({name:t,prefix:e,encode:n,decode:r}){return new Gm(t,e,n,r)}function ho({name:t,prefix:e,alphabet:n}){const{encode:r,decode:o}=Km(n,t);return zs({prefix:e,name:t,encode:r,decode:s=>Ks(o(s))})}function Xm(t,e,n,r){let o=t.length;for(;t[o-1]==="=";)--o;const s=new Uint8Array(o*n/8|0);let i=0,a=0,c=0;for(let l=0;l<o;++l){const d=e[t[l]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<n|d,i+=n,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=n||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Ym(t,e,n){const r=e[e.length-1]==="=",o=(1<<n)-1;let s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>n;)i-=n,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<n-i]),r)for(;(s.length*n&7)!==0;)s+="=";return s}function Zm(t){const e={};for(let n=0;n<t.length;++n)e[t[n]]=n;return e}function Ce({name:t,prefix:e,bitsPerChar:n,alphabet:r}){const o=Zm(r);return zs({prefix:e,name:t,encode(s){return Ym(s,r,n)},decode(s){return Xm(s,o,n,t)}})}const Be=ho({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Jm=ho({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Qm=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Be,base58flickr:Jm},Symbol.toStringTag,{value:"Module"})),Wr=Ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ew=Ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),tw=Ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),nw=Ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),rw=Ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ow=Ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),sw=Ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),iw=Ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),aw=Ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),cw=Object.freeze(Object.defineProperty({__proto__:null,base32:Wr,base32hex:rw,base32hexpad:sw,base32hexpadupper:iw,base32hexupper:ow,base32pad:tw,base32padupper:nw,base32upper:ew,base32z:aw},Symbol.toStringTag,{value:"Module"})),Vo=ho({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),lw=ho({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),dw=Object.freeze(Object.defineProperty({__proto__:null,base36:Vo,base36upper:lw},Symbol.toStringTag,{value:"Module"}));var uw=If,zl=128,fw=-128,hw=Math.pow(2,31);function If(t,e,n){e=e||[],n=n||0;for(var r=n;t>=hw;)e[n++]=t&255|zl,t/=128;for(;t&fw;)e[n++]=t&255|zl,t>>>=7;return e[n]=t|0,If.bytes=n-r+1,e}var pw=Ia,gw=128,Wl=127;function Ia(t,r){var n=0,r=r||0,o=0,s=r,i,a=t.length;do{if(s>=a)throw Ia.bytes=0,new RangeError("Could not decode varint");i=t[s++],n+=o<28?(i&Wl)<<o:(i&Wl)*Math.pow(2,o),o+=7}while(i>=gw);return Ia.bytes=s-r,n}var mw=Math.pow(2,7),ww=Math.pow(2,14),yw=Math.pow(2,21),bw=Math.pow(2,28),vw=Math.pow(2,35),Sw=Math.pow(2,42),xw=Math.pow(2,49),Ew=Math.pow(2,56),Aw=Math.pow(2,63),kw=function(t){return t<mw?1:t<ww?2:t<yw?3:t<bw?4:t<vw?5:t<Sw?6:t<xw?7:t<Ew?8:t<Aw?9:10},Cw={encode:uw,decode:pw,encodingLength:kw},as=Cw;function Ra(t,e=0){return[as.decode(t,e),as.decode.bytes]}function cs(t,e,n=0){return as.encode(t,e,n),e}function ls(t){return as.encodingLength(t)}function po(t,e){const n=e.byteLength,r=ls(t),o=r+ls(n),s=new Uint8Array(o+n);return cs(t,s,0),cs(n,s,r),s.set(e,o),new _c(t,n,e,s)}function Rf(t){const e=Ks(t),[n,r]=Ra(e),[o,s]=Ra(e.subarray(r)),i=e.subarray(r+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new _c(n,o,i,e)}function Iw(t,e){if(t===e)return!0;{const n=e;return t.code===n.code&&t.size===n.size&&n.bytes instanceof Uint8Array&&jm(t.bytes,n.bytes)}}class _c{code;size;digest;bytes;constructor(e,n,r,o){this.code=e,this.size=n,this.digest=r,this.bytes=o}}function Vl(t,e){const{bytes:n,version:r}=t;return r===0?Tw(n,Ta(t),e??Be.encoder):Pw(n,Ta(t),e??Wr.encoder)}const Gl=new WeakMap;function Ta(t){const e=Gl.get(t);if(e==null){const n=new Map;return Gl.set(t,n),n}return e}class le{code;version;multihash;bytes;"/";constructor(e,n,r,o){this.code=n,this.version=e,this.multihash=r,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:e,multihash:n}=this;if(e!==Ar)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==Nw)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return le.createV0(n)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:e,digest:n}=this.multihash,r=po(e,n);return le.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return le.equals(this,e)}static equals(e,n){const r=n;return r!=null&&e.code===r.code&&e.version===r.version&&Iw(e.multihash,r.multihash)}toString(e){return Vl(this,e)}toJSON(){return{"/":Vl(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;const n=e;if(n instanceof le)return n;if(n["/"]!=null&&n["/"]===n.bytes||n.asCID===n){const{version:r,code:o,multihash:s,bytes:i}=n;return new le(r,o,s,i??Xl(r,o,s.bytes))}else if(n[Lw]===!0){const{version:r,multihash:o,code:s}=n,i=Rf(o);return le.create(r,s,i)}else return null}static create(e,n,r){if(typeof n!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(n!==Ar)throw new Error(`Version 0 CID must use dag-pb (code: ${Ar}) block encoding`);return new le(e,n,r,r.bytes)}case 1:{const o=Xl(e,n,r.bytes);return new le(e,n,r,o)}default:throw new Error("Invalid version")}}static createV0(e){return le.create(0,Ar,e)}static createV1(e,n){return le.create(1,e,n)}static decode(e){const[n,r]=le.decodeFirst(e);if(r.length!==0)throw new Error("Incorrect length");return n}static decodeFirst(e){const n=le.inspectBytes(e),r=n.size-n.multihashSize,o=Ks(e.subarray(r,r+n.multihashSize));if(o.byteLength!==n.multihashSize)throw new Error("Incorrect length");const s=o.subarray(n.multihashSize-n.digestSize),i=new _c(n.multihashCode,n.digestSize,s,o);return[n.version===0?le.createV0(i):le.createV1(n.codec,i),e.subarray(n.size)]}static inspectBytes(e){let n=0;const r=()=>{const[u,f]=Ra(e.subarray(n));return n+=f,u};let o=r(),s=Ar;if(o===18?(o=0,n=0):s=r(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);const i=n,a=r(),c=r(),l=n+c,d=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:l}}static parse(e,n){const[r,o]=Rw(e,n),s=le.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ta(s).set(r,e),s}}function Rw(t,e){switch(t[0]){case"Q":{const n=e??Be;return[Be.prefix,n.decode(`${Be.prefix}${t}`)]}case Be.prefix:{const n=e??Be;return[Be.prefix,n.decode(t)]}case Wr.prefix:{const n=e??Wr;return[Wr.prefix,n.decode(t)]}case Vo.prefix:{const n=e??Vo;return[Vo.prefix,n.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function Tw(t,e,n){const{prefix:r}=n;if(r!==Be.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);const o=e.get(r);if(o==null){const s=n.encode(t).slice(1);return e.set(r,s),s}else return o}function Pw(t,e,n){const{prefix:r}=n,o=e.get(r);if(o==null){const s=n.encode(t);return e.set(r,s),s}else return o}const Ar=112,Nw=18;function Xl(t,e,n){const r=ls(t),o=r+ls(e),s=new Uint8Array(o+n.byteLength);return cs(t,s,0),cs(e,s,r),s.set(n,o),s}const Lw=Symbol.for("@ipld/js-cid/CID"),Tf=0,Bw="identity",Pf=Ks;function _w(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return po(Tf,Pf(t))}const go={code:Tf,name:Bw,encode:Pf,digest:_w};function st(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let n=0;n<t.byteLength;n++)if(t[n]!==e[n])return!1;return!0}function Ue(t=0){return new Uint8Array(t)}function It(t=0){return new Uint8Array(t)}function Pa(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));const n=It(e);let r=0;for(const o of t)n.set(o,r),r+=o.length;return n}const Nf=Symbol.for("@achingbrain/uint8arraylist");function Yl(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let n=0;for(const r of t){const o=n+r.byteLength;if(e<o)return{buf:r,index:e-n};n=o}throw new RangeError("index is out of bounds")}function Eo(t){return!!t?.[Nf]}class se{bufs;length;[Nf]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let n=0;for(const r of e)if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.push(r);else if(Eo(r)){n+=r.byteLength;for(const o of r.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=n}prepend(...e){this.prependAll(e)}prependAll(e){let n=0;for(const r of e.reverse())if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.unshift(r);else if(Eo(r))n+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=n}get(e){const n=Yl(this.bufs,e);return n.buf[n.index]}set(e,n){const r=Yl(this.bufs,e);r.buf[r.index]=n}write(e,n=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(n+r,e[r]);else if(Eo(e))for(let r=0;r<e.length;r++)this.set(n+r,e.get(r));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,n){const{bufs:r,length:o}=this._subList(e,n);return Pa(r,o)}subarray(e,n){const{bufs:r,length:o}=this._subList(e,n);return r.length===1?r[0]:Pa(r,o)}sublist(e,n){const{bufs:r,length:o}=this._subList(e,n),s=new se;return s.length=o,s.bufs=r,s}_subList(e,n){if(e=e??0,n=n??this.length,e<0&&(e=this.length+e),n<0&&(n=this.length+n),e<0||n>this.length)throw new RangeError("index is out of bounds");if(e===n)return{bufs:[],length:0};if(e===0&&n===this.length)return{bufs:[...this.bufs],length:this.length};const r=[];let o=0;for(let s=0;s<this.bufs.length;s++){const i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;const l=e>=a&&e<c,d=n>a&&n<=c;if(l&&d){if(e===a&&n===c){r.push(i);break}const u=e-a;r.push(i.subarray(u,u+(n-e)));break}if(l){if(e===0){r.push(i);continue}r.push(i.subarray(e-a));continue}if(d){if(n===c){r.push(i);break}r.push(i.subarray(0,n-a));break}r.push(i)}return{bufs:r,length:n-e}}indexOf(e,n=0){if(!Eo(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(n=Number(n??0),isNaN(n)&&(n=0),n<0&&(n=this.length+n),n<0&&(n=0),e.length===0)return n>this.length?this.length:n;const o=r.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");const s=256,i=new Int32Array(s);for(let u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[r[u]]=u;const a=i,c=this.byteLength-r.byteLength,l=r.byteLength-1;let d;for(let u=n;u<=c;u+=d){d=0;for(let f=l;f>=0;f--){const h=this.get(u+f);if(r[f]!==h){d=Math.max(1,f-a[h]);break}}if(d===0)return u}return-1}getInt8(e){const n=this.subarray(e,e+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt8(0)}setInt8(e,n){const r=It(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,n),this.write(r,e)}getInt16(e,n){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,n)}setInt16(e,n,r){const o=Ue(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,n,r),this.write(o,e)}getInt32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,n)}setInt32(e,n,r){const o=Ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,n,r),this.write(o,e)}getBigInt64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,n)}setBigInt64(e,n,r){const o=Ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,n,r),this.write(o,e)}getUint8(e){const n=this.subarray(e,e+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint8(0)}setUint8(e,n){const r=It(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,n),this.write(r,e)}getUint16(e,n){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,n)}setUint16(e,n,r){const o=Ue(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,n,r),this.write(o,e)}getUint32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,n)}setUint32(e,n,r){const o=Ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,n,r),this.write(o,e)}getBigUint64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,n)}setBigUint64(e,n,r){const o=Ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,n,r),this.write(o,e)}getFloat32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,n)}setFloat32(e,n,r){const o=Ue(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,n,r),this.write(o,e)}getFloat64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,n)}setFloat64(e,n,r){const o=Ue(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,n,r),this.write(o,e)}equals(e){if(e==null||!(e instanceof se)||e.bufs.length!==this.bufs.length)return!1;for(let n=0;n<this.bufs.length;n++)if(!st(this.bufs[n],e.bufs[n]))return!1;return!0}static fromUint8Arrays(e,n){const r=new se;return r.bufs=e,n==null&&(n=e.reduce((o,s)=>o+s.byteLength,0)),r.length=n,r}}const Ow=ho({prefix:"9",name:"base10",alphabet:"0123456789"}),Dw=Object.freeze(Object.defineProperty({__proto__:null,base10:Ow},Symbol.toStringTag,{value:"Module"})),Fw=Ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Mw=Ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),jw=Object.freeze(Object.defineProperty({__proto__:null,base16:Fw,base16upper:Mw},Symbol.toStringTag,{value:"Module"})),Uw=Ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),$w=Object.freeze(Object.defineProperty({__proto__:null,base2:Uw},Symbol.toStringTag,{value:"Module"})),Lf=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Hw=Lf.reduce((t,e,n)=>(t[n]=e,t),[]),qw=Lf.reduce((t,e,n)=>{const r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return t[r]=n,t},[]);function Kw(t){return t.reduce((e,n)=>(e+=Hw[n],e),"")}function zw(t){const e=[];for(const n of t){const r=n.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${n}`);const o=qw[r];if(o==null)throw new Error(`Non-base256emoji character: ${n}`);e.push(o)}return new Uint8Array(e)}const Ww=zs({prefix:"🚀",name:"base256emoji",encode:Kw,decode:zw}),Vw=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:Ww},Symbol.toStringTag,{value:"Module"})),Gw=Ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Xw=Ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Yw=Ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Zw=Ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Jw=Object.freeze(Object.defineProperty({__proto__:null,base64:Gw,base64pad:Xw,base64url:Yw,base64urlpad:Zw},Symbol.toStringTag,{value:"Module"})),Qw=Ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),ey=Object.freeze(Object.defineProperty({__proto__:null,base8:Qw},Symbol.toStringTag,{value:"Module"})),ty=zs({prefix:"\0",name:"identity",encode:t=>$m(t),decode:t=>Um(t)}),ny=Object.freeze(Object.defineProperty({__proto__:null,identity:ty},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const ry=20;function oy({name:t,code:e,encode:n,minDigestLength:r,maxDigestLength:o}){return new sy(t,e,n,r,o)}class sy{name;code;encode;minDigestLength;maxDigestLength;constructor(e,n,r,o,s){this.name=e,this.code=n,this.encode=r,this.minDigestLength=o??ry,this.maxDigestLength=s}digest(e,n){if(n?.truncate!=null){if(n.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&n.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Zl(r,this.code,n?.truncate):r.then(o=>Zl(o,this.code,n?.truncate))}else throw Error("Unknown type, must be binary type")}}function Zl(t,e,n){if(n!=null&&n!==t.byteLength){if(n>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,n)}return po(e,t)}function iy(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}const Oc=oy({name:"sha2-256",code:18,encode:iy("SHA-256")}),Jl={...ny,...$w,...ey,...Dw,...jw,...cw,...dw,...Qm,...Jw,...Vw};function Bf(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const Ql=Bf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),bi=Bf("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=It(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),_f={utf8:Ql,"utf-8":Ql,hex:Jl.base16,latin1:bi,ascii:bi,binary:bi,...Jl};function we(t,e="utf8"){const n=_f[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.decoder.decode(`${n.prefix}${t}`)}function ee(t,e="utf8"){const n=_f[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.encoder.encode(t).substring(1)}const ay=parseInt("11111",2),Na=parseInt("10000000",2),cy=parseInt("01111111",2),ed={0:kr,1:kr,2:ly,3:fy,4:hy,5:uy,6:dy,16:kr,22:kr,48:kr};function gr(t,e={offset:0}){const n=t[e.offset]&ay;if(e.offset++,ed[n]!=null)return ed[n](t,e);throw new Error("No decoder for tag "+n)}function mo(t,e){let n=0;if((t[e.offset]&Na)===Na){const r=t[e.offset]&cy;let o="0x";e.offset++;for(let s=0;s<r;s++,e.offset++)o+=t[e.offset].toString(16).padStart(2,"0");n=parseInt(o,16)}else n=t[e.offset],e.offset++;return n}function kr(t,e){mo(t,e);const n=[];for(;!(e.offset>=t.byteLength);){const r=gr(t,e);if(r===null)break;n.push(r)}return n}function ly(t,e){const n=mo(t,e),r=e.offset,o=e.offset+n,s=[];for(let i=r;i<o;i++)i===r&&t[i]===0||s.push(t[i]);return e.offset+=n,Uint8Array.from(s)}function dy(t,e){const n=mo(t,e),r=e.offset+n,o=t[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<r;){const l=t[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let d=0;for(let u=0;u<c.length;u++)d+=c[u]<<u*7;a+=`.${d}`,c=[]}}return a}function uy(t,e){return e.offset++,null}function fy(t,e){const n=mo(t,e),r=t[e.offset];e.offset++;const o=t.subarray(e.offset,e.offset+n-1);if(e.offset+=n,r!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function hy(t,e){const n=mo(t,e),r=t.subarray(e.offset,e.offset+n);return e.offset+=n,r}function py(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);const n=new se;for(let r=0;r<e.length;r+=2)n.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return n}function Ws(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);const e=py(t.byteLength);return new se(Uint8Array.from([e.byteLength|Na]),e)}function Ke(t){const e=new se,n=128;return(t.subarray()[0]&n)===n&&e.append(Uint8Array.from([0])),e.append(t),new se(Uint8Array.from([2]),Ws(e),e)}function Dc(t){const e=Uint8Array.from([0]),n=new se(e,t);return new se(Uint8Array.from([3]),Ws(n),n)}function gy(t){return new se(Uint8Array.from([4]),Ws(t),t)}function kt(t,e=48){const n=new se;for(const r of t)n.append(r);return new se(Uint8Array.from([e]),Ws(n),n)}async function my(t,e,n){const r=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["sign"]);n?.signal?.throwIfAborted();const o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function wy(t,e,n,r){const o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();const s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,n.subarray());return r?.signal?.throwIfAborted(),s}const yy=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),by=Uint8Array.from([6,5,43,129,4,0,34]),vy=Uint8Array.from([6,5,43,129,4,0,35]),Of={ext:!0,kty:"EC",crv:"P-256"},Df={ext:!0,kty:"EC",crv:"P-384"},Ff={ext:!0,kty:"EC",crv:"P-521"},zn=32,Wn=48,Vn=66;function Sy(t){const e=gr(t);return xy(e)}function xy(t){const e=t[1],n=ee(e,"base64url"),r=t[2][1][0],o=1;let s,i;if(e.byteLength===zn)return s=ee(r.subarray(o,o+zn),"base64url"),i=ee(r.subarray(o+zn),"base64url"),new vi({...Of,key_ops:["sign"],d:n,x:s,y:i});if(e.byteLength===Wn)return s=ee(r.subarray(o,o+Wn),"base64url"),i=ee(r.subarray(o+Wn),"base64url"),new vi({...Df,key_ops:["sign"],d:n,x:s,y:i});if(e.byteLength===Vn)return s=ee(r.subarray(o,o+Vn),"base64url"),i=ee(r.subarray(o+Vn),"base64url"),new vi({...Ff,key_ops:["sign"],d:n,x:s,y:i});throw new ot(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function Mf(t){const e=gr(t);return Ey(e)}function Ey(t){const e=t[1][1][0],n=1;let r,o;if(e.byteLength===zn*2+1)return r=ee(e.subarray(n,n+zn),"base64url"),o=ee(e.subarray(n+zn),"base64url"),new Go({...Of,key_ops:["verify"],x:r,y:o});if(e.byteLength===Wn*2+1)return r=ee(e.subarray(n,n+Wn),"base64url"),o=ee(e.subarray(n+Wn),"base64url"),new Go({...Df,key_ops:["verify"],x:r,y:o});if(e.byteLength===Vn*2+1)return r=ee(e.subarray(n,n+Vn),"base64url"),o=ee(e.subarray(n+Vn),"base64url"),new Go({...Ff,key_ops:["verify"],x:r,y:o});throw new ot(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Ay(t){return kt([Ke(Uint8Array.from([1])),gy(we(t.d??"","base64url")),kt([jf(t.crv)],160),kt([Dc(new se(Uint8Array.from([4]),we(t.x??"","base64url"),we(t.y??"","base64url")))],161)]).subarray()}function ky(t){return kt([Ke(Uint8Array.from([1])),kt([jf(t.crv)],160),kt([Dc(new se(Uint8Array.from([4]),we(t.x??"","base64url"),we(t.y??"","base64url")))],161)]).subarray()}function jf(t){if(t==="P-256")return yy;if(t==="P-384")return by;if(t==="P-521")return vy;throw new ot(`Invalid curve ${t}`)}class Go{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=ky(this.jwk)),this._raw}toMultihash(){return go.digest(Js(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return Be.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:st(this.raw,e.raw)}async verify(e,n,r){return wy(this.jwk,n,e,r)}}class vi{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Go({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=Ay(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:st(this.raw,e.raw)}async sign(e,n){return my(this.jwk,e,n)}}const Nn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function wo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function La(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Sn(t,...e){if(!wo(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Uf(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");La(t.outputLen),La(t.blockLen)}function ds(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Cy(t,e){Sn(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function ir(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Si(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function it(t,e){return t<<32-e|t>>>e}const $f=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Iy=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function dn(t){if(Sn(t),$f)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Iy[t[n]];return e}const gt={_0:48,_9:57,A:65,F:70,a:97,f:102};function td(t){if(t>=gt._0&&t<=gt._9)return t-gt._0;if(t>=gt.A&&t<=gt.F)return t-(gt.A-10);if(t>=gt.a&&t<=gt.f)return t-(gt.a-10)}function us(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if($f)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){const i=td(t.charCodeAt(s)),a=td(t.charCodeAt(s+1));if(i===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a}return r}function Ry(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Fc(t){return typeof t=="string"&&(t=Ry(t)),Sn(t),t}function lt(...t){let e=0;for(let r=0;r<t.length;r++){const o=t[r];Sn(o),e+=o.length}const n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){const s=t[r];n.set(s,o),o+=s.length}return n}class Hf{}function qf(t){const e=r=>t().update(Fc(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Mc(t=32){if(Nn&&typeof Nn.getRandomValues=="function")return Nn.getRandomValues(new Uint8Array(t));if(Nn&&typeof Nn.randomBytes=="function")return Uint8Array.from(Nn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function Ty(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const o=BigInt(32),s=BigInt(4294967295),i=Number(n>>o&s),a=Number(n&s),c=r?4:0,l=r?0:4;t.setUint32(e+c,i,r),t.setUint32(e+l,a,r)}function Py(t,e,n){return t&e^~t&n}function Ny(t,e,n){return t&e^t&n^e&n}let Kf=class extends Hf{constructor(e,n,r,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Si(this.buffer)}update(e){ds(this),e=Fc(e),Sn(e);const{view:n,buffer:r,blockLen:o}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(o-this.pos,s-i);if(a===o){const c=Si(e);for(;o<=s-i;i+=o)this.process(c,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ds(this),Cy(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:o,isLE:s}=this;let{pos:i}=this;n[i++]=128,ir(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(r,0),i=0);for(let u=i;u<o;u++)n[u]=0;Ty(r,o-8,BigInt(this.length*8),s),this.process(r,0);const a=Si(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};const Nt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Re=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Ao=BigInt(2**32-1),nd=BigInt(32);function Ly(t,e=!1){return e?{h:Number(t&Ao),l:Number(t>>nd&Ao)}:{h:Number(t>>nd&Ao)|0,l:Number(t&Ao)|0}}function By(t,e=!1){const n=t.length;let r=new Uint32Array(n),o=new Uint32Array(n);for(let s=0;s<n;s++){const{h:i,l:a}=Ly(t[s],e);[r[s],o[s]]=[i,a]}return[r,o]}const rd=(t,e,n)=>t>>>n,od=(t,e,n)=>t<<32-n|e>>>n,Ln=(t,e,n)=>t>>>n|e<<32-n,Bn=(t,e,n)=>t<<32-n|e>>>n,ko=(t,e,n)=>t<<64-n|e>>>n-32,Co=(t,e,n)=>t>>>n-32|e<<64-n;function mt(t,e,n,r){const o=(e>>>0)+(r>>>0);return{h:t+n+(o/2**32|0)|0,l:o|0}}const _y=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Oy=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Dy=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Fy=(t,e,n,r,o)=>e+n+r+o+(t/2**32|0)|0,My=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),jy=(t,e,n,r,o,s)=>e+n+r+o+s+(t/2**32|0)|0,Uy=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Lt=new Uint32Array(64);class $y extends Kf{constructor(e=32){super(64,e,8,!1),this.A=Nt[0]|0,this.B=Nt[1]|0,this.C=Nt[2]|0,this.D=Nt[3]|0,this.E=Nt[4]|0,this.F=Nt[5]|0,this.G=Nt[6]|0,this.H=Nt[7]|0}get(){const{A:e,B:n,C:r,D:o,E:s,F:i,G:a,H:c}=this;return[e,n,r,o,s,i,a,c]}set(e,n,r,o,s,i,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,n){for(let u=0;u<16;u++,n+=4)Lt[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const f=Lt[u-15],h=Lt[u-2],g=it(f,7)^it(f,18)^f>>>3,m=it(h,17)^it(h,19)^h>>>10;Lt[u]=m+Lt[u-7]+g+Lt[u-16]|0}let{A:r,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=it(a,6)^it(a,11)^it(a,25),h=d+f+Py(a,c,l)+Uy[u]+Lt[u]|0,m=(it(r,2)^it(r,13)^it(r,22))+Ny(r,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=r,r=h+m|0}r=r+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,s,i,a,c,l,d)}roundClean(){ir(Lt)}destroy(){this.set(0,0,0,0,0,0,0,0),ir(this.buffer)}}const zf=By(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Hy=zf[0],qy=zf[1],Bt=new Uint32Array(80),_t=new Uint32Array(80);class Ky extends Kf{constructor(e=64){super(128,e,16,!1),this.Ah=Re[0]|0,this.Al=Re[1]|0,this.Bh=Re[2]|0,this.Bl=Re[3]|0,this.Ch=Re[4]|0,this.Cl=Re[5]|0,this.Dh=Re[6]|0,this.Dl=Re[7]|0,this.Eh=Re[8]|0,this.El=Re[9]|0,this.Fh=Re[10]|0,this.Fl=Re[11]|0,this.Gh=Re[12]|0,this.Gl=Re[13]|0,this.Hh=Re[14]|0,this.Hl=Re[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:f,Gh:h,Gl:g,Hh:m,Hl:b}=this;return[e,n,r,o,s,i,a,c,l,d,u,f,h,g,m,b]}set(e,n,r,o,s,i,a,c,l,d,u,f,h,g,m,b){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=d|0,this.Fh=u|0,this.Fl=f|0,this.Gh=h|0,this.Gl=g|0,this.Hh=m|0,this.Hl=b|0}process(e,n){for(let y=0;y<16;y++,n+=4)Bt[y]=e.getUint32(n),_t[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){const v=Bt[y-15]|0,L=_t[y-15]|0,k=Ln(v,L,1)^Ln(v,L,8)^rd(v,L,7),T=Bn(v,L,1)^Bn(v,L,8)^od(v,L,7),E=Bt[y-2]|0,S=_t[y-2]|0,C=Ln(E,S,19)^ko(E,S,61)^rd(E,S,6),N=Bn(E,S,19)^Co(E,S,61)^od(E,S,6),D=Dy(T,N,_t[y-7],_t[y-16]),A=Fy(D,k,C,Bt[y-7],Bt[y-16]);Bt[y]=A|0,_t[y]=D|0}let{Ah:r,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:f,Fh:h,Fl:g,Gh:m,Gl:b,Hh:w,Hl:I}=this;for(let y=0;y<80;y++){const v=Ln(u,f,14)^Ln(u,f,18)^ko(u,f,41),L=Bn(u,f,14)^Bn(u,f,18)^Co(u,f,41),k=u&h^~u&m,T=f&g^~f&b,E=My(I,L,T,qy[y],_t[y]),S=jy(E,w,v,k,Hy[y],Bt[y]),C=E|0,N=Ln(r,o,28)^ko(r,o,34)^ko(r,o,39),D=Bn(r,o,28)^Co(r,o,34)^Co(r,o,39),A=r&s^r&a^s&a,x=o&i^o&c^i&c;w=m|0,I=b|0,m=h|0,b=g|0,h=u|0,g=f|0,{h:u,l:f}=mt(l|0,d|0,S|0,C|0),l=a|0,d=c|0,a=s|0,c=i|0,s=r|0,i=o|0;const P=_y(C,D,x);r=Oy(P,S,N,A),o=P|0}({h:r,l:o}=mt(this.Ah|0,this.Al|0,r|0,o|0)),{h:s,l:i}=mt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=mt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=mt(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:f}=mt(this.Eh|0,this.El|0,u|0,f|0),{h,l:g}=mt(this.Fh|0,this.Fl|0,h|0,g|0),{h:m,l:b}=mt(this.Gh|0,this.Gl|0,m|0,b|0),{h:w,l:I}=mt(this.Hh|0,this.Hl|0,w|0,I|0),this.set(r,o,s,i,a,c,l,d,u,f,h,g,m,b,w,I)}roundClean(){ir(Bt,_t)}destroy(){ir(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Wf=qf(()=>new $y),zy=qf(()=>new Ky);const jc=BigInt(0),Ba=BigInt(1);function mn(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function rt(t,e,n=""){const r=wo(t),o=t?.length,s=e!==void 0;if(!r||s&&o!==e){const i=n&&`"${n}" `,a=s?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function Io(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Vf(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?jc:BigInt("0x"+t)}function Vs(t){return Vf(dn(t))}function to(t){return Sn(t),Vf(dn(Uint8Array.from(t).reverse()))}function Uc(t,e){return us(t.toString(16).padStart(e*2,"0"))}function Gf(t,e){return Uc(t,e).reverse()}function he(t,e,n){let r;if(typeof e=="string")try{r=us(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(wo(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const o=r.length;if(typeof n=="number"&&o!==n)throw new Error(t+" of length "+n+" expected, got "+o);return r}function sd(t){return Uint8Array.from(t)}const xi=t=>typeof t=="bigint"&&jc<=t;function Wy(t,e,n){return xi(t)&&xi(e)&&xi(n)&&e<=t&&t<n}function _a(t,e,n,r){if(!Wy(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Xf(t){let e;for(e=0;t>jc;t>>=Ba,e+=1);return e}const yo=t=>(Ba<<BigInt(t))-Ba;function Vy(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=h=>new Uint8Array(h),o=h=>Uint8Array.of(h);let s=r(t),i=r(t),a=0;const c=()=>{s.fill(1),i.fill(0),a=0},l=(...h)=>n(i,s,...h),d=(h=r(0))=>{i=l(o(0),h),s=l(),h.length!==0&&(i=l(o(1),h),s=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const g=[];for(;h<e;){s=l();const m=s.slice();g.push(m),h+=s.length}return lt(...g)};return(h,g)=>{c(),d(h);let m;for(;!(m=g(u()));)d();return c(),m}}function bo(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(o,s,i){const a=t[o];if(i&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([o,s])=>r(o,s,!1)),Object.entries(n).forEach(([o,s])=>r(o,s,!0))}function fs(t){const e=new WeakMap;return(n,...r)=>{const o=e.get(n);if(o!==void 0)return o;const s=t(n,...r);return e.set(n,s),s}}const $e=BigInt(0),ke=BigInt(1),rn=BigInt(2),Yf=BigInt(3),Zf=BigInt(4),Jf=BigInt(5),Gy=BigInt(7),Qf=BigInt(8),Xy=BigInt(9),eh=BigInt(16);function ye(t,e){const n=t%e;return n>=$e?n:e+n}function fe(t,e,n){let r=t;for(;e-- >$e;)r*=r,r%=n;return r}function id(t,e){if(t===$e)throw new Error("invert: expected non-zero number");if(e<=$e)throw new Error("invert: expected positive modulus, got "+e);let n=ye(t,e),r=e,o=$e,s=ke;for(;n!==$e;){const a=r/n,c=r%n,l=o-s*a;r=n,n=c,o=s,s=l}if(r!==ke)throw new Error("invert: does not exist");return ye(o,e)}function $c(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function th(t,e){const n=(t.ORDER+ke)/Zf,r=t.pow(e,n);return $c(t,r,e),r}function Yy(t,e){const n=(t.ORDER-Jf)/Qf,r=t.mul(e,rn),o=t.pow(r,n),s=t.mul(e,o),i=t.mul(t.mul(s,rn),o),a=t.mul(s,t.sub(i,t.ONE));return $c(t,a,e),a}function Zy(t){const e=xn(t),n=nh(t),r=n(e,e.neg(e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+Gy)/eh;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,r);const u=a.mul(l,o),f=a.mul(l,s),h=a.eql(a.sqr(d),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,d,h),d=a.cmov(f,u,g);const m=a.eql(a.sqr(d),c),b=a.cmov(l,d,m);return $c(a,b,c),b}}function nh(t){if(t<Yf)throw new Error("sqrt is not defined for small field");let e=t-ke,n=0;for(;e%rn===$e;)e/=rn,n++;let r=rn;const o=xn(t);for(;ad(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return th;let s=o.pow(r,e);const i=(e+ke)/rn;return function(c,l){if(c.is0(l))return l;if(ad(c,l)!==1)throw new Error("Cannot find square root");let d=n,u=c.mul(c.ONE,s),f=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let g=1,m=c.sqr(f);for(;!c.eql(m,c.ONE);)if(g++,m=c.sqr(m),g===d)throw new Error("Cannot find square root");const b=ke<<BigInt(d-g-1),w=c.pow(u,b);d=g,u=c.sqr(w),f=c.mul(f,u),h=c.mul(h,w)}return h}}function Jy(t){return t%Zf===Yf?th:t%Qf===Jf?Yy:t%eh===Xy?Zy(t):nh(t)}const Qy=(t,e)=>(ye(t,e)&ke)===ke,eb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function tb(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=eb.reduce((r,o)=>(r[o]="function",r),e);return bo(t,n),t}function nb(t,e,n){if(n<$e)throw new Error("invalid exponent, negatives unsupported");if(n===$e)return t.ONE;if(n===ke)return e;let r=t.ONE,o=e;for(;n>$e;)n&ke&&(r=t.mul(r,o)),o=t.sqr(o),n>>=ke;return r}function rh(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),o=e.reduce((i,a,c)=>t.is0(a)?i:(r[c]=i,t.mul(i,a)),t.ONE),s=t.inv(o);return e.reduceRight((i,a,c)=>t.is0(a)?i:(r[c]=t.mul(i,r[c]),t.mul(i,a)),s),r}function ad(t,e){const n=(t.ORDER-ke)/rn,r=t.pow(e,n),o=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),i=t.eql(r,t.neg(t.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function oh(t,e){e!==void 0&&La(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function xn(t,e,n=!1,r={}){if(t<=$e)throw new Error("invalid field: expected ORDER > 0, got "+t);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const f=e;f.BITS&&(o=f.BITS),f.sqrt&&(s=f.sqrt),typeof f.isLE=="boolean"&&(n=f.isLE),typeof f.modFromBytes=="boolean"&&(i=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(o=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:l}=oh(t,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:l,MASK:yo(c),ZERO:$e,ONE:ke,allowedLengths:a,create:f=>ye(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return $e<=f&&f<t},is0:f=>f===$e,isValidNot0:f=>!u.is0(f)&&u.isValid(f),isOdd:f=>(f&ke)===ke,neg:f=>ye(-f,t),eql:(f,h)=>f===h,sqr:f=>ye(f*f,t),add:(f,h)=>ye(f+h,t),sub:(f,h)=>ye(f-h,t),mul:(f,h)=>ye(f*h,t),pow:(f,h)=>nb(u,f,h),div:(f,h)=>ye(f*id(h,t),t),sqrN:f=>f*f,addN:(f,h)=>f+h,subN:(f,h)=>f-h,mulN:(f,h)=>f*h,inv:f=>id(f,t),sqrt:s||(f=>(d||(d=Jy(t)),d(u,f))),toBytes:f=>n?Gf(f,l):Uc(f,l),fromBytes:(f,h=!0)=>{if(a){if(!a.includes(f.length)||f.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);const m=new Uint8Array(l);m.set(f,n?0:m.length-f.length),f=m}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let g=n?to(f):Vs(f);if(i&&(g=ye(g,t)),!h&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:f=>rh(u,f),cmov:(f,h,g)=>g?h:f});return Object.freeze(u)}function sh(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function ih(t){const e=sh(t);return e+Math.ceil(e/2)}function rb(t,e,n=!1){const r=t.length,o=sh(e),s=ih(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const i=n?to(t):Vs(t),a=ye(i,e-ke)+ke;return n?Gf(a,o):Uc(a,o)}const ar=BigInt(0),on=BigInt(1);function hs(t,e){const n=e.negate();return t?n:e}function sn(t,e){const n=rh(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function ah(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ei(t,e){ah(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,s=yo(t),i=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function cd(t,e,n){const{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n;let a=Number(t&o),c=t>>i;a>r&&(a-=s,c+=on);const l=e*r,d=l+Math.abs(a)-1,u=a===0,f=a<0,h=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:f,isNegF:h,offsetF:l}}function ob(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function sb(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const Ai=new WeakMap,ch=new WeakMap;function ki(t){return ch.get(t)||1}function ld(t){if(t!==ar)throw new Error("invalid wNAF")}class lh{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>ar;)n&on&&(r=r.add(o)),o=o.double(),n>>=on;return r}precomputeWindow(e,n){const{windows:r,windowSize:o}=Ei(n,this.bits),s=[];let i=e,a=i;for(let c=0;c<r;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE;const i=Ei(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:f,offsetF:h}=cd(r,a,i);r=c,d?s=s.add(hs(f,n[h])):o=o.add(hs(u,n[l]))}return ld(r),{p:o,f:s}}wNAFUnsafe(e,n,r,o=this.ZERO){const s=Ei(e,this.bits);for(let i=0;i<s.windows&&r!==ar;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=cd(r,i,s);if(r=a,!l){const u=n[c];o=o.add(d?u.negate():u)}}return ld(r),o}getPrecomputes(e,n,r){let o=Ai.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Ai.set(n,o))),o}cached(e,n,r){const o=ki(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){const s=ki(e);return s===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,o)}createCache(e,n){ah(n,this.bits),ch.set(e,n),Ai.delete(e)}hasCache(e){return ki(e)!==1}}function ib(t,e,n,r){let o=e,s=t.ZERO,i=t.ZERO;for(;n>ar||r>ar;)n&on&&(s=s.add(o)),r&on&&(i=i.add(o)),o=o.double(),n>>=on,r>>=on;return{p1:s,p2:i}}function dh(t,e,n,r){ob(n,t),sb(r,e);const o=n.length,s=r.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,a=Xf(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=yo(c),d=new Array(Number(l)+1).fill(i),u=Math.floor((e.BITS-1)/c)*c;let f=i;for(let h=u;h>=0;h-=c){d.fill(i);for(let m=0;m<s;m++){const b=r[m],w=Number(b>>BigInt(h)&l);d[w]=d[w].add(n[m])}let g=i;for(let m=d.length-1,b=i;m>0;m--)b=b.add(d[m]),g=g.add(b);if(f=f.add(g),h!==0)for(let m=0;m<c;m++)f=f.double()}return f}function dd(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return tb(e),e}else return xn(t,{isLE:n})}function uh(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>ar))throw new Error(`CURVE.${c} must be positive bigint`)}const o=dd(e.p,n.Fp,r),s=dd(e.n,n.Fn,r),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}const Ot=BigInt(0),be=BigInt(1),Ci=BigInt(2),ab=BigInt(8);function cb(t,e,n,r){const o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function lb(t,e={}){const n=uh("edwards",t,e,e.FpFnLE),{Fp:r,Fn:o}=n;let s=n.CURVE;const{h:i}=s;bo(e,{},{uvRatio:"function"});const a=Ci<<BigInt(o.BYTES*8)-be,c=b=>r.create(b),l=e.uvRatio||((b,w)=>{try{return{isValid:!0,value:r.sqrt(r.div(b,w))}}catch{return{isValid:!1,value:Ot}}});if(!cb(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(b,w,I=!1){const y=I?be:Ot;return _a("coordinate "+b,w,y,a),w}function u(b){if(!(b instanceof g))throw new Error("ExtendedPoint expected")}const f=fs((b,w)=>{const{X:I,Y:y,Z:v}=b,L=b.is0();w==null&&(w=L?ab:r.inv(v));const k=c(I*w),T=c(y*w),E=r.mul(v,w);if(L)return{x:Ot,y:be};if(E!==be)throw new Error("invZ was invalid");return{x:k,y:T}}),h=fs(b=>{const{a:w,d:I}=s;if(b.is0())throw new Error("bad point: ZERO");const{X:y,Y:v,Z:L,T:k}=b,T=c(y*y),E=c(v*v),S=c(L*L),C=c(S*S),N=c(T*w),D=c(S*c(N+E)),A=c(C+c(I*c(T*E)));if(D!==A)throw new Error("bad point: equation left != right (1)");const x=c(y*v),P=c(L*k);if(x!==P)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(w,I,y,v){this.X=d("x",w),this.Y=d("y",I),this.Z=d("z",y,!0),this.T=d("t",v),Object.freeze(this)}static CURVE(){return s}static fromAffine(w){if(w instanceof g)throw new Error("extended point not allowed");const{x:I,y}=w||{};return d("x",I),d("y",y),new g(I,y,be,c(I*y))}static fromBytes(w,I=!1){const y=r.BYTES,{a:v,d:L}=s;w=sd(rt(w,y,"point")),mn(I,"zip215");const k=sd(w),T=w[y-1];k[y-1]=T&-129;const E=to(k),S=I?a:r.ORDER;_a("point.y",E,Ot,S);const C=c(E*E),N=c(C-be),D=c(L*C-v);let{isValid:A,value:x}=l(N,D);if(!A)throw new Error("bad point: invalid y coordinate");const P=(x&be)===be,R=(T&128)!==0;if(!I&&x===Ot&&R)throw new Error("bad point: x=0 and x_0=1");return R!==P&&(x=c(-x)),g.fromAffine({x,y:E})}static fromHex(w,I=!1){return g.fromBytes(he("point",w),I)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,I=!0){return m.createCache(this,w),I||this.multiply(Ci),this}assertValidity(){h(this)}equals(w){u(w);const{X:I,Y:y,Z:v}=this,{X:L,Y:k,Z:T}=w,E=c(I*T),S=c(L*v),C=c(y*T),N=c(k*v);return E===S&&C===N}is0(){return this.equals(g.ZERO)}negate(){return new g(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:w}=s,{X:I,Y:y,Z:v}=this,L=c(I*I),k=c(y*y),T=c(Ci*c(v*v)),E=c(w*L),S=I+y,C=c(c(S*S)-L-k),N=E+k,D=N-T,A=E-k,x=c(C*D),P=c(N*A),R=c(C*A),O=c(D*N);return new g(x,P,O,R)}add(w){u(w);const{a:I,d:y}=s,{X:v,Y:L,Z:k,T}=this,{X:E,Y:S,Z:C,T:N}=w,D=c(v*E),A=c(L*S),x=c(T*y*N),P=c(k*C),R=c((v+L)*(E+S)-D-A),O=P-x,j=P+x,M=c(A-I*D),B=c(R*O),F=c(j*M),U=c(R*M),H=c(O*j);return new g(B,F,H,U)}subtract(w){return this.add(w.negate())}multiply(w){if(!o.isValidNot0(w))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:I,f:y}=m.cached(this,w,v=>sn(g,v));return sn(g,[I,y])[0]}multiplyUnsafe(w,I=g.ZERO){if(!o.isValid(w))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return w===Ot?g.ZERO:this.is0()||w===be?this:m.unsafe(this,w,y=>sn(g,y),I)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(w){return f(this,w)}clearCofactor(){return i===be?this:this.multiplyUnsafe(i)}toBytes(){const{x:w,y:I}=this.toAffine(),y=r.toBytes(I);return y[y.length-1]|=w&be?128:0,y}toHex(){return dn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(w){return sn(g,w)}static msm(w,I){return dh(g,o,w,I)}_setWindowSize(w){this.precompute(w)}toRawBytes(){return this.toBytes()}}g.BASE=new g(s.Gx,s.Gy,be,c(s.Gx*s.Gy)),g.ZERO=new g(Ot,be,be,Ot),g.Fp=r,g.Fn=o;const m=new lh(g,o.BITS);return g.BASE.precompute(8),g}function db(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is required');bo(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:o,Fp:s,Fn:i}=t,a=n.randomBytes||Mc,c=n.adjustScalarBytes||(S=>S),l=n.domain||((S,C,N)=>{if(mn(N,"phflag"),C.length||N)throw new Error("Contexts/pre-hash are not supported");return S});function d(S){return i.create(to(S))}function u(S){const C=y.secretKey;S=he("private key",S,C);const N=he("hashed private key",e(S),2*C),D=c(N.slice(0,C)),A=N.slice(C,2*C),x=d(D);return{head:D,prefix:A,scalar:x}}function f(S){const{head:C,prefix:N,scalar:D}=u(S),A=o.multiply(D),x=A.toBytes();return{head:C,prefix:N,scalar:D,point:A,pointBytes:x}}function h(S){return f(S).pointBytes}function g(S=Uint8Array.of(),...C){const N=lt(...C);return d(e(l(N,he("context",S),!!r)))}function m(S,C,N={}){S=he("message",S),r&&(S=r(S));const{prefix:D,scalar:A,pointBytes:x}=f(C),P=g(N.context,D,S),R=o.multiply(P).toBytes(),O=g(N.context,R,x,S),j=i.create(P+O*A);if(!i.isValid(j))throw new Error("sign failed: invalid s");const M=lt(R,i.toBytes(j));return rt(M,y.signature,"result")}const b={zip215:!0};function w(S,C,N,D=b){const{context:A,zip215:x}=D,P=y.signature;S=he("signature",S,P),C=he("message",C),N=he("publicKey",N,y.publicKey),x!==void 0&&mn(x,"zip215"),r&&(C=r(C));const R=P/2,O=S.subarray(0,R),j=to(S.subarray(R,P));let M,B,F;try{M=t.fromBytes(N,x),B=t.fromBytes(O,x),F=o.multiplyUnsafe(j)}catch{return!1}if(!x&&M.isSmallOrder())return!1;const U=g(A,B.toBytes(),M.toBytes(),C);return B.add(M.multiplyUnsafe(U)).subtract(F).clearCofactor().is0()}const I=s.BYTES,y={secretKey:I,publicKey:I,signature:2*I,seed:I};function v(S=a(y.seed)){return rt(S,y.seed,"seed")}function L(S){const C=E.randomSecretKey(S);return{secretKey:C,publicKey:h(C)}}function k(S){return wo(S)&&S.length===i.BYTES}function T(S,C){try{return!!t.fromBytes(S,C)}catch{return!1}}const E={getExtendedPublicKey:f,randomSecretKey:v,isValidSecretKey:k,isValidPublicKey:T,toMontgomery(S){const{y:C}=t.fromBytes(S),N=y.publicKey,D=N===32;if(!D&&N!==57)throw new Error("only defined for 25519 and 448");const A=D?s.div(be+C,be-C):s.div(C-be,C+be);return s.toBytes(A)},toMontgomerySecret(S){const C=y.secretKey;rt(S,C);const N=e(S.subarray(0,C));return c(N).subarray(0,C)},randomPrivateKey:v,precompute(S=8,C=t.BASE){return C.precompute(S,!1)}};return Object.freeze({keygen:L,getPublicKey:h,sign:m,verify:w,utils:E,Point:t,lengths:y})}function ub(t){const e={a:t.a,d:t.d,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp,r=xn(e.n,t.nBitLength,!0),o={Fp:n,Fn:r,uvRatio:t.uvRatio},s={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:o,hash:t.hash,eddsaOpts:s}}function fb(t,e){const n=e.Point;return Object.assign({},e,{ExtendedPoint:n,CURVE:t,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function hb(t){const{CURVE:e,curveOpts:n,hash:r,eddsaOpts:o}=ub(t),s=lb(e,n),i=db(s,r,o);return fb(t,i)}const pb=BigInt(1),ud=BigInt(2);BigInt(3);const gb=BigInt(5),mb=BigInt(8),Hc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),fh={p:Hc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:mb,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function wb(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=Hc,a=t*t%s*t%s,c=fe(a,ud,s)*a%s,l=fe(c,pb,s)*t%s,d=fe(l,gb,s)*l%s,u=fe(d,e,s)*d%s,f=fe(u,n,s)*u%s,h=fe(f,r,s)*f%s,g=fe(h,o,s)*h%s,m=fe(g,o,s)*h%s,b=fe(m,e,s)*d%s;return{pow_p_5_8:fe(b,ud,s)*t%s,b2:a}}function yb(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const fd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function bb(t,e){const n=Hc,r=ye(e*e*e,n),o=ye(r*r*e,n),s=wb(t*o).pow_p_5_8;let i=ye(t*r*s,n);const a=ye(e*i*i,n),c=i,l=ye(i*fd,n),d=a===t,u=a===ye(-t,n),f=a===ye(-t*fd,n);return d&&(i=c),(u||f)&&(i=l),Qy(i,n)&&(i=ye(-i,n)),{isValid:d||u,value:i}}const vb=xn(fh.p,{isLE:!0}),Sb={...fh,Fp:vb,hash:zy,adjustScalarBytes:yb,uvRatio:bb},ps=hb(Sb);class hd extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}}class pd extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class xb extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}const Rt={get(t=globalThis){const e=t.crypto;if(e?.subtle==null)throw new xb("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}},gs=32,yt=64,Oa=32;let Gn;const hh=(async()=>{try{return await Rt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Eb(){const t=ps.utils.randomPrivateKey(),e=ps.getPublicKey(t);return{privateKey:Pb(t,e),publicKey:e}}async function Ab(t,e){let n;t.length===yt?n=t.subarray(0,32):n=t;const r={crv:"Ed25519",kty:"OKP",x:ee(t.subarray(32),"base64url"),d:ee(n,"base64url"),ext:!0,key_ops:["sign"]},o=await Rt.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),s=await Rt.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function kb(t,e){const n=t.subarray(0,Oa);return ps.sign(e instanceof Uint8Array?e:e.subarray(),n)}async function Cb(t,e){return Gn==null&&(Gn=await hh),Gn?Ab(t,e):kb(t,e)}async function Ib(t,e,n){if(t.buffer instanceof ArrayBuffer){const r=await Rt.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await Rt.get().subtle.verify({name:"Ed25519"},r,e,n instanceof Uint8Array?n:n.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Rb(t,e,n){return ps.verify(e,n instanceof Uint8Array?n:n.subarray(),t)}async function Tb(t,e,n){return Gn==null&&(Gn=await hh),Gn?Ib(t,e,n):Rb(t,e,n)}function Pb(t,e){const n=new Uint8Array(yt);for(let r=0;r<Oa;r++)n[r]=t[r],n[Oa+r]=e[r];return n}function Gs(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}class ph{type="Ed25519";raw;constructor(e){this.raw=no(e,gs)}toMultihash(){return go.digest(Js(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return Be.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:st(this.raw,e.raw)}verify(e,n,r){r?.signal?.throwIfAborted();const o=Tb(this.raw,n,e);return Gs(o)?o.then(s=>(r?.signal?.throwIfAborted(),s)):o}}class Da{type="Ed25519";raw;publicKey;constructor(e,n){this.raw=no(e,yt),this.publicKey=new ph(n)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:st(this.raw,e.raw)}sign(e,n){n?.signal?.throwIfAborted();const r=Cb(this.raw,e);return Gs(r)?r.then(o=>(n?.signal?.throwIfAborted(),o)):(n?.signal?.throwIfAborted(),r)}}function Nb(t){if(t.length>yt){t=no(t,yt+gs);const r=t.subarray(0,yt),o=t.subarray(yt,t.length);return new Da(r,o)}t=no(t,yt);const e=t.subarray(0,yt),n=t.subarray(gs);return new Da(e,n)}function gh(t){return t=no(t,gs),new ph(t)}async function Lb(){const{privateKey:t,publicKey:e}=Eb();return new Da(t,e)}function no(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new ot(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}const Bb=Math.pow(2,7),_b=Math.pow(2,14),Ob=Math.pow(2,21),qc=Math.pow(2,28),Kc=Math.pow(2,35),zc=Math.pow(2,42),Wc=Math.pow(2,49),oe=128,Te=127;function En(t){if(t<Bb)return 1;if(t<_b)return 2;if(t<Ob)return 3;if(t<qc)return 4;if(t<Kc)return 5;if(t<zc)return 6;if(t<Wc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function mh(t,e,n=0){switch(En(t)){case 8:e[n++]=t&255|oe,t/=128;case 7:e[n++]=t&255|oe,t/=128;case 6:e[n++]=t&255|oe,t/=128;case 5:e[n++]=t&255|oe,t/=128;case 4:e[n++]=t&255|oe,t>>>=7;case 3:e[n++]=t&255|oe,t>>>=7;case 2:e[n++]=t&255|oe,t>>>=7;case 1:{e[n++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Db(t,e,n=0){switch(En(t)){case 8:e.set(n++,t&255|oe),t/=128;case 7:e.set(n++,t&255|oe),t/=128;case 6:e.set(n++,t&255|oe),t/=128;case 5:e.set(n++,t&255|oe),t/=128;case 4:e.set(n++,t&255|oe),t>>>=7;case 3:e.set(n++,t&255|oe),t>>>=7;case 2:e.set(n++,t&255|oe),t>>>=7;case 1:{e.set(n++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function wh(t,e){let n=t[e],r=0;if(r+=n&Te,n<oe||(n=t[e+1],r+=(n&Te)<<7,n<oe)||(n=t[e+2],r+=(n&Te)<<14,n<oe)||(n=t[e+3],r+=(n&Te)<<21,n<oe)||(n=t[e+4],r+=(n&Te)*qc,n<oe)||(n=t[e+5],r+=(n&Te)*Kc,n<oe)||(n=t[e+6],r+=(n&Te)*zc,n<oe)||(n=t[e+7],r+=(n&Te)*Wc,n<oe))return r;throw new RangeError("Could not decode varint")}function Fb(t,e){let n=t.get(e),r=0;if(r+=n&Te,n<oe||(n=t.get(e+1),r+=(n&Te)<<7,n<oe)||(n=t.get(e+2),r+=(n&Te)<<14,n<oe)||(n=t.get(e+3),r+=(n&Te)<<21,n<oe)||(n=t.get(e+4),r+=(n&Te)*qc,n<oe)||(n=t.get(e+5),r+=(n&Te)*Kc,n<oe)||(n=t.get(e+6),r+=(n&Te)*zc,n<oe)||(n=t.get(e+7),r+=(n&Te)*Wc,n<oe))return r;throw new RangeError("Could not decode varint")}function Mb(t,e,n=0){return e==null&&(e=It(En(t))),e instanceof Uint8Array?mh(t,e,n):Db(t,e,n)}function yh(t,e=0){return t instanceof Uint8Array?wh(t,e):Fb(t,e)}const Vc=new Float32Array([-0]),Kt=new Uint8Array(Vc.buffer);function jb(t,e,n){Vc[0]=t,e[n]=Kt[0],e[n+1]=Kt[1],e[n+2]=Kt[2],e[n+3]=Kt[3]}function Ub(t,e){return Kt[0]=t[e],Kt[1]=t[e+1],Kt[2]=t[e+2],Kt[3]=t[e+3],Vc[0]}const Gc=new Float64Array([-0]),Pe=new Uint8Array(Gc.buffer);function $b(t,e,n){Gc[0]=t,e[n]=Pe[0],e[n+1]=Pe[1],e[n+2]=Pe[2],e[n+3]=Pe[3],e[n+4]=Pe[4],e[n+5]=Pe[5],e[n+6]=Pe[6],e[n+7]=Pe[7]}function Hb(t,e){return Pe[0]=t[e],Pe[1]=t[e+1],Pe[2]=t[e+2],Pe[3]=t[e+3],Pe[4]=t[e+4],Pe[5]=t[e+5],Pe[6]=t[e+6],Pe[7]=t[e+7],Gc[0]}const qb=BigInt(Number.MAX_SAFE_INTEGER),Kb=BigInt(Number.MIN_SAFE_INTEGER);class Ne{lo;hi;constructor(e,n){this.lo=e|0,this.hi=n|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){const n=~this.lo+1>>>0;let r=~this.hi>>>0;return n===0&&(r=r+1>>>0),-(n+r*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){const n=~this.lo+1>>>0;let r=~this.hi>>>0;return n===0&&(r=r+1>>>0),-(BigInt(n)+(BigInt(r)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,n=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?n===0?e<16384?e<128?1:2:e<2097152?3:4:n<16384?n<128?5:6:n<2097152?7:8:r<128?9:10}static fromBigInt(e){if(e===0n)return un;if(e<qb&&e>Kb)return this.fromNumber(Number(e));const n=e<0n;n&&(e=-e);let r=e>>32n,o=e-(r<<32n);return n&&(r=~r|0n,o=~o|0n,++o>gd&&(o=0n,++r>gd&&(r=0n))),new Ne(Number(o),Number(r))}static fromNumber(e){if(e===0)return un;const n=e<0;n&&(e=-e);let r=e>>>0,o=(e-r)/4294967296>>>0;return n&&(o=~o>>>0,r=~r>>>0,++r>4294967295&&(r=0,++o>4294967295&&(o=0))),new Ne(r,o)}static from(e){return typeof e=="number"?Ne.fromNumber(e):typeof e=="bigint"?Ne.fromBigInt(e):typeof e=="string"?Ne.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new Ne(e.low>>>0,e.high>>>0):un}}const un=new Ne(0,0);un.toBigInt=function(){return 0n};un.zzEncode=un.zzDecode=function(){return this};un.length=function(){return 1};const gd=4294967296n;function zb(t){let e=0,n=0;for(let r=0;r<t.length;++r)n=t.charCodeAt(r),n<128?e+=1:n<2048?e+=2:(n&64512)===55296&&(t.charCodeAt(r+1)&64512)===56320?(++r,e+=4):e+=3;return e}function Wb(t,e,n){if(n-e<1)return"";let o;const s=[];let i=0,a;for(;e<n;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function bh(t,e,n){const r=n;let o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[n++]=o:o<2048?(e[n++]=o>>6|192,e[n++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[n++]=o>>18|240,e[n++]=o>>12&63|128,e[n++]=o>>6&63|128,e[n++]=o&63|128):(e[n++]=o>>12|224,e[n++]=o>>6&63|128,e[n++]=o&63|128);return n-r}function tt(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function Ro(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}class Vb{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,tt(this,10);return e}int32(){return this.uint32()|0}sint32(){const e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw tt(this,4);return Ro(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw tt(this,4);return Ro(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw tt(this,4);const e=Ub(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw tt(this,4);const e=Hb(this.buf,this.pos);return this.pos+=8,e}bytes(){const e=this.uint32(),n=this.pos,r=this.pos+e;if(r>this.len)throw tt(this,e);return this.pos+=e,n===r?new Uint8Array(0):this.buf.subarray(n,r)}string(){const e=this.bytes();return Wb(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw tt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw tt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new Ne(0,0);let n=0;if(this.len-this.pos>4){for(;n<4;++n)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<n*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;n=0}else{for(;n<3;++n){if(this.pos>=this.len)throw tt(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<n*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<n*7)>>>0,e}if(this.len-this.pos>4){for(;n<5;++n)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<n*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;n<5;++n){if(this.pos>=this.len)throw tt(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<n*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw tt(this,8);const e=Ro(this.buf,this.pos+=4),n=Ro(this.buf,this.pos+=4);return new Ne(e,n)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=wh(this.buf,this.pos);return this.pos+=En(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function Gb(t){return new Vb(t instanceof Uint8Array?t:t.subarray())}function Xs(t,e,n){const r=Gb(t);return e.decode(r,void 0,n)}function Xb(t){let r,o=8192;return function(i){if(i<1||i>4096)return It(i);o+i>8192&&(r=It(8192),o=0);const a=r.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}class Ur{fn;len;next;val;constructor(e,n,r){this.fn=e,this.len=n,this.next=void 0,this.val=r}}function Ii(){}class Yb{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const Zb=Xb();function Jb(t){return globalThis.Buffer!=null?It(t):Zb(t)}class Fa{len;head;tail;states;constructor(){this.len=0,this.head=new Ur(Ii,0,0),this.tail=this.head,this.states=null}_push(e,n,r){return this.tail=this.tail.next=new Ur(e,n,r),this.len+=n,this}uint32(e){return this.len+=(this.tail=this.tail.next=new e0((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(To,10,Ne.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const n=Ne.fromBigInt(e);return this._push(To,n.length(),n)}uint64Number(e){return this._push(mh,En(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const n=Ne.fromBigInt(e).zzEncode();return this._push(To,n.length(),n)}sint64Number(e){const n=Ne.fromNumber(e).zzEncode();return this._push(To,n.length(),n)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ri,1,e?1:0)}fixed32(e){return this._push(Cr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const n=Ne.fromBigInt(e);return this._push(Cr,4,n.lo)._push(Cr,4,n.hi)}fixed64Number(e){const n=Ne.fromNumber(e);return this._push(Cr,4,n.lo)._push(Cr,4,n.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(jb,4,e)}double(e){return this._push($b,8,e)}bytes(e){const n=e.length>>>0;return n===0?this._push(Ri,1,0):this.uint32(n)._push(t0,n,e)}string(e){const n=zb(e);return n!==0?this.uint32(n)._push(bh,n,e):this._push(Ri,1,0)}fork(){return this.states=new Yb(this),this.head=this.tail=new Ur(Ii,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Ur(Ii,0,0),this.len=0),this}ldelim(){const e=this.head,n=this.tail,r=this.len;return this.reset().uint32(r),r!==0&&(this.tail.next=e.next,this.tail=n,this.len+=r),this}finish(){let e=this.head.next;const n=Jb(this.len);let r=0;for(;e!=null;)e.fn(e.val,n,r),r+=e.len,e=e.next;return n}}function Ri(t,e,n){e[n]=t&255}function Qb(t,e,n){for(;t>127;)e[n++]=t&127|128,t>>>=7;e[n]=t}class e0 extends Ur{next;constructor(e,n){super(Qb,e,n),this.next=void 0}}function To(t,e,n){for(;t.hi!==0;)e[n++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[n++]=t.lo&127|128,t.lo=t.lo>>>7;e[n++]=t.lo}function Cr(t,e,n){e[n]=t&255,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}function t0(t,e,n){e.set(t,n)}globalThis.Buffer!=null&&(Fa.prototype.bytes=function(t){const e=t.length>>>0;return this.uint32(e),e>0&&this._push(n0,e,t),this},Fa.prototype.string=function(t){const e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(r0,e,t),this});function n0(t,e,n){e.set(t,n)}function r0(t,e,n){t.length<40?bh(t,e,n):e.utf8Write!=null?e.utf8Write(t,n):e.set(we(t),n)}function o0(){return new Fa}function Ys(t,e){const n=o0();return e.encode(t,n,{lengthDelimited:!1}),n.finish()}var ms;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(ms||(ms={}));function vh(t,e,n,r){return{name:t,type:e,encode:n,decode:r}}function s0(t){function e(o){if(t[o.toString()]==null)throw new Error("Invalid enum value");return t[o]}const n=function(s,i){const a=e(s);i.int32(a)},r=function(s){const i=s.int32();return e(i)};return vh("enum",ms.VARINT,n,r)}function Zs(t,e){return vh("message",ms.LENGTH_DELIMITED,t,e)}class md extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var de;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(de||(de={}));var Ma;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(Ma||(Ma={}));(function(t){t.codec=()=>s0(Ma)})(de||(de={}));var wn;(function(t){let e;t.codec=()=>(e==null&&(e=Zs((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),de.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{s.Type=de.codec().decode(n);break}case 2:{s.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>Ys(n,t.codec()),t.decode=(n,r)=>Xs(n,t.codec(),r)})(wn||(wn={}));var ws;(function(t){let e;t.codec=()=>(e==null&&(e=Zs((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),de.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{s.Type=de.codec().decode(n);break}case 2:{s.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>Ys(n,t.codec()),t.decode=(n,r)=>Xs(n,t.codec(),r)})(ws||(ws={}));const Sh=Wf;class xh{type="RSA";jwk;_raw;_multihash;constructor(e,n){this.jwk=e,this._multihash=n}get raw(){return this._raw==null&&(this._raw=Ah(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return le.createV1(114,this._multihash)}toString(){return Be.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:st(this.raw,e.raw)}verify(e,n,r){return v0(this.jwk,n,e,r)}}class i0{type="RSA";jwk;_raw;publicKey;constructor(e,n){this.jwk=e,this.publicKey=n}get raw(){return this._raw==null&&(this._raw=u0(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:st(this.raw,e.raw)}sign(e,n){return b0(this.jwk,e,n)}}const a0=8192,Eh=18,c0=1062,l0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function d0(t){return{n:ee(t[1],"base64url"),e:ee(t[2],"base64url"),d:ee(t[3],"base64url"),p:ee(t[4],"base64url"),q:ee(t[5],"base64url"),dp:ee(t[6],"base64url"),dq:ee(t[7],"base64url"),qi:ee(t[8],"base64url"),kty:"RSA"}}function u0(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new ot("JWK was missing components");return kt([Ke(Uint8Array.from([0])),Ke(we(t.n,"base64url")),Ke(we(t.e,"base64url")),Ke(we(t.d,"base64url")),Ke(we(t.p,"base64url")),Ke(we(t.q,"base64url")),Ke(we(t.dp,"base64url")),Ke(we(t.dq,"base64url")),Ke(we(t.qi,"base64url"))]).subarray()}function f0(t){const e=gr(t[1],{offset:0});return{kty:"RSA",n:ee(e[0],"base64url"),e:ee(e[1],"base64url")}}function Ah(t){if(t.n==null||t.e==null)throw new ot("JWK was missing components");return kt([l0,Dc(kt([Ke(we(t.n,"base64url")),Ke(we(t.e,"base64url"))]))]).subarray()}function h0(t){const e=gr(t);return p0(e)}function p0(t){const e=d0(t);return w0(e)}function g0(t,e){if(t.byteLength>=c0)throw new Ef("Key size is too large");const n=gr(t,{offset:0});return m0(n,t,e)}function m0(t,e,n){const r=f0(t);if(n==null){const o=Sh(wn.encode({Type:de.RSA,Data:e}));n=po(Eh,o)}return new xh(r,n)}function w0(t){if(S0(t)>a0)throw new ot("Key size is too large");const e=y0(t),n=Sh(wn.encode({Type:de.RSA,Data:Ah(e.publicKey)})),r=po(Eh,n);return new i0(e.privateKey,new xh(e.publicKey,r))}function y0(t){if(t==null)throw new ot("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function b0(t,e,n){const r=await Rt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);n?.signal?.throwIfAborted();const o=await Rt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function v0(t,e,n,r){const o=await Rt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const s=await Rt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,n instanceof Uint8Array?n:n.subarray());return r?.signal?.throwIfAborted(),s}function S0(t){if(t.kty!=="RSA")throw new ot("invalid key type");if(t.n==null)throw new ot("invalid key modulus");return we(t.n,"base64url").length*8}class kh extends Hf{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,Uf(e);const r=Fc(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const o=this.blockLen,s=new Uint8Array(o);s.set(r.length>o?e.create().update(r).digest():r);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),ir(s)}update(e){return ds(this),this.iHash.update(e),this}digestInto(e){ds(this),Sn(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ch=(t,e,n)=>new kh(t,e).update(n).digest();Ch.create=(t,e)=>new kh(t,e);const wd=(t,e)=>(t+(t>=0?e:-e)/Ih)/e;function x0(t,e,n){const[[r,o],[s,i]]=e,a=wd(i*t,n),c=wd(-o*t,n);let l=t-a*r-c*s,d=-a*o-c*i;const u=l<xt,f=d<xt;u&&(l=-l),f&&(d=-d);const h=yo(Math.ceil(Xf(n)/2))+Xn;if(l<xt||l>=h||d<xt||d>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:f,k2:d}}function ja(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Ti(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return mn(n.lowS,"lowS"),mn(n.prehash,"prehash"),n.format!==void 0&&ja(n.format),n}class E0 extends Error{constructor(e=""){super(e)}}const bt={Err:E0,_tlv:{encode:(t,e)=>{const{Err:n}=bt;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,o=Io(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Io(o.length/2|128):"";return Io(t)+s+o+e},decode(t,e){const{Err:n}=bt;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const o=e[r++],s=!!(o&128);let i=0;if(!s)i=o;else{const c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(r+=c,i<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+i);if(a.length!==i)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+i)}}},_int:{encode(t){const{Err:e}=bt;if(t<xt)throw new e("integer: negative integers are not allowed");let n=Io(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=bt;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Vs(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=bt,o=he("signature",t),{v:s,l:i}=r.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:l,l:d}=r.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){const{_tlv:e,_int:n}=bt,r=e.encode(2,n.encode(t.r)),o=e.encode(2,n.encode(t.s)),s=r+o;return e.encode(48,s)}},xt=BigInt(0),Xn=BigInt(1),Ih=BigInt(2),Po=BigInt(3),A0=BigInt(4);function $n(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let o=he("private key",e);try{r=t.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function k0(t,e={}){const n=uh("weierstrass",t,e),{Fp:r,Fn:o}=n;let s=n.CURVE;const{h:i,n:a}=s;bo(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Th(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(D,A,x){const{x:P,y:R}=A.toAffine(),O=r.toBytes(P);if(mn(x,"isCompressed"),x){d();const j=!r.isOdd(R);return lt(Rh(j),O)}else return lt(Uint8Array.of(4),O,r.toBytes(R))}function f(D){rt(D,void 0,"Point");const{publicKey:A,publicKeyUncompressed:x}=l,P=D.length,R=D[0],O=D.subarray(1);if(P===A&&(R===2||R===3)){const j=r.fromBytes(O);if(!r.isValid(j))throw new Error("bad point: is not on curve, wrong x");const M=m(j);let B;try{B=r.sqrt(M)}catch(H){const q=H instanceof Error?": "+H.message:"";throw new Error("bad point: is not on curve, sqrt error"+q)}d();const F=r.isOdd(B);return(R&1)===1!==F&&(B=r.neg(B)),{x:j,y:B}}else if(P===x&&R===4){const j=r.BYTES,M=r.fromBytes(O.subarray(0,j)),B=r.fromBytes(O.subarray(j,j*2));if(!b(M,B))throw new Error("bad point: is not on curve");return{x:M,y:B}}else throw new Error(`bad point: got length ${P}, expected compressed=${A} or uncompressed=${x}`)}const h=e.toBytes||u,g=e.fromBytes||f;function m(D){const A=r.sqr(D),x=r.mul(A,D);return r.add(r.add(x,r.mul(D,s.a)),s.b)}function b(D,A){const x=r.sqr(A),P=m(D);return r.eql(x,P)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const w=r.mul(r.pow(s.a,Po),A0),I=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(w,I)))throw new Error("bad curve params: a or b");function y(D,A,x=!1){if(!r.isValid(A)||x&&r.is0(A))throw new Error(`bad point coordinate ${D}`);return A}function v(D){if(!(D instanceof S))throw new Error("ProjectivePoint expected")}function L(D){if(!c||!c.basises)throw new Error("no endo");return x0(D,c.basises,o.ORDER)}const k=fs((D,A)=>{const{X:x,Y:P,Z:R}=D;if(r.eql(R,r.ONE))return{x,y:P};const O=D.is0();A==null&&(A=O?r.ONE:r.inv(R));const j=r.mul(x,A),M=r.mul(P,A),B=r.mul(R,A);if(O)return{x:r.ZERO,y:r.ZERO};if(!r.eql(B,r.ONE))throw new Error("invZ was invalid");return{x:j,y:M}}),T=fs(D=>{if(D.is0()){if(e.allowInfinityPoint&&!r.is0(D.Y))return;throw new Error("bad point: ZERO")}const{x:A,y:x}=D.toAffine();if(!r.isValid(A)||!r.isValid(x))throw new Error("bad point: x or y not field elements");if(!b(A,x))throw new Error("bad point: equation left != right");if(!D.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function E(D,A,x,P,R){return x=new S(r.mul(x.X,D),x.Y,x.Z),A=hs(P,A),x=hs(R,x),A.add(x)}class S{constructor(A,x,P){this.X=y("x",A),this.Y=y("y",x,!0),this.Z=y("z",P),Object.freeze(this)}static CURVE(){return s}static fromAffine(A){const{x,y:P}=A||{};if(!A||!r.isValid(x)||!r.isValid(P))throw new Error("invalid affine point");if(A instanceof S)throw new Error("projective point not allowed");return r.is0(x)&&r.is0(P)?S.ZERO:new S(x,P,r.ONE)}static fromBytes(A){const x=S.fromAffine(g(rt(A,void 0,"point")));return x.assertValidity(),x}static fromHex(A){return S.fromBytes(he("pointHex",A))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(A=8,x=!0){return N.createCache(this,A),x||this.multiply(Po),this}assertValidity(){T(this)}hasEvenY(){const{y:A}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(A)}equals(A){v(A);const{X:x,Y:P,Z:R}=this,{X:O,Y:j,Z:M}=A,B=r.eql(r.mul(x,M),r.mul(O,R)),F=r.eql(r.mul(P,M),r.mul(j,R));return B&&F}negate(){return new S(this.X,r.neg(this.Y),this.Z)}double(){const{a:A,b:x}=s,P=r.mul(x,Po),{X:R,Y:O,Z:j}=this;let M=r.ZERO,B=r.ZERO,F=r.ZERO,U=r.mul(R,R),H=r.mul(O,O),q=r.mul(j,j),K=r.mul(R,O);return K=r.add(K,K),F=r.mul(R,j),F=r.add(F,F),M=r.mul(A,F),B=r.mul(P,q),B=r.add(M,B),M=r.sub(H,B),B=r.add(H,B),B=r.mul(M,B),M=r.mul(K,M),F=r.mul(P,F),q=r.mul(A,q),K=r.sub(U,q),K=r.mul(A,K),K=r.add(K,F),F=r.add(U,U),U=r.add(F,U),U=r.add(U,q),U=r.mul(U,K),B=r.add(B,U),q=r.mul(O,j),q=r.add(q,q),U=r.mul(q,K),M=r.sub(M,U),F=r.mul(q,H),F=r.add(F,F),F=r.add(F,F),new S(M,B,F)}add(A){v(A);const{X:x,Y:P,Z:R}=this,{X:O,Y:j,Z:M}=A;let B=r.ZERO,F=r.ZERO,U=r.ZERO;const H=s.a,q=r.mul(s.b,Po);let K=r.mul(x,O),W=r.mul(P,j),V=r.mul(R,M),G=r.add(x,P),X=r.add(O,j);G=r.mul(G,X),X=r.add(K,W),G=r.sub(G,X),X=r.add(x,R);let Z=r.add(O,M);return X=r.mul(X,Z),Z=r.add(K,V),X=r.sub(X,Z),Z=r.add(P,R),B=r.add(j,M),Z=r.mul(Z,B),B=r.add(W,V),Z=r.sub(Z,B),U=r.mul(H,X),B=r.mul(q,V),U=r.add(B,U),B=r.sub(W,U),U=r.add(W,U),F=r.mul(B,U),W=r.add(K,K),W=r.add(W,K),V=r.mul(H,V),X=r.mul(q,X),W=r.add(W,V),V=r.sub(K,V),V=r.mul(H,V),X=r.add(X,V),K=r.mul(W,X),F=r.add(F,K),K=r.mul(Z,X),B=r.mul(G,B),B=r.sub(B,K),K=r.mul(G,W),U=r.mul(Z,U),U=r.add(U,K),new S(B,F,U)}subtract(A){return this.add(A.negate())}is0(){return this.equals(S.ZERO)}multiply(A){const{endo:x}=e;if(!o.isValidNot0(A))throw new Error("invalid scalar: out of range");let P,R;const O=j=>N.cached(this,j,M=>sn(S,M));if(x){const{k1neg:j,k1:M,k2neg:B,k2:F}=L(A),{p:U,f:H}=O(M),{p:q,f:K}=O(F);R=H.add(K),P=E(x.beta,U,q,j,B)}else{const{p:j,f:M}=O(A);P=j,R=M}return sn(S,[P,R])[0]}multiplyUnsafe(A){const{endo:x}=e,P=this;if(!o.isValid(A))throw new Error("invalid scalar: out of range");if(A===xt||P.is0())return S.ZERO;if(A===Xn)return P;if(N.hasCache(this))return this.multiply(A);if(x){const{k1neg:R,k1:O,k2neg:j,k2:M}=L(A),{p1:B,p2:F}=ib(S,P,O,M);return E(x.beta,B,F,R,j)}else return N.unsafe(P,A)}multiplyAndAddUnsafe(A,x,P){const R=this.multiplyUnsafe(x).add(A.multiplyUnsafe(P));return R.is0()?void 0:R}toAffine(A){return k(this,A)}isTorsionFree(){const{isTorsionFree:A}=e;return i===Xn?!0:A?A(S,this):N.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:A}=e;return i===Xn?this:A?A(S,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(A=!0){return mn(A,"isCompressed"),this.assertValidity(),h(S,this,A)}toHex(A=!0){return dn(this.toBytes(A))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(A=!0){return this.toBytes(A)}_setWindowSize(A){this.precompute(A)}static normalizeZ(A){return sn(S,A)}static msm(A,x){return dh(S,o,A,x)}static fromPrivateKey(A){return S.BASE.multiply($n(o,A))}}S.BASE=new S(s.Gx,s.Gy,r.ONE),S.ZERO=new S(r.ZERO,r.ONE,r.ZERO),S.Fp=r,S.Fn=o;const C=o.BITS,N=new lh(S,e.endo?Math.ceil(C/2):C);return S.BASE.precompute(8),S}function Rh(t){return Uint8Array.of(t?2:3)}function Th(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function C0(t,e={}){const{Fn:n}=t,r=e.randomBytes||Mc,o=Object.assign(Th(t.Fp,n),{seed:ih(n.ORDER)});function s(h){try{return!!$n(n,h)}catch{return!1}}function i(h,g){const{publicKey:m,publicKeyUncompressed:b}=o;try{const w=h.length;return g===!0&&w!==m||g===!1&&w!==b?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=r(o.seed)){return rb(rt(h,o.seed,"seed"),n.ORDER)}function c(h,g=!0){return t.BASE.multiply($n(n,h)).toBytes(g)}function l(h){const g=a(h);return{secretKey:g,publicKey:c(g)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:g,publicKey:m,publicKeyUncompressed:b}=o;if(n.allowedLengths||g===m)return;const w=he("key",h).length;return w===m||w===b}function u(h,g,m=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(g)===!1)throw new Error("second arg must be public key");const b=$n(n,h);return t.fromHex(g).multiply(b).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>$n(n,h),precompute(h=8,g=t.BASE){return g.precompute(h,!1)}},lengths:o})}function I0(t,e,n={}){Uf(e),bo(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Mc,o=n.hmac||((x,...P)=>Ch(e,x,lt(...P))),{Fp:s,Fn:i}=t,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h}=C0(t,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function b(x){const P=a>>Xn;return x>P}function w(x,P){if(!i.isValidNot0(P))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return P}function I(x,P){ja(P);const R=h.signature,O=P==="compact"?R:P==="recovered"?R+1:void 0;return rt(x,O,`${P} signature`)}class y{constructor(P,R,O){this.r=w("r",P),this.s=w("s",R),O!=null&&(this.recovery=O),Object.freeze(this)}static fromBytes(P,R=m){I(P,R);let O;if(R==="der"){const{r:F,s:U}=bt.toSig(rt(P));return new y(F,U)}R==="recovered"&&(O=P[0],R="compact",P=P.subarray(1));const j=i.BYTES,M=P.subarray(0,j),B=P.subarray(j,j*2);return new y(i.fromBytes(M),i.fromBytes(B),O)}static fromHex(P,R){return this.fromBytes(us(P),R)}addRecoveryBit(P){return new y(this.r,this.s,P)}recoverPublicKey(P){const R=s.ORDER,{r:O,s:j,recovery:M}=this;if(M==null||![0,1,2,3].includes(M))throw new Error("recovery id invalid");if(a*Ih<R&&M>1)throw new Error("recovery id is ambiguous for h>1 curve");const F=M===2||M===3?O+a:O;if(!s.isValid(F))throw new Error("recovery id 2 or 3 invalid");const U=s.toBytes(F),H=t.fromBytes(lt(Rh((M&1)===0),U)),q=i.inv(F),K=L(he("msgHash",P)),W=i.create(-K*q),V=i.create(j*q),G=t.BASE.multiplyUnsafe(W).add(H.multiplyUnsafe(V));if(G.is0())throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return b(this.s)}toBytes(P=m){if(ja(P),P==="der")return us(bt.hexFromSig(this));const R=i.toBytes(this.r),O=i.toBytes(this.s);if(P==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return lt(Uint8Array.of(this.recovery),R,O)}return lt(R,O)}toHex(P){return dn(this.toBytes(P))}assertValidity(){}static fromCompact(P){return y.fromBytes(he("sig",P),"compact")}static fromDER(P){return y.fromBytes(he("sig",P),"der")}normalizeS(){return this.hasHighS()?new y(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return dn(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return dn(this.toBytes("compact"))}}const v=n.bits2int||function(P){if(P.length>8192)throw new Error("input is too large");const R=Vs(P),O=P.length*8-c;return O>0?R>>BigInt(O):R},L=n.bits2int_modN||function(P){return i.create(v(P))},k=yo(c);function T(x){return _a("num < 2^"+c,x,xt,k),i.toBytes(x)}function E(x,P){return rt(x,void 0,"message"),P?rt(e(x),void 0,"prehashed message"):x}function S(x,P,R){if(["recovered","canonical"].some(W=>W in R))throw new Error("sign() legacy options not supported");const{lowS:O,prehash:j,extraEntropy:M}=Ti(R,g);x=E(x,j);const B=L(x),F=$n(i,P),U=[T(F),T(B)];if(M!=null&&M!==!1){const W=M===!0?r(h.secretKey):M;U.push(he("extraEntropy",W))}const H=lt(...U),q=B;function K(W){const V=v(W);if(!i.isValidNot0(V))return;const G=i.inv(V),X=t.BASE.multiply(V).toAffine(),Z=i.create(X.x);if(Z===xt)return;const ce=i.create(G*i.create(q+Z*F));if(ce===xt)return;let Ie=(X.x===Z?0:2)|Number(X.y&Xn),Me=ce;return O&&b(ce)&&(Me=i.neg(ce),Ie^=1),new y(Z,Me,Ie)}return{seed:H,k2sig:K}}function C(x,P,R={}){x=he("message",x);const{seed:O,k2sig:j}=S(x,P,R);return Vy(e.outputLen,i.BYTES,o)(O,j)}function N(x){let P;const R=typeof x=="string"||wo(x),O=!R&&x!==null&&typeof x=="object"&&typeof x.r=="bigint"&&typeof x.s=="bigint";if(!R&&!O)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(O)P=new y(x.r,x.s);else if(R){try{P=y.fromBytes(he("sig",x),"der")}catch(j){if(!(j instanceof bt.Err))throw j}if(!P)try{P=y.fromBytes(he("sig",x),"compact")}catch{return!1}}return P||!1}function D(x,P,R,O={}){const{lowS:j,prehash:M,format:B}=Ti(O,g);if(R=he("publicKey",R),P=E(he("message",P),M),"strict"in O)throw new Error("options.strict was renamed to lowS");const F=B===void 0?N(x):y.fromBytes(he("sig",x),B);if(F===!1)return!1;try{const U=t.fromBytes(R);if(j&&F.hasHighS())return!1;const{r:H,s:q}=F,K=L(P),W=i.inv(q),V=i.create(K*W),G=i.create(H*W),X=t.BASE.multiplyUnsafe(V).add(U.multiplyUnsafe(G));return X.is0()?!1:i.create(X.x)===H}catch{return!1}}function A(x,P,R={}){const{prehash:O}=Ti(R,g);return P=E(P,O),y.fromBytes(x,"recovered").recoverPublicKey(P).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h,Point:t,sign:C,verify:D,recoverPublicKey:A,Signature:y,hash:e})}function R0(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp;let r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0;const o=xn(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),s={Fp:n,Fn:o,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function T0(t){const{CURVE:e,curveOpts:n}=R0(t),r={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,hash:t.hash,ecdsaOpts:r}}function P0(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,oh(n.Fn.ORDER,n.Fn.BITS))})}function N0(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:o}=T0(t),s=k0(e,n),i=I0(s,r,o);return P0(t,i)}function L0(t,e){const n=r=>N0({...t,hash:r});return{...n(e),create:n}}const Xc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},B0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},yd=BigInt(2);function _0(t){const e=Xc.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,u=fe(d,n,e)*d%e,f=fe(u,n,e)*d%e,h=fe(f,yd,e)*l%e,g=fe(h,o,e)*h%e,m=fe(g,s,e)*g%e,b=fe(m,a,e)*m%e,w=fe(b,c,e)*b%e,I=fe(w,a,e)*m%e,y=fe(I,n,e)*d%e,v=fe(y,i,e)*g%e,L=fe(v,r,e)*l%e,k=fe(L,yd,e);if(!Ua.eql(Ua.sqr(k),t))throw new Error("Cannot find square root");return k}const Ua=xn(Xc.p,{sqrt:_0}),Wt=L0({...Xc,Fp:Ua,lowS:!0,endo:B0},Wf);function O0(t,e,n){const r=Oc.digest(e instanceof Uint8Array?e:e.subarray());if(Gs(r))return r.then(({digest:o})=>(n?.signal?.throwIfAborted(),Wt.sign(o,t).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new hd(String(o))});try{return Wt.sign(r.digest,t).toDERRawBytes()}catch(o){throw new hd(String(o))}}function D0(t,e,n,r){const o=Oc.digest(n instanceof Uint8Array?n:n.subarray());if(Gs(o))return o.then(({digest:s})=>(r?.signal?.throwIfAborted(),Wt.verify(e,s,t))).catch(s=>{throw s.name==="AbortError"?s:new pd(String(s))});try{return r?.signal?.throwIfAborted(),Wt.verify(e,o.digest,t)}catch(s){throw new pd(String(s))}}class Ph{type="secp256k1";raw;_key;constructor(e){this._key=$0(e),this.raw=j0(this._key)}toMultihash(){return go.digest(Js(this))}toCID(){return le.createV1(114,this.toMultihash())}toString(){return Be.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:st(this.raw,e.raw)}verify(e,n,r){return D0(this._key,n,e,r)}}class F0{type="secp256k1";raw;publicKey;constructor(e,n){this.raw=U0(e),this.publicKey=new Ph(n??H0(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:st(this.raw,e.raw)}sign(e,n){return O0(this.raw,e,n)}}function M0(t){return new F0(t)}function Nh(t){return new Ph(t)}function j0(t){return Wt.ProjectivePoint.fromHex(t).toRawBytes(!0)}function U0(t){try{return Wt.getPublicKey(t,!0),t}catch(e){throw new Af(String(e))}}function $0(t){try{return Wt.ProjectivePoint.fromHex(t),t}catch(e){throw new Ef(String(e))}}function H0(t){try{return Wt.getPublicKey(t,!0)}catch(e){throw new Af(String(e))}}async function q0(t,e){return Lb()}function $a(t,e){const{Type:n,Data:r}=wn.decode(t),o=r??new Uint8Array;switch(n){case de.RSA:return g0(o,e);case de.Ed25519:return gh(o);case de.secp256k1:return Nh(o);case de.ECDSA:return Mf(o);default:throw new qs}}function K0(t){const{Type:e,Data:n}=wn.decode(t.digest),r=n??new Uint8Array;switch(e){case de.Ed25519:return gh(r);case de.secp256k1:return Nh(r);case de.ECDSA:return Mf(r);default:throw new qs}}function Js(t){return wn.encode({Type:de[t.type],Data:t.raw})}function z0(t){const e=ws.decode(t),n=e.Data??new Uint8Array;switch(e.Type){case de.RSA:return h0(n);case de.Ed25519:return Nb(n);case de.secp256k1:return M0(n);case de.ECDSA:return Sy(n);default:throw new qs}}function W0(t){return ws.encode({Type:de[t.type],Data:t.raw})}const Lh=Symbol.for("nodejs.util.inspect.custom"),V0=114;class Yc{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[kf]=!0;toString(){return this.string==null&&(this.string=Be.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return le.createV1(V0,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return st(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return st(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Lh](){return`PeerId(${this.toString()})`}}class Bh extends Yc{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class _h extends Yc{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class Oh extends Yc{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}const G0=2336;class Dh{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=go.digest(we(this.url))}[Lh](){return`PeerId(${this.url})`}[kf]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return le.createV1(G0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=ee(e)),e.toString()===this.toString())}}const X0=114,bd=2336;function Y0(t,e){let n;if(t.charAt(0)==="1"||t.charAt(0)==="Q")n=Rf(Be.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return Z0(le.parse(t));throw new ot('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return Fh(n)}function cr(t){if(t.type==="Ed25519")return new _h({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new Oh({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new Bh({multihash:t.toCID().multihash,publicKey:t});throw new qs}function Fh(t){if(Q0(t))return new Bh({multihash:t});if(J0(t))try{const e=K0(t);if(e.type==="Ed25519")return new _h({multihash:t,publicKey:e});if(e.type==="secp256k1")return new Oh({multihash:t,publicKey:e})}catch{const n=ee(t.digest);return new Dh(new URL(n))}throw new Bm("Supplied PeerID Multihash is invalid")}function Z0(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==X0&&t.code!==bd)throw new Lm("Supplied PeerID CID is invalid");if(t.code===bd){const e=ee(t.multihash.digest);return new Dh(new URL(e))}return Fh(t.multihash)}function J0(t){return t.code===go.code}function Q0(t){return t.code===Oc.code}class Mh extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class ev extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class Ir extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class vd extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}}class tv extends Event{data;constructor(e,n){super("message",n),this.data=e}}class Zc extends Event{error;local;constructor(e,n,r){super("close",r),this.error=n,this.local=e}}class nv extends Zc{constructor(e,n){super(!0,e,n)}}class rv extends Zc{constructor(e,n){super(!1,e,n)}}const ov=t=>t/2**32|0,sv=t=>t>>>0;function iv(t,e,n,r){const o=ov(n),s=sv(n);t.setUint32(e,r?s:o,r),t.setUint32(e+4,r?o:s,r)}function Ha(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const qa=t=>t?`"${t}" `:"";function Tt(t,e=""){if(typeof t!="number")throw new TypeError(qa(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(qa(e)+"expected integer >= 0, got "+t);return t}function Pt(t,e,n=""){if(Ha(t)&&(e===void 0||t.length===e))return t;e!==void 0&&Tt(e,"length");const r=Ha(t),o=e!==void 0?` of length ${e}`:"",s=r?`length=${t.length}`:`type=${typeof t}`,i=qa(n)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}function Jc(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Tt(t.outputLen),Tt(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}const av=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)},Sd=(t,e)=>{av(t,e);const n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function ys(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function jh(t,e){Pt(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function HI(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function fn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Pi(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function at(t,e){return t<<32-e|t>>>e}function qI(t,e){return t<<e|t>>>32-e>>>0}const cv=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function lv(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function dv(t){for(let e=0;e<t.length;e++)t[e]=lv(t[e]);return t}const KI=cv?t=>t:dv,Uh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",uv=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Qc(t){if(Pt(t),Uh)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=uv[t[n]];return e}function xd(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function $h(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Uh)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}const e=t.length,n=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){const i=xd(t.charCodeAt(s)),a=xd(t.charCodeAt(s+1));if(i===void 0||a===void 0){const c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a}return r}function fv(t){const e=globalThis;if(typeof e.scheduler?.yield=="function"){const n=e.scheduler.yield();return t&&n.catch(t),n}return new Promise(n=>e.setTimeout(n,0))}async function zI(t,e,n,r){if(Tt(t,"iters"),Tt(e,"tick"),typeof n!="function")throw new TypeError("callback must be a function");let o=Date.now();for(let s=0;s<t;s++){n(s);const i=Date.now()-o;i>=0&&i<e||(await fv(r),o=Date.now())}}function hv(t){if(typeof t!="string")throw new TypeError("string expected");const e=new TextEncoder().encode(t);try{return new Uint8Array(e)}finally{fn(e)}}function WI(t,e=""){return typeof t=="string"?hv(t):Pt(t,void 0,e)}function pv(t,e,n="opts"){return Sd(t,"defaults"),e!==void 0&&Sd(e,n),Object.assign(Object.create(null),t,e)}function gv(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=pv({},e,"info");const n=(o,s)=>t(s).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function mv(t=32){Tt(t,"bytesLength");const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}const wv=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function yv(t,e,n){return t&e^~t&n}function bv(t,e,n){return t&e^t&n^e&n}class vv{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,n,r,o){this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Pi(this.buffer)}update(e){ys(this),Pt(e);const{view:n,buffer:r,blockLen:o}=this,s=e.length;let i=!1;for(let a=0;a<s;){const c=Math.min(o-this.pos,s-a);if(c===o){const l=Pi(e);for(;o<=s-a;a+=o)this.process(l,a);i=!0;continue}r.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(n,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){ys(this),jh(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:o,isLE:s}=this;let{pos:i}=this;n[i++]=128,n.fill(0,i),this.padOffset>o-i&&(this.process(r,0),n.fill(0)),iv(r,o-8,this.length*8,s),this.process(r,0),this.roundClean();const a=e===n?r:Pi(e),c=this.outputLen,l=c/4,d=this.get();if(c%4||l>d.length)throw new Error("invalid outputLen");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneIntoMeta(e){const{buffer:n,length:r,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=r,e.pos=i,i&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Sv=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),xv=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Dt=new Uint32Array(64);class Ev extends vv{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,n){super(64,e,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){const{A:e,B:n,C:r,D:o,E:s,F:i,G:a,H:c}=this;return[e,n,r,o,s,i,a,c]}set(e,n,r,o,s,i,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,n){for(let u=0;u<16;u++,n+=4)Dt[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const f=Dt[u-15],h=Dt[u-2],g=at(f,7)^at(f,18)^f>>>3,m=at(h,17)^at(h,19)^h>>>10;Dt[u]=m+Dt[u-7]+g+Dt[u-16]|0}let{A:r,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=at(a,6)^at(a,11)^at(a,25),h=d+f+yv(a,c,l)+xv[u]+Dt[u]|0,m=(at(r,2)^at(r,13)^at(r,22))+bv(r,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=r,r=h+m|0}r=r+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,s,i,a,c,l,d)}roundClean(){fn(Dt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),fn(this.buffer)}}class Av extends Ev{constructor(){super(32,Sv)}}const Ni=gv(()=>new Av,wv(1));function Hh(t,e,n=()=>{}){if(!Array.isArray(t))throw new TypeError(`"${e}" expected array, got type=${typeof t}`);for(let r=0;r<t.length;r++)n(t[r],`${e}[${r}]`);return t}const Yn=(t,e,n)=>Pt(t,e,n),qh=Tt;function Zn(t,e="object"){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`);return t}function Vr(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}const kv=Qc,Cv=t=>$h(t),Kh=Ha,zh=t=>mv(t),bs=BigInt(0),Ed=BigInt(1),Iv=t=>t?`"${t}" `:"";function Qs(t,e=""){if(typeof t!="boolean")throw new TypeError(Iv(e)+"expected boolean, got type="+typeof t);return t}function Rv(t){if(typeof t=="bigint"){if(!hn(t))throw new RangeError("positive bigint expected, got "+t)}else qh(t);return t}function Ka(t,e=""){if(typeof t!="number"){const n=e&&`"${e}" `;throw new TypeError(n+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){const n=e&&`"${e}" `;throw new RangeError(n+"expected safe integer, got "+t)}}function Wh(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?bs:BigInt("0x"+t)}function Vh(t){return Wh(Qc(t))}function vs(t){return Wh(Qc(ro(Pt(t)).reverse()))}function Gh(t,e){if(Tt(e),e===0)throw new Error("zero output length is invalid");t=Rv(t);const n=e*2,r=t.toString(16);if(r.length>n)throw new RangeError("number is too large");return $h(r.padStart(n,"0"))}function Xh(t,e){return Gh(t,e).reverse()}function ro(t){return Uint8Array.from(Yn(t))}function hn(t){return typeof t=="bigint"&&bs<=t}function Yh(t,e,n){return hn(t)&&hn(e)&&hn(n)&&e<=t&&t<n}function Gr(t,e,n,r){if(!Yh(e,n,r))throw new RangeError("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Tv(t){if(t<bs)throw new Error("expected non-negative bigint, got "+t);return t===bs?0:t.toString(2).length}const Pv=t=>(Ka(t,"n"),(Ed<<BigInt(t))-Ed);function Ss(t,e={},n={},r="object"){Zn(t,r),Zn(e,"fields"),Zn(n,"optFields");function o(i,a,c){const l=r==="object"?`param "${String(i)}"`:`"${r}.${String(i)}"`,d=t[i];if(!Object.hasOwn(t,i)&&(c?d!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&d===void 0)return;const u=typeof d;if(u!==a||d===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${u}`)}const s=(i,a)=>Object.entries(i).forEach(([c,l])=>o(c,l,a));s(e,!1),s(n,!0)}const Se=BigInt(0),ae=BigInt(1),an=BigInt(2),Zh=BigInt(3),el=BigInt(4),Jh=BigInt(5),Nv=BigInt(7),Qh=BigInt(8),Lv=BigInt(9),Bv=BigInt(15),ep=BigInt(16),_v=BigInt("0x10000000000000000");function ie(t,e){if(e<=Se)throw new Error("mod: expected positive modulus, got "+e);const n=t%e;return n>=Se?n:e+n}function Ov(t,e,n){if(n<=ae)throw new Error("pow: expected modulus > 1, got "+n);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<Se)throw new Error("invalid exponent, negatives unsupported");if(e===Se)return ae;if(e===ae)return t;let r=t%n;if(r<Se&&(r+=n),e<_v){let a=ae;for(;e>Se;)e&ae&&(a=a*r%n),r=r*r%n,e>>=ae;return a}const o=[];for(;e>Se;)o.push(Number(e&Bv)),e>>=el;const s=new Array(16);s[0]=ae,s[1]=r;for(let a=2;a<16;a++)s[a]=s[a-1]*r%n;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%n,i=i*i%n,i=i*i%n,i=i*i%n;const c=o[a];c!==0&&(i=i*s[c]%n)}return i}function nt(t,e,n){if(n<=ae)throw new Error("pow2: expected modulus > 1, got "+n);if(e<Se)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >Se;)r*=r,r%=n;return r}function Ad(t,e){if(t===Se)throw new Error("invert: expected non-zero number");if(e<=ae)throw new Error("invert: expected modulus > 1, got "+e);let n=ie(t,e),r=e,o=Se,s=ae;for(;n!==Se;){const a=r/n,c=r-n*a,l=o-s*a;r=n,n=c,o=s,s=l}if(r!==ae)throw new Error("invert: does not exist");return ie(o,e)}function tl(t,e,n){const r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function nl(t,e){if((t&ae)===Se)throw new Error(e+": expected odd modulus, got "+t)}function tp(t,e){const n=t,r=(n.ORDER+ae)/el,o=n.pow(e,r);return tl(n,o,e),o}function Dv(t,e){const n=t,r=(n.ORDER-Jh)/Qh,o=n.mul(e,an),s=n.pow(o,r),i=n.mul(e,s),a=n.mul(n.mul(i,an),s),c=n.mul(i,n.sub(a,n.ONE));return tl(n,c,e),c}function Fv(t){const e=rl(t),n=np(t),r=n(e,e.neg(e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+Nv)/ep;return((a,c)=>{const l=a;let d=l.pow(c,i),u=l.mul(d,r);const f=l.mul(d,o),h=l.mul(d,s),g=l.eql(l.sqr(u),c),m=l.eql(l.sqr(f),c);d=l.cmov(d,u,g),u=l.cmov(h,f,m);const b=l.eql(l.sqr(u),c),w=l.cmov(d,u,b);return tl(l,w,c),w})}function np(t){if(t<Zh)throw new Error("sqrt is not defined for small field");nl(t,"tonelliShanks");let e=t-ae,n=0;for(;e%an===Se;)e/=an,n++;let r=an;const o=rl(t);for(;xs(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return tp;let s=o.pow(r,e);const i=(e+ae)/an;return function(c,l){const d=c;if(d.is0(l))return l;if(xs(d,l)!==1)throw new Error("Cannot find square root");let u=n,f=d.mul(d.ONE,s),h=d.pow(l,e),g=d.pow(l,i);for(;!d.eql(h,d.ONE);){if(d.is0(h))throw new Error("Cannot find square root: probably non-prime P");let m=1,b=d.sqr(h);for(;!d.eql(b,d.ONE);)if(m++,b=d.sqr(b),m===u)throw new Error("Cannot find square root");const w=ae<<BigInt(u-m-1),I=d.pow(f,w);u=m,f=d.sqr(I),h=d.mul(h,f),g=d.mul(g,I)}return g}}function Mv(t){return nl(t,"Fp.sqrt"),t%el===Zh?tp:t%Qh===Jh?Dv:t%ep===Lv?Fv(t):np(t)}const jv=(t,e)=>(ie(t,e)&ae)===ae,Uv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function oo(t){if(Zn(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);Ka(t.BYTES,"BYTES"),Ka(t.BITS,"BITS");for(const e of Uv)Vr(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=ae)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function rp(t,e,n=!1){oo(t),Hh(e,"nums"),Qs(n,"passZero");const r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),s=e.reduce((a,c,l)=>r.is0(c)?a:(o[l]=a,r.mul(a,c)),r.ONE),i=r.inv(s);return e.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),i),o}function xs(t,e){oo(t);const n=t;nl(n.ORDER,"FpLegendre");const r=(n.ORDER-ae)/an,o=n.pow(e,r),s=n.eql(o,n.ONE),i=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function $v(t,e){if(e!==void 0&&qh(e),t<=Se)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);const n=Tv(t);if(e!==void 0&&e<n)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${n})`);const r=e!==void 0?e:n,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}const kd=new WeakMap;class Cd{ORDER;BITS;BYTES;isLE;ZERO=Se;ONE=ae;_lengths;_mod;constructor(e,n={}){if(e<=ae)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:!0}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));const{nBitLength:o,nByteLength:s}=$v(e,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return ie(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Se<=e&&e<this.ORDER}is0(e){return e===Se}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ae)===ae}neg(e){return ie(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return ie(e*e,this.ORDER)}add(e,n){return ie(e+n,this.ORDER)}sub(e,n){return ie(e-n,this.ORDER)}mul(e,n){return ie(e*n,this.ORDER)}pow(e,n){return Ov(e,n,this.ORDER)}div(e,n){return ie(e*Ad(n,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return Ad(e,this.ORDER)}sqrt(e){let n=kd.get(this);return n||kd.set(this,n=Mv(this.ORDER)),n(this,e)}toBytes(e){return this.isLE?Xh(e,this.BYTES):Gh(e,this.BYTES)}fromBytes(e,n=!1){Yn(e);const{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);const l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?vs(e):Vh(e);if(a&&(c=ie(c,i)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return rp(this,e,!0)}cmov(e,n,r){return Qs(r,"condition"),r?n:e}}function rl(t,e={}){return Object.freeze(Cd.prototype),new Cd(t,e)}const ol=BigInt(0),so=BigInt(1),Hv=BigInt(4),Li=16,Id=128,qv=5,Rd=2**31;function sl(t){const e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);Vr(e.fromAffine,"Point.fromAffine"),Vr(e.fromBytes,"Point.fromBytes"),Vr(e.fromHex,"Point.fromHex"),Zn(e.BASE,"Point.BASE"),Zn(e.ZERO,"Point.ZERO"),oo(e.Fp),oo(e.Fn)}function Kv(t,e){sl(t),op(e,t);const n=rp(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function zv(t,e,n=1){if(!Number.isSafeInteger(t)||t<n||t>e)throw new Error("invalid window size, expected ["+n+".."+e+"], got W="+t)}function Wv(t,e){const n=t*(4*e+128);if(n>Rd)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+Rd/2**20+" MiB")}function Vv(t,e){if(t!==void 0){Vr(t,"randomBytes");try{const n=t(e);if(!Kh(n)||n.length!==e)return}catch{return}return t}}function op(t,e){Hh(t,"points"),t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function Gv(t,e,n){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,o)=>{if(!(n===void 0?e.isValid(r):hn(r)&&r<n))throw new Error("invalid scalar at index "+o)})}const sp=new WeakMap;function Bi(t){return sp.get(t)||1}function Xv(t,e){const n=t.double(),r=[t];for(let o=1;o<e;o++)r.push(r[o-1].add(n));return r}function Yv(t,e){const n=2**e,r=n/2,o=BigInt(n-1),s=[];for(;t>ol;){let i=0;t&so&&(i=Number(t&o),i>=r&&(i-=n),t-=BigInt(i)),s.push(i),t>>=so}return s}function Zv(t,e,n){const r=2**e,o=r/2,s=BigInt(r-1),i=BigInt(e),a=[];for(let c=0;c<n;c++){let l=Number(t&s);t>>=i,l>o&&(l-=r,t+=so),a.push(l)}if(t!==ol)throw new Error("invalid wnaf");return a}function Jv(t,e,n){let r=0;for(const s of n)r=Math.max(r,s.length);let o=t;for(let s=r-1;s>=0;s--){s!==r-1&&(o=o.double());for(let i=0;i<n.length;i++){const a=n[i][s];if(a){const c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}class Qv{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,n){sl(e),this.randomBytes=Vv(n,Li),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,n,r){const o=Math.ceil(r/n)+1,s=2**(n-1),i=[];let a=e;for(let c=0;c<o;c++){let l=a;for(let d=0;d<s;d++)i.push(l),l=l.add(a);a=i[i.length-1].double()}return{W:n,bits:r,windows:o,comp:i}}wnafCachedCT(e,n){const{W:r,windows:o,comp:s}=e,i=2**(r-1),a=Zv(n,r,o);let c=this.ZERO,l=this.BASE;for(let d=0;d<o;d++){const u=a[d],f=d*i,h=Math.abs(u)-1;let g=s[f];for(let b=1;b<i;b++)g=b===h?s[f+b]:g;const m=g.negate();u===0?l=l.add(s[f]):c=c.add(u<0?m:g)}return{p:c,f:l}}getWnafPrecomputes(e,n,r,o){let s=this.wnafPrecomputes.get(n),i=s?.find(a=>a.W===e&&a.bits===r);return i||(i=this.buildWnafTable(n,e,r),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(n,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,n){if(this.assertPoint(e),!Yh(n,so,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,n,r,o){const s=Bi(e);return s===1?this.fixedWindowCT(e,n,r):this.wnafCachedCT(this.getWnafPrecomputes(s,e,r,o),n)}mulCT(e,n,r){return this.validateMulInput(e,n),this.runCT(e,n,this.bits,r)}mulCTBlinded(e,n,r){if(this.validateMulInput(e,n),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");const o=this.Point.Fn.BITS+Id,s=this.randomBytes(Li);if(!Kh(s)||s.length!==Li)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;const i=n+Vh(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,r)}fixedWindowCT(e,n,r){const o=qv,s=1<<o,i=Pv(o),a=new Array(s);a[0]=this.ZERO;for(let d=1;d<s;d++)a[d]=a[d-1].add(e);const c=Math.ceil(r/o);let l=this.ZERO;for(let d=c-1;d>=0;d--){if(d!==c-1)for(let h=0;h<o;h++)l=l.double();const u=Number(n>>BigInt(d*o)&i);let f=a[0];for(let h=1;h<s;h++)f=h===u?a[h]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(e,n){return this.randomBytes===void 0?!1:n===so?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,n,r,o){return this.shouldBlind(e,r)?this.mulCTBlinded(e,n,o):this.mulCT(e,n,o)}mulUnsafe(e,n,r){if(this.assertPoint(e),!hn(n))throw new Error("invalid scalar");const o=Bi(e);if(o===1||n>=this.Point.Fn.ORDER)return eS(this.Point,[e],[n],!0);const s=this.getWnafPrecomputes(o,e,this.bits,r);return this.wnafCachedCT(s,n).p}setWindowSize(e,n){this.assertPoint(e),zv(n,this.bits);const r=Math.ceil((this.bits+Id)/n)+1;Wv(r*2**(n-1),this.Point.Fp.BYTES),sp.set(e,n),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Bi(e)!==1}}function eS(t,e,n,r=!1){if(sl(t),op(e,t),Qs(r,"allowOversized"),Gv(n,t.Fn,r?t.Fn.ORDER**Hv:void 0),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const o=e.map(i=>Xv(i,4)),s=n.map(i=>Yv(i,4));return Jv(t.ZERO,o,s)}function Td(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return oo(e),e}else return rl(t,{isLE:n})}function tS(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);Ss(n);for(const c of["p","n","h"]){const l=e[c];if(!(hn(l)&&l!==ol))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Td(e.p,n.Fp,r),s=Td(e.n,n.Fn,r),a=["Gx","Gy","a","d"];for(const c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function nS(t,e){return function(r){const o=t(r);return{secretKey:o,publicKey:e(o)}}}const No=BigInt(0),Lo=BigInt(1),Bo=BigInt(2),rS=BigInt(4),Pd=BigInt(8);function oS(t,e,n,r){const o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function sS(t,e={}){Ss(e,{},{},"extraOpts");const n=e,r=tS("edwards",t,n,n.FpFnLE),{Fp:o,Fn:s}=r;let i=r.CURVE;const{h:a}=i;if(xs(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(xs(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Ss(n,{},{uvRatio:"function",randomBytes:"function"});const c=n.randomBytes===void 0?zh:n.randomBytes,l=Bo<<BigInt(o.BYTES*8)-Lo;function d(I){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(I)}const u=n.uvRatio===void 0?(I,y)=>{try{return{isValid:!0,value:o.sqrt(o.div(I,y))}}catch{return{isValid:!1,value:No}}}:n.uvRatio;if(!oS(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");const f=o.eql(i.a,o.neg(o.ONE))?I=>o.neg(I):o.eql(i.a,o.ONE)?I=>I:I=>o.mul(i.a,I);function h(I,y,v=!1){const L=v?Lo:No;return Gr("coordinate "+I,y,L,l),y}function g(I){if(!(I instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.Gy));static ZERO=new m(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(y,v,L,k){this.X=h("x",y),this.Y=h("y",v),this.Z=h("z",L,!0),this.T=h("t",k),Object.freeze(this)}static CURVE(){return i}static fromAffine(y){if(y instanceof m)throw new Error("extended point not allowed");const{x:v,y:L}=y||{};return h("x",v),h("y",L),new m(v,L,o.ONE,o.mul(v,L))}static fromBytes(y,v=!1){const L=o.BYTES,{a:k,d:T}=i;y=ro(Yn(y,L,"point")),Qs(v,"zip215");const E=ro(y),S=y[L-1];E[L-1]=S&-129;const C=vs(E),N=v?l:o.ORDER;Gr("point.y",C,No,N);const D=o.sqr(C),A=o.sub(D,o.ONE),x=o.sub(o.mulN(T,D),k);let{isValid:P,value:R}=u(A,x);if(!P)throw new Error("bad point: invalid y coordinate");const O=d(R),j=(S&128)!==0;if(!v&&o.is0(R)&&j)throw new Error("bad point: x=0 and x_0=1");return j!==O&&(R=o.neg(R)),m.fromAffine({x:R,y:C})}static fromHex(y,v=!1){return m.fromBytes(Cv(y),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=6,v=!0){return w.setWindowSize(this,y),v||this.multiply(Bo),this}assertValidity(){const y=this,{a:v,d:L}=i;if(y.is0())throw new Error("bad point: ZERO");const{X:k,Y:T,Z:E,T:S}=y,C=o.sqr(k),N=o.sqr(T),D=o.sqr(E),A=o.sqr(D),x=o.mul(C,v),P=o.mul(o.add(x,N),D),R=o.add(A,o.mul(L,o.mul(C,N)));if(!o.eql(P,R))throw new Error("bad point: equation left != right (1)");const O=o.mul(k,T),j=o.mul(E,S);if(!o.eql(O,j))throw new Error("bad point: equation left != right (2)")}equals(y){g(y);const{X:v,Y:L,Z:k}=this,{X:T,Y:E,Z:S}=y,C=o.mul(v,S),N=o.mul(T,k),D=o.mul(L,S),A=o.mul(E,k);return o.eql(C,N)&&o.eql(D,A)}is0(){return this.equals(m.ZERO)}negate(){return new m(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){const{X:y,Y:v,Z:L}=this,k=o.sqr(y),T=o.sqr(v),E=o.mul(o.sqr(L),Bo),S=f(k),C=o.addN(y,v),N=o.sub(o.subN(o.sqr(C),k),T),D=o.addN(S,T),A=o.subN(D,E),x=o.subN(S,T),P=o.mul(N,A),R=o.mul(D,x),O=o.mul(N,x),j=o.mul(A,D);return new m(P,R,j,O)}add(y){g(y);const{d:v}=i,{X:L,Y:k,Z:T,T:E}=this,{X:S,Y:C,Z:N,T:D}=y,A=o.mul(L,S),x=o.mul(k,C),P=o.mul(o.mulN(E,v),D),R=o.mul(T,N),O=o.sub(o.subN(o.mulN(o.addN(L,k),o.addN(S,C)),A),x),j=o.subN(R,P),M=o.addN(R,P),B=o.sub(x,f(A)),F=o.mul(O,j),U=o.mul(M,B),H=o.mul(O,B),q=o.mul(j,M);return new m(F,U,q,H)}subtract(y){return g(y),this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");const{p:v,f:L}=w.mulSecret(this,y,a,b);return b([v,L])[0]}multiplyUnsafe(y){if(!s.isValid(y))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return y===No?m.ZERO:this.is0()||y===Lo?this:w.mulUnsafe(this,y,b)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.mulUnsafe(this,i.n).is0()}toAffine(y){const v=this;let L=y;if(L!=null&&typeof L!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof L);const{X:k,Y:T,Z:E}=v,S=v.is0();L==null&&(L=S?o.create(Pd):o.inv(E));const C=o.mul(k,L),N=o.mul(T,L),D=o.mul(E,L);if(S)return{x:o.ZERO,y:o.ONE};if(!o.eql(D,o.ONE))throw new Error("invZ was invalid");return{x:C,y:N}}clearCofactor(){return a===Lo?this:a===Bo?this.double():a===rS?this.double().double():a===Pd?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){const{x:y,y:v}=this.toAffine(),L=o.toBytes(v);return L[L.length-1]|=d(y)?128:0,L}toHex(){return kv(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const b=I=>Kv(m,I),w=new Qv(m,c);return w.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}const en=BigInt(0),Xe=BigInt(1),_o=BigInt(2);function Nd(t,e){return t+e-(e>>Xe<<Xe)}function iS(t){const e=BigInt(6)*t;return(n,r,o)=>{const s=r+o,a=((e+o-r)*n+r)%t;return{x_2:a,x_3:s-a}}}function aS(t){return Ss(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...t})}function cS(t){const e=aS(t),{P:n,type:r,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=e.scalarMultBase,c=r==="x25519";if(!c&&r!=="x448")throw new Error("invalid type");const l=i===void 0?zh:i,d=c?255:448,u=iS(n),f=c?32:56,h=BigInt(c?9:5),g=BigInt(c?121665:39081),m=c?_o**BigInt(254):_o**BigInt(447),b=c?BigInt(8)*(_o**BigInt(251)-Xe):BigInt(4)*(_o**BigInt(445)-Xe),w=m+b+Xe,I=R=>ie(R,n),y=v(h);function v(R){return Xh(I(R),f)}function L(R){const O=ro(Yn(R,f,"uCoordinate"));return c&&(O[31]&=127),I(vs(O))}function k(R){return vs(o(ro(Yn(R,f,"scalar"))))}const T=new Set(c?[en,Xe,n-Xe,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[en,Xe,n-Xe]);function E(R,O){const j=L(O);if(T.has(j))throw new Error("invalid private or public key received");const M=D(j,k(R));if(M===en)throw new Error("invalid private or public key received");return v(M)}function S(R){if(a===void 0)return E(R,y);const O=k(R);Gr("scalar",O,m,w);const j=I(a(O));if(j===en)throw new Error("invalid private or public key received");return v(j)}const C=S,N=E;function D(R,O){Gr("u",R,en,n),Gr("scalar",O,m,w);const j=O,M=R;let B=Xe,F=en,U=R,H=Xe;const q=j^j>>Xe;for(let V=BigInt(d-1);V>=en;V--){const G=Nd(n,q>>V);({x_2:B,x_3:U}=u(G,B,U)),{x_2:F,x_3:H}=u(G,F,H);const X=B+F,Z=I(X*X),ce=B-F,Ie=I(ce*ce),Me=Z-Ie,ne=U+H,Ve=U-H,Yt=I(Ve*X),Zt=I(ne*ce),je=Yt+Zt,Jt=Yt-Zt;U=I(je*je),H=I(M*I(Jt*Jt)),B=I(Z*Ie),F=I(Me*(Z+I(g*Me)))}const K=Nd(n,j);({x_2:B,x_3:U}=u(K,B,U)),{x_2:F,x_3:H}=u(K,F,H);const W=s(F);return I(B*W)}const A={secretKey:f,publicKey:f,seed:f},x=R=>(R=R===void 0?l(f):R,Yn(R,A.seed,"seed"),R),P={randomSecretKey:x};return Object.freeze(A),Object.freeze(P),Object.freeze({keygen:nS(x,C),getSharedSecret:N,getPublicKey:C,scalarMult:E,scalarMultBase:S,utils:P,GuBytes:y.slice(),lengths:A})}const Ld=BigInt(0),lS=BigInt(1),Bd=BigInt(2),dS=BigInt(3),uS=BigInt(5),fS=BigInt(8),ei=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),hS={p:ei,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:fS,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ip(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=ei,a=t*t%s*t%s,c=nt(a,Bd,s)*a%s,l=nt(c,lS,s)*t%s,d=nt(l,uS,s)*l%s,u=nt(d,e,s)*d%s,f=nt(u,n,s)*u%s,h=nt(f,r,s)*f%s,g=nt(h,o,s)*h%s,m=nt(g,o,s)*h%s,b=nt(m,e,s)*d%s;return{pow_p_5_8:nt(b,Bd,s)*t%s,b2:a}}function pS(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const _d=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function gS(t,e){const n=ei,r=ie(e*e*e,n),o=ie(r*r*e,n),s=ip(t*o).pow_p_5_8;let i=ie(t*r*s,n);const a=ie(e*i*i,n),c=i,l=ie(i*_d,n),d=a===t,u=a===ie(-t,n),f=a===ie(-t*_d,n);return d&&(i=c),(u||f)&&(i=l),jv(i,n)&&(i=ie(-i,n)),{isValid:d||u,value:i}}const Od=sS(hS,{uvRatio:gS}),Oo=(()=>{const t=ei,e=n=>{const{pow_p_5_8:r,b2:o}=ip(n);return ie(nt(r,dS,t)*o,t)};return cS({P:t,type:"x25519",powPminus2:e,adjustScalarBytes:pS,scalarMultBase:n=>{const r=ie(n,Od.Fn.ORDER);if(r===Ld)return Ld;const o=Od.BASE.multiply(r);return ie((o.Z+o.Y)*e(ie(o.Z-o.Y,t)),t)}})})();class Dd{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,n){if(Jc(e),Pt(n,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?e.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),fn(o)}update(e){return ys(this),this.iHash.update(e),this}digestInto(e){ys(this),jh(e,this),this.finished=!0;const n=e.subarray(0,this.outputLen);this.iHash.digestInto(n),this.oHash.update(n),this.oHash.digestInto(n),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});const{oHash:n,iHash:r,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ap=(()=>{const t=((e,n,r)=>new Dd(e,n).update(r).digest());return t.create=(e,n)=>new Dd(e,n),t})();function Fd(){const t={};return t.promise=new Promise((e,n)=>{t.resolve=e,t.reject=n}),t}class Md{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}}class _i{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Md(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const n=this.head;this.head=n.next=new Md(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){const n=this.tail.next;this.tail.next=null,this.tail=n,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}class mS extends Error{type;code;constructor(e,n){super(e??"The operation was aborted"),this.type="aborted",this.code=n??"ABORT_ERR"}}function wS(t={}){return yS(n=>{const r=n.shift();if(r==null)return{done:!0};if(r.error!=null)throw r.error;return{done:r.done===!0,value:r.value}},t)}function yS(t,e){e=e??{};let n=e.onEnd,r=new _i,o,s,i,a=Fd();const c=async()=>{try{return r.isEmpty()?i?{done:!0}:await new Promise((b,w)=>{s=I=>{s=null,r.push(I);try{b(t(r))}catch(y){w(y)}return o}}):t(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Fd()})}},l=b=>s!=null?s(b):(r.push(b),o),d=b=>(r=new _i,s!=null?s({error:b}):(r.push({error:b}),o)),u=b=>{if(i)return o;if(e?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:b})},f=b=>i?o:(i=!0,b!=null?d(b):l({done:!0})),h=()=>(r=new _i,f(),{done:!0}),g=b=>(f(b),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:g,push:u,end:f,get readableLength(){return r.size},onEmpty:async b=>{const w=b?.signal;if(w?.throwIfAborted(),r.isEmpty())return;let I,y;w!=null&&(I=new Promise((v,L)=>{y=()=>{L(new mS)},w.addEventListener("abort",y)}));try{await Promise.race([a.promise,I])}finally{y!=null&&w!=null&&w?.removeEventListener("abort",y)}}},n==null)return o;const m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(b){return m.throw(b),n!=null&&(n(b),n=void 0),{done:!0}},return(){return m.return(),n!=null&&(n(),n=void 0),{done:!0}},push:u,end(b){return m.end(b),n!=null&&(n(b),n=void 0),o},get readableLength(){return m.readableLength},onEmpty:b=>m.onEmpty(b)},o}class il extends Error{name="TimeoutError";constructor(e,n){super(e,n),Error.captureStackTrace?.(this,il)}}const jd=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function bS(t,e){const{milliseconds:n,fallback:r,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e;let a,c;const d=new Promise((u,f)=>{if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(i?.aborted){f(jd(i));return}if(i&&(c=()=>{f(jd(i))},i.addEventListener("abort",c,{once:!0})),t.then(u,f),n===Number.POSITIVE_INFINITY)return;const h=new il;a=s.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){f(g)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?u():o instanceof Error?f(o):(h.message=o??`Promise timed out after ${n} milliseconds`,f(h))},n)}).finally(()=>{d.clear(),c&&i&&i.removeEventListener("abort",c)});return d.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},d}const vS=t=>{const e=t.addEventListener||t.on||t.addListener,n=t.removeEventListener||t.off||t.removeListener;if(!e||!n)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:n.bind(t)}};function SS(t,e,n){let r;const o=new Promise((s,i)=>{if(n={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...n},!(n.count>=0&&(n.count===Number.POSITIVE_INFINITY||Number.isInteger(n.count))))throw new TypeError("The `count` option should be at least 0 or more");n.signal?.throwIfAborted();const a=[e].flat(),c=[],{addListener:l,removeListener:d}=vS(t),u=async(...h)=>{const g=n.multiArgs?h:h[0];if(n.filter)try{if(!await n.filter(g))return}catch(m){r(),i(m);return}c.push(g),n.count===c.length&&(r(),s(c))},f=(...h)=>{r(),i(n.rejectionMultiArgs?h:h[0])};r=()=>{for(const h of a)d(h,u);for(const h of n.rejectionEvents)a.includes(h)||d(h,f)};for(const h of a)l(h,u);for(const h of n.rejectionEvents)a.includes(h)||l(h,f);n.signal&&n.signal.addEventListener("abort",()=>{f(n.signal.reason)},{once:!0}),n.resolveImmediately&&s(c)});if(o.cancel=r,typeof n.timeout=="number"){const s=bS(o,{milliseconds:n.timeout});return s.cancel=()=>{r(),s.clear()},s}return o}function xS(t,e,n){typeof n=="function"&&(n={filter:n}),n={...n,count:1,resolveImmediately:!1};const r=SS(t,e,n),o=r.then(s=>s[0]);return o.cancel=r.cancel,o}class Es extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class ES extends Error{static name="StreamClosedError";name="StreamClosedError"}function AS(t){return t.reason}function cp(t,e,n){if(e==null||t==null)return t;const r=AS;if(e.aborted)return t.catch(()=>{}),Promise.reject(r(e));let o;return Promise.race([t,new Promise((s,i)=>{o=()=>{i(r(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}const kS=Math.pow(2,20)*4;class lp extends Fm{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??kS,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new se,this.writeBuffer=new se,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);const n=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",n);const r=o=>{this.onDrainPromise?.reject(o.error??new ES)};this.addEventListener("close",r)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),cp(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;const e=wS(),n=s=>{e.push(s.data)};this.addEventListener("message",n);const r=s=>{e.end(s.error)};this.addEventListener("close",r);const o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",n),this.removeEventListener("close",r),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Ir(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(n){this.log("failed to send reset to remote - %e",n)}this.dispatchEvent(new nv(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Ir("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Ir("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Ir(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Ir(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");const e=new ev;this.dispatchEvent(new rv(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new Zc))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0;const n=this.writeBuffer.byteLength;let r=0;for(;this.writeBuffer.byteLength>0;){const o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}const s=this.writeBuffer.sublist(0,o),i=new se(s);this.writeBuffer.consume(s.byteLength);const a=this.sendData(s);if(e=a.canSendMore,r+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",r,n,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}const e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new tv(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new vd(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new vd(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}}const CS=4194304;class Ud extends Error{static name="UnwrappedError";name="UnwrappedError"}class dp extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class IS extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class RS extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function TS(t){return typeof t?.closeRead=="function"}function PS(t){return typeof t?.close=="function"}function Oi(t){return TS(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:PS(t)?t.status!=="open":!1}function NS(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function LS(t,e){const n=e?.maxBufferSize??CS,r=new se;let o,s=!1;if(!NS(t))throw new Mh("Argument should be a Stream or a Multiaddr");const i=d=>{if(r.append(d.data),r.byteLength>n){const u=r.byteLength;r.consume(r.byteLength),o?.reject(new Error(`Read buffer overflow - ${u} > ${n}`))}o?.resolve()};t.addEventListener("message",i);const a=d=>{d.error!=null?o?.reject(d.error):o?.resolve()};t.addEventListener("close",a);const c=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",c);const l={readBuffer:r,async read(d){if(s===!0)throw new Ud("Stream was unwrapped");if(Oi(t)){if(d?.bytes==null)return null;if(r.byteLength<d.bytes)throw t.log.error("closed after reading %d/%d bytes",r.byteLength,d.bytes),new Es(`Unexpected EOF - stream closed after reading ${r.byteLength}/${d.bytes} bytes`)}const u=d?.bytes??1;for(o=Promise.withResolvers();;){if(r.byteLength>=u){o.resolve();break}if(await cp(o.promise,d?.signal),Oi(t)){if(r.byteLength===0&&d?.bytes==null)return null;break}o=Promise.withResolvers()}const f=d?.bytes??r.byteLength;if(r.byteLength<f){if(Oi(t))throw t.log.error("closed while reading %d/%d bytes",r.byteLength,f),new Es(`Unexpected EOF - stream closed while reading ${r.byteLength}/${f} bytes`);return l.read(d)}const h=r.sublist(0,f);return r.consume(f),h},async write(d,u){if(s===!0)throw new Ud("Stream was unwrapped");t.send(d)||await xS(t,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",i),t.removeEventListener("close",a),t.removeEventListener("remoteCloseWrite",c),r.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",r.byteLength),t.push(r))),t}};return l}function $d(t,e={}){const n=LS(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=En(e.maxDataLength));const r=e?.lengthDecoder??yh,o=e?.lengthEncoder??Mb;return{async read(i){let a=-1;const c=new se;for(;;){const d=await n.read({...i,bytes:1});if(d==null)break;c.append(d);try{a=r(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new dp("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new RS(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new IS(`Message length too long - ${a} > ${e.maxDataLength}`);const l=await n.read({...i,bytes:a});if(l==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new Es(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw t.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Es(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await n.write(new se(o(i.byteLength),i),a)},async writeV(i,a){const c=new se(...i.flatMap(l=>[o(l.byteLength),l]));await n.write(c,a)},unwrap(){return n.unwrap()}}}const BS=1024*1024*4,_S=1024*1024*4;class OS{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new se,this.maxBufferSize=e.maxBufferSize??BS,this.maxDataLength=e.maxDataLength??_S,this.lengthDecoder=e.lengthDecoder??yh,this.encodingLength=e.encodingLength??En}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new Mh(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let n;try{n=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(n<0||n>this.maxDataLength)throw new dp("Invalid message length");const r=this.encodingLength(n),o=r+n;if(this.buffer.byteLength>=o){const s=this.buffer.sublist(r,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}}var DS={};const io=65535,Hd=io-16,vo=!!DS?.DUMP_SESSION_KEYS,qd=16;function za(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const As=t=>t?`"${t}" `:"";function Wa(t,e=""){if(typeof t!="boolean")throw new TypeError(As(e)+"expected boolean, got type="+typeof t);return t}function Jn(t,e=""){if(typeof t!="number")throw new TypeError(As(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(As(e)+"expected integer >= 0, got "+t);return t}function ve(t,e,n=""){if(za(t)&&(e===void 0||t.length===e))return t;e!==void 0&&Jn(e,"length");const r=za(t),o=e!==void 0?` of length ${e}`:"",s=r?`length=${t.length}`:`type=${typeof t}`,i=As(n)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}const Kd=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`)};function zd(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function FS(t,e){ve(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function Et(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function zt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function MS(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const Qn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function jS(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function US(t){for(let e=0;e<t.length;e++)t[e]=jS(t[e]);return t}const cn=Qn?t=>t:US;function $S(t,e){return!t.byteLength||!e.byteLength?!1:t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function HS(t,e){if($S(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function qS(t,e){return Kd(t,"defaults"),Kd(e,"opts"),Object.assign(t,e)}function KS(t,e){if(t=ve(t),e=ve(e),t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}function zS(t,e,n){const r=e,o=(()=>[]),s=(a,c)=>r(c,...o(a)).update(a).digest(),i=r(new Uint8Array(t),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>r(a,...c),s}const WS=(t,e)=>{function n(r,...o){if(ve(r,void 0,"key"),t.nonceLength!==void 0){const u=o[0];ve(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}const s=t.tagLength,i=t.nonceLength!==void 0?1:0;if(!t.withAAD){for(let u=i;u<o.length;u++)if(za(o[u]))throw new Error("AAD not supported")}t.withAAD&&o[i]!==void 0&&ve(o[i],void 0,"AAD");const a=e(r,...o),c=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");ve(f,void 0,"output")}};let l=!1;return{encrypt(u,f){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,ve(u,void 0,"data"),c(a.encrypt.length,f),a.encrypt(u,f)},decrypt(u,f){if(ve(u,void 0,"data"),s&&u.length<s)throw new Error('"ciphertext" expected length >= tagLength='+s);return c(a.decrypt.length,f),a.decrypt(u,f)}}}return Object.assign(n,t),n};function Va(t,e,n=!0){if(e===void 0)return new Uint8Array(t);if(ve(e,t,"output"),n&&!ks(e))throw new Error("invalid output, must be aligned");return e}function VS(t,e,n){Jn(t),Jn(e),Wa(n);const r=new Uint8Array(16),o=MS(r);return o.setBigUint64(0,BigInt(e),n),o.setBigUint64(8,BigInt(t),n),r}function ks(t){return t.byteOffset%4===0}function Cs(t){return Uint8Array.from(ve(t))}const up=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),GS=cn(Et(up("expand 16-byte k"))),XS=cn(Et(up("expand 32-byte k")));function te(t,e){return t<<e|t>>>32-e}const Rr=64,YS=16,Ga=2**32-1,Wd=Uint32Array.of();function ZS(t,e,n,r,o,s,i,a){const c=o.length,l=new Uint8Array(Rr),d=Et(l),u=Qn&&ks(o)&&ks(s),f=u?Et(o):Wd,h=u?Et(s):Wd;if(!Qn){for(let g=0;g<c;i++){if(t(e,n,r,d,i,a),cn(d),i>=Ga)throw new Error("arx: counter overflow");const m=Math.min(Rr,c-g);for(let b=0,w;b<m;b++)w=g+b,s[w]=o[w]^l[b];g+=m}return}for(let g=0;g<c;i++){if(t(e,n,r,d,i,a),i>=Ga)throw new Error("arx: counter overflow");const m=Math.min(Rr,c-g);if(u&&m===Rr){const b=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,I;w<YS;w++)I=b+w,h[I]=f[I]^d[w];g+=Rr;continue}for(let b=0,w;b<m;b++)w=g+b,s[w]=o[w]^l[b];g+=m}}function JS(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:s,rounds:i}=qS({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Jn(o),Jn(i),Wa(s),Wa(n),(a,c,l,d,u=0)=>{ve(a,void 0,"key"),ve(c,void 0,"nonce"),ve(l,void 0,"data");const f=l.length,h=d!==void 0;if(d=Va(f,d,!1),h&&HS(l,d),Jn(u),u<0||u>=Ga)throw new Error("arx: counter overflow");const g=[];let m=a.length,b,w;if(m===32)g.push(b=Cs(a)),w=XS;else if(m===16&&n)b=new Uint8Array(32),b.set(a),b.set(a,16),w=GS,g.push(b);else throw ve(a,32,"arx key"),new Error("invalid key size");(!Qn||!ks(c))&&g.push(c=Cs(c));let I=Et(b);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");const L=c.subarray(0,16);if(Qn)r(w,I,Et(L),I);else{const k=cn(Uint32Array.from(w));r(k,I,Et(L),I),zt(k),cn(I)}c=c.subarray(16)}else Qn||cn(I);const y=16-o;if(y!==c.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){const L=new Uint8Array(12);L.set(c,s?0:12-c.length),c=L,g.push(c)}const v=cn(Et(c));try{return ZS(t,w,I,v,l,d,u,i),d}finally{zt(...g)}}}function Ee(t,e){return t[e++]&255|(t[e++]&255)<<8}class QS{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=Cs(ve(e,32,"key"));const n=Ee(e,0),r=Ee(e,2),o=Ee(e,4),s=Ee(e,6),i=Ee(e,8),a=Ee(e,10),c=Ee(e,12),l=Ee(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let d=0;d<8;d++)this.pad[d]=Ee(e,16+2*d)}process(e,n,r=!1){const o=r?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],d=i[3],u=i[4],f=i[5],h=i[6],g=i[7],m=i[8],b=i[9],w=Ee(e,n+0),I=Ee(e,n+2),y=Ee(e,n+4),v=Ee(e,n+6),L=Ee(e,n+8),k=Ee(e,n+10),T=Ee(e,n+12),E=Ee(e,n+14);let S=s[0]+(w&8191),C=s[1]+((w>>>13|I<<3)&8191),N=s[2]+((I>>>10|y<<6)&8191),D=s[3]+((y>>>7|v<<9)&8191),A=s[4]+((v>>>4|L<<12)&8191),x=s[5]+(L>>>1&8191),P=s[6]+((L>>>14|k<<2)&8191),R=s[7]+((k>>>11|T<<5)&8191),O=s[8]+((T>>>8|E<<8)&8191),j=s[9]+(E>>>5|o),M=0,B=M+S*a+C*(5*b)+N*(5*m)+D*(5*g)+A*(5*h);M=B>>>13,B&=8191,B+=x*(5*f)+P*(5*u)+R*(5*d)+O*(5*l)+j*(5*c),M+=B>>>13,B&=8191;let F=M+S*c+C*a+N*(5*b)+D*(5*m)+A*(5*g);M=F>>>13,F&=8191,F+=x*(5*h)+P*(5*f)+R*(5*u)+O*(5*d)+j*(5*l),M+=F>>>13,F&=8191;let U=M+S*l+C*c+N*a+D*(5*b)+A*(5*m);M=U>>>13,U&=8191,U+=x*(5*g)+P*(5*h)+R*(5*f)+O*(5*u)+j*(5*d),M+=U>>>13,U&=8191;let H=M+S*d+C*l+N*c+D*a+A*(5*b);M=H>>>13,H&=8191,H+=x*(5*m)+P*(5*g)+R*(5*h)+O*(5*f)+j*(5*u),M+=H>>>13,H&=8191;let q=M+S*u+C*d+N*l+D*c+A*a;M=q>>>13,q&=8191,q+=x*(5*b)+P*(5*m)+R*(5*g)+O*(5*h)+j*(5*f),M+=q>>>13,q&=8191;let K=M+S*f+C*u+N*d+D*l+A*c;M=K>>>13,K&=8191,K+=x*a+P*(5*b)+R*(5*m)+O*(5*g)+j*(5*h),M+=K>>>13,K&=8191;let W=M+S*h+C*f+N*u+D*d+A*l;M=W>>>13,W&=8191,W+=x*c+P*a+R*(5*b)+O*(5*m)+j*(5*g),M+=W>>>13,W&=8191;let V=M+S*g+C*h+N*f+D*u+A*d;M=V>>>13,V&=8191,V+=x*l+P*c+R*a+O*(5*b)+j*(5*m),M+=V>>>13,V&=8191;let G=M+S*m+C*g+N*h+D*f+A*u;M=G>>>13,G&=8191,G+=x*d+P*l+R*c+O*a+j*(5*b),M+=G>>>13,G&=8191;let X=M+S*b+C*m+N*g+D*h+A*f;M=X>>>13,X&=8191,X+=x*u+P*d+R*l+O*c+j*a,M+=X>>>13,X&=8191,M=(M<<2)+M|0,M=M+B|0,B=M&8191,M=M>>>13,F+=M,s[0]=B,s[1]=F,s[2]=U,s[3]=H,s[4]=q,s[5]=K,s[6]=W,s[7]=V,s[8]=G,s[9]=X}finalize(){const{h:e,pad:n}=this,r=new Uint16Array(10);let o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+o,o=r[a]>>>13,r[a]&=8191;r[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)r[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+n[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+n[a]|0)+(i>>>16)|0,e[a]=i&65535;zt(r)}update(e){zd(this),ve(e),e=Cs(e);const{buffer:n,blockLen:r}=this,o=e.length;for(let s=0;s<o;){const i=Math.min(r-this.pos,o-s);if(i===r){for(;r<=o-s;s+=r)this.process(e,s);continue}n.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,zt(this.h,this.r,this.buffer,this.pad)}digestInto(e){zd(this),FS(e,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:o}=this;if(o){for(n[o++]=1;o<16;o++)n[o]=0;this.process(n,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=r[i]>>>0,e[s++]=r[i]>>>8}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}}const ex=zS(32,t=>new QS(t));function tx(t,e,n,r,o,s=20){let i=t[0],a=t[1],c=t[2],l=t[3],d=e[0],u=e[1],f=e[2],h=e[3],g=e[4],m=e[5],b=e[6],w=e[7],I=o,y=n[0],v=n[1],L=n[2],k=i,T=a,E=c,S=l,C=d,N=u,D=f,A=h,x=g,P=m,R=b,O=w,j=I,M=y,B=v,F=L;for(let H=0;H<s;H+=2)k=k+C|0,j=te(j^k,16),x=x+j|0,C=te(C^x,12),k=k+C|0,j=te(j^k,8),x=x+j|0,C=te(C^x,7),T=T+N|0,M=te(M^T,16),P=P+M|0,N=te(N^P,12),T=T+N|0,M=te(M^T,8),P=P+M|0,N=te(N^P,7),E=E+D|0,B=te(B^E,16),R=R+B|0,D=te(D^R,12),E=E+D|0,B=te(B^E,8),R=R+B|0,D=te(D^R,7),S=S+A|0,F=te(F^S,16),O=O+F|0,A=te(A^O,12),S=S+A|0,F=te(F^S,8),O=O+F|0,A=te(A^O,7),k=k+N|0,F=te(F^k,16),R=R+F|0,N=te(N^R,12),k=k+N|0,F=te(F^k,8),R=R+F|0,N=te(N^R,7),T=T+D|0,j=te(j^T,16),O=O+j|0,D=te(D^O,12),T=T+D|0,j=te(j^T,8),O=O+j|0,D=te(D^O,7),E=E+A|0,M=te(M^E,16),x=x+M|0,A=te(A^x,12),E=E+A|0,M=te(M^E,8),x=x+M|0,A=te(A^x,7),S=S+C|0,B=te(B^S,16),P=P+B|0,C=te(C^P,12),S=S+C|0,B=te(B^S,8),P=P+B|0,C=te(C^P,7);let U=0;r[U++]=i+k|0,r[U++]=a+T|0,r[U++]=c+E|0,r[U++]=l+S|0,r[U++]=d+C|0,r[U++]=u+N|0,r[U++]=f+D|0,r[U++]=h+A|0,r[U++]=g+x|0,r[U++]=m+P|0,r[U++]=b+R|0,r[U++]=w+O|0,r[U++]=I+j|0,r[U++]=y+M|0,r[U++]=v+B|0,r[U++]=L+F|0}const nx=JS(tx,{counterRight:!1,counterLength:4,allowShortKeys:!1}),rx=new Uint8Array(16),Vd=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(rx.subarray(n))},ox=new Uint8Array(32);function Gd(t,e,n,r,o){o!==void 0&&ve(o,void 0,"AAD");const s=t(e,n,ox),i=VS(r.length,o?o.length:0,!0),a=ex.create(s);o&&Vd(a,o),Vd(a,r),a.update(i);const c=a.digest();return zt(s,i),c}const sx=t=>(e,n,r)=>({encrypt(s,i){const a=s.length;i=Va(a+16,i,!1),i.set(s);const c=i.subarray(0,-16);t(e,n,c,c,1);const l=Gd(t,e,n,c,r);return i.set(l,a),zt(l),i},decrypt(s,i){i=Va(s.length-16,i,!1);const a=s.subarray(0,-16),c=s.subarray(-16),l=Gd(t,e,n,a,r);if(!KS(c,l))throw zt(l),new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,n,i,i,1),zt(l),i}}),Xd=WS({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},sx(nx));function ix(t,e,n){return Jc(t),n===void 0&&(n=new Uint8Array(t.outputLen)),ap(t,n,e)}const Tr=Uint8Array.of(0),ax=Uint8Array.of();function cx(t,e,n,r=32,o){Jc(t),Tt(r,"length"),Pt(e,void 0,"prk");const s=t.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(r>255*s)throw new Error("Length must be <= 255*HashLen");const i=Math.ceil(r/s);if(n===void 0?n=ax:Pt(n,void 0,"info"),!i)return new Uint8Array;const a=new Uint8Array(i*s),{iHash:c,oHash:l}=ap.create(t,e),d=new Uint8Array(s),u=i>1?t.create():void 0;for(let h=0;h<i-1;h++){Tr[0]=h+1;const g=c._cloneInto(u);h&&g.update(d),g.update(n).update(Tr).digestInto(d),l._cloneInto(u).update(d).digestInto(d),a.set(d,s*h)}if(Tr[0]=i,i>1&&c.update(d),c.update(n).update(Tr).digestInto(d),l.update(d).digestInto(d),a.set(d,s*(i-1)),c.destroy(),l.destroy(),u?.destroy(),d!==a&&fn(d),fn(Tr),r===a.length)return a;const f=a.slice(0,r);return fn(a),f}const fp={hashSHA256(t){return Ni(t.subarray())},getHKDF(t,e){const n=ix(Ni,e,t),o=cx(Ni,n,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){const t=Oo.utils.randomSecretKey();return{publicKey:Oo.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:Oo.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return Oo.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,n,r){return Xd(r,e,n).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,n,r,o){return Xd(r,e,n).decrypt(t.subarray(),o)}},lx=fp;function dx(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,n)=>t.generateX25519SharedKey(e.privateKey,n).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}const Is=t=>{const e=It(2);return e[0]=t>>8,e[1]=t,e};Is.bytes=2;const Rs=t=>{if(t.length<2)throw RangeError("Could not decode int16BE");if(t instanceof Uint8Array){let e=0;return e+=t[0]<<8,e+=t[1],e}return t.getUint16(0)};Rs.bytes=2;function ux(t){return{xxHandshakeSuccesses:t.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:t.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:t.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:t.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:t.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function hp(t,e){!e.enabled||!vo||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${ee(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${ee(t.privateKey,"hex")}`)):e("Missing local static keys."))}function pp(t,e){!e.enabled||!vo||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${ee(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${ee(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function fx(t,e){!e.enabled||!vo||e(t?`REMOTE_STATIC_PUBLIC_KEY ${ee(t.subarray(),"hex")}`:"Missing remote static public key.")}function gp(t,e){!e.enabled||!vo||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${ee(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function mp(t,e,n){!n.enabled||!vo||(n(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&ee(t.k,"hex")}`),n(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&ee(e.k,"hex")}`))}class Xr extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=Xr.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}const hx=0,px=4294967295,gx="Cipherstate has reached maximum n, a new handshake must be performed";class mx{n;bytes;view;constructor(e=hx){this.n=e,this.bytes=Ue(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>px)throw new Error(gx)}}const er=Ue(0);class Do{k;n;crypto;constructor(e,n=void 0,r=0){this.crypto=e,this.k=n,this.n=new mx(r)}hasKey(){return!!this.k}encryptWithAd(e,n){if(!this.hasKey())return n;this.n.assertValue();const r=this.crypto.encrypt(n,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,n,r){if(!this.hasKey())return n;this.n.assertValue();const o=this.crypto.decrypt(n,this.n.getBytes(),e,this.k,r);return this.n.increment(),o}}class wx{cs;ck;h;crypto;constructor(e,n){this.crypto=e;const r=we(n,"utf-8");this.h=bx(e,r),this.ck=this.h,this.cs=new Do(e)}mixKey(e){const[n,r]=this.crypto.hkdf(this.ck,e);this.ck=n,this.cs=new Do(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new se(this.h,e))}encryptAndHash(e){const n=this.cs.encryptWithAd(this.h,e);return this.mixHash(n),n}decryptAndHash(e){const n=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),n}split(){const[e,n]=this.crypto.hkdf(this.ck,er);return[new Do(this.crypto,e),new Do(this.crypto,n)]}}class yx{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:n,protocolName:r,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=n,this.ss=new wx(n,r),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,n=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<n+32)throw new Error("message is not long enough");this.re=e.sublist(n,n+32),this.ss.mixHash(this.re)}readS(e,n=0){if(this.rs)throw new Error("remote static public key is already set");const r=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<n+r)throw new Error("message is not long enough");const o=e.sublist(n,n+r);return this.rs=this.ss.decryptAndHash(o),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class wp extends yx{writeMessageA(e){return new se(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const n=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new se(n,r,this.ss.encryptAndHash(e))}writeMessageC(e){const n=this.writeS();return this.writeSE(),new se(n,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(n){throw new Xr(`handshake stage 0 validation fail: ${n.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();const n=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+n))}catch(n){throw new Xr(`handshake stage 1 validation fail: ${n.message}`)}}readMessageC(e){try{const n=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(n))}catch(n){throw new Xr(`handshake stage 2 validation fail: ${n.message}`)}}}function bx(t,e){if(e.length<=32){const n=Ue(32);return n.set(e),n}else return t.hash(e)}var Ts;(function(t){let e;t.codec=()=>(e==null&&(e=Zs((n,r,o={})=>{if(o.lengthDelimited!==!1&&r.fork(),n.webtransportCerthashes!=null)for(const s of n.webtransportCerthashes)r.uint32(10),r.bytes(s);if(n.streamMuxers!=null)for(const s of n.streamMuxers)r.uint32(18),r.string(s);o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={webtransportCerthashes:[],streamMuxers:[]},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new md('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(n.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new md('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(n.string());break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>Ys(n,t.codec()),t.decode=(n,r)=>Xs(n,t.codec(),r)})(Ts||(Ts={}));var Ps;(function(t){let e;t.codec=()=>(e==null&&(e=Zs((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.identityKey!=null&&n.identityKey.byteLength>0&&(r.uint32(10),r.bytes(n.identityKey)),n.identitySig!=null&&n.identitySig.byteLength>0&&(r.uint32(18),r.bytes(n.identitySig)),n.extensions!=null&&(r.uint32(34),Ts.codec().encode(n.extensions,r)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={identityKey:Ue(0),identitySig:Ue(0)},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{s.identityKey=n.bytes();break}case 2:{s.identitySig=n.bytes();break}case 4:{s.extensions=Ts.codec().decode(n,n.uint32(),{limits:o.limits?.extensions});break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>Ys(n,t.codec()),t.decode=(n,r)=>Xs(n,t.codec(),r)})(Ps||(Ps={}));async function yp(t,e,n){const r=await t.sign(vp(e));return Ps.encode({identityKey:Js(t.publicKey),identitySig:r,extensions:n})}async function bp(t,e,n){try{const r=Ps.decode(t),o=$a(r.identityKey);if(n?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${n}`);if(!e)throw new Error("Remote static does not exist");const s=vp(e);if(!await o.verify(s,r.identitySig))throw new Error("Invalid payload signature");return r}catch(r){throw new Pm(r.message)}}function vp(t){const e=we("noise-libp2p-static-key:");return t instanceof Uint8Array?Pa([e,t],e.length+t.length):(t.prepend(e),t)}class vx extends lp{stream;handshake;metrics;decoder;constructor(e,n,r){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=n,this.metrics=r,this.decoder=new OS({lengthDecoder:Rs,maxBufferSize:16*1024*1024,encodingLength:()=>2});const o=c=>{try{for(const l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);const s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);const i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);const a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){const n=new se;for(let r=0;r<e.byteLength;r+=Hd){let o=r+Hd;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(r,o)):s=this.handshake.encrypt(e.sublist(r,o)),this.metrics?.encryptedPackets.increment(),n.append(Is(s.byteLength)),n.append(s)}return n}decrypt(e){const n=new se;for(let r=0;r<e.byteLength;r+=io){let o=r+io;if(o>e.byteLength&&(o=e.byteLength),o-qd<r)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(r,o):s=e.sublist(r,o);const i=e.subarray(r,o-qd);try{const a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),n.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return n}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}}function Yd(t,e,n){return new vx(t,e,n)}async function Sx(t,e){const{log:n,connection:r,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await yp(s,a.publicKey,l),u=new wp({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});hp(u.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(u.writeMessageA(er),e),n.trace("Stage 0 - Initiator finished sending first message."),pp(u.e,n),n.trace("Stage 1 - Initiator waiting to receive first message from responder...");const f=u.readMessageB(await r.read(e));n.trace("Stage 1 - Initiator received the message."),gp(u.re,n),fx(u.rs,n),n.trace("Initiator going to check remote's signature...");const h=await bp(f,u.rs,c);n.trace("All good with the signature!"),n.trace("Stage 2 - Initiator sending third handshake message."),await r.write(u.writeMessageC(d),e),n.trace("Stage 2 - Initiator sent message with signed payload.");const[g,m]=u.ss.split();return mp(g,m,n),{payload:h,encrypt:b=>g.encryptWithAd(er,b),decrypt:(b,w)=>m.decryptWithAd(er,b,w)}}async function xx(t,e){const{log:n,connection:r,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await yp(s,a.publicKey,l),u=new wp({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});hp(u.s,n),n.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await r.read(e)),n.trace("Stage 0 - Responder received first message."),gp(u.re,n),n.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await r.write(u.writeMessageB(d),e),n.trace("Stage 1 - Responder sent the second handshake message with signed payload."),pp(u.e,n),n.trace("Stage 2 - Responder waiting for third handshake message...");const f=u.readMessageC(await r.read(e));n.trace("Stage 2 - Responder received the message, finished handshake.");const h=await bp(f,u.rs,c),[g,m]=u.ss.split();return mp(g,m,n),{payload:h,encrypt:b=>m.encryptWithAd(er,b),decrypt:(b,w)=>g.decryptWithAd(er,b,w)}}class Ex{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,n={}){const{staticNoiseKey:r,extensions:o,crypto:s,prologueBytes:i}=n,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");const c=s??lx;this.crypto=dx(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?ux(a):void 0,r?this.staticKey=c.generateX25519KeyPairFromSeed(r):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??Ue(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Mm]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,n){const r=e.log?.newScope("noise")??this.log,o=$d(e,{lengthEncoder:Is,lengthDecoder:Rs,maxDataLength:io}),s=await this.performHandshakeInitiator(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=$a(s.payload.identityKey);return{connection:Yd(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:cr(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;const n=this.components.upgrader.getStreamMuxers();if(n!=null)for(const r of e){const o=n.get(r);if(o!=null)return o}if(e.length)throw new Nm("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,n){const r=e.log?.newScope("noise")??this.log,o=$d(e,{lengthEncoder:Is,lengthDecoder:Rs,maxDataLength:io}),s=await this.performHandshakeResponder(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=$a(s.payload.identityKey);return{connection:Yd(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:cr(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,n,r,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Sx({connection:e,privateKey:n,remoteIdentityKey:o,log:r.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,n,r,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await xx({connection:e,privateKey:n,remoteIdentityKey:o,log:r.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}}function Ax(t={}){return e=>new Ex(e,t)}const kx="termdock-e2ee-v1",Xa=3600*1e3,Zd=512*1024*1024,Ya=4*1024*1024,Xo=()=>{},ti=Object.assign(Xo,{enabled:!1,error:Xo,trace:Xo,newScope:()=>ti});Object.freeze(ti);async function Sp(){const t=await q0();return{privateKey:t,peerId:cr(t.publicKey).toString()}}function Cx(t){return btoa(String.fromCharCode(...W0(t.privateKey)))}function Jd(t){if(t.length>512||!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Invalid identity encoding");const e=z0(Uint8Array.from(atob(t),n=>n.charCodeAt(0)));if(e.type!=="Ed25519")throw new Error("Only Ed25519 device identities are supported");return{privateKey:e,peerId:cr(e.publicKey).toString()}}class xp{constructor(e=Xo){this.consumed=e}consumed;chunks=[];size=0;ended=!1;error;wake;push(e){if(this.ended)throw this.error??new Error("Byte stream closed");if(this.size+e.byteLength>Ya)throw new Error("Secure stream buffer limit exceeded");this.chunks.push(e.slice()),this.size+=e.byteLength,this.wake?.()}end(e){this.ended=!0,this.error??=e,this.wake?.()}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const e=this.chunks.shift();if(e)this.size-=e.byteLength,yield e,this.consumed();else{if(this.ended)return;await new Promise(n=>{this.wake=n})}}}}class Ix extends lp{constructor(e,n){super({log:ti,direction:n?"outbound":"inbound",maxReadBufferLength:Ya,maxWriteBufferLength:Ya}),this.duplex=e,this.finished=e.sink(this.outgoing).catch(r=>{this.abort(lr(r))}),this.readTransport()}duplex;outgoing=new xp(()=>this.onMuxerDrain());finished;async readTransport(){try{for await(const e of this.duplex.source)this.onData(e.slice());this.onTransportClosed()}catch(e){this.onTransportClosed(lr(e))}}sendData(e){return this.outgoing.push(e.subarray()),{sentBytes:e.byteLength,canSendMore:!1}}sendReset(e){this.outgoing.end(e),this.duplex.close?.(e)}sendPause(){}sendResume(){}async close(){this.outgoing.end(),this.duplex.close?.(),this.onTransportClosed(),await this.finished}}function lr(t){return t instanceof Error?t:new Error("Secure transport failed")}class Rx extends Error{code="E2EE_REHANDSHAKE_REQUIRED";constructor(){super("Encrypted connection lifetime reached; establish a new handshake without replaying pending input")}}function Tx(t){const e=t?.maxAgeMs??Xa,n=t?.maxBytesPerDirection??Zd;if(!Number.isSafeInteger(e)||e<=0||e>Xa||!Number.isSafeInteger(n)||n<=0||n>Zd)throw new Error("Encrypted connection limits cannot exceed the production maximum");return{maxAgeMs:e,maxBytesPerDirection:n}}async function Px(t){const{identity:e,duplex:n,initiator:r,targetPinnedPeerId:o,signal:s}=t,i=Tx(t.limits);if(typeof Reflect.get(Promise,"withResolvers")!="function"||typeof globalThis.crypto?.getRandomValues!="function")throw new Error("End-to-end encryption requires Node.js 22+ or a modern browser with Promise.withResolvers and secure random support");if(r&&!o)throw new Error("A pinned target identity is required");const a=o?Y0(o):void 0;if(a&&a.type!=="Ed25519")throw new Error("Only Ed25519 target identities are supported");if(e.peerId!==cr(e.privateKey.publicKey).toString())throw new Error("Local identity mismatch");if(s?.aborted)throw s.reason??new Error("Connection aborted");const c=new Ix(n,r),l=new AbortController,d=setTimeout(()=>{const h=new Error("Encrypted handshake timed out");l.abort(h),c.abort(h)},15e3),u=()=>{l.abort(s?.reason),c.abort(lr(s?.reason))};s?.addEventListener("abort",u,{once:!0}),c.addEventListener("close",()=>s?.removeEventListener("abort",u),{once:!0});const f=Ax({crypto:fp,prologueBytes:new TextEncoder().encode(kx)})({privateKey:e.privateKey,peerId:cr(e.privateKey.publicKey),logger:{forComponent:()=>ti},upgrader:{getStreamMuxers:()=>new Map}});try{const h=await(r?f.secureOutbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}):f.secureInbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}));if(h.remotePeer.type!=="Ed25519")throw new Error("Unsupported remote identity");return{authenticatedPeerId:h.remotePeer.toString(),duplex:Nx(h.connection,i)}}catch(h){throw c.abort(lr(h)),h}finally{clearTimeout(d),s?.removeEventListener("abort",u)}}function Nx(t,e){const n=new xp,r=performance.now(),o=Date.now();let s=0,i=0,a;const c=()=>(a??=new Rx,n.end(a),t.abort(a),a),l=setTimeout(c,e.maxAgeMs);typeof l=="object"&&l.unref?.();const d=(f,h)=>{if(a)throw a;if(Math.max(performance.now()-r,Date.now()-o)>=e.maxAgeMs||f+h>=e.maxBytesPerDirection)throw c()};t.addEventListener("message",f=>{try{d(i,f.data.byteLength),i+=f.data.byteLength,n.push(f.data.subarray())}catch(h){t.abort(lr(h))}}),t.addEventListener("close",f=>{clearTimeout(l),n.end(f.error)},{once:!0});let u=!1;return{source:n,async sink(f){if(u)throw new Error("Secure sink already consumed");u=!0;try{for await(const h of f)d(s,h.byteLength),s+=h.byteLength,t.send(h)||await t.onDrain()}catch(h){throw t.abort(lr(h)),h}},close(f){f?t.abort(f):t.close()}}}const Ep=1012,Ap="Encrypted transport renewed";class al{constructor(e=64){this.limit=e}limit;items=[];wake;ended=!1;error;push(e){if(this.ended)throw new Error("Channel closed");if(this.items.length>=this.limit)throw this.end(new Error("Channel queue exceeded")),this.error;this.items.push(e),this.wake?.()}end(e){this.ended=!0,this.error??=e,this.wake?.()}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const e=this.items.shift();if(e!==void 0){yield e;continue}if(this.ended)return;await new Promise(n=>{this.wake=n}),this.wake=void 0}}}const Di=2*1024*1024,Lx=new TextEncoder,Bx=new TextDecoder("utf-8",{fatal:!0});class _x{constructor(e){this.duplex=e;const n=this;this.done=e.sink((async function*(){for await(const r of n.outgoing)try{yield r}finally{n.outgoingBytes-=r.byteLength}})()),this.done.catch(r=>this.close(r instanceof Error?r:new Error("Transport failed")))}duplex;outgoing=new al(256);outgoingBytes=0;get hasPendingWrites(){return this.outgoingBytes>0}done;send(e){const n=Lx.encode(JSON.stringify(e));if(n.length>Di)throw new Error("Record too large");const r=new Uint8Array(n.length+4);if(new DataView(r.buffer).setUint32(0,n.length),r.set(n,4),this.outgoingBytes+r.byteLength>4*1024*1024)throw new Error("Record queue byte budget exceeded");this.outgoingBytes+=r.byteLength;try{this.outgoing.push(r)}catch(o){throw this.outgoingBytes-=r.byteLength,o}}close(e){this.outgoing.end(e),this.duplex.close?.(e)}async*read(){let e=new Uint8Array(0);for await(const n of this.duplex.source){if(e.length+n.length>Di*2+8)throw new Error("Record buffer exceeded");const r=new Uint8Array(e.length+n.length);for(r.set(e),r.set(n,e.length),e=r;e.length>=4;){const o=new DataView(e.buffer,e.byteOffset,4).getUint32(0);if(o>Di||o===0)throw new Error("Invalid record size");if(e.length<o+4)break;const s=JSON.parse(Bx.decode(e.subarray(4,o+4)));if(!s||typeof s!="object"||typeof s.id!="string"||typeof s.type!="string")throw new Error("Invalid record");yield s,e=e.slice(o+4)}}if(e.length)throw new Error("Truncated record")}}function kp(t){let e="";for(let n=0;n<t.length;n+=8192)e+=String.fromCharCode(...t.subarray(n,n+8192));return btoa(e)}function Cp(t){const e=atob(t);return Uint8Array.from(e,n=>n.charCodeAt(0))}function Ox(t){const e=new al(64);t.binaryType="arraybuffer";const n=r=>{e.end(r),t.close(1e3)};return t.addEventListener("message",r=>{try{if(!(r.data instanceof ArrayBuffer)||r.data.byteLength>1024*1024)throw new Error("Invalid encrypted frame");e.push(new Uint8Array(r.data))}catch{n(new Error("Encrypted transport rejected frame"))}}),t.addEventListener("close",()=>e.end()),t.addEventListener("error",()=>e.end(new Error("Encrypted transport disconnected"))),{source:e,close:n,async sink(r){try{for await(const o of r)for(let s=0;s<o.length;s+=64*1024){const i=Date.now();for(;t.bufferedAmount>256*1024;){if(t.readyState!==1||Date.now()-i>15e3)throw new Error("Encrypted transport congested");await new Promise(a=>setTimeout(a,10))}if(t.readyState!==1)throw new Error("Encrypted transport closed");t.send(o.subarray(s,s+64*1024))}}catch(o){throw n(o instanceof Error?o:new Error("Encrypted transport failed")),o}}}}const Ip=8,Rp=128,Dx=5*1024*1024,Fx=Rp+Ip+8,Mx=256,Fo=3e4,Pr=64*1024;function $t(t){return t instanceof Error?t:new Error(String(t??"Secure connection closed"))}function Qd(t){if(!t.startsWith("/")||t.startsWith("//")||t.includes("#"))throw new Error("A local API path is required");return t}class Tp extends EventTarget{constructor(e,n,r){super(),this.url=e,this.transmit=n,this.disconnect=r}url;transmit;disconnect;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;binaryType="arraybuffer";bufferedAmount=0;protocol="termdock-e2ee-v1";extensions="";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;send(e){if(this.readyState!==1)throw new Error("Secure socket is not open");if(typeof e!="string"||new TextEncoder().encode(e).length>1024*1024)throw new Error("Unsupported socket payload");this.transmit(e)}close(e=1e3,n=""){this.readyState!==3&&(this.disconnect(),this.finish(e,n))}accept(e){if(this.readyState!==3)if(e.type==="ws-ready"){this.readyState=1;const n=new Event("open");this.dispatchEvent(n),this.onopen?.(n)}else if(e.type==="ws-data"&&typeof e.data=="string"){const n=new MessageEvent("message",{data:e.data});this.dispatchEvent(n),this.onmessage?.(n)}else e.type==="ws-close"?this.finish(typeof e.code=="number"?e.code:1e3,typeof e.reason=="string"?e.reason:""):e.type==="error"&&this.fail($t(e.error))}fail(e){if(this.readyState===3)return;const n=new Event("error");this.dispatchEvent(n),this.onerror?.(n),this.finish(1006,e.message)}finish(e,n){if(this.readyState===3)return;this.readyState=3;const r=new CloseEvent("close",{code:e,reason:n,wasClean:e===1e3});this.dispatchEvent(r),this.onclose?.(r)}}class jx{constructor(e,n,r){this.channel=e,this.identity=n,this.targetPeerId=r,this.read().catch(o=>this.close($t(o))),e.done.catch(o=>this.close($t(o)))}channel;identity;targetPeerId;establishedAt=performance.now();establishedWallTime=Date.now();lastInputAt=-1/0;pending=new Map;waiting=[];stopped=!1;closeReason;get canSwitchTransport(){return!this.channel.hasPendingWrites&&performance.now()-this.lastInputAt>=2e3&&![...this.pending.values()].some(e=>e.kind!=="socket")&&!this.waiting.some(e=>e.kind!=="socket")}get renewalDue(){return!this.stopped&&Math.max(performance.now()-this.establishedAt,Date.now()-this.establishedWallTime)>=Xa-5*6e4}get closed(){return this.stopped}hasCapacity(e){if(this.pending.size>=Fx)return!1;const n=[...this.pending.values()].filter(r=>r.kind===e).length;return e==="http"?n<Ip:e==="socket"?n<Rp:!0}allocate(e){if(this.stopped)throw this.closeReason??new Error("Secure connection closed");const n=crypto.randomUUID(),r=new al(4);return this.pending.set(n,{queue:r,kind:e}),{id:n,queue:r}}reserve(e,n){return n?.aborted?Promise.reject(n.reason):this.stopped?Promise.reject(this.closeReason??new Error("Secure connection closed")):this.hasCapacity(e)?Promise.resolve(this.allocate(e)):this.waiting.length>=Mx?Promise.reject(new Error("连接繁忙,请稍后重试。")):new Promise((r,o)=>{const s=l=>{this.waiting=this.waiting.filter(d=>d!==c),c.cleanup(),o(l)},i=()=>s(n?.reason??new Error("Request aborted")),a=setTimeout(()=>s(new Error("连接等待超时,请重试。")),Fo),c={kind:e,resolve:r,reject:o,cleanup:()=>{clearTimeout(a),n?.removeEventListener("abort",i)}};this.waiting.push(c),n?.addEventListener("abort",i,{once:!0})})}dispatchWaiting(){if(!this.stopped)for(let e=0;e<this.waiting.length;){const n=this.waiting[e];if(!this.hasCapacity(n.kind)){e++;continue}this.waiting.splice(e,1),n.cleanup(),n.resolve(this.allocate(n.kind))}}async read(){try{for await(const e of this.channel.read()){const n=this.pending.get(e.id);n&&(n.socket?(n.socket.accept(e),(e.type==="ws-close"||e.type==="error")&&this.release(e.id)):(n.queue.push(e),(e.type==="end"||e.type==="error")&&(n.cancelUpload?.(),this.release(e.id))))}}finally{this.close(new Error("Secure connection closed"))}}release(e){this.pending.get(e)?.queue.end(),this.pending.delete(e),this.dispatchWaiting()}async request(e,n){const{id:r,queue:o}=await this.reserve("request"),s=setTimeout(()=>this.close(new Error("Secure connection timed out")),Math.max(1e3,Math.min(Fo,n?.timeoutMs??Fo)));try{if(this.stopped)throw this.closeReason;this.channel.send({...e,id:r});const i=(await o[Symbol.asyncIterator]().next()).value;if(!i)throw new Error("Secure request closed");if(i.type==="error")throw $t(i.error);return i}finally{clearTimeout(s),this.release(r)}}openSocket(e){Qd(e);let n;const r=new AbortController,o=new Tp(e,s=>{if(n){try{JSON.parse(s)?.type==="input"&&(this.lastInputAt=performance.now())}catch{}this.channel.send({id:n,type:"ws-data",data:s})}},()=>{if(r.abort(),n)try{this.channel.send({id:n,type:"ws-close"})}finally{this.release(n)}});return this.reserve("socket",r.signal).then(s=>{if(n=s.id,o.readyState===3){this.release(n);return}const i=this.pending.get(n);if(!i)throw new Error("Secure connection closed");i.socket=o,this.channel.send({id:n,type:"ws-open",path:e})}).catch(s=>{n&&this.release(n),o.fail($t(s))}),o}async fetch(e,n){const r=typeof location>"u"?"https://termdock.invalid":location.origin,o=e instanceof Request?e:null,s=new URL(o?.url??String(e),r);if(s.origin!==r)throw new Error("Only current-service API requests are supported");const i=new Request(s,o?new Request(o,n):n),a=i.method.toUpperCase(),c=Qd(s.pathname+s.search),l=s.pathname==="/api/terminal/fs/upload"?110*1024*1024:Dx;if(i.signal.aborted)throw i.signal.reason;const d={};i.headers.forEach((v,L)=>{["cookie","authorization","host","connection","content-length"].includes(L)||(d[L]=v)});const{id:u,queue:f}=await this.reserve("http",i.signal),h=f[Symbol.asyncIterator]();let g;const m=()=>{g?.cancel().catch(()=>{})},b=this.pending.get(u);if(!b)throw new Error("Secure connection closed");b.cancelUpload=m;const w=()=>{m();try{this.channel.send({id:u,type:"cancel"})}catch{}f.end($t(i.signal.reason??"Request aborted")),this.release(u)};i.signal.addEventListener("abort",w,{once:!0});const I=()=>{i.signal.removeEventListener("abort",w),this.release(u)},y=async()=>{let v;try{const L=(await Promise.race([h.next(),new Promise((k,T)=>{v=setTimeout(()=>T(new Error("服务响应超时,请重试。")),Fo)})])).value;if(!L)throw new Error("Secure response ended unexpectedly");if(L.type==="error")throw $t(L.error);return L}finally{clearTimeout(v)}};try{if(i.signal.aborted)throw i.signal.reason;if(this.channel.send({id:u,type:"http",method:a,path:c,headers:d}),i.body){const E=i.body.getReader();g=E;let S=0,C=0;try{for(;;){const{done:N,value:D}=await E.read();if(N)break;if(S+=D.byteLength,S>l)throw new Error("Request body exceeds upload limit");for(let A=0;A<D.byteLength;A+=Pr){if(this.channel.send({id:u,type:"upload",data:kp(D.subarray(A,A+Pr))}),(await y()).type!=="upload-ack")throw new Error("Invalid upload acknowledgement");C+=Math.min(Pr,D.byteLength-A),n?.onUploadProgress?.(C)}}}catch(N){throw await E.cancel(N).catch(()=>{}),N}finally{g=void 0,E.releaseLock()}}if(i.signal.aborted||this.stopped)throw new Error("Request aborted");this.channel.send({id:u,type:"upload-end"});const v=await y();if(v.type!=="head"||typeof v.status!="number")throw new Error("Invalid response header");const L=new Headers(v.headers);if(a==="HEAD"||[204,205,304].includes(v.status)){if((await y()).type!=="end")throw new Error("Unexpected response body");return I(),new Response(null,{status:v.status,headers:L})}let k=!1;const T=new ReadableStream({pull:async E=>{try{k&&(this.channel.send({id:u,type:"ack"}),k=!1);const S=await y();if(S.type==="end"){E.close(),I();return}if(S.type!=="chunk"||typeof S.data!="string")throw new Error("Invalid response chunk");const C=Cp(S.data);if(C.length>Pr)throw new Error("Response chunk exceeds budget");E.enqueue(C),k=!0}catch(S){E.error(S),w(),I()}},cancel:()=>{w(),I()}},{highWaterMark:Pr,size:E=>E.byteLength});return new Response(T,{status:v.status,headers:L})}catch(v){throw w(),I(),v}}retire(){for(const e of this.pending.values())e.socket?.accept({id:"",type:"ws-close",code:Ep,reason:Ap});this.close()}close(e=new Error("Secure connection closed")){if(!this.stopped){this.stopped=!0,this.closeReason=e;for(const n of this.waiting.splice(0))n.cleanup(),n.reject(e);for(const n of this.pending.values())n.queue.end(e),n.cancelUpload?.(),n.socket?.fail(e);this.pending.clear(),this.channel.close(e)}}}async function yn(t){const e=new URL(t.url);if(!["wss:","ws:"].includes(e.protocol))throw new Error("A WebSocket endpoint is required");if(e.protocol==="ws:"&&!["127.0.0.1","localhost","[::1]"].includes(e.hostname))throw new Error("Remote secure channels require WSS");const n=t.identity??await Sp(),r=(t.socketFactory??(c=>new WebSocket(c)))(e.href),o=Ox(r),s=new AbortController,i=setTimeout(()=>s.abort(new Error("Secure handshake timed out")),2e4),a=t.signal?AbortSignal.any([t.signal,s.signal]):s.signal;try{await new Promise((d,u)=>{if(a.aborted){u(a.reason);return}const f=()=>{a.removeEventListener("abort",m),r.removeEventListener("open",h),r.removeEventListener("error",g),r.removeEventListener("close",g)},h=()=>{f(),d()},g=()=>{f(),u(new Error("Secure transport unavailable"))},m=()=>{f(),u(a.reason)};a.addEventListener("abort",m,{once:!0}),r.addEventListener("open",h),r.addEventListener("error",g),r.addEventListener("close",g),r.readyState===1&&h()});const c=await Px({identity:n,duplex:o,initiator:!0,targetPinnedPeerId:t.targetPeerId,signal:a}),l=new jx(new _x(c.duplex),n,c.authenticatedPeerId);if(t.pairingCode)try{await l.request({type:"pair",code:t.pairingCode})}catch(d){throw l.close($t(d)),d}return l}catch(c){throw r.close(),c}finally{clearTimeout(i)}}const eu=256*1024,Ux=1024*1024;class $x extends EventTarget{constructor(e,n,r=o=>new WebSocket(o)){if(super(),this.url=e,!/^[a-zA-Z0-9_.:-]{1,160}$/.test(n))throw new Error("Invalid target identity");this.upstream=r(e),this.deadline=setTimeout(()=>this.fail("Relay connection timed out"),2e4),this.upstream.addEventListener("message",o=>{if(this.readyState!==3)try{if(typeof o.data!="string"||new TextEncoder().encode(o.data).length>eu)throw new Error("Invalid relay envelope");const s=JSON.parse(o.data);if(s.type==="ready"&&!this.requested){this.requested=!0,this.transmit({type:"open",streamId:this.streamId,serviceId:n});return}if(s.streamId!==this.streamId)return;if(s.type==="opened"&&this.readyState===0){clearTimeout(this.deadline),this.readyState=1;const l=new Event("open");this.dispatchEvent(l),this.onopen?.(l);return}if(s.type==="close"){this.finish(1001,"Relay route closed"),this.upstream.close();return}if(s.type!=="data"||this.readyState!==1||s.encoding!=="base64"||typeof s.payload!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(s.payload))throw new Error("Invalid ciphertext relay frame");const i=Cp(s.payload),a=this.binaryType==="blob"?new Blob([i]):i.buffer,c=new MessageEvent("message",{data:a});this.dispatchEvent(c),this.onmessage?.(c)}catch{this.fail("Relay protocol rejected frame")}}),this.upstream.addEventListener("close",o=>this.finish(o.code||1006,"Relay disconnected")),this.upstream.addEventListener("error",()=>this.fail("Relay transport unavailable"))}url;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;protocol="";extensions="";binaryType="arraybuffer";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;upstream;streamId=crypto.randomUUID();requested=!1;deadline;get bufferedAmount(){return this.upstream.bufferedAmount}transmit(e){const n=JSON.stringify(e);if(this.upstream.readyState!==1||this.upstream.bufferedAmount+n.length>Ux||n.length>eu)throw new Error("Relay unavailable or congested");this.upstream.send(n)}send(e){if(this.readyState!==1)throw new Error("Relay socket is not open");let n;if(ArrayBuffer.isView(e))n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof ArrayBuffer)n=new Uint8Array(e);else throw new Error("Relay secure transport requires binary bytes");try{this.transmit({type:"data",streamId:this.streamId,encoding:"base64",payload:kp(n)})}catch(r){throw this.fail("Relay transport congested"),r}}close(e=1e3,n=""){if(this.readyState!==3){try{this.requested&&this.transmit({type:"close",streamId:this.streamId})}catch{}this.finish(e,n),this.upstream.close()}}fail(e){if(this.readyState===3)return;const n=new Event("error");this.dispatchEvent(n),this.onerror?.(n),this.finish(1006,e),this.upstream.close()}finish(e,n){if(this.readyState===3)return;clearTimeout(this.deadline),this.readyState=3;const r=new CloseEvent("close",{code:e,reason:n,wasClean:e===1e3});this.dispatchEvent(r),this.onclose?.(r)}}function Pp(t){return e=>new $x(e,t)}function Hx(t){if(typeof t!="string"||!t.startsWith("/api/")||/[\\\x00-\x20\x7f#]/.test(t))return null;const e=t.split("?")[0];if(e.includes("//"))return null;try{const r=e.split("/").map((o,s)=>{if(s===0||o===""&&s===e.split("/").length-1)return o;const i=decodeURIComponent(o);if(!i||i==="."||i===".."||/[\\/\x00-\x1f\x7f]/.test(i)||/%[a-f0-9]{2}/i.test(i))throw new Error("Ambiguous API path");return i}).join("/");return r.endsWith("/")&&!r.startsWith("/api/terminal/fs/preview/")?null:r}catch{return null}}function qx(t){if(!("serviceWorker"in navigator))return()=>{};const e=new Set,n=r=>{if(r.source!==navigator.serviceWorker.controller||r.data?.type!=="termdock-secure-fetch"||r.ports.length!==1)return;const o=r.ports[0],{path:s,method:i,headers:a,body:c,expectedTargetPeerId:l,previewPrefix:d}=r.data;let u;try{u=new URL(s,location.origin)}catch{o.close();return}if(u.origin!==location.origin||!u.pathname.startsWith("/api/")||e.size>=32||typeof i!="string"||c!==void 0&&(!(c instanceof ArrayBuffer)||c.byteLength>5*1024*1024)){o.postMessage({type:"error"}),o.close();return}if(d!==void 0&&(typeof d!="string"||!d.endsWith("/")||!/^\/api\/terminal\/fs\/preview\/[a-f0-9]{32}\//.test(d)||!["GET","HEAD"].includes(i)||!Hx(u.pathname)?.startsWith(d))){o.postMessage({type:"error"}),o.close();return}const f=new AbortController;let h,g,m=!1,b=!1;const w=()=>{b||(b=!0,e.delete(w),f.abort(),h?.cancel().catch(()=>{}),o.close())};e.add(w),o.onmessage=I=>{if(I.data?.type==="cancel"){w();return}I.data?.type!=="pull"||m||b||(m=!0,(async()=>{if(!h){o.postMessage({type:"end"}),w();return}if(!g?.length){const v=await h.read();if(v.done){o.postMessage({type:"end"}),w();return}g=v.value}const y=g.slice(0,64*1024);g=g.subarray(y.length),o.postMessage({type:"chunk",data:y.buffer},[y.buffer])})().catch(()=>{o.postMessage({type:"error"}),w()}).finally(()=>{m=!1}))},o.onmessageerror=w,o.start(),(async()=>{const I=await t();if(b)return;if(l&&l!==I.targetPeerId)throw new Error("Preview target changed");const y=await I.fetch(u.pathname+u.search,{method:i,headers:a,body:["GET","HEAD"].includes(i)?void 0:c,signal:f.signal});if(b){await y.body?.cancel();return}h=y.body?.getReader();const v={};y.headers.forEach((L,k)=>{v[k]=L}),o.postMessage({type:"head",status:y.status,headers:v,bodyless:!h,targetPeerId:I.targetPeerId})})().catch(()=>{b||(o.postMessage({type:"error"}),w())})};return navigator.serviceWorker.addEventListener("message",n),()=>{navigator.serviceWorker.removeEventListener("message",n);for(const r of[...e])r()}}class Je extends Error{constructor(){super("Device authorization expired or revoked")}}const Mo=new WeakMap;function mr(t,e={}){const n=Mo.get(t);if(!t.closed&&n&&(!n.settled||Date.now()-n.at<(e.maxAgeMs??1e3)))return n.pending;const r={at:Date.now(),settled:!1,pending:void 0},o=Kx(t,e.timeoutMs??5e3).then(s=>(r.at=Date.now(),r.settled=!0,s),s=>{throw Mo.get(t)===r&&Mo.delete(t),s});return r.pending=o,Mo.set(t,r),o}async function Kx(t,e){const n=await t.request({type:"permissions"},{timeoutMs:e});if(n.type!=="result"||typeof n.fullService!="boolean"||!Array.isArray(n.grants))throw new Error("Invalid permission response");const r=n.grants,o=n.fullService===!0;if(!o&&r.length===0)throw new Je;return{fullService:o,grants:r,canManage:o&&r.length>0||r.some(s=>s.actions.includes("authorization.manage"))}}const Np="termdock-secure-last-path:",zx=10*6e4;function Lp(t){try{const e=JSON.parse(sessionStorage.getItem(Np+t)||"null");return e&&typeof e.key=="string"&&Date.now()-e.at<zx?e.key:void 0}catch{return}}function Za(t,e){try{sessionStorage.setItem(Np+t,JSON.stringify({key:e,at:Date.now()}))}catch{}}function Bp(t,e,n=!1){return new Promise((r,o)=>{let s=0,i=0,a=!1,c,l;const d=new Set,u=()=>{clearTimeout(l);for(const h of d)h.abort();d.clear()},f=()=>{if(a)return;if(s>=t.length){i||(a=!0,u(),o(c||new Error("没有可用的连接路线。")));return}if(i>=(n?1:2))return;const h=t[s++],g=performance.now(),m=w=>{performance.getEntriesByName("termdock:connection-path").length>64&&performance.clearMeasures("termdock:connection-path"),performance.measure("termdock:connection-path",{start:g,end:performance.now(),detail:{path:h.key.startsWith("relay:")?"relay":"direct",ok:w}})},b=new AbortController;d.add(b),i++,h.run(b.signal).then(w=>{if(m(!0),d.delete(b),a){e(w);return}a=!0,u(),r({value:w,key:h.key})},w=>{if(m(!1),d.delete(b),i--,!a){if(c=w,w instanceof Je){a=!0,u(),o(w);return}f()}}),clearTimeout(l),!n&&s<t.length&&(l=setTimeout(f,400))};f()})}const Wx=3,Vx=1/0,Gx=10,_p="termdock-secure-workspace-limit";function Op(t){return t===1/0||Number.isInteger(t)&&t>=3&&t<=Gx}function Xx(){try{const t=localStorage.getItem(_p),e=t==="unlimited"?1/0:Number(t);if(Op(e))return e}catch{}return navigator.maxTouchPoints>0?Wx:Vx}function Yx(t,e,n,r){if(t.length<=r)return t;const o=new Set(["root",e,...n?[n]:[]]),s=[...t].reverse().sort((i,a)=>a.touchedAt-i.touchedAt);for(const i of s){if(o.size>=r)break;o.add(i.key)}return t.filter(i=>o.has(i.key))}const Dp="termdock-workspace",ao="termdock:workspace-visibility",Ja="termdock:workspace-activate";function ni(){return window.parent!==window&&location.pathname==="/workspace.html"&&new URLSearchParams(location.search).get(Dp)||"root"}let tu,nu;function ut(){try{if(window.parent===window)return window.__termdockWorkspaceHost;const t=window.parent.__termdockWorkspaceHost;return t&&t!==tu&&(tu=t,nu={...t,subscribe(e){const n=t.subscribe(e,ni()),r=o=>{o.persisted||n()};return window.addEventListener("pagehide",r),()=>{n(),window.removeEventListener("pagehide",r)}}}),t?nu:void 0}catch{return}}function Yo(){const t=ut();return!t||t.snapshot().activeKey===ni()}function Ns(t,e=!0){return ut()?.activate(t,e)??!1}function Mn(t){ut()?.report(ni(),t)}const Qa="termdock-secure-workspace-session:",Fp="termdock-secure-last-workspace";function Zx(){for(const t of["sessionStorage","localStorage"])try{const e=window[t].getItem(Fp);if(e)return e}catch{}return null}function Jx(t){for(const e of["sessionStorage","localStorage"])try{window[e].setItem(Fp,t)}catch{}}function VI(t){if(t)try{const e=JSON.parse(localStorage.getItem(Qa+t)||"null");return localStorage.removeItem(Qa+t),e&&typeof e.sessionId=="string"&&Date.now()-e.at<6e4?e.sessionId:void 0}catch{return}}function Qx(t){if(window.parent!==window||window.termdockDesktop)return;if(window.__termdockWorkspaceHost)return window.__termdockWorkspaceHost;let e={activeKey:"root",items:[{key:"root",service:t,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]};try{const u=Zx(),f=t&&u!==t.targetPeerId?gn().find(h=>h.targetPeerId===u):void 0;f?.targetPeerId&&(e={activeKey:f.targetPeerId,items:[...e.items,{key:f.targetPeerId,service:f,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]})}catch{}let n=Xx(),r=e.activeKey==="root"?"root":null;const o=new Map,s=new Map([["root",window]]),i=new Set,a=()=>{for(const u of[...o.keys()])u()},c=()=>{const u=Yx(e.items,e.activeKey,r,n),f=new Set(u.map(h=>h.key));e={...e,items:u};for(const[h,g]of o)g&&!f.has(g)&&o.delete(h);for(const h of s.keys())f.has(h)||s.delete(h);for(const h of i)f.has(h)||i.delete(h)},l=(u,f)=>{try{const h=f.document.createEvent("CustomEvent");if(h.initCustomEvent(ao,!1,!1,{active:e.activeKey===u}),f.dispatchEvent(h),e.activeKey===u){const g=f.document.createEvent("Event");if(g.initEvent("resize",!1,!1),f.dispatchEvent(g),i.delete(u)){const m=f.document.createEvent("Event");m.initEvent(Ja,!1,!1),f.dispatchEvent(m)}}else f.document.activeElement?.blur?.()}catch{}},d={snapshot:()=>e,subscribe:(u,f)=>(o.set(u,f),()=>{o.delete(u)}),present(u){r=u},retentionLimit:()=>n,setRetentionLimit(u){if(Op(u)){n=u;try{localStorage.setItem(_p,u===1/0?"unlimited":String(u))}catch{}c(),a()}},activate(u,f=!0){const h=$s(u);if(!h?.targetPeerId)return!1;const g=e.items.find(w=>w.service?.targetPeerId===h.targetPeerId),m=g?.key||h.targetPeerId,b=g?{...g,service:h,touchedAt:Date.now()}:{key:m,service:h,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()};e={activeKey:m,items:g?e.items.map(w=>w===g?b:w):[...e.items,b]},c(),Jx(h.targetPeerId),f&&i.add(m),a();for(const[w,I]of s)l(w,I);return!0},report(u,f){const h=e.items.find(m=>m.key===u);if(!h||f.service&&h.service?.targetPeerId&&f.service.targetPeerId!==h.service.targetPeerId)return;const g={...h,...f};JSON.stringify(g)!==JSON.stringify(h)&&(e={...e,items:e.items.map(m=>m===h?g:m)},a())},attach(u,f){f&&e.items.some(h=>h.key===u)?(s.set(u,f),l(u,f)):s.delete(u)},focusSession(u,f){const h=gn().find(m=>m.targetPeerId===u);if(!h)return!1;try{localStorage.setItem(Qa+u,JSON.stringify({sessionId:f,at:Date.now()}))}catch{return!1}d.activate(h,!1);const g=s.get(e.activeKey);if(g){const m=g.document.createEvent("CustomEvent");m.initCustomEvent("termdock:workspace-session",!1,!1,null),g.dispatchEvent(m)}return!0}};return window.__termdockWorkspaceHost=d,d}let Fi;async function Qe(){return Fi||(Fi=(async()=>{const t=await new Promise((e,n)=>{const r=indexedDB.open("termdock-device-identity",1);r.onupgradeneeded=()=>r.result.createObjectStore("keys"),r.onsuccess=()=>e(r.result),r.onerror=()=>n(r.error)});try{const e=await new Promise((o,s)=>{const i=t.transaction("keys").objectStore("keys").get("identity");i.onsuccess=()=>o(i.result),i.onerror=()=>s(i.error)});if(e)return Jd(e);const n=await Sp();let r=n;return await new Promise((o,s)=>{const i=t.transaction("keys","readwrite"),a=i.objectStore("keys"),c=a.get("identity");c.onsuccess=()=>{typeof c.result=="string"?r=Jd(c.result):a.put(Cx(n),"identity")},i.oncomplete=()=>o(),i.onerror=()=>s(i.error)}),r}finally{t.close()}})()),Fi}const Ye="termdock:secure-state";let J,jn,_e,dr="direct",Zo=!1,ru=0,Jo=!1,ou=-1/0;const ur=globalThis.fetch.bind(globalThis);function re(){return Nc()}function nn(){return J}function eE(){return _e}function Mp(){J?.close(),_e?.close(),J=void 0,_e=void 0}async function jp(){const t=await ur("/api/auth/status",{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error("Failed to query auth status");return t.json()}async function tE(){if(re()){await dt();return}if((await jp()).enabled)return;const t=await ur("/api/auth/open/parameters",{cache:"no-store"});if(!t.ok)throw new Error("Open service unavailable");const{serviceIdentity:e}=await t.json();if(typeof e!="string"||!e)throw new Error("Invalid service identity");await Ze({url:location.origin,targetPeerId:e,serviceName:location.hostname})}async function nE(t,e){const{startPasswordBootstrap:n,finishPasswordBootstrap:r}=await Gt(async()=>{const{startPasswordBootstrap:l,finishPasswordBootstrap:d}=await import("./passwordBootstrap-CazWrYzP.js");return{startPasswordBootstrap:l,finishPasswordBootstrap:d}},__vite__mapDeps([0,1,2,3])),o=l=>t===location.origin?l:new URL(l,t).href,s=async(l,d)=>{const u=await ur(o(l),{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(15e3),...d?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}:{}});if(!u.ok)throw new Error(u.status===429?"尝试次数较多,请稍后再试。":u.status===401?"密码不正确,请重新输入。":"暂时无法登录这台服务,请稍后重试。");return u.json()},{saltHex:i}=await s("/api/auth/password/parameters"),a=await Qe(),c=await n(e,i);try{const l=await s("/api/auth/password/start",{startLoginRequest:c.startLoginRequest,clientIdentity:a.peerId});let d;try{d=await r(c,l,{clientIdentity:a.peerId,origin:location.origin})}catch{throw new Error("密码不正确,或服务身份无法验证。请检查后重试。")}return await s("/api/auth/password/finish",{attemptId:d.attemptId,finishLoginRequest:d.finishLoginRequest}),{url:t,targetPeerId:d.serverIdentity,serviceName:new URL(t).host,serviceOrigin:t}}finally{c.passwordKey=""}}async function cl(t,e){const n=re();if(n&&(n.serviceOrigin||n.url)===t)return await ec(n,e),n;try{return await nE(t,e)}catch(r){if(!(r instanceof TypeError)&&!(r instanceof DOMException))throw r;const o=(await He()).find(i=>i.targetPeerId&&(i.serviceOrigin||i.url)===t);if(!o?.targetPeerId)throw new Error("暂时连不上这台服务,请检查地址和网络。");const s={...o,targetPeerId:o.targetPeerId,serviceName:o.label};return await ec(s,e),s}}async function ec(t,e){const n=await ll(t),{startPasswordBootstrap:r,finishPasswordBootstrap:o}=await Gt(async()=>{const{startPasswordBootstrap:i,finishPasswordBootstrap:a}=await import("./passwordBootstrap-CazWrYzP.js");return{startPasswordBootstrap:i,finishPasswordBootstrap:a}},__vite__mapDeps([0,1,2,3]));let s;try{const i=await n.request({type:"password-parameters"},{timeoutMs:5e3});s=await r(e,String(i.saltHex));const a=await n.request({type:"password-start",startLoginRequest:s.startLoginRequest,origin:location.origin}),c=await o(s,a,{clientIdentity:(await Qe()).peerId,origin:location.origin});if(c.serverIdentity!==t.targetPeerId)throw new Error("服务身份发生变化。");await n.request({type:"password-finish",attemptId:c.attemptId,finishLoginRequest:c.finishLoginRequest})}catch{throw new Error("暂时无法登录,请检查目标服务密码与入口授权后重试。")}finally{s&&(s.passwordKey=""),n.close()}}async function rE(t){try{const e=re(),n=e?.serviceOrigin||location.origin,r=await cl(n,t);return await Ze({...r,routes:e?.routes,serviceName:e?.serviceName||r.serviceName}),Response.json({ok:!0})}catch(e){return Response.json({error:e instanceof Error?e.message:"暂时无法登录,请重试。",code:"INVALID_PASSWORD"},{status:401})}}async function su(t,e){const n=Oe(t),r=(await He()).find(i=>(i.serviceOrigin||i.url)===n&&i.targetPeerId);if(e===void 0&&r?.targetPeerId)try{return await Ze({...r,targetPeerId:r.targetPeerId,serviceName:r.label}),{}}catch(i){if(!(i instanceof Je))throw i}if(e!==void 0){const i=await cl(n,e);if(r?.targetPeerId&&r.targetPeerId!==i.targetPeerId)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await Ze({...i,routes:r?.routes,serviceName:r?.label||i.serviceName}),{}}const o=await ur(new URL("/api/auth/open/parameters",n).href,{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(1e4)}).catch(()=>{throw new Error("暂时连不上这台服务,请检查地址和网络后重试。")});if(o.status===403)return{passwordRequired:!0};if(!o.ok)throw new Error("这台服务暂时不可用,请稍后重试。");const{serviceIdentity:s}=await o.json();if(typeof s!="string"||!s)throw new Error("这不是可连接的 Termdock 服务。");if(r?.targetPeerId&&r.targetPeerId!==s)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await Ze({url:n,targetPeerId:s,serviceName:r?.label||new URL(n).host,serviceOrigin:n}),{}}function Vt(t){const e=[...t.routes||[]];if(t.entryServiceId&&t.entryServiceId!==t.targetPeerId&&e.unshift({url:t.url,targetPeerId:t.entryServiceId}),!e.length&&t.routes===void 0)try{const n=JSON.parse(localStorage.getItem(Pc)||"null");n&&n.targetPeerId!==t.targetPeerId&&new URL(n.url).host===new URL(t.url).host&&e.push(n)}catch{}return e.flatMap((n,r)=>{try{return n.targetPeerId&&n.targetPeerId!==t.targetPeerId&&e.findIndex(o=>o.targetPeerId===n.targetPeerId)===r?[{url:Oe(n.url),targetPeerId:n.targetPeerId}]:[]}catch{return[]}}).slice(0,4)}function wr(t){const e=Vt(t),n=[t.serviceOrigin||t.url,...(t.routes||[]).slice(0,4).filter(o=>o.targetPeerId===t.targetPeerId).map(o=>o.url)],r=new Set;for(const o of n)try{const s=Oe(o);e.some(i=>i.url===s)||r.add(s)}catch{}return[...r]}function bn(t){const e=new URL("/api/federation/secure",Oe(t));return e.protocol=e.protocol==="https:"?"wss:":"ws:",e.href}async function Xt(t,e){return yn({url:bn(t.url),targetPeerId:t.targetPeerId,identity:await Qe(),signal:e?AbortSignal.any([e,AbortSignal.timeout(5e3)]):AbortSignal.timeout(5e3)})}async function ll(t,e){const n=await Qe(),r=wr(t).map(i=>({key:`direct:${i}`,run:a=>yn({url:bn(i),targetPeerId:t.targetPeerId,identity:n,signal:AbortSignal.any([a,AbortSignal.timeout(8e3),...e?[e]:[]])})}));for(const i of Vt(t))r.push({key:`relay:${i.targetPeerId}:${i.url}`,run:async a=>{e&&(a=AbortSignal.any([a,e]));const c=[J,_e].find(d=>d&&!d.closed&&d.targetPeerId===i.targetPeerId),l=c||await Xt(i,a);try{if(a.aborted)throw a.reason;const d=await l.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(a.aborted)throw a.reason;if(typeof d.routeToken!="string")throw new Error("入口未允许此设备连接该服务。");const u=new URL(bn(i.url));return u.pathname="/api/federation/relay",u.searchParams.set("routeToken",d.routeToken),await yn({url:u.href,targetPeerId:t.targetPeerId,identity:n,socketFactory:Pp(t.targetPeerId),signal:AbortSignal.any([a,AbortSignal.timeout(8e3)])})}finally{c||l.close()}}});const o=Lp(t.targetPeerId);r.sort((i,a)=>+(a.key===o)-+(i.key===o));const s=await Bp(r,i=>i.close());return Za(t.targetPeerId,s.key),s.value}async function oE(t,e){const n=await ll(t,e);try{const o=(await n.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node;if(o?.serviceId!==t.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");return{...o,serviceId:t.targetPeerId}}finally{n.close()}}async function sE(t,e){const n=await ll(t,e),r=()=>n.close();e.addEventListener("abort",r,{once:!0});try{if(e.aborted||(await mr(n,{timeoutMs:3e3}),e.aborted))throw e.reason;return n}catch(o){throw n.close(),o}finally{e.removeEventListener("abort",r)}}async function Ze(t,e={}){const n=J,r=_e,o=await Qe(),s=Oe(t.serviceOrigin||t.url),i=(await He()).find(w=>w.targetPeerId===t.targetPeerId),a={...t,routes:t.routes??i?.routes},c=Vt(a),l=wr(a);let d,u,f=t.pairingCode,h="direct";const g=new Set,m=new Map,b=async(w,I)=>{if(n&&!n.closed&&n.targetPeerId===w.targetPeerId)return n;if(r&&!r.closed&&r.targetPeerId===w.targetPeerId)return r;const y=m.get(w.targetPeerId);if(y&&!y.closed)return y;const v=await Xt(w,I);return g.add(v),m.set(w.targetPeerId,v),v};try{if(t.routeCode&&t.entryServiceId){const E=c.find(N=>N.targetPeerId===t.entryServiceId);if(!E)throw new Error("邀请缺少入口信息。");if((await(await b(E)).request({type:"route-pair",code:t.routeCode})).serviceId!==t.targetPeerId)throw new Error("邀请的目标服务不一致。");t.routeOnly&&await Ct({id:t.targetPeerId,url:s,label:t.serviceName||new URL(s).host,targetPeerId:t.targetPeerId,serviceOrigin:s,routes:c})}const w=[],I=async(E,S)=>{const C=()=>E.close();S.addEventListener("abort",C,{once:!0});try{if(S.aborted||(await mr(E),S.aborted))throw S.reason}catch(N){throw E.close(),N}finally{S.removeEventListener("abort",C)}};for(const E of l)w.push({key:`direct:${E}`,run:async S=>{const C=await yn({url:bn(E),targetPeerId:t.targetPeerId,pairingCode:f,identity:o,signal:AbortSignal.any([S,AbortSignal.timeout(8e3)])});return f=void 0,await I(C,S),{client:C,path:"direct"}}});for(const E of c)w.push({key:`relay:${E.targetPeerId}:${E.url}`,run:async S=>{let C,N;try{if(C=await b(E,S),S.aborted)throw S.reason;const D=await C.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(S.aborted)throw S.reason;if(typeof D.routeToken!="string"||!D.routeToken)throw new Error("入口未允许此设备连接该服务。");const A=new URL(bn(E.url));return A.pathname="/api/federation/relay",A.searchParams.set("routeToken",D.routeToken),N=await yn({url:A.href,targetPeerId:t.targetPeerId,pairingCode:f,identity:o,socketFactory:Pp(t.targetPeerId),signal:AbortSignal.any([S,AbortSignal.timeout(8e3)])}),f=void 0,await I(N,S),{client:N,entry:C,path:"relay"}}catch(D){throw N?.close(),C&&C!==r&&C!==n&&C.close(),D}}});const y=Lp(t.targetPeerId);w.sort((E,S)=>+(S.key===y)-+(E.key===y));const v=await Bp(w,E=>{E.client.close(),E.entry&&E.entry!==n&&E.entry!==r&&E.entry.close()},!!f);if(d=v.value.client,u=v.value.entry,h=v.value.path,e.renewIfCurrent){if(J!==e.renewIfCurrent||n!==e.renewIfCurrent||n.closed||!n.canSwitchTransport||re()?.targetPeerId!==t.targetPeerId){d.close();for(const E of g)E!==_e&&E!==J&&E.close();return J??n}J=d,dr=h,_e=u,Za(t.targetPeerId,v.key),n.retire();for(const E of new Set([r,...g]))E&&E!==n&&E!==d&&E!==u&&E.close();return window.dispatchEvent(new Event(Ye)),d}if(Za(t.targetPeerId,v.key),J!==n&&J&&!J.closed&&J.targetPeerId===t.targetPeerId){d.close();for(const E of g)E!==_e&&E.close();return J}h==="direct"&&new URL(s).host===location.host&&Cm(t.targetPeerId);const L=(await He()).find(E=>E.targetPeerId===t.targetPeerId||!E.targetPeerId&&(E.serviceOrigin||E.url)===s),k=L?.label||t.serviceName||new URL(s).host,T={url:s,targetPeerId:t.targetPeerId,serviceName:k,serviceOrigin:s,routes:a.routes??c};if(await(e.rememberOnly?Rm:Ct)({id:L?.id||t.targetPeerId,...T,label:k}),Kn!=="unpaired"&&Kn!==t.targetPeerId&&ut()&&Ns({id:L?.id||t.targetPeerId,...T,label:k})){d.close();for(const E of g)E!==n&&E!==r&&E.close();return n||d}vf(T),J=d,dr=h,_e=u;for(const E of new Set([n,r,...g]))E&&E!==d&&E!==u&&E.close();return Kn!==t.targetPeerId?(location.reload(),new Promise(()=>{})):(window.dispatchEvent(new Event(Ye)),d)}catch(w){d?.close();for(const I of g)I!==r&&I.close();throw w}}async function iE(){const t=J,e=re();if(!(Jo||Zo||jn||!t?.renewalDue||!t.canSwitchTransport||!e||performance.now()-ou<3e4)){ou=performance.now(),Jo=!0;try{await Ze(e,{renewIfCurrent:t})}catch(n){console.debug("[connection] renewal deferred",{reason:n instanceof Error?n.message:"unknown"})}finally{Jo=!1}}}async function aE(){const t=J,e=re();if(Date.now()-ru<6e4||Jo||Zo||dr!=="relay"||!t||t.closed||!t.canSwitchTransport||!e?.serviceOrigin)return;Zo=!0,ru=Date.now();let n;try{for(const o of wr(e))try{n=await yn({url:bn(o),targetPeerId:e.targetPeerId,identity:await Qe(),signal:AbortSignal.timeout(3e3)}),await mr(n);break}catch(s){if(n?.close(),n=void 0,s instanceof Je)throw s}if(!n||J!==t||!t.canSwitchTransport)return;const r=_e;J=n,n=void 0,_e=void 0,dr="direct",t.close(),r?.close(),window.dispatchEvent(new Event(Ye))}catch(r){r instanceof Je&&J===t&&(Mp(),window.dispatchEvent(new Event("auth:unauthorized")))}finally{n?.close(),Zo=!1}}function cE(){return dr}async function lE(t){return t?(t.throwIfAborted(),new Promise((e,n)=>{const r=()=>n(t.reason);t.addEventListener("abort",r,{once:!0}),dt().then(o=>{t.removeEventListener("abort",r),t.aborted?n(t.reason):e(o)},o=>{t.removeEventListener("abort",r),n(o)})})):dt()}async function dt(){if(J&&!J.closed){const e=J;return iE(),e}if(J=void 0,jn)return jn;const t=re();if(!t)throw new Error("DEVICE_PAIRING_REQUIRED");return jn=Ze(t,{rememberOnly:!0}).catch(e=>{if(J&&!J.closed&&J.targetPeerId===t.targetPeerId)return J;throw e}).finally(()=>{jn=void 0}),jn}function Up(t){const e=new URL(t,location.href);if(J&&!J.closed)return J.openSocket(e.pathname+e.search);let n;const r=new Tp(t,o=>n?.send(o),()=>n?.close());return dt().then(o=>{r.readyState!==3&&(n=o.openSocket(e.pathname+e.search),n.onopen=()=>r.accept({type:"ws-ready",id:""}),n.onmessage=s=>r.accept({type:"ws-data",id:"",data:s.data}),n.onclose=s=>r.accept({type:"ws-close",id:"",code:s.code,reason:s.reason}),n.onerror=()=>r.fail(new Error("Encrypted connection unavailable")))}).catch(o=>r.fail(o)),r}function dE(){qx(dt),window.fetch=async(t,e)=>{const n=new URL(t instanceof Request?t.url:String(t),location.href);if(!n.pathname.startsWith("/api/"))return ur(t,e);if(n.origin!==location.origin)throw new Error("Remote business API requires a paired encrypted service");if(n.pathname==="/api/meta")return ur(t,e);if(n.pathname==="/api/auth/status"){if(!re()){const s=await jp();return Response.json({enabled:s.enabled,authenticated:!1})}try{const s=await mr(await dt());return Response.json({enabled:s.grants.length>0,authenticated:!0})}catch(s){if(s instanceof Je)return Response.json({enabled:!0,authenticated:!1});throw s}}if(n.pathname==="/api/auth/login"){const i=await new Request(t instanceof Request?t:n.href,e).json();return rE(typeof i.password=="string"?i.password:"")}if(n.pathname==="/api/csrf-token")return Response.json({csrfToken:"encrypted-device-channel"});if(n.pathname==="/api/auth/logout")return J&&!J.closed&&await J.request({type:"logout"}),J?.close(),_e?.close(),J=void 0,_e=void 0,km(),location.reload(),Response.json({ok:!0});const r=e?.signal!==void 0?e.signal:t instanceof Request?t.signal:void 0,o=await lE(r);return t instanceof Request?o.fetch(t,e):o.fetch(n.pathname+n.search,e)}}async function uE(t){if(!t.targetPeerId)throw new Error("请先连接这台服务,再查看可中转的服务。");for(const e of wr({...t,targetPeerId:t.targetPeerId})){let n;const r={url:e,targetPeerId:t.targetPeerId};try{n=await Xt(r)}catch{continue}try{const o=await n.request({type:"route-targets"},{timeoutMs:5e3});if(!Array.isArray(o.items))throw new Error("入口服务需要更新后才能查看中转列表。");return{route:r,canManage:o.canManage===!0,items:o.items}}catch(o){throw o instanceof Error&&/UNKNOWN|UNSUPPORTED/i.test(o.message)?new Error("入口服务需要更新后才能查看中转列表。"):o}finally{n.close()}}throw new Error("暂时连不上中转入口,请检查地址和网络后重试。")}async function fE(t,e){const n=await Xt(t);try{const r=await n.request({type:"route-targets"},{timeoutMs:5e3}),o=(Array.isArray(r.items)?r.items:[]).find(c=>c.serviceId===e);if(!o)throw new Error("该服务已不可见,请刷新列表或请入口管理员授权。");if(!o.available)throw new Error("入口暂时无法中转到这台服务,请稍后重试。");const s=(await He()).find(c=>c.targetPeerId===o.serviceId),i=[t,...(s?.routes||[]).filter(c=>c.targetPeerId!==t.targetPeerId)];if(i.length>4)throw new Error("这台服务已保存 4 个备用连接,请先移除一个后重试。");if(!o.authorized){if(!r.canManage)throw new Error("请先让入口管理员授权此设备。");await n.request({type:"route-grant",serviceId:o.serviceId,subjectId:(await Qe()).peerId})}const a=s?.serviceOrigin||s?.url||o.url||t.url;return{url:a,serviceOrigin:a,targetPeerId:o.serviceId,serviceName:s?.label||o.label||(o.url?new URL(o.url).host:`中转服务 ${o.serviceId.slice(0,8)}`),routes:i}}finally{n.close()}}async function hE(t,e){const n=await Xt(t);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),o=(await Qe()).peerId;return{canManage:r.canManage===!0,grants:(Array.isArray(r.grants)?r.grants:[]).filter(s=>s.subjectId===o&&s.targetServiceId===e)}}finally{n.close()}}async function pE(t,e,n){if(n!==void 0&&(await cl(Oe(e.url),n)).targetPeerId!==e.targetPeerId)throw new Error("入口服务的身份已改变,请重新连接并确认。");const r=await Xt(e);try{await r.request({type:"route-grant",serviceId:t.targetPeerId,subjectId:(await Qe()).peerId,url:Oe(t.serviceOrigin||t.url)})}finally{r.close()}}async function gE(t,e){const n=await Xt(e);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),o=(await Qe()).peerId,s=(Array.isArray(r.grants)?r.grants:[]).filter(i=>i.subjectId===o&&i.targetServiceId===t&&i.active);for(const i of s)await n.request({type:"route-revoke",grantId:i.id})}finally{n.close()}}async function $p(t,e){const n=await Xt(e);try{const r=await n.request({type:"route-invite-create",serviceId:t.targetPeerId});if(typeof r.routeCode!="string"||typeof r.expiresAt!="number")throw new Error("暂时无法生成备用连接邀请。");return{routeCode:r.routeCode,expiresAt:r.expiresAt}}finally{n.close()}}async function Qo(t,e){const n=(await He()).find(o=>o.id===t.id||t.targetPeerId&&o.targetPeerId===t.targetPeerId)||t;await Ct({...n,url:n.serviceOrigin||n.url,entryServiceId:void 0,routes:e});const r=re();r&&r.targetPeerId===t.targetPeerId&&vf({...r,url:r.serviceOrigin||r.url,entryServiceId:void 0,routes:e})}async function mE(t,e){const n=t.targetPeerId;if(!n)throw new Error("请先连接这台服务,再添加备用地址。");let r;try{r=Oe(e)}catch{throw new Error("请输入有效的 HTTPS 地址,例如 https://电脑地址:9834。")}const o=async()=>(await He()).find(a=>a.targetPeerId===n)||t,s=a=>{const c=a.routes??Vt({...a,targetPeerId:n});if(Oe(a.serviceOrigin||a.url)===r||c.some(l=>Oe(l.url)===r))throw new Error("这个地址已经在连接列表中。");if(c.length>=4)throw new Error("最多保存 4 个备用地址或入口,请先移除不再使用的连接。");return[...c,{url:r,targetPeerId:n}]};s(await o());let i;try{try{i=await yn({url:bn(r),targetPeerId:n,identity:await Qe(),signal:AbortSignal.timeout(5e3)}),await mr(i)}catch(l){throw l instanceof Je?new Error("这台服务尚未授权当前设备,请先恢复设备授权。"):new Error("无法验证这个地址。请确认能访问该地址、HTTPS 证书受信任,且运行的是同一台 Termdock 服务。")}const a=await o(),c=s(a);if(await Qo(a,c),re()?.targetPeerId===n&&Kn===n&&(!J||J.closed)){const l=J,d=_e;J=i,i=void 0,_e=void 0,dr="direct",l?.close(),d?.close(),window.dispatchEvent(new Event(Ye))}return c}finally{i?.close()}}async function iu(t,e){await ec(t,e),await Ze({...t,pairingCode:void 0,routeCode:void 0})}function wE(){let t=!1,e=!1,n=!1,r;const o=new Map,s=new Map,i=async(u,f,h)=>{const g=JSON.stringify(h);if(o.get(f.serviceId)===g)return;const m=AbortSignal.timeout(1e4),b=await u.fetch("/api/csrf-token",{signal:m});if(!b.ok)throw new Error("CONNECTION_AUTHORIZATION_REQUIRED");const w=await b.json();if(typeof w.csrfToken!="string")throw new Error("INVALID_CSRF_TOKEN");const I=await u.fetch("/api/terminal/operations/collaboration-connections",{method:"POST",signal:m,headers:{"Content-Type":"application/json","X-XSRF-TOKEN":w.csrfToken},body:JSON.stringify({origin:f.origin,nodes:h})});if(!I.ok){const y=await I.json().catch(()=>({}));throw new Error(y.error||`HTTP_${I.status}`)}o.set(f.serviceId,g)},a=async()=>{if(t){n=!0;return}const u=re(),f=nn();if(!(e||!u||!f||f.closed)){t=!0,n=!1;try{let h;const g=await Promise.race([He(),new Promise((v,L)=>{h=setTimeout(()=>L(new Error("SERVICE_DIRECTORY_TIMEOUT")),8e3)})]).finally(()=>clearTimeout(h));g.some(v=>v.targetPeerId===u.targetPeerId)||g.push({...u,id:u.targetPeerId,label:u.serviceName||u.url});const m=[...new Map(g.filter(v=>!!v.targetPeerId).map(v=>[v.targetPeerId,v])).values()].slice(0,64);if(m.length<2)return;const b=[];for(const v of m)try{const L=`${v.targetPeerId}:${v.serviceOrigin||v.url}`;let k=s.get(L);if(!k){const T=v.targetPeerId===u.targetPeerId?(await f.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node:await oE({...v,targetPeerId:v.targetPeerId},AbortSignal.timeout(8e3));if(T?.serviceId!==v.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");const E=T.origin||v.serviceOrigin||v.url,S=new URL(E);if(S.protocol!=="https:"||S.origin!==E)throw new Error("INVALID_SERVICE_ORIGIN");k={serviceId:T.serviceId,origin:E,...T.caFingerprint256?{caFingerprint256:T.caFingerprint256}:{}},s.set(L,k)}b.push({service:v,node:k})}catch{}if(e||nn()!==f||re()?.targetPeerId!==u.targetPeerId)return;const w=b.find(v=>v.node.serviceId===u.targetPeerId);if(!w||b.length<2){c(3e4);return}const I=b.map(v=>v.node).sort((v,L)=>v.serviceId.localeCompare(L.serviceId));await i(f,w.node,I);let y=b.length<m.length;for(const v of b){if(v===w||o.get(v.node.serviceId)===JSON.stringify(I))continue;let L;try{L=await sE({...v.service,targetPeerId:v.node.serviceId},AbortSignal.timeout(8e3)),await i(L,v.node,I)}catch{y=!0}finally{L?.close()}}window.dispatchEvent(new CustomEvent("termdock:collaboration-enrollment",{detail:{ok:!0}})),y&&c(3e4)}catch(h){window.dispatchEvent(new CustomEvent("termdock:collaboration-enrollment",{detail:{ok:!1,error:h instanceof Error?h.message:"CONNECTION_ENROLLMENT_FAILED"}})),c(3e4)}finally{t=!1,n&&c(100)}}};function c(u=100){e||(clearTimeout(r),r=setTimeout(()=>{a()},u))}const l=()=>{c()},d=Hs(l);window.addEventListener(Ye,l),window.addEventListener("termdock:collaboration-enroll",l),window.addEventListener("online",l),window.addEventListener("pageshow",l),window.addEventListener("pagehide",u=>{u.persisted||(e=!0,clearTimeout(r),d(),window.removeEventListener("termdock:collaboration-enroll",l),window.removeEventListener(Ye,l),window.removeEventListener("online",l),window.removeEventListener("pageshow",l))}),c()}var jo={},au;function yE(){if(au)return jo;au=1;var t=mm();return jo.createRoot=t.createRoot,jo.hydrateRoot=t.hydrateRoot,jo}var bE=yE();const vE=bf(bE);const Hp=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim();const SE=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const xE=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,r)=>r?r.toUpperCase():n.toLowerCase());const cu=t=>{const e=xE(t);return e.charAt(0).toUpperCase()+e.slice(1)};var Mi={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const EE=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1},AE=_.createContext({}),kE=()=>_.useContext(AE),CE=_.forwardRef(({color:t,size:e,strokeWidth:n,absoluteStrokeWidth:r,className:o="",children:s,iconNode:i,...a},c)=>{const{size:l=24,strokeWidth:d=2,absoluteStrokeWidth:u=!1,color:f="currentColor",className:h=""}=kE()??{},g=r??u?Number(n??d)*24/Number(e??l):n??d;return _.createElement("svg",{ref:c,...Mi,width:e??l??Mi.width,height:e??l??Mi.height,stroke:t??f,strokeWidth:g,className:Hp("lucide",h,o),...!s&&!EE(a)&&{"aria-hidden":"true"},...a},[...i.map(([m,b])=>_.createElement(m,b)),...Array.isArray(s)?s:[s]])});const xe=(t,e)=>{const n=_.forwardRef(({className:r,...o},s)=>_.createElement(CE,{ref:s,iconNode:e,className:Hp(`lucide-${SE(cu(t))}`,`lucide-${t}`,r),...o}));return n.displayName=cu(t),n};const IE=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],qp=xe("arrow-left",IE);const RE=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],TE=xe("arrow-right",RE);const PE=[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]],NE=xe("arrow-up-right",PE);const LE=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M11.68 2.009A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673c-.824-.85-1.678-1.731-2.21-3.348",key:"xaq59h"}],["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}]],Kp=xe("bell-dot",LE);const BE=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],dl=xe("check",BE);const _E=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],zp=xe("chevron-down",_E);const OE=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],vn=xe("chevron-right",OE);const DE=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],FE=xe("chevron-up",DE);const ME=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Wp=xe("copy",ME);const jE=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],Vp=xe("ellipsis",jE);const UE=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],De=xe("loader-circle",UE);const $E=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],HE=xe("monitor",$E);const qE=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],KE=xe("pencil",qE);const zE=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Gp=xe("plus",zE);const WE=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],ri=xe("server",WE);const VE=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],Xp=xe("smartphone",VE);const GE=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],XE=xe("terminal",GE);const YE=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Yp=xe("x",YE),ZE={},lu=t=>{let e;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(e):d;if(!Object.is(f,e)){const h=e;e=u??(typeof f!="object"||f===null)?f:Object.assign({},e,f),n.forEach(g=>g(e,h))}},o=()=>e,c={setState:r,getState:o,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(ZE?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},l=e=t(r,o,c);return c},JE=t=>t?lu(t):lu;var ji={exports:{}},Ui={},$i={exports:{}},Hi={};var du;function QE(){if(du)return Hi;du=1;var t=Rc();function e(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var n=typeof Object.is=="function"?Object.is:e,r=t.useState,o=t.useEffect,s=t.useLayoutEffect,i=t.useDebugValue;function a(u,f){var h=f(),g=r({inst:{value:h,getSnapshot:f}}),m=g[0].inst,b=g[1];return s(function(){m.value=h,m.getSnapshot=f,c(m)&&b({inst:m})},[u,h,f]),o(function(){return c(m)&&b({inst:m}),u(function(){c(m)&&b({inst:m})})},[u]),i(h),h}function c(u){var f=u.getSnapshot;u=u.value;try{var h=f();return!n(u,h)}catch{return!0}}function l(u,f){return f()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?l:a;return Hi.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:d,Hi}var uu;function e1(){return uu||(uu=1,$i.exports=QE()),$i.exports}var fu;function t1(){if(fu)return Ui;fu=1;var t=Rc(),e=e1();function n(l,d){return l===d&&(l!==0||1/l===1/d)||l!==l&&d!==d}var r=typeof Object.is=="function"?Object.is:n,o=e.useSyncExternalStore,s=t.useRef,i=t.useEffect,a=t.useMemo,c=t.useDebugValue;return Ui.useSyncExternalStoreWithSelector=function(l,d,u,f,h){var g=s(null);if(g.current===null){var m={hasValue:!1,value:null};g.current=m}else m=g.current;g=a(function(){function w(k){if(!I){if(I=!0,y=k,k=f(k),h!==void 0&&m.hasValue){var T=m.value;if(h(T,k))return v=T}return v=k}if(T=v,r(y,k))return T;var E=f(k);return h!==void 0&&h(T,E)?(y=k,T):(y=k,v=E)}var I=!1,y,v,L=u===void 0?null:u;return[function(){return w(d())},L===null?void 0:function(){return w(L())}]},[d,u,f,h]);var b=o(l,g[0],g[1]);return i(function(){m.hasValue=!0,m.value=b},[b]),c(b),b},Ui}var hu;function n1(){return hu||(hu=1,ji.exports=t1()),ji.exports}var r1=n1();const o1=bf(r1),Zp={},{useDebugValue:s1}=ze,{useSyncExternalStoreWithSelector:i1}=o1;let pu=!1;const a1=t=>t;function c1(t,e=a1,n){(Zp?"production":void 0)!=="production"&&n&&!pu&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),pu=!0);const r=i1(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,n);return s1(r),r}const gu=t=>{(Zp?"production":void 0)!=="production"&&typeof t!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof t=="function"?JE(t):t,n=(r,o)=>c1(e,r,o);return Object.assign(n,e),n},oi=t=>t?gu(t):gu,ul=t=>`@collaboration:${t}`,Jp=oi(t=>({activePaneId:null,setActivePane:e=>t({activePaneId:e}),docks:{},hosts:{},setDock:(e,n)=>t(r=>{const o={...r.docks};return n?o[e]=n:delete o[e],{docks:o,...!n&&r.activePaneId===ul(e)?{activePaneId:r.docks[e]?.sessionId??null}:{}}}),setHost:(e,n)=>t(r=>{const o={...r.hosts};return n?o[e]=n:delete o[e],{hosts:o}})})),ln=new Map;let Yr;function Qp(){const t=Jp.getState().activePaneId;for(const[n,r]of ln)if(r.requiresFocus&&t===ul(n))return r.receive;const e=ln.get(Yr??"");return e&&!e.requiresFocus?e.receive:void 0}function GI(t){const e=ln.get(t);e&&(e.requiresFocus?Jp.getState().setActivePane(ul(t)):Yr=t)}function l1(t){const e=Qp();return!e||!t?!1:(e(t),!0)}function XI(t,e="default",n=!1){ln.set(e,{receive:t,requiresFocus:n}),n||(Yr=e);const r=o=>{const{text:s,nonce:i}=o.detail??{};!s||Qp()!==t||(t(s),o.stopImmediatePropagation(),i&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:i,ok:!0}})))};return window.addEventListener("termdock-insert-reference",r,!0),()=>{ln.get(e)?.receive===t&&(ln.delete(e),Yr===e&&(Yr=[...ln.keys()].at(-1))),window.removeEventListener("termdock-insert-reference",r,!0)}}const d1=/^[A-Za-z0-9_@%+=:,./-]$/;function u1(t){return Array.from(t,e=>(e.codePointAt(0)??0)>127||d1.test(e)?e:`\\${e}`).join("")}function f1(t,e){if(!e)return!1;try{const n=new URL(e.serviceOrigin||e.url);return n.origin===t&&/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})$/.test(n.hostname)&&!(e.routes??[]).some(r=>r.targetPeerId!==e.targetPeerId)}catch{return!1}}function h1(t){const e=s=>s.target instanceof Element?s.target.closest("[data-termdock-terminal-dropzone]"):null,n=()=>!f1(location.origin,Nc()),r=s=>{const i=e(s);!i||!n()||!s.dataTransfer?.types.includes("Files")||(s.preventDefault(),s.stopImmediatePropagation(),s.dataTransfer.dropEffect="copy",i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="remote")},o=s=>{const i=e(s),a=Array.from(s.dataTransfer?.files??[]);if(!i||!a.length||!n())return;s.preventDefault(),s.stopImmediatePropagation();const c=i.dataset.termdockTerminalDropzone??"";i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="uploading",Gt(async()=>{const{uploadFiles:l}=await Promise.resolve().then(()=>E2);return{uploadFiles:l}},void 0).then(({uploadFiles:l})=>l("/tmp",a)).then(l=>{if(l.files.length!==a.length||l.files.some(d=>!d.path))throw new Error("Upload did not return every file path");delete i.dataset.nativeFileDrag,delete i.dataset.nativeFileDropState,t({sessionKey:c,paths:l.files.map(d=>d.path)})}).catch(l=>{i.dataset.nativeFileDropState="error",i.dispatchEvent(new CustomEvent("termdock:file-drop-error",{bubbles:!0,detail:l instanceof Error?l.message:"File upload failed"})),window.setTimeout(()=>{i.dataset.nativeFileDropState==="error"&&(delete i.dataset.nativeFileDrag,delete i.dataset.nativeFileDropState)},3e3)})};return window.addEventListener("dragover",r,!0),window.addEventListener("drop",o,!0),()=>{window.removeEventListener("dragover",r,!0),window.removeEventListener("drop",o,!0)}}function et(){return typeof window>"u"?null:window.termdockDesktop??null}const qi=new Set;let mu=!1;function YI(t){const e=et();if(!e)return()=>{};if(qi.add(t),!mu){const n=r=>{if(!l1(r.paths.map(u1).join(" ")+" "))for(const o of qi)o(r)};h1(n),e.onNativeFileDrop(n),mu=!0}return()=>{qi.delete(t)}}function eg(t=navigator.userAgent,e=navigator.maxTouchPoints){const n=/iPad/.test(t)||/Macintosh/.test(t)&&e>1?"iPad":/iPhone/.test(t)?"iPhone":/Android/.test(t)?"Android":/Windows/.test(t)?"Windows":/Macintosh|Mac OS X/.test(t)?"Mac":/Linux/.test(t)?"Linux":"设备",r=/Electron/.test(t)?"Termdock":/Edg\//.test(t)?"Edge":/Firefox|FxiOS/.test(t)?"Firefox":/Chrome|CriOS/.test(t)?"Chrome":/Safari/.test(t)?"Safari":"浏览器";return`${n} · ${r}`}let p1;function g1(){return p1??=(async()=>{const t=navigator.userAgent,[e,n]=eg().split(" · "),r=/(?:Edg|Firefox|FxiOS|Chrome|CriOS|Version)\/([\d.]+)/g,o=[...t.matchAll(r)],s=/(?:CPU (?:iPhone )?OS |Mac OS X |Android )([\d._]+)/.exec(t)?.[1]?.replaceAll("_","."),i={system:`${e}${s?` ${s}`:""}`,client:`${n}${o.length?` ${o.at(-1)[1]}`:""}`,mode:matchMedia("(display-mode: standalone)").matches||navigator.standalone?"已安装的网页应用":"网页"},a=et();if(a){i.mode="桌面客户端";const l=/Electron\/([\d.]+)/.exec(t)?.[1];i.client=l?`Termdock(Electron ${l})`:"Termdock";try{Object.assign(i,await a.deviceInfo?.())}catch{}return i}const c=navigator.userAgentData;try{const l=await c?.getHighEntropyValues(["model","architecture","bitness","platformVersion"]);typeof l?.model=="string"&&l.model&&(i.model=l.model),typeof l?.architecture=="string"&&l.architecture&&(i.arch=`${l.architecture}${l.bitness?` ${l.bitness} 位`:""}`)}catch{}return i})()}function m1({service:t,onBusyChange:e,onConnect:n,onConnectWithPassword:r}){const[o,s]=_.useState(),[i,a]=_.useState(!0),[c,l]=_.useState(!1),[d,u]=_.useState(""),[f,h]=_.useState(0),[g,m]=_.useState(),[b,w]=_.useState("");_.useEffect(()=>{let v=!1,L=!1,k;a(!0),u(""),s(void 0);const T=async E=>{try{const S=await uE(t);if(v)return;L=!0,s(S),u("")}catch(S){!v&&(!L||E)&&u(S instanceof Error?S.message:"暂时无法读取中转列表,请重试。")}finally{v||(a(!1),k=setTimeout(()=>{T(!1)},2e3))}};return T(!0),()=>{v=!0,clearTimeout(k)}},[t.id,t.url,f]);const I=async v=>{if(!c){l(!0),e(!0),u("");try{await v()}catch(L){u(L instanceof Error?L.message:"暂时无法连接,请重试。")}finally{l(!1),e(!1)}}},y=async v=>{const L=await fE(o.route,v.serviceId);try{await n(L)}catch(k){if(!(k instanceof Je))throw k;m(L)}};return p.jsxs("div",{className:"service-form",children:[g?p.jsxs("form",{className:"service-form",onSubmit:v=>{v.preventDefault(),I(async()=>{try{await r?.(g,b)}finally{w("")}})},children:[p.jsxs("p",{className:"service-help",children:["已通过“",t.label,"”连接到“",g.serviceName,"”。请登录目标服务,完成此设备的访问授权。"]}),r?p.jsxs(p.Fragment,{children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"目标服务密码"}),p.jsx("input",{type:"password",autoFocus:!0,required:!0,autoComplete:"current-password",value:b,disabled:c,onChange:v=>w(v.target.value)})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:c||!b,children:c?"正在登录…":"登录并连接"})]}):p.jsx("p",{className:"service-help",children:"请让目标服务管理员邀请此设备后再连接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>{m(void 0),w(""),u(""),h(v=>v+1)},children:"返回中转列表"})]}):p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["通过“",t.label,"”连接下方服务。",o?.canManage?"选择未授权的服务会授权此设备使用该中转。":"这里只显示已授权给此设备的中转。","目标服务会单独验证访问权限。"]}),i?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(De,{size:16,className:"service-spinning"}),"正在读取可中转的服务…"]}):o&&p.jsxs("div",{className:"service-list",children:[o.items.map(v=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:c||!v.available,onClick:()=>{I(()=>y(v))},children:[p.jsx("span",{className:"service-icon",children:p.jsx(ri,{size:19})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:v.label||(v.url?new URL(v.url).host:`中转服务 ${v.serviceId.slice(0,8)}`)}),p.jsx("span",{className:"service-description",children:v.available?v.authorized?"已获中转授权 · 连接":"授权此设备并连接":"中转暂不可用"})]}),p.jsx(vn,{size:16})]},v.serviceId)),o.items.length===0&&p.jsx("p",{className:"service-empty",children:o.canManage?"暂无可中转的服务。可在本机 Mac 客户端连接目标服务,或在目标服务的“备用连接”中启用本入口。":"暂无已授权的中转服务,请让入口管理员分享备用连接邀请。"})]}),c&&p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(De,{size:16,className:"service-spinning"}),"正在授权并连接目标服务…"]}),!i&&p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>h(v=>v+1),children:"刷新列表"})]}),d&&p.jsx("p",{className:"service-error",role:"alert",children:d})]})}const tc="#termdock-invite=";function tg(t){const e=new URL(t.entryUrl);e.hash="",e.search="",e.pathname="/";const n=new TextEncoder().encode(JSON.stringify(t));return e.hash=tc.slice(1)+btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.href}function Ls(t){const e=new URL(t);if(!["https:","http:"].includes(e.protocol)||!e.hash.startsWith(tc))throw new Error("这不是有效的 Termdock 邀请链接");const n=e.hash.slice(tc.length);if(n.length>8192)throw new Error("邀请链接过长");let r;try{const i=n.replace(/-/g,"+").replace(/_/g,"/");r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(atob(i),a=>a.charCodeAt(0))))}catch{throw new Error("邀请链接不完整,请重新复制")}if(r.v!==1||typeof r.serviceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(r.serviceId)||r.routeOnly!==!0&&(typeof r.code!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(r.code)))throw new Error("邀请信息无效或版本不兼容");const o=new URL(r.entryUrl);if(o.origin!==e.origin||o.username||o.password||!["https:","http:"].includes(o.protocol))throw new Error("邀请地址与服务不一致");if(o.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(o.hostname))throw new Error("远程邀请需要 HTTPS");if(r.entryServiceId!==void 0&&(typeof r.entryServiceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(r.entryServiceId)))throw new Error("邀请入口身份无效");if(r.routeCode!==void 0&&(typeof r.routeCode!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(r.routeCode)||!r.entryServiceId))throw new Error("邀请入口权限无效");if(r.routeOnly===!0&&(!r.entryServiceId||!r.routeCode||r.code!==void 0))throw new Error("备用连接邀请不完整");let s=o.origin;if(r.serviceUrl!==void 0){const i=new URL(r.serviceUrl);if(!["https:","http:"].includes(i.protocol)||i.username||i.password)throw new Error("目标服务地址无效");s=r.entryServiceId&&r.entryServiceId!==r.serviceId?i.origin:o.origin}return{url:o.origin,targetPeerId:r.serviceId,pairingCode:r.code,...r.routeOnly===!0?{routeOnly:!0}:{},serviceOrigin:s,serviceName:typeof r.name=="string"?r.name.slice(0,120):void 0,entryServiceId:r.entryServiceId,routeCode:r.routeCode}}function w1({service:t,onBusyChange:e}){const n={...t,targetPeerId:t.targetPeerId,serviceName:t.label},[r,o]=_.useState(()=>t.routes??Vt(n)),[s,i]=_.useState([]),[a,c]=_.useState(!0),[l,d]=_.useState(!1),[u,f]=_.useState(""),h=B=>{d(B),e(B)},[g,m]=_.useState(),[b,w]=_.useState(""),[I,y]=_.useState(""),[v,L]=_.useState(""),[k,T]=_.useState(!1),[E,S]=_.useState(),[C,N]=_.useState(),[D,A]=_.useState(!1);_.useEffect(()=>{let B=!1;return He().then(F=>{B||i(F.filter(U=>U.targetPeerId&&U.targetPeerId!==t.targetPeerId))}).catch(()=>{B||f("暂时无法读取可用服务。")}).finally(()=>{B||c(!1)}),()=>{B=!0}},[t.targetPeerId]);const x=B=>s.find(F=>F.targetPeerId===B.targetPeerId)?.label||new URL(B.url).host,P=async B=>{h(!0),f(""),L("");try{await B()}catch(F){const U=F instanceof Error?F.message:"";f(/AUTHORIZATION|DENIED/.test(U)?"当前设备没有入口管理权限。请让管理员分享备用连接邀请,或使用入口密码授权。":"暂时无法完成。请确认入口能连接目标服务,且目标地址、证书和授权有效。")}finally{h(!1)}},R=async(B,F)=>{const U={url:B.serviceOrigin||B.url,targetPeerId:B.targetPeerId};await P(async()=>{const H=await hE(U,n.targetPeerId);if(!H.grants.some(K=>K.active)){if(!H.canManage&&F===void 0){m(B);return}await pE(n,U,F)}const q=[...r.filter(K=>K.targetPeerId!==U.targetPeerId),U];await Qo(t,q),o(q),m(void 0),w("")})};if(C)return p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["把链接发给需要使用此备用连接的人。它只允许通过入口连接“",t.label,"”,对方仍需获得目标服务的访问权限。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用连接邀请"}),p.jsx("input",{readOnly:!0,value:C,onFocus:B=>B.target.select()})]}),p.jsxs("button",{type:"button",className:"service-button service-primary",onClick:()=>{navigator.clipboard.writeText(C).then(()=>A(!0)).catch(()=>f("无法自动复制,请长按链接复制。"))},children:[p.jsx(Wp,{size:16}),D?"已复制":"复制邀请链接"]}),p.jsx("button",{type:"button",className:"service-button service-secondary",onClick:()=>{N(void 0),A(!1)},children:"返回备用连接"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});if(g)return p.jsxs("form",{className:"service-form",onSubmit:B=>{B.preventDefault(),R(g,b).finally(()=>w(""))},children:[p.jsxs("p",{className:"service-help",children:["需要“",g.label,"”的管理员授权。若这是你的服务,可以使用它的密码;否则请管理员分享备用连接邀请。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"入口服务密码"}),p.jsx("input",{type:"password",required:!0,value:b,onChange:B=>w(B.target.value),autoComplete:"current-password",disabled:l,autoFocus:!0})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||!b,children:l?"正在授权…":"授权并启用"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{m(void 0),w("")},children:"取消"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});const O=r.filter(B=>B.targetPeerId===n.targetPeerId),j=r.filter(B=>B.targetPeerId!==n.targetPeerId),M=async()=>{if(!l){h(!0),T(!0),f(""),L("");try{o(await mE({...t,routes:r},I)),y(""),L("备用地址已验证并保存。")}catch(B){f(B instanceof Error?B.message:"暂时无法添加地址,请重试。")}finally{h(!1),T(!1)}}};return p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"电脑换了网络?添加它在新网络下的地址,原地址连不上时会自动尝试。只接受同一台服务。"}),p.jsxs("form",{className:"service-form",onSubmit:B=>{B.preventDefault(),M()},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用地址"}),p.jsx("input",{value:I,onChange:B=>{y(B.target.value),f(""),L("")},required:!0,disabled:l||r.length>=4,inputMode:"url",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:192.168.10.20:9834"})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||r.length>=4||!I.trim(),children:k?p.jsxs(p.Fragment,{children:[p.jsx(De,{size:16,className:"service-spinning"}),"正在验证…"]}):"验证并添加"})]}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u}),v&&p.jsx("p",{role:"status",className:"service-help",children:v}),r.length>=4&&p.jsx("p",{className:"service-help",children:"已保存 4 个备用连接。移除不再使用的地址或入口后,可以继续添加。"}),p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"首选地址"}),p.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url})]}),O.length>0&&p.jsx("div",{className:"service-list",children:O.map(B=>p.jsxs("div",{className:"service-route-item",children:[p.jsxs("div",{className:"service-route-line",children:[p.jsx("span",{className:"service-address service-route-address",children:B.url}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`移除地址 ${B.url}`,disabled:l,onClick:()=>S(B),children:"移除"})]}),E?.targetPeerId===B.targetPeerId&&E.url===B.url&&p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"从备用连接中移除此地址?不会停止正在运行的终端。"}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>S(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{P(async()=>{const F=r.filter(U=>U.targetPeerId!==B.targetPeerId||U.url!==B.url);await Qo(t,F),o(F),S(void 0)})},children:"确认移除"})]})]})]},B.url))}),p.jsxs("details",{className:"service-relay-options",children:[p.jsxs("summary",{children:["通过其他服务中转",j.length?`(${j.length})`:""]}),p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"所有直连地址都不可用时,尝试下方已授权入口;直连恢复后自动切回。"}),j.length>0&&p.jsx("div",{className:"service-list",children:j.map(B=>p.jsxs("div",{className:"service-route-item",children:[p.jsxs("div",{className:"service-route-line",children:[p.jsx("span",{className:"service-icon",children:p.jsx(ri,{size:18})}),p.jsx("span",{className:"service-name",children:x(B)}),p.jsx(dl,{size:16,className:"service-selected"})]}),E?.targetPeerId===B.targetPeerId?p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["撤销此设备经“",x(B),"”连接目标的权限?如当前无法直连,目标服务将断开。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>S(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{P(async()=>{await gE(n.targetPeerId,B);const F=r.filter(U=>U.targetPeerId!==B.targetPeerId);await Qo(t,F),o(F),S(void 0)})},children:"确认撤销"})]})]}):p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{P(async()=>{const F=await $p(n,B);N(tg({v:1,routeOnly:!0,serviceId:n.targetPeerId,name:t.label,serviceUrl:t.serviceOrigin||t.url,entryUrl:B.url,entryServiceId:B.targetPeerId,routeCode:F.routeCode}))})},children:"分享备用连接"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>S(B),children:"撤销授权"})]})]},B.targetPeerId))}),a?p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(De,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"添加中转入口"}),s.filter(B=>!r.some(F=>F.targetPeerId===B.targetPeerId)).map(B=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:l||r.length>=4,onClick:()=>{R(B)},children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:B.label}),p.jsx("span",{className:"service-description",children:"验证并授权后启用"})]}),p.jsx(vn,{size:16})]},B.id)),s.length===0&&p.jsx("p",{className:"service-empty",children:"添加并登录另一台服务后,可以将它设为中转入口。"})]})]})]}),l&&!k&&p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(De,{size:16,className:"service-spinning"}),"正在验证连接与授权…"]})]})}function y1({current:t,renderRoutes:e,renderRelayServices:n,onOpen:r,onAdd:o,onInvite:s,hideHeader:i,onNavigation:a,onBusyChange:c,initiallyAdding:l=!1}){const[d,u]=_.useState([]),[f,h]=_.useState(!0),[g,m]=_.useState(l?{kind:"add"}:{kind:"list"}),[b,w]=_.useState(!1),I=_.useCallback(A=>{w(A),c?.(A)},[c]),[y,v]=_.useState(""),L=_.useCallback(()=>{m(A=>A.kind==="routes"||A.kind==="relay-services"?{kind:"edit",service:A.service}:{kind:"list"}),v("")},[]),k=g.kind==="add"?"添加服务":g.kind==="edit"?"服务设置":g.kind==="routes"?"备用连接":g.kind==="relay-services"?"可中转的服务":void 0;_.useEffect(()=>{a?.({title:k,...k?{back:L}:{}})},[k,L,a]),_.useEffect(()=>{let A=!1,x=0;const P=async()=>{const O=++x;try{const j=await He();!A&&x===O&&(u(j),v(""))}catch{!A&&x===O&&v("暂时无法读取服务列表,请重试。")}finally{!A&&x===O&&h(!1)}};P();const R=Hs(()=>{P()});return()=>{A=!0,R()}},[]);const T=async A=>{if(!b){I(!0),v("");try{await A()}catch(x){v(x instanceof Error?x.message:"暂时无法完成,请重试。")}finally{I(!1)}}},E=g.kind==="edit"||g.kind==="routes"||g.kind==="relay-services"?d.find(A=>St(A,g.service))||g.service:void 0,S=t?d.find(A=>St(A,t))||t:void 0,C=d.filter(A=>!t||!St(A,t)),N=S?[S,...C]:C,D=p.jsxs(p.Fragment,{children:[f?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(De,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{className:"service-list",children:[N.map(A=>{const x=!!t&&St(A,t);return p.jsxs("div",{className:"service-row",children:[p.jsxs("button",{type:"button",className:"service-row-open",disabled:b||x,onClick:()=>{T(async()=>{(await r(A))?.passwordRequired&&m({kind:"add",input:A.serviceOrigin||A.url,passwordRequired:!0})})},"aria-label":x?`当前服务 ${A.label}`:`打开 ${A.label}`,children:[p.jsx("span",{className:"service-icon",children:p.jsx(ri,{size:20})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:A.label}),p.jsx("span",{className:"service-description",children:x?"当前服务":new URL(A.serviceOrigin||A.url).host})]}),x?p.jsx(dl,{size:17,className:"service-selected"}):p.jsx(vn,{size:16,className:"service-muted"})]}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`管理 ${A.label}`,disabled:b,onClick:()=>{m({kind:"edit",service:A}),v("")},children:p.jsx(Vp,{size:19})})]},A.id)}),N.length===0&&p.jsx("p",{className:"service-empty",children:"还没有添加服务。连接你的电脑,或粘贴收到的邀请链接。"})]}),p.jsxs("div",{className:`service-actions${s?" service-actions-pair":""}`,children:[p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:b,onClick:()=>{m({kind:"add"}),v("")},children:[p.jsx(Gp,{size:16}),"添加服务"]}),s&&p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:b,onClick:s,children:[p.jsx(Xp,{size:16}),"邀请设备"]})]})]});return p.jsxs("div",{className:"service-manager",children:[!i&&p.jsxs("div",{className:"service-heading",children:[k&&p.jsx("button",{type:"button",className:"service-icon-button","aria-label":"返回服务",disabled:b,onClick:L,children:p.jsx(qp,{size:20})}),p.jsx("h2",{children:k||"服务"})]}),g.kind==="relay-services"?n?.(E,I):g.kind==="routes"?e?.(E,I):g.kind==="list"?D:g.kind==="add"?p.jsx(b1,{onSave:A=>T(async()=>{const x=Oe(A);u(await Ct({id:x,url:x,label:new URL(x).host})),L()}),initialInput:g.input,passwordRequired:g.passwordRequired,busy:b,onSubmit:async(A,x)=>{let P;return await T(async()=>{P=await o(A,x),P?.passwordRequired||L()}),P}}):p.jsx(v1,{onRelayServices:n&&g.service.targetPeerId?()=>m({kind:"relay-services",service:g.service}):void 0,onRoutes:e&&g.service.targetPeerId?()=>m({kind:"routes",service:g.service}):void 0,service:E,busy:b,canRemove:!t||!St(g.service,t),onSave:A=>{T(async()=>{u(await Ct({...E,label:A})),L()})},onRemove:()=>{T(async()=>{u(await Tm(g.service.id)),L()})}}),y&&p.jsx("p",{className:"service-error",role:"alert",children:y})]})}function b1({busy:t,onSubmit:e,onSave:n,initialInput:r="",passwordRequired:o=!1}){const[s,i]=_.useState(r),[a,c]=_.useState(""),[l,d]=_.useState(o);return p.jsxs("form",{className:"service-form",onSubmit:async u=>{u.preventDefault(),(await e(s.trim(),l?a:void 0))?.passwordRequired&&d(!0),c("")},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务地址或邀请链接"}),p.jsx("input",{value:s,onChange:u=>{i(u.target.value),d(!1),c("")},disabled:t,required:!0,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:电脑地址:9834 或 https://…"})]}),l?p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务密码"}),p.jsx("input",{type:"password",value:a,onChange:u=>c(u.target.value),disabled:t,required:!0,autoFocus:!0,autoComplete:"current-password",placeholder:"输入这台服务的密码"})]}):p.jsx("p",{className:"service-help",children:"连接自己的服务,输入地址即可;收到邀请时,粘贴完整链接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:t||!s.trim()||s.includes("#termdock-invite="),onClick:()=>{n(s.trim())},children:"仅保存,不连接"}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:t||!s.trim()||l&&!a,children:t?p.jsxs(p.Fragment,{children:[p.jsx(De,{size:16,className:"service-spinning"}),"正在连接…"]}):l?"登录并连接":"继续"})]})}function v1({service:t,busy:e,canRemove:n,onSave:r,onRemove:o,onRoutes:s,onRelayServices:i}){const[a,c]=_.useState(t.label),[l,d]=_.useState(!1);return p.jsxs("form",{className:"service-form",onSubmit:u=>{u.preventDefault(),r(a.trim())},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务名称"}),p.jsx("input",{value:a,onChange:u=>c(u.target.value),disabled:e,required:!0,maxLength:120,placeholder:"例如:办公室电脑"})]}),p.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:e||!a.trim(),children:"保存名称"}),i&&p.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:i,children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:"可中转的服务"}),p.jsx("span",{className:"service-description",children:"通过这台服务连接其他电脑"})]}),p.jsx(vn,{size:16})]}),s&&p.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:s,children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:"备用连接"}),p.jsx("span",{className:"service-description",children:"添加其他网络地址或授权入口"})]}),p.jsx(vn,{size:16})]}),n&&p.jsx("div",{className:"service-remove",children:l?p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["从列表移除“",t.label,"”?不会停止服务或删除终端。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:e,onClick:()=>d(!1),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:o,children:"确认移除"})]})]}):p.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:()=>d(!0),children:"移除服务"})})]})}var _n={},Ki,wu;function S1(){return wu||(wu=1,Ki=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Ki}var zi={},Ft={},yu;function An(){if(yu)return Ft;yu=1;let t;const e=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Ft.getSymbolSize=function(r){if(!r)throw new Error('"version" cannot be null or undefined');if(r<1||r>40)throw new Error('"version" should be in range from 1 to 40');return r*4+17},Ft.getSymbolTotalCodewords=function(r){return e[r]},Ft.getBCHDigit=function(n){let r=0;for(;n!==0;)r++,n>>>=1;return r},Ft.setToSJISFunction=function(r){if(typeof r!="function")throw new Error('"toSJISFunc" is not a valid function.');t=r},Ft.isKanjiModeEnabled=function(){return typeof t<"u"},Ft.toSJIS=function(r){return t(r)},Ft}var Wi={},bu;function fl(){return bu||(bu=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+n)}}t.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},t.from=function(r,o){if(t.isValid(r))return r;try{return e(r)}catch{return o}}})(Wi)),Wi}var Vi,vu;function x1(){if(vu)return Vi;vu=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(e){const n=Math.floor(e/8);return(this.buffer[n]>>>7-e%8&1)===1},put:function(e,n){for(let r=0;r<n;r++)this.putBit((e>>>n-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const n=Math.floor(this.length/8);this.buffer.length<=n&&this.buffer.push(0),e&&(this.buffer[n]|=128>>>this.length%8),this.length++}},Vi=t,Vi}var Gi,Su;function E1(){if(Su)return Gi;Su=1;function t(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return t.prototype.set=function(e,n,r,o){const s=e*this.size+n;this.data[s]=r,o&&(this.reservedBit[s]=!0)},t.prototype.get=function(e,n){return this.data[e*this.size+n]},t.prototype.xor=function(e,n,r){this.data[e*this.size+n]^=r},t.prototype.isReserved=function(e,n){return this.reservedBit[e*this.size+n]},Gi=t,Gi}var Xi={},xu;function A1(){return xu||(xu=1,(function(t){const e=An().getSymbolSize;t.getRowColCoords=function(r){if(r===1)return[];const o=Math.floor(r/7)+2,s=e(r),i=s===145?26:Math.ceil((s-13)/(2*o-2))*2,a=[s-7];for(let c=1;c<o-1;c++)a[c]=a[c-1]-i;return a.push(6),a.reverse()},t.getPositions=function(r){const o=[],s=t.getRowColCoords(r),i=s.length;for(let a=0;a<i;a++)for(let c=0;c<i;c++)a===0&&c===0||a===0&&c===i-1||a===i-1&&c===0||o.push([s[a],s[c]]);return o}})(Xi)),Xi}var Yi={},Eu;function k1(){if(Eu)return Yi;Eu=1;const t=An().getSymbolSize,e=7;return Yi.getPositions=function(r){const o=t(r);return[[0,0],[o-e,0],[0,o-e]]},Yi}var Zi={},Au;function C1(){return Au||(Au=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},t.from=function(o){return t.isValid(o)?parseInt(o,10):void 0},t.getPenaltyN1=function(o){const s=o.size;let i=0,a=0,c=0,l=null,d=null;for(let u=0;u<s;u++){a=c=0,l=d=null;for(let f=0;f<s;f++){let h=o.get(u,f);h===l?a++:(a>=5&&(i+=e.N1+(a-5)),l=h,a=1),h=o.get(f,u),h===d?c++:(c>=5&&(i+=e.N1+(c-5)),d=h,c=1)}a>=5&&(i+=e.N1+(a-5)),c>=5&&(i+=e.N1+(c-5))}return i},t.getPenaltyN2=function(o){const s=o.size;let i=0;for(let a=0;a<s-1;a++)for(let c=0;c<s-1;c++){const l=o.get(a,c)+o.get(a,c+1)+o.get(a+1,c)+o.get(a+1,c+1);(l===4||l===0)&&i++}return i*e.N2},t.getPenaltyN3=function(o){const s=o.size;let i=0,a=0,c=0;for(let l=0;l<s;l++){a=c=0;for(let d=0;d<s;d++)a=a<<1&2047|o.get(l,d),d>=10&&(a===1488||a===93)&&i++,c=c<<1&2047|o.get(d,l),d>=10&&(c===1488||c===93)&&i++}return i*e.N3},t.getPenaltyN4=function(o){let s=0;const i=o.data.length;for(let c=0;c<i;c++)s+=o.data[c];return Math.abs(Math.ceil(s*100/i/5)-10)*e.N4};function n(r,o,s){switch(r){case t.Patterns.PATTERN000:return(o+s)%2===0;case t.Patterns.PATTERN001:return o%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(o+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return o*s%2+o*s%3===0;case t.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case t.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}t.applyMask=function(o,s){const i=s.size;for(let a=0;a<i;a++)for(let c=0;c<i;c++)s.isReserved(c,a)||s.xor(c,a,n(o,c,a))},t.getBestMask=function(o,s){const i=Object.keys(t.Patterns).length;let a=0,c=1/0;for(let l=0;l<i;l++){s(l),t.applyMask(l,o);const d=t.getPenaltyN1(o)+t.getPenaltyN2(o)+t.getPenaltyN3(o)+t.getPenaltyN4(o);t.applyMask(l,o),d<c&&(c=d,a=l)}return a}})(Zi)),Zi}var Uo={},ku;function ng(){if(ku)return Uo;ku=1;const t=fl(),e=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],n=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return Uo.getBlocksCount=function(o,s){switch(s){case t.L:return e[(o-1)*4+0];case t.M:return e[(o-1)*4+1];case t.Q:return e[(o-1)*4+2];case t.H:return e[(o-1)*4+3];default:return}},Uo.getTotalCodewordsCount=function(o,s){switch(s){case t.L:return n[(o-1)*4+0];case t.M:return n[(o-1)*4+1];case t.Q:return n[(o-1)*4+2];case t.H:return n[(o-1)*4+3];default:return}},Uo}var Ji={},Nr={},Cu;function I1(){if(Cu)return Nr;Cu=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let r=1;for(let o=0;o<255;o++)t[o]=r,e[r]=o,r<<=1,r&256&&(r^=285);for(let o=255;o<512;o++)t[o]=t[o-255]})(),Nr.log=function(r){if(r<1)throw new Error("log("+r+")");return e[r]},Nr.exp=function(r){return t[r]},Nr.mul=function(r,o){return r===0||o===0?0:t[e[r]+e[o]]},Nr}var Iu;function R1(){return Iu||(Iu=1,(function(t){const e=I1();t.mul=function(r,o){const s=new Uint8Array(r.length+o.length-1);for(let i=0;i<r.length;i++)for(let a=0;a<o.length;a++)s[i+a]^=e.mul(r[i],o[a]);return s},t.mod=function(r,o){let s=new Uint8Array(r);for(;s.length-o.length>=0;){const i=s[0];for(let c=0;c<o.length;c++)s[c]^=e.mul(o[c],i);let a=0;for(;a<s.length&&s[a]===0;)a++;s=s.slice(a)}return s},t.generateECPolynomial=function(r){let o=new Uint8Array([1]);for(let s=0;s<r;s++)o=t.mul(o,new Uint8Array([1,e.exp(s)]));return o}})(Ji)),Ji}var Qi,Ru;function T1(){if(Ru)return Qi;Ru=1;const t=R1();function e(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(r){this.degree=r,this.genPoly=t.generateECPolynomial(this.degree)},e.prototype.encode=function(r){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(r.length+this.degree);o.set(r);const s=t.mod(o,this.genPoly),i=this.degree-s.length;if(i>0){const a=new Uint8Array(this.degree);return a.set(s,i),a}return s},Qi=e,Qi}var ea={},ta={},na={},Tu;function rg(){return Tu||(Tu=1,na.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),na}var ct={},Pu;function og(){if(Pu)return ct;Pu=1;const t="[0-9]+",e="[A-Z $%*+\\-./:]+";let n="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";n=n.replace(/u/g,"\\u");const r="(?:(?![A-Z0-9 $%*+\\-./:]|"+n+`)(?:.|[\r
3
3
  ]))+`;ct.KANJI=new RegExp(n,"g"),ct.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),ct.BYTE=new RegExp(r,"g"),ct.NUMERIC=new RegExp(t,"g"),ct.ALPHANUMERIC=new RegExp(e,"g");const o=new RegExp("^"+n+"$"),s=new RegExp("^"+t+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return ct.testKanji=function(c){return o.test(c)},ct.testNumeric=function(c){return s.test(c)},ct.testAlphanumeric=function(c){return i.test(c)},ct}var Nu;function kn(){return Nu||(Nu=1,(function(t){const e=rg(),n=og();t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(s,i){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!e.isValid(i))throw new Error("Invalid version: "+i);return i>=1&&i<10?s.ccBits[0]:i<27?s.ccBits[1]:s.ccBits[2]},t.getBestModeForData=function(s){return n.testNumeric(s)?t.NUMERIC:n.testAlphanumeric(s)?t.ALPHANUMERIC:n.testKanji(s)?t.KANJI:t.BYTE},t.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},t.isValid=function(s){return s&&s.bit&&s.ccBits};function r(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+o)}}t.from=function(s,i){if(t.isValid(s))return s;try{return r(s)}catch{return i}}})(ta)),ta}var Lu;function P1(){return Lu||(Lu=1,(function(t){const e=An(),n=ng(),r=fl(),o=kn(),s=rg(),i=7973,a=e.getBCHDigit(i);function c(f,h,g){for(let m=1;m<=40;m++)if(h<=t.getCapacity(m,g,f))return m}function l(f,h){return o.getCharCountIndicator(f,h)+4}function d(f,h){let g=0;return f.forEach(function(m){const b=l(m.mode,h);g+=b+m.getBitsLength()}),g}function u(f,h){for(let g=1;g<=40;g++)if(d(f,g)<=t.getCapacity(g,h,o.MIXED))return g}t.from=function(h,g){return s.isValid(h)?parseInt(h,10):g},t.getCapacity=function(h,g,m){if(!s.isValid(h))throw new Error("Invalid QR Code version");typeof m>"u"&&(m=o.BYTE);const b=e.getSymbolTotalCodewords(h),w=n.getTotalCodewordsCount(h,g),I=(b-w)*8;if(m===o.MIXED)return I;const y=I-l(m,h);switch(m){case o.NUMERIC:return Math.floor(y/10*3);case o.ALPHANUMERIC:return Math.floor(y/11*2);case o.KANJI:return Math.floor(y/13);case o.BYTE:default:return Math.floor(y/8)}},t.getBestVersionForData=function(h,g){let m;const b=r.from(g,r.M);if(Array.isArray(h)){if(h.length>1)return u(h,b);if(h.length===0)return 1;m=h[0]}else m=h;return c(m.mode,m.getLength(),b)},t.getEncodedBits=function(h){if(!s.isValid(h)||h<7)throw new Error("Invalid QR Code version");let g=h<<12;for(;e.getBCHDigit(g)-a>=0;)g^=i<<e.getBCHDigit(g)-a;return h<<12|g}})(ea)),ea}var ra={},Bu;function N1(){if(Bu)return ra;Bu=1;const t=An(),e=1335,n=21522,r=t.getBCHDigit(e);return ra.getEncodedBits=function(s,i){const a=s.bit<<3|i;let c=a<<10;for(;t.getBCHDigit(c)-r>=0;)c^=e<<t.getBCHDigit(c)-r;return(a<<10|c)^n},ra}var oa={},sa,_u;function L1(){if(_u)return sa;_u=1;const t=kn();function e(n){this.mode=t.NUMERIC,this.data=n.toString()}return e.getBitsLength=function(r){return 10*Math.floor(r/3)+(r%3?r%3*3+1:0)},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(r){let o,s,i;for(o=0;o+3<=this.data.length;o+=3)s=this.data.substr(o,3),i=parseInt(s,10),r.put(i,10);const a=this.data.length-o;a>0&&(s=this.data.substr(o),i=parseInt(s,10),r.put(i,a*3+1))},sa=e,sa}var ia,Ou;function B1(){if(Ou)return ia;Ou=1;const t=kn(),e=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function n(r){this.mode=t.ALPHANUMERIC,this.data=r}return n.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(o){let s;for(s=0;s+2<=this.data.length;s+=2){let i=e.indexOf(this.data[s])*45;i+=e.indexOf(this.data[s+1]),o.put(i,11)}this.data.length%2&&o.put(e.indexOf(this.data[s]),6)},ia=n,ia}var aa,Du;function _1(){if(Du)return aa;Du=1;const t=kn();function e(n){this.mode=t.BYTE,typeof n=="string"?this.data=new TextEncoder().encode(n):this.data=new Uint8Array(n)}return e.getBitsLength=function(r){return r*8},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(n){for(let r=0,o=this.data.length;r<o;r++)n.put(this.data[r],8)},aa=e,aa}var ca,Fu;function O1(){if(Fu)return ca;Fu=1;const t=kn(),e=An();function n(r){this.mode=t.KANJI,this.data=r}return n.getBitsLength=function(o){return o*13},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(r){let o;for(o=0;o<this.data.length;o++){let s=e.toSJIS(this.data[o]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
4
- Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),r.put(s,13)}},ca=n,ca}var la={exports:{}},Mu;function D1(){return Mu||(Mu=1,(function(t){var e={single_source_shortest_paths:function(n,r,o){var s={},i={};i[r]=0;var a=e.PriorityQueue.make();a.push(r,0);for(var c,l,d,u,f,h,g,m,b;!a.empty();){c=a.pop(),l=c.value,u=c.cost,f=n[l]||{};for(d in f)f.hasOwnProperty(d)&&(h=f[d],g=u+h,m=i[d],b=typeof i[d]>"u",(b||m>g)&&(i[d]=g,a.push(d,g),s[d]=l))}if(typeof o<"u"&&typeof i[o]>"u"){var w=["Could not find a path from ",r," to ",o,"."].join("");throw new Error(w)}return s},extract_shortest_path_from_predecessor_list:function(n,r){for(var o=[],s=r;s;)o.push(s),n[s],s=n[s];return o.reverse(),o},find_path:function(n,r,o){var s=e.single_source_shortest_paths(n,r,o);return e.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(n){var r=e.PriorityQueue,o={},s;n=n||{};for(s in r)r.hasOwnProperty(s)&&(o[s]=r[s]);return o.queue=[],o.sorter=n.sorter||r.default_sorter,o},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var o={value:n,cost:r};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=e})(la)),la.exports}var ju;function F1(){return ju||(ju=1,(function(t){const e=kn(),n=L1(),r=B1(),o=_1(),s=O1(),i=og(),a=An(),c=D1();function l(w){return unescape(encodeURIComponent(w)).length}function d(w,I,y){const v=[];let L;for(;(L=w.exec(y))!==null;)v.push({data:L[0],index:L.index,mode:I,length:L[0].length});return v}function u(w){const I=d(i.NUMERIC,e.NUMERIC,w),y=d(i.ALPHANUMERIC,e.ALPHANUMERIC,w);let v,L;return a.isKanjiModeEnabled()?(v=d(i.BYTE,e.BYTE,w),L=d(i.KANJI,e.KANJI,w)):(v=d(i.BYTE_KANJI,e.BYTE,w),L=[]),I.concat(y,v,L).sort(function(T,E){return T.index-E.index}).map(function(T){return{data:T.data,mode:T.mode,length:T.length}})}function f(w,I){switch(I){case e.NUMERIC:return n.getBitsLength(w);case e.ALPHANUMERIC:return r.getBitsLength(w);case e.KANJI:return s.getBitsLength(w);case e.BYTE:return o.getBitsLength(w)}}function h(w){return w.reduce(function(I,y){const v=I.length-1>=0?I[I.length-1]:null;return v&&v.mode===y.mode?(I[I.length-1].data+=y.data,I):(I.push(y),I)},[])}function g(w){const I=[];for(let y=0;y<w.length;y++){const v=w[y];switch(v.mode){case e.NUMERIC:I.push([v,{data:v.data,mode:e.ALPHANUMERIC,length:v.length},{data:v.data,mode:e.BYTE,length:v.length}]);break;case e.ALPHANUMERIC:I.push([v,{data:v.data,mode:e.BYTE,length:v.length}]);break;case e.KANJI:I.push([v,{data:v.data,mode:e.BYTE,length:l(v.data)}]);break;case e.BYTE:I.push([{data:v.data,mode:e.BYTE,length:l(v.data)}])}}return I}function m(w,I){const y={},v={start:{}};let L=["start"];for(let C=0;C<w.length;C++){const T=w[C],E=[];for(let S=0;S<T.length;S++){const k=T[S],N=""+C+S;E.push(N),y[N]={node:k,lastCount:0},v[N]={};for(let D=0;D<L.length;D++){const A=L[D];y[A]&&y[A].node.mode===k.mode?(v[A][N]=f(y[A].lastCount+k.length,k.mode)-f(y[A].lastCount,k.mode),y[A].lastCount+=k.length):(y[A]&&(y[A].lastCount=k.length),v[A][N]=f(k.length,k.mode)+4+e.getCharCountIndicator(k.mode,I))}}L=E}for(let C=0;C<L.length;C++)v[L[C]].end=0;return{map:v,table:y}}function b(w,I){let y;const v=e.getBestModeForData(w);if(y=e.from(I,v),y!==e.BYTE&&y.bit<v.bit)throw new Error('"'+w+'" cannot be encoded with mode '+e.toString(y)+`.
5
- Suggested mode is: `+e.toString(v));switch(y===e.KANJI&&!a.isKanjiModeEnabled()&&(y=e.BYTE),y){case e.NUMERIC:return new n(w);case e.ALPHANUMERIC:return new r(w);case e.KANJI:return new s(w);case e.BYTE:return new o(w)}}t.fromArray=function(I){return I.reduce(function(y,v){return typeof v=="string"?y.push(b(v,null)):v.data&&y.push(b(v.data,v.mode)),y},[])},t.fromString=function(I,y){const v=u(I,a.isKanjiModeEnabled()),L=g(v),C=m(L,y),T=c.find_path(C.map,"start","end"),E=[];for(let S=1;S<T.length-1;S++)E.push(C.table[T[S]].node);return t.fromArray(h(E))},t.rawSplit=function(I){return t.fromArray(u(I,a.isKanjiModeEnabled()))}})(oa)),oa}var Uu;function M1(){if(Uu)return zi;Uu=1;const t=An(),e=fl(),n=x1(),r=E1(),o=A1(),s=k1(),i=C1(),a=ng(),c=T1(),l=P1(),d=N1(),u=kn(),f=F1();function h(C,T){const E=C.size,S=s.getPositions(T);for(let k=0;k<S.length;k++){const N=S[k][0],D=S[k][1];for(let A=-1;A<=7;A++)if(!(N+A<=-1||E<=N+A))for(let x=-1;x<=7;x++)D+x<=-1||E<=D+x||(A>=0&&A<=6&&(x===0||x===6)||x>=0&&x<=6&&(A===0||A===6)||A>=2&&A<=4&&x>=2&&x<=4?C.set(N+A,D+x,!0,!0):C.set(N+A,D+x,!1,!0))}}function g(C){const T=C.size;for(let E=8;E<T-8;E++){const S=E%2===0;C.set(E,6,S,!0),C.set(6,E,S,!0)}}function m(C,T){const E=o.getPositions(T);for(let S=0;S<E.length;S++){const k=E[S][0],N=E[S][1];for(let D=-2;D<=2;D++)for(let A=-2;A<=2;A++)D===-2||D===2||A===-2||A===2||D===0&&A===0?C.set(k+D,N+A,!0,!0):C.set(k+D,N+A,!1,!0)}}function b(C,T){const E=C.size,S=l.getEncodedBits(T);let k,N,D;for(let A=0;A<18;A++)k=Math.floor(A/3),N=A%3+E-8-3,D=(S>>A&1)===1,C.set(k,N,D,!0),C.set(N,k,D,!0)}function w(C,T,E){const S=C.size,k=d.getEncodedBits(T,E);let N,D;for(N=0;N<15;N++)D=(k>>N&1)===1,N<6?C.set(N,8,D,!0):N<8?C.set(N+1,8,D,!0):C.set(S-15+N,8,D,!0),N<8?C.set(8,S-N-1,D,!0):N<9?C.set(8,15-N-1+1,D,!0):C.set(8,15-N-1,D,!0);C.set(S-8,8,1,!0)}function I(C,T){const E=C.size;let S=-1,k=E-1,N=7,D=0;for(let A=E-1;A>0;A-=2)for(A===6&&A--;;){for(let x=0;x<2;x++)if(!C.isReserved(k,A-x)){let P=!1;D<T.length&&(P=(T[D]>>>N&1)===1),C.set(k,A-x,P),N--,N===-1&&(D++,N=7)}if(k+=S,k<0||E<=k){k-=S,S=-S;break}}}function y(C,T,E){const S=new n;E.forEach(function(x){S.put(x.mode.bit,4),S.put(x.getLength(),u.getCharCountIndicator(x.mode,C)),x.write(S)});const k=t.getSymbolTotalCodewords(C),N=a.getTotalCodewordsCount(C,T),D=(k-N)*8;for(S.getLengthInBits()+4<=D&&S.put(0,4);S.getLengthInBits()%8!==0;)S.putBit(0);const A=(D-S.getLengthInBits())/8;for(let x=0;x<A;x++)S.put(x%2?17:236,8);return v(S,C,T)}function v(C,T,E){const S=t.getSymbolTotalCodewords(T),k=a.getTotalCodewordsCount(T,E),N=S-k,D=a.getBlocksCount(T,E),A=S%D,x=D-A,P=Math.floor(S/D),R=Math.floor(N/D),O=R+1,j=P-R,M=new c(j);let B=0;const F=new Array(D),U=new Array(D);let H=0;const q=new Uint8Array(C.buffer);for(let X=0;X<D;X++){const Z=X<x?R:O;F[X]=q.slice(B,B+Z),U[X]=M.encode(F[X]),B+=Z,H=Math.max(H,Z)}const K=new Uint8Array(S);let W=0,V,G;for(V=0;V<H;V++)for(G=0;G<D;G++)V<F[G].length&&(K[W++]=F[G][V]);for(V=0;V<j;V++)for(G=0;G<D;G++)K[W++]=U[G][V];return K}function L(C,T,E,S){let k;if(Array.isArray(C))k=f.fromArray(C);else if(typeof C=="string"){let P=T;if(!P){const R=f.rawSplit(C);P=l.getBestVersionForData(R,E)}k=f.fromString(C,P||40)}else throw new Error("Invalid data");const N=l.getBestVersionForData(k,E);if(!N)throw new Error("The amount of data is too big to be stored in a QR Code");if(!T)T=N;else if(T<N)throw new Error(`
4
+ Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),r.put(s,13)}},ca=n,ca}var la={exports:{}},Mu;function D1(){return Mu||(Mu=1,(function(t){var e={single_source_shortest_paths:function(n,r,o){var s={},i={};i[r]=0;var a=e.PriorityQueue.make();a.push(r,0);for(var c,l,d,u,f,h,g,m,b;!a.empty();){c=a.pop(),l=c.value,u=c.cost,f=n[l]||{};for(d in f)f.hasOwnProperty(d)&&(h=f[d],g=u+h,m=i[d],b=typeof i[d]>"u",(b||m>g)&&(i[d]=g,a.push(d,g),s[d]=l))}if(typeof o<"u"&&typeof i[o]>"u"){var w=["Could not find a path from ",r," to ",o,"."].join("");throw new Error(w)}return s},extract_shortest_path_from_predecessor_list:function(n,r){for(var o=[],s=r;s;)o.push(s),n[s],s=n[s];return o.reverse(),o},find_path:function(n,r,o){var s=e.single_source_shortest_paths(n,r,o);return e.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(n){var r=e.PriorityQueue,o={},s;n=n||{};for(s in r)r.hasOwnProperty(s)&&(o[s]=r[s]);return o.queue=[],o.sorter=n.sorter||r.default_sorter,o},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var o={value:n,cost:r};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=e})(la)),la.exports}var ju;function F1(){return ju||(ju=1,(function(t){const e=kn(),n=L1(),r=B1(),o=_1(),s=O1(),i=og(),a=An(),c=D1();function l(w){return unescape(encodeURIComponent(w)).length}function d(w,I,y){const v=[];let L;for(;(L=w.exec(y))!==null;)v.push({data:L[0],index:L.index,mode:I,length:L[0].length});return v}function u(w){const I=d(i.NUMERIC,e.NUMERIC,w),y=d(i.ALPHANUMERIC,e.ALPHANUMERIC,w);let v,L;return a.isKanjiModeEnabled()?(v=d(i.BYTE,e.BYTE,w),L=d(i.KANJI,e.KANJI,w)):(v=d(i.BYTE_KANJI,e.BYTE,w),L=[]),I.concat(y,v,L).sort(function(T,E){return T.index-E.index}).map(function(T){return{data:T.data,mode:T.mode,length:T.length}})}function f(w,I){switch(I){case e.NUMERIC:return n.getBitsLength(w);case e.ALPHANUMERIC:return r.getBitsLength(w);case e.KANJI:return s.getBitsLength(w);case e.BYTE:return o.getBitsLength(w)}}function h(w){return w.reduce(function(I,y){const v=I.length-1>=0?I[I.length-1]:null;return v&&v.mode===y.mode?(I[I.length-1].data+=y.data,I):(I.push(y),I)},[])}function g(w){const I=[];for(let y=0;y<w.length;y++){const v=w[y];switch(v.mode){case e.NUMERIC:I.push([v,{data:v.data,mode:e.ALPHANUMERIC,length:v.length},{data:v.data,mode:e.BYTE,length:v.length}]);break;case e.ALPHANUMERIC:I.push([v,{data:v.data,mode:e.BYTE,length:v.length}]);break;case e.KANJI:I.push([v,{data:v.data,mode:e.BYTE,length:l(v.data)}]);break;case e.BYTE:I.push([{data:v.data,mode:e.BYTE,length:l(v.data)}])}}return I}function m(w,I){const y={},v={start:{}};let L=["start"];for(let k=0;k<w.length;k++){const T=w[k],E=[];for(let S=0;S<T.length;S++){const C=T[S],N=""+k+S;E.push(N),y[N]={node:C,lastCount:0},v[N]={};for(let D=0;D<L.length;D++){const A=L[D];y[A]&&y[A].node.mode===C.mode?(v[A][N]=f(y[A].lastCount+C.length,C.mode)-f(y[A].lastCount,C.mode),y[A].lastCount+=C.length):(y[A]&&(y[A].lastCount=C.length),v[A][N]=f(C.length,C.mode)+4+e.getCharCountIndicator(C.mode,I))}}L=E}for(let k=0;k<L.length;k++)v[L[k]].end=0;return{map:v,table:y}}function b(w,I){let y;const v=e.getBestModeForData(w);if(y=e.from(I,v),y!==e.BYTE&&y.bit<v.bit)throw new Error('"'+w+'" cannot be encoded with mode '+e.toString(y)+`.
5
+ Suggested mode is: `+e.toString(v));switch(y===e.KANJI&&!a.isKanjiModeEnabled()&&(y=e.BYTE),y){case e.NUMERIC:return new n(w);case e.ALPHANUMERIC:return new r(w);case e.KANJI:return new s(w);case e.BYTE:return new o(w)}}t.fromArray=function(I){return I.reduce(function(y,v){return typeof v=="string"?y.push(b(v,null)):v.data&&y.push(b(v.data,v.mode)),y},[])},t.fromString=function(I,y){const v=u(I,a.isKanjiModeEnabled()),L=g(v),k=m(L,y),T=c.find_path(k.map,"start","end"),E=[];for(let S=1;S<T.length-1;S++)E.push(k.table[T[S]].node);return t.fromArray(h(E))},t.rawSplit=function(I){return t.fromArray(u(I,a.isKanjiModeEnabled()))}})(oa)),oa}var Uu;function M1(){if(Uu)return zi;Uu=1;const t=An(),e=fl(),n=x1(),r=E1(),o=A1(),s=k1(),i=C1(),a=ng(),c=T1(),l=P1(),d=N1(),u=kn(),f=F1();function h(k,T){const E=k.size,S=s.getPositions(T);for(let C=0;C<S.length;C++){const N=S[C][0],D=S[C][1];for(let A=-1;A<=7;A++)if(!(N+A<=-1||E<=N+A))for(let x=-1;x<=7;x++)D+x<=-1||E<=D+x||(A>=0&&A<=6&&(x===0||x===6)||x>=0&&x<=6&&(A===0||A===6)||A>=2&&A<=4&&x>=2&&x<=4?k.set(N+A,D+x,!0,!0):k.set(N+A,D+x,!1,!0))}}function g(k){const T=k.size;for(let E=8;E<T-8;E++){const S=E%2===0;k.set(E,6,S,!0),k.set(6,E,S,!0)}}function m(k,T){const E=o.getPositions(T);for(let S=0;S<E.length;S++){const C=E[S][0],N=E[S][1];for(let D=-2;D<=2;D++)for(let A=-2;A<=2;A++)D===-2||D===2||A===-2||A===2||D===0&&A===0?k.set(C+D,N+A,!0,!0):k.set(C+D,N+A,!1,!0)}}function b(k,T){const E=k.size,S=l.getEncodedBits(T);let C,N,D;for(let A=0;A<18;A++)C=Math.floor(A/3),N=A%3+E-8-3,D=(S>>A&1)===1,k.set(C,N,D,!0),k.set(N,C,D,!0)}function w(k,T,E){const S=k.size,C=d.getEncodedBits(T,E);let N,D;for(N=0;N<15;N++)D=(C>>N&1)===1,N<6?k.set(N,8,D,!0):N<8?k.set(N+1,8,D,!0):k.set(S-15+N,8,D,!0),N<8?k.set(8,S-N-1,D,!0):N<9?k.set(8,15-N-1+1,D,!0):k.set(8,15-N-1,D,!0);k.set(S-8,8,1,!0)}function I(k,T){const E=k.size;let S=-1,C=E-1,N=7,D=0;for(let A=E-1;A>0;A-=2)for(A===6&&A--;;){for(let x=0;x<2;x++)if(!k.isReserved(C,A-x)){let P=!1;D<T.length&&(P=(T[D]>>>N&1)===1),k.set(C,A-x,P),N--,N===-1&&(D++,N=7)}if(C+=S,C<0||E<=C){C-=S,S=-S;break}}}function y(k,T,E){const S=new n;E.forEach(function(x){S.put(x.mode.bit,4),S.put(x.getLength(),u.getCharCountIndicator(x.mode,k)),x.write(S)});const C=t.getSymbolTotalCodewords(k),N=a.getTotalCodewordsCount(k,T),D=(C-N)*8;for(S.getLengthInBits()+4<=D&&S.put(0,4);S.getLengthInBits()%8!==0;)S.putBit(0);const A=(D-S.getLengthInBits())/8;for(let x=0;x<A;x++)S.put(x%2?17:236,8);return v(S,k,T)}function v(k,T,E){const S=t.getSymbolTotalCodewords(T),C=a.getTotalCodewordsCount(T,E),N=S-C,D=a.getBlocksCount(T,E),A=S%D,x=D-A,P=Math.floor(S/D),R=Math.floor(N/D),O=R+1,j=P-R,M=new c(j);let B=0;const F=new Array(D),U=new Array(D);let H=0;const q=new Uint8Array(k.buffer);for(let X=0;X<D;X++){const Z=X<x?R:O;F[X]=q.slice(B,B+Z),U[X]=M.encode(F[X]),B+=Z,H=Math.max(H,Z)}const K=new Uint8Array(S);let W=0,V,G;for(V=0;V<H;V++)for(G=0;G<D;G++)V<F[G].length&&(K[W++]=F[G][V]);for(V=0;V<j;V++)for(G=0;G<D;G++)K[W++]=U[G][V];return K}function L(k,T,E,S){let C;if(Array.isArray(k))C=f.fromArray(k);else if(typeof k=="string"){let P=T;if(!P){const R=f.rawSplit(k);P=l.getBestVersionForData(R,E)}C=f.fromString(k,P||40)}else throw new Error("Invalid data");const N=l.getBestVersionForData(C,E);if(!N)throw new Error("The amount of data is too big to be stored in a QR Code");if(!T)T=N;else if(T<N)throw new Error(`
6
6
  The chosen QR Code version cannot contain this amount of data.
7
7
  Minimum version required to store current data is: `+N+`.
8
- `);const D=y(T,E,k),A=t.getSymbolSize(T),x=new r(A);return h(x,T),g(x),m(x,T),w(x,E,0),T>=7&&b(x,T),I(x,D),isNaN(S)&&(S=i.getBestMask(x,w.bind(null,x,E))),i.applyMask(S,x),w(x,E,S),{modules:x,version:T,errorCorrectionLevel:E,maskPattern:S,segments:k}}return zi.create=function(T,E){if(typeof T>"u"||T==="")throw new Error("No input text");let S=e.M,k,N;return typeof E<"u"&&(S=e.from(E.errorCorrectionLevel,e.M),k=l.from(E.version),N=i.from(E.maskPattern),E.toSJISFunc&&t.setToSJISFunction(E.toSJISFunc)),L(T,k,S,N)},zi}var da={},ua={},$u;function sg(){return $u||($u=1,(function(t){function e(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let r=n.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+n);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(s){return[s,s]}))),r.length===6&&r.push("F","F");const o=parseInt(r.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+r.slice(0,6).join("")}}t.getOptions=function(r){r||(r={}),r.color||(r.color={});const o=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,s=r.width&&r.width>=21?r.width:void 0,i=r.scale||4;return{width:s,scale:s?4:i,margin:o,color:{dark:e(r.color.dark||"#000000ff"),light:e(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},t.getScale=function(r,o){return o.width&&o.width>=r+o.margin*2?o.width/(r+o.margin*2):o.scale},t.getImageWidth=function(r,o){const s=t.getScale(r,o);return Math.floor((r+o.margin*2)*s)},t.qrToImageData=function(r,o,s){const i=o.modules.size,a=o.modules.data,c=t.getScale(i,s),l=Math.floor((i+s.margin*2)*c),d=s.margin*c,u=[s.color.light,s.color.dark];for(let f=0;f<l;f++)for(let h=0;h<l;h++){let g=(f*l+h)*4,m=s.color.light;if(f>=d&&h>=d&&f<l-d&&h<l-d){const b=Math.floor((f-d)/c),w=Math.floor((h-d)/c);m=u[a[b*i+w]?1:0]}r[g++]=m.r,r[g++]=m.g,r[g++]=m.b,r[g]=m.a}}})(ua)),ua}var Hu;function j1(){return Hu||(Hu=1,(function(t){const e=sg();function n(o,s,i){o.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=i,s.width=i,s.style.height=i+"px",s.style.width=i+"px"}function r(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}t.render=function(s,i,a){let c=a,l=i;typeof c>"u"&&(!i||!i.getContext)&&(c=i,i=void 0),i||(l=r()),c=e.getOptions(c);const d=e.getImageWidth(s.modules.size,c),u=l.getContext("2d"),f=u.createImageData(d,d);return e.qrToImageData(f.data,s,c),n(u,l,d),u.putImageData(f,0,0),l},t.renderToDataURL=function(s,i,a){let c=a;typeof c>"u"&&(!i||!i.getContext)&&(c=i,i=void 0),c||(c={});const l=t.render(s,i,c),d=c.type||"image/png",u=c.rendererOpts||{};return l.toDataURL(d,u.quality)}})(da)),da}var fa={},qu;function U1(){if(qu)return fa;qu=1;const t=sg();function e(o,s){const i=o.a/255,a=s+'="'+o.hex+'"';return i<1?a+" "+s+'-opacity="'+i.toFixed(2).slice(1)+'"':a}function n(o,s,i){let a=o+s;return typeof i<"u"&&(a+=" "+i),a}function r(o,s,i){let a="",c=0,l=!1,d=0;for(let u=0;u<o.length;u++){const f=Math.floor(u%s),h=Math.floor(u/s);!f&&!l&&(l=!0),o[u]?(d++,u>0&&f>0&&o[u-1]||(a+=l?n("M",f+i,.5+h+i):n("m",c,0),c=0,l=!1),f+1<s&&o[u+1]||(a+=n("h",d),d=0)):c++}return a}return fa.render=function(s,i,a){const c=t.getOptions(i),l=s.modules.size,d=s.modules.data,u=l+c.margin*2,f=c.color.light.a?"<path "+e(c.color.light,"fill")+' d="M0 0h'+u+"v"+u+'H0z"/>':"",h="<path "+e(c.color.dark,"stroke")+' d="'+r(d,l,c.margin)+'"/>',g='viewBox="0 0 '+u+" "+u+'"',b='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+g+' shape-rendering="crispEdges">'+f+h+`</svg>
9
- `;return typeof a=="function"&&a(null,b),b},fa}var Ku;function $1(){if(Ku)return _n;Ku=1;const t=S1(),e=M1(),n=j1(),r=U1();function o(s,i,a,c,l){const d=[].slice.call(arguments,1),u=d.length,f=typeof d[u-1]=="function";if(!f&&!t())throw new Error("Callback required as last argument");if(f){if(u<2)throw new Error("Too few arguments provided");u===2?(l=a,a=i,i=c=void 0):u===3&&(i.getContext&&typeof l>"u"?(l=c,c=void 0):(l=c,c=a,a=i,i=void 0))}else{if(u<1)throw new Error("Too few arguments provided");return u===1?(a=i,i=c=void 0):u===2&&!i.getContext&&(c=a,a=i,i=void 0),new Promise(function(h,g){try{const m=e.create(a,c);h(s(m,i,c))}catch(m){g(m)}})}try{const h=e.create(a,c);l(null,s(h,i,c))}catch(h){l(h)}}return _n.create=e.create,_n.toCanvas=o.bind(null,n.render),_n.toDataURL=o.bind(null,n.renderToDataURL),_n.toString=o.bind(null,function(s,i,a){return r.render(s,a)}),_n}var H1=$1();const $o="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-base text-foreground focus:outline-none focus:ring-2 focus:ring-ring sm:text-sm",Ge="appearance-none min-h-11 rounded-lg px-3 py-2 text-sm hover:bg-hover focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",On=`${Ge} bg-primary text-primary-foreground hover:opacity-90`;function q1(t){return t.serviceName||new URL(t.url).hostname}function zu(t){return t.includes("service:*")?"完整权限":t.includes("session.input")?"可操作":t.includes("session.view")?"只读":t.includes("route.use")?"仅中转":"自定义权限"}function K1({profile:t,subjectId:e}){return p.jsxs("details",{className:"mt-2 text-xs text-muted-foreground",children:[p.jsx("summary",{className:"cursor-pointer leading-relaxed",children:[t?.model||t?.hostname||t?.system,t?.route,`ID ${e.slice(-8)}`].filter(Boolean).join(" · ")}),p.jsxs("dl",{className:"mt-2 space-y-2 rounded-lg bg-surface-2 p-3",children:[[["设备型号",t?.model],["主机名称",t?.hostname],["操作系统",t?.system],["客户端",t?.client],["打开方式",t?.mode],["处理器",t?.cpu],["架构",t?.arch],["最近连接路径",t?.route],["首次记录",t?.firstSeenAt?new Date(t.firstSeenAt).toLocaleString():void 0],["最近连接",t?.lastSeenAt?new Date(t.lastSeenAt).toLocaleString():void 0],["设备标识",e]].filter(([,n])=>n).map(([n,r])=>p.jsxs("div",{children:[p.jsx("dt",{children:n}),p.jsx("dd",{className:"mt-0.5 select-text break-all text-foreground",children:r})]},n)),p.jsx("p",{className:"leading-relaxed",children:t?"系统、硬件与路径由设备报告;连接时间由服务记录。":"此设备尚未报告详情,更新客户端并重新连接后可补齐。"})]})]})}function z1(){const t=getComputedStyle(document.documentElement),e=t.getPropertyValue("--background").trim(),n=t.getPropertyValue("--foreground").trim(),r=o=>{const s=o.replace("#","");return parseInt(s.slice(0,2),16)*.299+parseInt(s.slice(2,4),16)*.587+parseInt(s.slice(4,6),16)*.114};if(!e||!n)throw new Error("Theme unavailable");return r(e)<r(n)?{dark:e,light:n}:{dark:n,light:e}}function W1({onConnect:t,onClose:e,onConnectWithPassword:n,onAddService:r,onOpenService:o,currentIdentity:s,currentServiceName:i,currentServiceId:a,currentServiceOrigin:c,hasBackup:l=!1,paired:d=!1,initialInvite:u,sessions:f=[],grants:h=[],onCreateInvite:g,onRevoke:m,onRename:b,loading:w=!1,loadError:I,onRetry:y}){const[v,L]=_.useState(!1),[C,T]=_.useState(""),[E,S]=_.useState({}),[k,N]=_.useState(""),[D,A]=_.useState(""),[x,P]=_.useState(!1),[R,O]=_.useState(!1),[j,M]=_.useState(!d),[B,F]=_.useState(!0),[U,H]=_.useState("read"),[q,K]=_.useState("all"),[W,V]=_.useState([]),[G,X]=_.useState(!1),[Z,ce]=_.useState(""),[Ie,Me]=_.useState(""),[ne,Ve]=_.useState(),[Yt,Zt]=_.useState(""),[je,Jt]=_.useState("services"),[Qt,Rn]=_.useState(),[ui,Bl]=_.useState(""),[yr,_l]=_.useState(!1),[Ol,br]=_.useState(),[pt,So]=_.useState(!1),[Tn,Dl]=_.useState([]),fi=h.filter($=>$.revokedAt===void 0&&(!$.expiresAt||$.expiresAt>Date.now())),hi=h.filter($=>!fi.includes($)),vr=[...new Set(fi.map($=>$.subjectId))].map($=>{const z=fi.filter(ue=>ue.subjectId===$);return{subjectId:$,grants:z,name:$===s?"此设备":z.find(ue=>ue.label)?.label||"未命名设备"}}).sort(($,z)=>+(z.subjectId===s)-+($.subjectId===s)),Pn=!Qt&&!yr&&d&&!j&&!R&&!u,lm=()=>{Rn(void 0),_l(!1),M(!1),O(!1),Ve(void 0),X(!1),N(""),A(""),br(void 0)},Fl=()=>{O(!0),M(!1),X(!1),N(""),A("")},dm=$=>$.subjectId===s?"此设备":$.label||"未命名设备",pi=()=>{pt?So(!1):e()},Sr=_.useRef(null);_.useEffect(()=>{const $=document.activeElement;return Sr.current?.focus(),()=>{$?.focus()}},[]),_.useEffect(()=>{let $=!1;if(Zt(""),ne)try{H1.toDataURL(ne.url,{width:220,margin:3,errorCorrectionLevel:"M",color:z1()}).then(z=>{$||Zt(z)}).catch(()=>{})}catch{}return()=>{$=!0}},[ne]);async function gi($){P(!0),N(""),A("");try{await t($);const{url:z,targetPeerId:ue,serviceName:qe,serviceOrigin:mi}=$;await Ct({id:ue,url:z,targetPeerId:ue,label:qe||new URL(z).host,serviceOrigin:mi,entryServiceId:$.entryServiceId}),M(!1),A("已连接。")}catch(z){$.routeOnly&&z instanceof Je?L(!0):N("暂时无法连接,请检查网络,或确认邀请是否仍然有效。")}finally{P(!1)}}async function um($){if($.preventDefault(),!g)return;N(""),A("");const z=W.filter(qe=>f.some(mi=>mi.sessionId===qe));if(U!=="full"&&q==="selected"&&!z.length){N("请选择至少一个 Session。");return}const ue=Ie?new Date(Ie).getTime():void 0;if(ue!==void 0&&(!Number.isFinite(ue)||ue<=Date.now())){N("授权到期时间必须晚于现在。");return}P(!0);try{const qe=await g({...l?{includeBackup:B}:{},scope:U==="full"||q==="all"?{kind:"service"}:{kind:"sessions",sessionIds:z},actions:U==="full"?["service:*"]:U==="write"?["session.view","session.input","session.resize"]:["session.view"],...Z.trim()?{label:Z.trim()}:{},...ue===void 0?{}:{expiresAt:ue}});Ve(qe)}catch(qe){N(qe instanceof Error&&qe.message.startsWith("无法分享备用连接:")?"无法分享备用连接:需要入口管理员授权。你也可以关闭“包含备用连接”,生成直连邀请。":"暂时无法生成邀请,请确认当前设备有授权管理权限。")}finally{P(!1)}}async function fm(){if(ne)try{await navigator.clipboard.writeText(ne.url),A("邀请链接已复制。")}catch{N("浏览器未允许复制,请长按下方链接复制。")}}const hm=E.title||(Qt?"设备名称":yr?je==="devices"?"授权详情":"连接详情":pt?"选择终端":R?"邀请设备":j&&d?"添加服务":d?"服务与设备":"连接 Termdock"),pm=!!E.back||!!Qt||yr||pt||d&&(j||R),gm=()=>{if(E.back){E.back();return}pt?So(!1):lm()},Ml=$=>$.every(z=>z.routeTargetServiceId)?`${new Set($.map(z=>z.routeTargetServiceId)).size} 台服务`:$.some(z=>z.scope.kind==="service")?"全部终端":`${new Set($.flatMap(z=>z.scope.kind==="sessions"?z.scope.sessionIds:[])).size} 个终端`;return Tc.createPortal(p.jsx("div",{className:"fixed inset-0 z-modal-backdrop flex items-end justify-center bg-[var(--app-backdrop)] backdrop-blur-sm sm:items-center sm:p-6","data-sidebar-gesture-ignore":!0,onMouseDown:$=>{$.target===$.currentTarget&&!x&&pi()},children:p.jsxs("div",{ref:Sr,tabIndex:-1,role:"dialog","aria-modal":"true","aria-labelledby":"federation-title",className:"z-modal-panel flex max-h-[calc(100dvh-env(safe-area-inset-top)-12px)] w-full max-w-lg flex-col overflow-hidden rounded-t-2xl border border-border bg-surface font-sans text-foreground shadow-xl outline-none sm:max-h-[min(720px,90dvh)] sm:rounded-2xl",onKeyDown:$=>{if($.key==="Escape"&&!x&&($.stopPropagation(),pi()),$.key!=="Tab")return;const z=Sr.current?.querySelectorAll('button:not(:disabled), input:not(:disabled), textarea:not(:disabled), select:not(:disabled), [tabindex="0"], summary');if(!z?.length){$.preventDefault();return}const ue=z[0],qe=z[z.length-1];$.shiftKey&&(document.activeElement===ue||document.activeElement===Sr.current)?($.preventDefault(),qe.focus()):!$.shiftKey&&(document.activeElement===qe||document.activeElement===Sr.current)&&($.preventDefault(),ue.focus())},children:[p.jsxs("header",{className:"shrink-0 border-b border-border px-5 pt-3",children:[p.jsxs("div",{className:"flex min-h-12 items-center gap-2 pb-2",children:[pm&&p.jsx("button",{type:"button",className:`${Ge} -ml-3 inline-flex w-11 items-center justify-center text-muted-foreground`,disabled:x,onClick:gm,"aria-label":pt?"取消选择终端":je==="devices"?"返回设备":"返回服务",children:p.jsx(qp,{size:20})}),p.jsx("h2",{id:"federation-title",className:"min-w-0 flex-1 text-base font-semibold",children:hm}),p.jsx("button",{type:"button",className:`${Ge} -mr-3 inline-flex w-11 items-center justify-center text-muted-foreground`,disabled:x,onClick:pi,"aria-label":"关闭",children:p.jsx(Yp,{size:20})})]}),Pn&&!E.title&&p.jsx("div",{className:"flex gap-6",role:"tablist","aria-label":"管理内容",children:[["services","服务"],["devices","设备"]].map(([$,z])=>p.jsxs("button",{type:"button",role:"tab","aria-selected":je===$,"aria-controls":`federation-${$}`,id:`federation-tab-${$}`,className:`min-h-11 border-b-2 px-1 text-sm transition ${je===$?"border-primary font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"}`,onClick:()=>{Jt($),X(!1),br(void 0),N(""),A("")},children:[z,$==="devices"&&vr.length>0&&p.jsx("span",{className:"ml-1.5 text-xs text-muted-foreground",children:vr.length})]},$))})]}),p.jsxs("div",{className:"min-h-0 overflow-y-auto overscroll-contain px-5 py-4 pb-[max(20px,env(safe-area-inset-bottom))]",children:[(Pn&&je==="services"||j&&!R&&!u)&&p.jsx(y1,{renderRelayServices:($,z)=>p.jsx(m1,{service:$,onBusyChange:z,onConnect:t,onConnectWithPassword:n}),renderRoutes:($,z)=>p.jsx(w1,{service:$,onBusyChange:z}),hideHeader:!0,initiallyAdding:j,current:a?{id:a,targetPeerId:a,url:c||location.origin,label:i||"当前服务"}:void 0,onNavigation:S,onBusyChange:P,onInvite:g?Fl:void 0,onOpen:async $=>{if(o)return o($);$.targetPeerId?await gi({...$,targetPeerId:$.targetPeerId,serviceName:$.label}):r&&await r($.url)},onAdd:async($,z)=>{if(r)return r($,z);await gi(Ls($))}}),Pn&&je==="devices"&&p.jsxs("section",{role:"tabpanel",id:"federation-devices","aria-labelledby":"federation-tab-devices",children:[p.jsx("p",{className:"mb-2 text-xs leading-relaxed text-muted-foreground",children:"可访问此服务的设备"}),w?p.jsxs("p",{role:"status",className:"flex items-center gap-2 py-5 text-sm text-muted-foreground",children:[p.jsx(De,{size:16,className:"animate-spin"}),"正在读取设备…"]}):p.jsxs("div",{className:"divide-y divide-border",children:[vr.map($=>p.jsxs("div",{className:"py-3",children:[p.jsxs("div",{className:"flex items-center gap-3",children:[p.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-surface-2 text-muted-foreground",children:/iPhone|iPad|Android|手机|平板/i.test($.grants.find(z=>z.label)?.label||($.subjectId===s?navigator.userAgent:""))?p.jsx(Xp,{size:19}):p.jsx(HE,{size:19})}),p.jsxs("div",{className:"min-w-0 flex-1",children:[p.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[p.jsx("p",{className:"truncate text-sm font-medium",children:$.name}),b&&(m||$.subjectId===s)&&p.jsx("button",{type:"button","aria-label":`重命名 ${$.name}`,className:"inline-flex h-9 w-9 shrink-0 appearance-none items-center justify-center rounded-lg bg-transparent text-muted-foreground hover:bg-surface-2",onClick:()=>{Rn($.subjectId),Bl($.grants.find(z=>z.label)?.label||"")},children:p.jsx(KE,{size:14})})]}),$.subjectId===s&&$.grants.find(z=>z.label)?.label&&p.jsx("p",{className:"truncate text-xs text-muted-foreground",children:$.grants.find(z=>z.label)?.label}),p.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[zu($.grants.flatMap(z=>z.actions))," · ",Ml($.grants)]})]}),m&&$.subjectId!==s&&Ol!==$.subjectId&&p.jsx("button",{type:"button",className:`${Ge} -mr-2 text-xs text-muted-foreground hover:text-destructive`,disabled:x,"aria-label":`撤销 ${$.name} 的访问权限`,onClick:()=>br($.subjectId),children:"撤销"})]}),p.jsx(K1,{profile:$.grants.find(z=>z.deviceProfile)?.deviceProfile,subjectId:$.subjectId}),Ol===$.subjectId&&p.jsxs("div",{className:"mt-3 rounded-lg border border-border bg-background p-3",children:[p.jsx("p",{className:"text-xs leading-relaxed",children:"撤销后,这台设备将断开连接,需重新邀请才能访问。"}),p.jsxs("div",{className:"mt-2 flex justify-end gap-2",children:[p.jsx("button",{type:"button",className:`${Ge} text-xs text-muted-foreground`,disabled:x,onClick:()=>br(void 0),children:"取消"}),p.jsx("button",{type:"button",className:`${Ge} text-xs text-destructive`,disabled:x,onClick:async()=>{P(!0),N("");try{for(const z of $.grants)await m?.(z.id);br(void 0),A("设备访问权限已撤销。")}catch{N("暂时无法撤销,请重试。")}finally{P(!1)}},children:"确认撤销"})]})]})]},$.subjectId)),vr.length===0&&!I&&p.jsxs("p",{className:"py-5 text-sm text-muted-foreground",children:["暂无设备授权。",g?"可通过邀请添加设备。":""]})]}),g&&p.jsxs("button",{type:"button",className:`${Ge} mt-4 inline-flex w-full items-center justify-center gap-2 border border-border text-sm`,disabled:x,onClick:Fl,children:[p.jsx(Gp,{size:16}),"邀请设备"]}),hi.length>0&&p.jsxs("details",{className:"mt-4 text-xs text-muted-foreground",children:[p.jsxs("summary",{className:"cursor-pointer py-2",children:["已失效的授权(",hi.length,")"]}),p.jsx("div",{className:"mt-1 space-y-2 border-l border-border pl-3",children:hi.map($=>p.jsxs("p",{className:"flex gap-3",children:[p.jsx("span",{className:"min-w-0 flex-1 truncate",children:dm($)}),p.jsx("span",{className:"shrink-0",children:$.revokedAt!==void 0?"已撤销":"已到期"})]},$.id))})]})]}),Qt&&p.jsxs("form",{className:"space-y-4",onSubmit:async $=>{$.preventDefault(),P(!0),N("");try{await b?.(Qt,ui.trim()),Rn(void 0)}catch{N("暂时无法保存设备名称,请重试。")}finally{P(!1)}},children:[p.jsxs("label",{className:"block space-y-2 text-sm",children:[p.jsx("span",{children:"设备名称"}),p.jsx("input",{autoFocus:!0,className:$o,maxLength:80,required:!0,value:ui,onChange:$=>Bl($.target.value),placeholder:"例如:我的 iPhone、办公室电脑"})]}),p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"为设备起一个容易辨认的名字,会同步显示在此服务的设备列表中。"}),p.jsx("button",{type:"submit",className:`${On} w-full`,disabled:x||!ui.trim(),children:x?"正在保存…":"保存名称"})]}),yr&&p.jsx("section",{className:"space-y-5",children:je==="devices"?vr.map($=>p.jsxs("div",{className:"space-y-3",children:[p.jsx("h3",{className:"text-sm font-medium",children:$.name}),p.jsxs("dl",{className:"space-y-3 rounded-xl bg-surface-2 p-3 text-xs",children:[p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"访问权限"}),p.jsxs("dd",{className:"mt-1",children:[zu($.grants.flatMap(z=>z.actions))," · ",Ml($.grants)]})]}),$.grants.map(z=>p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:z.routeTargetServiceId?"允许经此入口访问":z.scope.kind==="sessions"?"可访问终端":"有效期"}),p.jsx("dd",{className:"mt-1 leading-relaxed",children:z.routeTargetServiceId?z.routeTargetName||"指定服务":z.scope.kind==="sessions"?z.scope.sessionIds.map(ue=>f.find(qe=>qe.sessionId===ue)?.name||ue).join("、"):z.expiresAt?new Date(z.expiresAt).toLocaleString():"保留至撤销"}),z.routeTargetServiceId&&m&&p.jsx("button",{type:"button",className:`${Ge} mt-1 -ml-3 text-xs text-destructive`,disabled:x,onClick:async()=>{P(!0),N("");try{await m(z.id)}catch{N("暂时无法撤销,请重试。")}finally{P(!1)}},children:"撤销此中转权限"})]},z.id)),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"设备标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed text-muted-foreground select-text",children:$.subjectId})]})]})]},$.subjectId)):p.jsxs("dl",{className:"space-y-4 text-xs",children:[p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"当前服务"}),p.jsx("dd",{className:"mt-1 text-sm",children:i||"当前服务"})]}),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"服务标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed select-text",children:a})]}),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"本设备标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed select-text",children:s})]})]})}),u&&!R&&p.jsxs("section",{className:"space-y-5 py-1",children:[p.jsxs("div",{className:"flex items-center gap-3",children:[p.jsx("span",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-surface-2 text-muted-foreground",children:p.jsx(ri,{size:22})}),p.jsxs("div",{className:"min-w-0",children:[p.jsx("p",{className:"text-xs text-muted-foreground",children:"你受邀连接"}),p.jsx("p",{className:"mt-1 break-words text-base font-medium",children:q1(u)})]})]}),u.routeOnly&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"此邀请提供备用连接,目标服务仍会验证你的访问权限。"}),v?p.jsxs("form",{className:"space-y-3",onSubmit:async $=>{$.preventDefault(),P(!0),N("");try{await n?.(u,C)}catch(z){N(z instanceof Error?z.message:"暂时无法登录,请重试。")}finally{T(""),P(!1)}},children:[p.jsxs("label",{className:"block space-y-2 text-sm",children:[p.jsx("span",{children:"目标服务密码"}),p.jsx("input",{className:$o,type:"password",required:!0,autoFocus:!0,autoComplete:"current-password",value:C,onChange:$=>T($.target.value)})]}),p.jsx("button",{className:`${On} w-full`,disabled:x||!C,children:x?"正在登录…":"登录并连接"})]}):p.jsx("button",{type:"button",className:`${On} w-full text-sm`,disabled:x,onClick:()=>{gi(u)},children:x?"正在连接…":"接受邀请"})]}),R&&!pt&&p.jsx("section",{children:ne?p.jsxs("div",{className:"space-y-4 text-center",children:[p.jsx("p",{className:"text-sm font-medium",children:"用另一台设备扫描二维码"}),Yt?p.jsx("img",{src:Yt,width:220,height:220,className:"mx-auto max-w-full rounded-xl",alt:"设备邀请二维码"}):p.jsx("div",{className:"mx-auto flex h-48 w-48 items-center justify-center",children:p.jsx(De,{size:22,className:"animate-spin text-muted-foreground"})}),p.jsxs("p",{className:"text-xs leading-relaxed text-muted-foreground",children:["仅限一台设备使用 · ",new Date(ne.expiresAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," 前有效"]}),p.jsxs("button",{type:"button",className:`${On} inline-flex w-full items-center justify-center gap-2 text-sm`,onClick:()=>{fm()},children:[p.jsx(Wp,{size:16}),"复制邀请链接"]}),p.jsxs("details",{className:"text-left text-xs text-muted-foreground",children:[p.jsx("summary",{className:"cursor-pointer py-2",children:"查看链接"}),p.jsx("p",{className:"mt-2 select-all break-all",children:ne.url})]})]}):p.jsxs("form",{className:"space-y-5",onSubmit:um,children:[p.jsxs("fieldset",{children:[p.jsx("legend",{className:"mb-2 text-sm font-medium",children:"访问权限"}),p.jsx("div",{className:"space-y-2",children:[["read","仅查看","查看终端画面,不可输入命令"],["write","可操作","查看终端画面,并输入命令"],["full","完整访问","包括文件、设置和权限管理"]].map(([$,z,ue])=>p.jsxs("label",{className:`flex cursor-pointer items-center gap-3 rounded-xl border px-3 py-2.5 transition focus-within:ring-2 focus-within:ring-ring ${U===$?"border-primary bg-primary/10":"border-border hover:bg-surface-2"}`,children:[p.jsx("input",{type:"radio",name:"federation-permission",value:$,checked:U===$,onChange:()=>H($),className:"sr-only"}),p.jsx("span",{"aria-hidden":"true",className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border ${U===$?"border-primary bg-primary text-primary-foreground":"border-border bg-background"}`,children:U===$&&p.jsx(dl,{size:13,strokeWidth:3})}),p.jsxs("span",{className:"min-w-0",children:[p.jsx("span",{className:"block text-sm font-medium text-foreground",children:z}),p.jsx("span",{className:"mt-0.5 block text-xs leading-relaxed text-muted-foreground",children:ue})]})]},$))})]}),U!=="full"&&p.jsxs("fieldset",{children:[p.jsx("legend",{className:"mb-2 text-sm font-medium",children:"可访问的终端"}),p.jsxs("div",{className:"flex gap-2",children:[p.jsx("button",{type:"button","aria-pressed":q==="all",className:`${Ge} flex-1 appearance-none border text-sm ${q==="all"?"border-primary bg-primary/10 text-foreground":"border-border text-muted-foreground"}`,onClick:()=>K("all"),children:"全部终端"}),p.jsxs("button",{type:"button","aria-pressed":q==="selected",className:`${Ge} inline-flex flex-1 appearance-none items-center justify-center gap-1 border text-sm ${q==="selected"?"border-primary bg-primary/10 text-foreground":"border-border text-muted-foreground"}`,onClick:()=>{Dl(W),So(!0)},children:[q==="selected"?`已选 ${W.length} 个`:"选择终端",p.jsx(vn,{size:14})]})]}),q==="all"&&p.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"包括之后新建的终端。"})]}),U==="write"&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"终端命令可读写该系统用户有权访问的文件。"}),U==="full"&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"拥有此服务的全部当前及未来权限。仅授予你完全信任的设备。"}),l&&p.jsxs("label",{className:"flex items-start gap-3 text-sm",children:[p.jsx("input",{type:"checkbox",className:"mt-0.5 h-4 w-4 accent-primary",checked:B,onChange:$=>F($.target.checked)}),p.jsxs("span",{children:["让新设备也能使用备用连接",p.jsx("span",{className:"mt-1 block text-xs leading-relaxed text-muted-foreground",children:"需要入口管理员授权;关闭后生成直接连接邀请。"})]})]}),p.jsxs("div",{children:[p.jsxs("button",{className:`${On} inline-flex w-full items-center justify-center gap-2 text-sm`,type:"submit",disabled:x||w,children:[x&&p.jsx(De,{size:16,className:"animate-spin"}),x?"正在生成…":"生成邀请"]}),p.jsxs("p",{className:"mt-2 text-center text-xs leading-relaxed text-muted-foreground",children:["链接 10 分钟内有效 · 访问权限",Ie?"按设定时间到期":"保留至撤销"]})]})]})}),pt&&p.jsxs("section",{children:[p.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"仅允许访问勾选的终端。"}),p.jsxs("div",{className:"space-y-1",children:[f.map($=>p.jsxs("label",{className:"flex min-h-12 cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm hover:bg-surface-2",children:[p.jsx("input",{type:"checkbox",className:"h-4 w-4 accent-primary",checked:Tn.includes($.sessionId),onChange:z=>Dl(z.target.checked?[...Tn,$.sessionId]:Tn.filter(ue=>ue!==$.sessionId))}),p.jsx("span",{className:"min-w-0 break-words",children:$.name})]},$.sessionId)),!f.length&&p.jsx("p",{className:"py-4 text-sm text-muted-foreground",children:"当前没有可共享的终端。"})]})]}),I&&p.jsxs("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:[I,y&&p.jsx("button",{type:"button",className:`${Ge} ml-1 text-sm underline`,onClick:y,children:"重试"})]}),!E.title&&!j&&!Qt&&!yr&&!pt&&!ne&&p.jsxs("div",{className:"mt-4 border-t border-border pt-2",children:[p.jsxs("button",{type:"button",className:`${Ge} -ml-3 inline-flex items-center gap-1 bg-transparent text-xs text-muted-foreground`,"aria-expanded":Pn?void 0:G,onClick:()=>Pn?_l(!0):X($=>!$),children:[R?"有效期与备注":j?"手动连接":je==="devices"?"授权详情":"连接详情",Pn?p.jsx(vn,{size:14}):p.jsx(zp,{size:13,className:G?"rotate-180":""})]}),G&&p.jsxs("section",{className:"space-y-3 pb-1 pt-2",children:[R&&p.jsxs(p.Fragment,{children:[p.jsxs("label",{className:"block space-y-1 text-sm",children:[p.jsx("span",{children:"设备备注(可选)"}),p.jsx("input",{className:$o,value:Z,onChange:$=>ce($.target.value),placeholder:"例如:工作电脑"})]}),p.jsxs("label",{className:"block space-y-1 text-sm",children:[p.jsx("span",{children:"授权到期时间"}),p.jsx("input",{type:"datetime-local",className:$o,value:Ie,onChange:$=>Me($.target.value)})]})]}),!R&&s&&p.jsxs("p",{className:"break-all text-xs leading-relaxed text-muted-foreground",children:["本设备身份:",s]})]})]}),k&&p.jsx("p",{role:"alert",className:"mt-3 text-sm text-destructive",children:k}),D&&p.jsx("p",{role:"status",className:"mt-3 text-sm text-muted-foreground",children:D})]}),pt&&p.jsx("footer",{className:"shrink-0 border-t border-border px-5 pt-3 pb-[max(16px,env(safe-area-inset-bottom))]",children:p.jsxs("button",{type:"button",className:`${On} w-full text-sm`,disabled:!Tn.length,onClick:()=>{V(Tn),K("selected"),So(!1)},children:["使用所选终端(",Tn.length,")"]})})]})}),document.body)}const V1={background:"#1C1B1A",foreground:"#CECDC3",cursor:"#CECDC3",cursorAccent:"#1C1B1A",selectionBackground:"#403E3C",selectionForeground:"#CECDC3",selectionInactiveBackground:"#403E3C50",black:"#6F6E69",red:"#AF3029",green:"#66800B",yellow:"#AD8301",blue:"#205EA6",magenta:"#A02F6F",cyan:"#24837B",white:"#CECDC3",brightBlack:"#6F6E69",brightRed:"#D14D41",brightGreen:"#879A39",brightYellow:"#D0A215",brightBlue:"#4385BE",brightMagenta:"#CE5D97",brightCyan:"#3AA99F",brightWhite:"#FFFCF0"},G1={background:"#FFFCF0",foreground:"#100F0F",cursor:"#100F0F",cursorAccent:"#FFFCF0",selectionBackground:"#CECDC3",selectionForeground:"#100F0F",selectionInactiveBackground:"#CECDC350",black:"#100F0F",red:"#AF3029",green:"#66800B",yellow:"#AD8301",blue:"#205EA6",magenta:"#A02F6F",cyan:"#24837B",white:"#575653",brightBlack:"#6F6E69",brightRed:"#D14D41",brightGreen:"#879A39",brightYellow:"#D0A215",brightBlue:"#4385BE",brightMagenta:"#CE5D97",brightCyan:"#3AA99F",brightWhite:"#100F0F"};function X1(t){return t==="light"?G1:V1}const nc="termdock:open-services";function ig(){window.dispatchEvent(new Event(nc))}function Y1({client:t,initialSessionId:e}){const[n,r]=_.useState([]),[o,s]=_.useState(),i=_.useRef();_.useEffect(()=>{if(!e||i.current===e)return;const f=n.find(h=>h.sessionId===e||h.sourceSessionId===e);f&&(i.current=e,s(f))},[n,e]);const[a,c]=_.useState("正在读取已授权 Session"),[l,d]=_.useState(()=>document.documentElement.dataset.theme==="light"?"light":"dark");_.useEffect(()=>{const f=new MutationObserver(()=>d(document.documentElement.dataset.theme==="light"?"light":"dark"));return f.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>f.disconnect()},[]);const u=_.useRef(null);return _.useEffect(()=>{let f=!0;const h=async()=>{try{const m=await t.request({type:"session-list"});if(f){const b=m.items;r(b),s(w=>{if(!w)return c(b.length?"选择一个已授权 Session":"暂无已授权的在线 Session"),w;const I=b.find(y=>y.sessionId===w.sessionId);if(!I){c("Session 已移除或授权失效");return}return I.canWrite===w.canWrite&&I.canResize===w.canResize?w:I})}}catch{f&&c("目标不可达或授权已失效")}};h();const g=setInterval(()=>{h()},15e3);return()=>{f=!1,clearInterval(g)}},[t]),_.useEffect(()=>{if(!o||!u.current)return;let f=!1,h=0,g;const m=new wm({theme:X1(l),cursorBlink:o.canWrite,disableStdin:!o.canWrite,convertEol:!1}),b=new ym;m.loadAddon(b),m.open(u.current),o.canResize&&b.fit(),c("正在建立加密终端连接");const w=t.openSocket(`/api/terminal/${encodeURIComponent(o.sessionId)}/ws?flow=2`),I=()=>{f||!o.canResize||(b.fit(),w.readyState===1&&w.send(JSON.stringify({type:"resize",cols:m.cols,rows:m.rows})))};w.onopen=()=>c(o.canWrite?"读写":"只读"),w.onmessage=C=>{try{const T=JSON.parse(C.data);if(f)return;if(T.type==="connected"){g=typeof T.streamEpoch=="string"?T.streamEpoch:void 0,h=Number.isSafeInteger(T.replayLastSeq)?T.replayLastSeq:0,!o.canResize&&Number.isSafeInteger(T.cols)&&Number.isSafeInteger(T.rows)&&T.cols>0&&T.rows>0&&m.resize(T.cols,T.rows);const E=Array.isArray(T.replayChunks)?T.replayChunks.filter(S=>typeof S=="string").join(""):"";m.write((T.replayOutOfWindow?"\x1Bc":"")+E,I)}else T.type==="data"&&typeof T.data=="string"?m.write(T.data,()=>{f||(Number.isSafeInteger(T.seq)&&(h=Math.max(h,T.seq)),w.readyState===1&&Number.isSafeInteger(T.flowSeq)&&w.send(JSON.stringify({type:"output-ack",flowSeq:T.flowSeq,since:h,epoch:g})))}):T.type==="pty-size"&&!o.canResize&&Number.isSafeInteger(T.cols)&&Number.isSafeInteger(T.rows)&&T.cols>0&&T.rows>0?m.resize(T.cols,T.rows):T.type==="error"&&c("目标拒绝终端操作,请检查有效授权")}catch{c("终端数据无效"),w.close()}},w.onclose=()=>c("连接已断开;画面已过期,重新选择 Session 可重连"),w.onerror=()=>c("目标不可达或授权不足");const y=m.onData(C=>{o.canWrite&&w.readyState===1&&w.send(JSON.stringify({type:"input",data:C}))}),v=setInterval(()=>{w.readyState===1&&w.send(JSON.stringify({type:"ping"}))},2e4),L=new ResizeObserver(I);return L.observe(u.current),()=>{f=!0,clearInterval(v),L.disconnect(),y.dispose(),w.onclose=null,w.onerror=null,w.close(),m.dispose()}},[t,o,l]),p.jsxs("div",{className:"flex h-dvh flex-col bg-background text-foreground",children:[p.jsxs("div",{className:"flex items-center gap-3 border-b border-border p-3 text-sm",children:[p.jsxs("span",{className:"min-w-0 flex-1",children:["已授权 Session · ",a]}),p.jsx("button",{type:"button",onClick:ig,className:"min-h-11 shrink-0 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2",children:"服务与设备"})]}),p.jsx("div",{className:"flex flex-wrap gap-2 p-2",children:n.map(f=>p.jsxs("button",{className:"rounded border border-border px-3 py-2 text-sm hover:bg-surface-2",onClick:()=>s({...f}),children:[f.name," · ",f.canWrite?"读写":"只读"]},`${t.targetPeerId}:${f.sessionId}`))}),p.jsx("div",{ref:u,className:"min-h-0 flex-1 overflow-auto p-2"})]})}function Z1(t){const e=t.serviceLabel?.trim();if(!e||/^https?:\/\//i.test(e)||e===t.serviceOrigin)return"远端服务";try{const n=new URL(t.serviceOrigin??"");if(e===n.host||e===n.hostname)return"远端服务"}catch{}return e}function rc(t){if(!t.startsWith("remote:"))return null;const e=t.slice(7).split(":");if(e.length!==2)return null;try{const n=decodeURIComponent(e[0]),r=decodeURIComponent(e[1]);return!r||new URL(n).origin!==n||!/^https?:/.test(n)?null:{origin:n,id:r}}catch{return null}}class J1{constructor(e){this.source=e,this.peers={state:e.peerProtocol==="unsupported"?"unsupported":e.readPeers?"loading":"unavailable",checkedAt:null}}source;local=null;remote=[];peers;localInFlight=null;peerInFlight=null;listeners=new Set;disposed=!1;peerTimer;lastPeerAttempt=-1/0;generation=0;localHealthy=!1;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}snapshot(){if(!this.local)return null;const e=new Map;for(const n of this.local.groups)for(const r of n.remoteSessions??[]){const o=rc(r.sessionId);o&&o.origin!==this.source.origin&&o.origin!==this.source.peerOrigin&&e.set(r.sessionId,{...r,status:"offline",serviceConnected:!1})}for(const n of this.remote)e.set(n.sessionId,n);for(const n of this.local.sessions)e.set(n.sessionId,n);return{groups:this.local.groups.map(n=>({...n,remoteSessions:n.remoteSessions?.map(r=>e.get(r.sessionId)??r)})),sessions:[...e.values()],peers:this.peers,capabilities:this.local.capabilities}}emit(){if(this.disposed||!this.localHealthy)return;const e=this.snapshot();if(e)for(const n of this.listeners)n(e)}load(){if(this.disposed)return Promise.reject(new Error("协作连接已切换,请重新加载"));if(this.localInFlight)return this.localInFlight;this.refreshPeers();const e=this.generation,n=Promise.resolve().then(()=>this.source.readLocal()).then(r=>{if(this.disposed)throw new Error("协作连接已切换,请重新加载");if(e!==this.generation)return this.load();if(!Array.isArray(r.groups)||!Array.isArray(r.sessions))throw new Error("协作会话响应无效,请更新服务后重试");return this.local=r,this.localHealthy=!0,this.emit(),this.snapshot()}).catch(r=>{throw e===this.generation&&(this.localHealthy=!1),r}).finally(()=>{this.localInFlight===n&&(this.localInFlight=null)});return this.localInFlight=n,n}invalidate(){this.generation++,this.localInFlight=null,this.localHealthy=!1}refreshPeers(e=!1){if(this.disposed||!this.source.readPeers||this.peerInFlight||!e&&Date.now()-this.lastPeerAttempt<2e3)return;this.lastPeerAttempt=Date.now(),this.peers.checkedAt||(this.peers={state:"loading",checkedAt:null}),this.emit();const n=this.source.readPeers;this.peerInFlight=Promise.race([Promise.resolve().then(()=>n()),new Promise((r,o)=>{this.peerTimer=setTimeout(()=>o(new Error("服务端协作目录加载超时,请检查服务连接")),2e4)})]).then(r=>{if(this.disposed)return;const o=r.origin===this.source.origin||!!this.source.peerOrigin&&r.origin===this.source.peerOrigin;if(!Array.isArray(r.sessions)||this.source.peerProtocol==="v2"&&(r.protocolVersion!==2||!o)||r.origin&&!o||r.protocolVersion!==void 0&&r.protocolVersion!==2)throw new Error("协作目录响应与当前服务不匹配,请升级服务后重试");this.remote=r.sessions.filter(i=>{const a=rc(i.sessionId);return a&&a.origin!==this.source.origin&&a.origin!==this.source.peerOrigin});const s=r.services?.filter(i=>i.origin!==this.source.origin&&i.origin!==this.source.peerOrigin);this.peers={state:s?.some(i=>!i.connected)?"partial":"ready",checkedAt:Date.now(),services:s}}).catch(r=>{this.disposed||(this.remote=this.remote.map(o=>({...o,status:"offline",serviceConnected:!1})),this.peers={state:"error",checkedAt:Date.now(),error:r instanceof Error?r.message:"跨服务会话加载失败"})}).finally(()=>{clearTimeout(this.peerTimer),this.peerInFlight=null,this.emit()})}dispose(){this.disposed=!0,clearTimeout(this.peerTimer),this.listeners.clear(),this.local=null,this.remote=[]}}async function Q1(t,e){const n=navigator.serviceWorker?.controller;if(!n)return null;const r=new MessageChannel;return new Promise(o=>{const s=a=>{clearTimeout(i),r.port1.close(),o(a)},i=setTimeout(()=>s(null),5e3);r.port1.onmessage=a=>{try{const c=new URL(a.data.url,location.origin);s(c.origin===location.origin&&/^\/__termdock-download\/[a-f0-9-]{36}$/.test(c.pathname)?c.href:null)}catch{s(null)}},r.port1.onmessageerror=()=>s(null);try{n.postMessage({type:"termdock:prepare-download",blob:t,filename:e},[r.port2])}catch{s(null)}})}const eA=4*1024*1024,tA=256*1024,nA=1440*6e4;let tr=0,Wu;function hl(){return typeof indexedDB>"u"?Promise.resolve(null):Wu??=new Promise(t=>{const e=indexedDB.open(`termdock-terminal-snapshots:${Kn}`,1);e.onupgradeneeded=()=>e.result.createObjectStore("snapshots",{keyPath:"id"}),e.onerror=()=>t(null),e.onblocked=()=>t(null),e.onsuccess=()=>{e.result.onversionchange=()=>{e.result.close(),Wu=void 0},t(e.result)}})}function oc(t){return!!t&&t.version===1&&typeof t.epoch=="string"&&t.epoch.length>0&&Number.isSafeInteger(t.cols)&&t.cols>0&&Number.isSafeInteger(t.rows)&&t.rows>0&&Number.isSafeInteger(t.seq)&&t.seq>0&&typeof t.data=="string"&&t.data.length*2<=tA&&t.savedAt<=Date.now()&&Date.now()-t.savedAt<nA}async function ZI(t){const e=tr;try{const n=await hl();return!n||e!==tr?null:await new Promise(r=>{const o=n.transaction("snapshots").objectStore("snapshots").get(t);o.onerror=()=>r(null),o.onsuccess=()=>r(e===tr&&oc(o.result)?o.result:null)})}catch{return null}}async function JI(t){const e=tr;if(oc(t))try{const n=await hl();if(!n||e!==tr)return;await new Promise(r=>{const o=n.transaction("snapshots","readwrite"),s=o.objectStore("snapshots");s.put(t);const i=s.getAll();i.onsuccess=()=>{let a=0,c=0;for(const l of i.result.sort((d,u)=>u.savedAt-d.savedAt))a+=l.data.length*2,(++c>32||a>eA||!oc(l))&&s.delete(l.id)},o.oncomplete=()=>r(),o.onerror=o.onabort=()=>r()})}catch{}}async function ag(){tr+=1;try{(await hl())?.transaction("snapshots","readwrite").objectStore("snapshots").clear()}catch{}}typeof window<"u"&&window.addEventListener("auth:unauthorized",()=>{ag()});const wt=new Map,Ht=new Map,rA=32*1024*1024,oA=8*1024*1024,sA=48;let $r=0,sc=0;function pl(){sc+=1,wt.clear(),$r=0;for(const t of Ht.values())t.controller.abort();Ht.clear()}typeof window<"u"&&window.addEventListener("auth:unauthorized",pl);function iA(t,e){const n=wt.get(t);if(n&&($r-=n.blob.size,wt.delete(t)),!(e.blob.size>oA))for(wt.set(t,e),$r+=e.blob.size;wt.size>sA||$r>rA;){const r=wt.keys().next().value;$r-=wt.get(r).blob.size,wt.delete(r)}}async function cg(t,e={}){const n=new URL(t,typeof location<"u"?location.origin:"http://localhost");if(!/^\/api\/terminal\/fs\/(read|blob)$/.test(n.pathname))return fetch(t,{signal:e.signal});if(e.signal?.aborted)throw e.signal.reason??new DOMException("Aborted","AbortError");n.searchParams.delete("requestSlotId"),n.searchParams.delete("action"),n.searchParams.sort();const r=n.href;let o=Ht.get(r);if(!o){const i=new AbortController,a=sc,c=wt.get(r),l=new Headers,d=c?.headers.get("ETag");d&&l.set("If-None-Match",d);const u=setTimeout(()=>i.abort(new DOMException("File preview timed out. Please retry.","TimeoutError")),e.timeoutMs??15e3),f={controller:i,readers:0,promise:Promise.resolve(null)};f.promise=(async()=>{const h=await fetch(r,{headers:l,signal:i.signal,cache:"no-cache"});let g;return h.status===304&&c?g=c:g={blob:await h.blob(),headers:new Headers(h.headers),status:h.status},sc===a&&!i.signal.aborted&&g.status===200&&g.headers.has("ETag")&&iA(r,g),h.status===401&&pl(),g})().finally(()=>{clearTimeout(u),Ht.get(r)===f&&Ht.delete(r)}),o=f,Ht.set(r,o)}const s=o;return s.readers+=1,new Promise((i,a)=>{let c=!1;const l=()=>c?!1:(c=!0,e.signal?.removeEventListener("abort",d),s.readers-=1,s.readers===0&&Ht.get(r)===s&&(Ht.delete(r),s.controller.abort()),!0),d=()=>{l()&&a(e.signal?.reason??new DOMException("Aborted","AbortError"))};if(e.signal?.addEventListener("abort",d,{once:!0}),e.signal?.aborted){d();return}s.promise.then(u=>{l()&&i(new Response(u.blob,{status:u.status,headers:u.headers}))},u=>{l()&&a(u)})})}const gl="auth:unauthorized";let Hn=null;class Ae extends Error{constructor(e,n,r){super(e),this.status=n,this.code=r,this.name="TerminalApiError"}status;code}async function aA(){const t=await fetch("/api/terminal/update");if(!t.ok)throw new Ae("Failed to load update state",t.status);return t.json()}async function cA(){const t=await Y(),e=await fetch("/api/terminal/update/check",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Ae("Failed to check for updates",e.status);return e.json()}async function lA(){const t=await Y(),e=await fetch("/api/terminal/update/restart",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to restart Termdock"}));throw new Ae(n.error||"Failed to restart Termdock",e.status)}return e.json()}async function dA(){const t=await fetch("/api/terminal/quota");if(!t.ok)throw new Ae("Failed to fetch quota",t.status);return t.json()}async function uA(){const t=await Y(),e=await fetch("/api/terminal/quota/refresh",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Ae("Failed to refresh quota",e.status);return e.json()}const Cn=8e3,lg=6e4,fA=32e3,dg=125e3,ft=1e4,nr=45e3,ug=8e3,fg=8e3,hg=15e3,hA=1e4,fr=5e3;let pA=0;const es=[];let ha=!1;function Mt(t,e={}){if(typeof window>"u")return;const n=JSON.stringify({level:t==="error"||t==="timeout_or_abort"||t==="response_body_timeout"||t==="response_body_parse_error"?"warn":"info",message:`DIFF_API ${t}`,data:{seq:++pA,ts:Date.now(),...e}});es.push(n),gA()}async function gA(){if(!ha){ha=!0;try{for(;es.length>0;){const t=es[0];try{await fetch("/api/client-log",{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:!0}),es.shift()}catch{break}}}finally{ha=!1}}}function ml(t,e,n){const r=new AbortController;let o=setTimeout(()=>{r.abort(new DOMException(n,"TimeoutError"))},e);const s=()=>r.abort(t?.reason);return t&&(t.aborted?s():t.addEventListener("abort",s,{once:!0})),{signal:r.signal,cleanup:()=>{o&&(clearTimeout(o),o=null),t?.removeEventListener("abort",s)}}}async function pe(t,e,n,r){const{signal:o,cleanup:s}=ml(e?.signal??void 0,n,r);try{return await fetch(t,{...e,signal:o})}catch(i){throw i instanceof DOMException&&i.name==="TimeoutError"?new Error(r):i}finally{s()}}async function pg(t,e,n){let r=null;const o=new Promise((s,i)=>{r=setTimeout(()=>i(new Error(n)),e)});try{return await Promise.race([t.text(),o])}finally{r&&clearTimeout(r)}}async function hr(t,e,n){const r=await pg(t,e,n);return JSON.parse(r)}if(typeof window<"u"&&!window.__termdockFetchPatched){window.__termdockFetchPatched=!0;const t=window.fetch.bind(window);window.fetch=async(...e)=>{const n=await t(...e);if(n.status===401){Hn=null,Al();try{window.dispatchEvent(new CustomEvent(gl))}catch{}}return n}}async function Y(){if(Hn)return Hn;const t=await pe("/api/csrf-token",void 0,ug,"CSRF token request timed out");if(!t.ok)throw new Error("Failed to get CSRF token");const e=await hr(t,fr,"CSRF token response timed out");if(!e.csrfToken)throw new Error("Invalid CSRF token response");return Hn=e.csrfToken,Hn}function wl(){Al(),Hn=null}const mA=2e4,Vu=8e3,wA=1500,gg=250,me=new Map,yl=new Map,yA=24,bA=40,vA=40;function SA(t){return t.retryState.retryCount>=2||t.pendingInputs.length>=vA?"congested":t.retryState.retryCount>=1||t.pendingInputs.length>=8?"degraded":"good"}function Gu(t){if(t.pendingInputs.length===0||t.ws.readyState!==WebSocket.OPEN)return;const e=t.pendingInputs.splice(0);for(const n of e)try{t.ws.send(JSON.stringify({type:"input",data:n}))}catch{}}function mg(t){if(t.ws.readyState!==WebSocket.OPEN)return;const e=SA(t);if(e==="good"){Gu(t);return}if(t.inputFlushTimer)return;const n=e==="congested"?bA:yA;t.inputFlushTimer=setTimeout(()=>{t.inputFlushTimer=null,Gu(t)},n)}const Zr=new Map;function xA(t,e,n,r){const o=Zr.get(t);o&&(Zr.delete(t),e?o.resolve({success:!0,layout:n}):o.reject(new Error(r||"Tmux action failed")))}const Un=new Map;function EA(t,e,n,r){const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/terminal/${t}/ws`,i=new URLSearchParams({flow:"2",transport:"tmux-client",active:yl.get(t)===!1?"0":"1"});e>0&&i.set("since",String(e)),n&&i.set("epoch",n);const a=r??Un.get(t);return a&&(i.set("cols",String(a.cols)),i.set("rows",String(a.rows))),`${s}?${i}`}const ic=new Map,ac=new Map;function AA(t,e,n){ic.set(t,e),ac.set(t,n)}function kA(t){const e=me.get(t);return e?.streamEpoch&&e.appliedSeq===e.lastSeq&&e.lastSeq>0?{seq:e.lastSeq,epoch:e.streamEpoch}:null}async function CA(t){const e=await Y(),n=await fetch("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({cols:t.cols||80,rows:t.rows||24,mode:t.mode||"shell",tmuxSessionName:t.tmuxSessionName,cwd:t.cwd,termType:t.termType})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to create terminal"}));throw new Error(r.error||"Failed to create terminal session")}return n.json()}function IA(t,e,n,r={}){const{maxRetries:o=10,initialRetryDelay:s=1e3,maxRetryDelay:i=2e4,connectionTimeout:a=15e3}=r,c={maxRetries:o,initialDelayMs:s,maxDelayMs:i,connectionTimeoutMs:a,retryCount:0,retryTimeout:null,connectionTimeoutId:null,isClosed:!1,isSuspended:!1};let l=null,d=ic.get(t)??0,u=ac.get(t);ac.delete(t),ic.delete(t);const f=[];let h=!1,g=null;const m=new WeakSet,b=()=>{c.retryTimeout&&(clearTimeout(c.retryTimeout),c.retryTimeout=null),c.connectionTimeoutId&&(clearTimeout(c.connectionTimeoutId),c.connectionTimeoutId=null),g&&(clearTimeout(g),g=null)},w=C=>{C.wakeProbe&&(clearTimeout(C.wakeProbe.timer),C.wakeProbe=void 0),C.heartbeatTimer&&(clearInterval(C.heartbeatTimer),C.heartbeatTimer=null),C.pongTimer&&(clearTimeout(C.pongTimer),C.pongTimer=null),C.inputFlushTimer&&(clearTimeout(C.inputFlushTimer),C.inputFlushTimer=null)},I=C=>{w(C),C.heartbeatTimer=setInterval(()=>{if(C.ws.readyState===WebSocket.OPEN){try{C.ws.send(JSON.stringify({type:"ping"}))}catch{}C.pongTimer&&clearTimeout(C.pongTimer),C.pongTimer=setTimeout(()=>{if(Date.now()-C.lastInboundAt>=Vu){h=!0,w(C);try{C.ws.close()}catch{}L(new Error("WebSocket heartbeat timeout"),!1)}},Vu)}},mA)},y=()=>{if(c.isClosed=!0,b(),l){w(l),me.delete(t);try{l.ws.close()}catch{}l=null}},v=()=>{if(c.isClosed)return;if(l){m.add(l.ws),w(l);try{l.ws.close()}catch{}}const C=EA(t,d,u,r.getDimensions?.()),T=Up(C);h=!1,c.connectionTimeoutId=setTimeout(()=>{T.readyState!==WebSocket.OPEN&&(h=!0,T.close(),L(new Error("WebSocket connection timeout"),!1))},a);const E={ws:T,onEvent:e,onError:n,reconnectNow:()=>{if(!c.isClosed&&(c.isSuspended=!1,!g)){if(b(),l){m.add(l.ws),w(l);try{l.ws.close()}catch{}}e({type:"reconnecting",attempt:Math.min(c.retryCount+1,o),maxAttempts:o}),c.retryCount=Math.min(c.retryCount+1,o),h=!0,g=setTimeout(()=>{g=null,h=!1,v()},0)}},suspendReconnect:()=>{c.isClosed||(c.isSuspended=!0,c.retryTimeout&&(clearTimeout(c.retryTimeout),c.retryTimeout=null))},retryState:c,lastSeq:d,pendingInputs:f,inputFlushTimer:null,heartbeatTimer:null,pongTimer:null,lastInboundAt:Date.now(),inboundSequence:0};T.onopen=()=>{c.isClosed||m.has(T)||h||(b(),c.retryCount=0,E.lastInboundAt=Date.now(),E.inboundSequence+=1,I(E),mg(E))},T.onmessage=S=>{if(!(c.isClosed||m.has(T)||h)){E.lastInboundAt=Date.now(),E.inboundSequence+=1;try{const k=JSON.parse(S.data);if(E.wakeProbe&&me.get(t)===E){const D=E.wakeProbe;E.wakeProbe=void 0,clearTimeout(D.timer);for(const A of D.listeners)A()}if(k.type==="pong"){E.pongTimer&&(clearTimeout(E.pongTimer),E.pongTimer=null);return}if(k.type==="tmux-result"&&k.reqId){xA(k.reqId,k.success!==!1,k.layout,k.error);return}if(k.type==="tmux-layout"&&k.layout){e({type:"tmux-layout",layout:k.layout});return}if(k.type==="tmux-screen-sync"&&Array.isArray(k.chunks)){e({type:"tmux-screen-sync",chunks:k.chunks.filter(D=>typeof D=="string"),cols:typeof k.cols=="number"?k.cols:void 0,rows:typeof k.rows=="number"?k.rows:void 0,generation:typeof k.generation=="number"?k.generation:void 0});return}if(k.type==="active-program"){e({type:"active-program",activeProgram:k.activeProgram,activeProgramRaw:k.activeProgramRaw,activeProgramSource:k.activeProgramSource});return}if(k.type==="cwd"){e({type:"cwd",cwd:k.cwd});return}if(k.type==="agent-status"){e({type:"agent-status",agentStatus:k.agentStatus??null,agentIndicator:k.agentIndicator??null,agentStatusDetail:k.agentStatusDetail??null,agent:k.agent??null,agentMessage:k.agentMessage??null,agentNativeSessionId:k.agentNativeSessionId??null,agentResumeRecovered:k.agentResumeRecovered===!0,agentRich:k.agentRich===!0,agentActivity:typeof k.agentActivity=="number"?k.agentActivity:0,agentCwd:k.agentCwd??null,reviewed:typeof k.reviewed=="boolean"?k.reviewed:null});return}if(k.type==="git-status"){e({type:"git-status",gitStatus:k.gitStatus??null});return}if(k.type==="quota-status"&&Array.isArray(k.providers)){window.dispatchEvent(new CustomEvent("termdock:quota-update",{detail:k.providers}));return}if(k.type==="focus-mode"){e({type:"focus-mode",focusTrackingRequested:k.focusTrackingRequested===!0});return}if(k.type==="resize-ack"){e({type:"resize-ack",seq:typeof k.seq=="number"?k.seq:void 0,cols:typeof k.cols=="number"?k.cols:void 0,rows:typeof k.rows=="number"?k.rows:void 0,ok:k.ok!==!1,error:typeof k.error=="string"?k.error:void 0,screenSyncPending:k.screenSyncPending===!0,screenSyncGeneration:typeof k.screenSyncGeneration=="number"?k.screenSyncGeneration:void 0});return}if(k.type==="pty-size"){e({type:"pty-size",cols:typeof k.cols=="number"?k.cols:void 0,rows:typeof k.rows=="number"?k.rows:void 0,source:typeof k.source=="string"?k.source:void 0});return}if(k.type==="shell-title"){e({type:"shell-title",title:typeof k.title=="string"?k.title:""});return}if(k.type==="prompt-state"){e({type:"prompt-state",state:k.state==="running"?"running":"idle",exitCode:typeof k.exitCode=="number"?k.exitCode:void 0});return}const N=k;if(N.type==="connected"){E.appliedSeq=void 0,u=N.streamEpoch,E.streamEpoch=u,E.outputProtocol=N.outputProtocol,typeof N.replayLastSeq=="number"&&N.replayLastSeq>=0&&(d=N.replayLastSeq,E.lastSeq=d),e(N),wg(t,yl.get(t)??!0);return}if(N.type==="exit"){y(),e(N);return}if(N.type==="data"){if(E.appliedSeq=void 0,typeof N.seq=="number"&&N.seq<=d)return;typeof N.flowSeq=="number"&&(E.flowSeq=N.flowSeq)}e(N),N.type==="data"&&typeof N.seq=="number"&&Number.isFinite(N.seq)&&N.seq>d&&(d=N.seq,E.lastSeq=d)}catch(k){n?.(k,!1)}}},T.onerror=()=>{c.isClosed||m.has(T)||h||(b(),w(E),h||(h=!0,L(new Error("WebSocket connection error"),!1)))},T.onclose=S=>{if(!(c.isClosed||m.has(T)||h)){if(S.code===Ep&&S.reason===Ap){E.reconnectNow();return}if(b(),w(E),h=!0,S.code===4001){console.warn("[Terminal] WS 4001: Session not found on server",{code:S.code,reason:S.reason,stack:new Error().stack}),L(new Error("Session not found on server"),!0);return}if(S.code===4003||S.code===4401){try{window.dispatchEvent(new CustomEvent(gl))}catch{}L(new Error("Authentication required"),!0);return}L(new Error("WebSocket connection closed"),!1)}},l=E,me.set(t,l)},L=(C,T)=>{if(!c.isClosed)if(T)n?.(C,!0),y();else{c.retryCount=Math.min(c.retryCount+1,Math.max(1,o));const E=Math.min(s*Math.pow(2,c.retryCount-1),i);if(e({type:"reconnecting",attempt:c.retryCount,maxAttempts:o}),c.isSuspended)return;c.retryTimeout=setTimeout(()=>{c.isClosed||v()},E)}};return v(),y}async function RA(t,e){const n=me.get(t);if(n){if(n.ws.readyState===WebSocket.OPEN){n.pendingInputs.push(e),mg(n);return}if(n.ws.readyState===WebSocket.CONNECTING){n.pendingInputs.push(e);return}}const r=await Y(),o=await fetch(`/api/terminal/${t}/input`,{method:"POST",headers:{"Content-Type":"text/plain","X-XSRF-TOKEN":r},body:e});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to send input"}));throw new Error(s.error||"Failed to send terminal input")}}function TA(t,e,n={}){const r=me.get(t);if(!r)return!1;if(r.retryState.isSuspended=!1,r.ws.readyState!==WebSocket.OPEN)return r.reconnectNow(),!0;const o=n.visible?gg:wA,s=Date.now()+o,i=r.wakeProbe,a=i?.listeners??new Set;if(e&&a.add(e),i&&i.deadline<=s)return!0;i&&clearTimeout(i.timer);const c=setTimeout(()=>{me.get(t)!==r||r.retryState.isClosed||(r.wakeProbe=void 0,r.reconnectNow())},o);if(r.wakeProbe={timer:c,listeners:a,deadline:s},i)return!0;try{r.ws.send(JSON.stringify({type:"ping"}))}catch{clearTimeout(c),r.wakeProbe=void 0,r.reconnectNow()}return!0}function PA(t){const e=me.get(t);return e?(e.reconnectNow(),!0):!1}function NA(){for(const t of me.values())t.suspendReconnect()}function LA(t,e,n){const r=me.get(t);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"focus",focused:e,reason:n}))}catch{}}function wg(t,e){yl.set(t,e);const n=me.get(t);!n||n.ws.readyState!==WebSocket.OPEN||n.outputProtocol!==2||n.ws.send(JSON.stringify({type:"output-subscription",active:e,since:n.lastSeq,epoch:n.streamEpoch}))}function BA(t){const e=me.get(t);!e||e.ws.readyState!==WebSocket.OPEN||e.outputProtocol!==2||(e.appliedSeq=e.lastSeq,!(!e.flowSeq||e.flowSeq===e.acknowledgedFlowSeq)&&(e.acknowledgedFlowSeq=e.flowSeq,e.ws.send(JSON.stringify({type:"output-ack",flowSeq:e.flowSeq,since:e.appliedSeq,epoch:e.streamEpoch}))))}function _A(t,e,n){const r=me.get(t);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"viewing",viewing:e,reason:n}))}catch{}}function cc(t){const e=me.get(t);if(!(!e||e.ws.readyState!==WebSocket.OPEN))try{e.ws.send(JSON.stringify({type:"agent-review-ack"}))}catch{}}function OA(t,e,n){const r=me.get(t);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"flow-control",paused:e,reason:n}))}catch{}}async function DA(t,e,n,r){Number.isFinite(e)&&Number.isFinite(n)&&e>=1&&n>=1&&(Un.delete(t),Un.set(t,{cols:Math.floor(e),rows:Math.floor(n)}),Un.size>256&&Un.delete(Un.keys().next().value));const o=me.get(t);if(o&&o.ws.readyState===WebSocket.OPEN)try{o.ws.send(JSON.stringify({type:"resize",cols:e,rows:n,seq:r}));return}catch{}const s=await Y(),i=await fetch(`/api/terminal/${t}/resize`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":s},body:JSON.stringify({cols:e,rows:n,seq:r})});if(!i.ok){const c=await i.json().catch(()=>({error:"Failed to resize terminal"}));throw new Error(c.error||"Failed to resize terminal")}const a=await i.json().catch(()=>({success:!0}));if(a?.success===!1||a?.ok===!1)throw new Error(a?.error||"Failed to resize terminal")}async function FA(t,e){const n=me.get(t);if(n&&n.ws.readyState===WebSocket.OPEN)return e.action==="scroll"?(n.ws.send(JSON.stringify({type:"tmux",...e})),{success:!0}):new Promise((s,i)=>{const a=Math.random().toString(36).substring(7);Zr.set(a,{resolve:s,reject:i}),n.ws.send(JSON.stringify({type:"tmux",reqId:a,...e})),setTimeout(()=>{Zr.has(a)&&(Zr.delete(a),i(new Error("Tmux action timed out")))},3e4)});const r=await Y(),o=await fetch(`/api/terminal/${t}/tmux`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(e)});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to execute tmux action"}));throw new Error(s.error||"Failed to execute tmux action")}return o.json()}async function MA(t){const e=me.get(t);if(e){e.retryState.isClosed=!0;try{e.ws.close()}catch{}me.delete(t)}const n=await Y(),r=await fetch(`/api/terminal/${t}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":n}});if(r.status!==404&&!r.ok){const o=await r.json().catch(()=>({error:"Failed to close terminal"}));throw new Error(o.error||"Failed to close terminal")}}async function jA(t,e){const n=me.get(t);if(n){n.retryState.isClosed=!0;try{n.ws.close()}catch{}me.delete(t)}const r=await Y(),o=await fetch(`/api/terminal/${t}/restart`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify({...e.cwd?{cwd:e.cwd}:{},cols:e.cols??80,rows:e.rows??24,mode:e.mode,tmuxSessionName:e.tmuxSessionName})});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to restart terminal"}));throw new Error(s.error||"Failed to restart terminal session")}return o.json()}async function UA(t){const e=await pe(`/api/terminal/${t}/health`,{method:"GET"},fg,"Terminal health check timed out");if(!e.ok){if(e.status===404)return{healthy:!1,sessionId:t};const n=await hr(e,fr,"Terminal health error response timed out").catch(()=>({error:"Failed to check terminal health"}));throw new Error(n.error||"Failed to check terminal health")}return hr(e,fr,"Terminal health response timed out")}async function $A(t){const e=await Y(),n=await pe("/api/terminal/force-kill",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)},hA,"Terminal force-kill request timed out");if(!n.ok){const r=await hr(n,fr,"Terminal force-kill error response timed out").catch(()=>({error:"Failed to force kill terminal"}));throw new Error(r.error||"Failed to force kill terminal")}}async function HA(){const t=await fetch("/api/terminal/tmux/sessions",{method:"GET"});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to list tmux sessions"}));throw new Error(n.error||"Failed to list tmux sessions")}const e=await t.json();return Array.isArray(e.sessions)?e.sessions:[]}async function qA(){const t=await fetch("/api/terminal/tmux/status",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to get tmux status"}));throw new Error(e.error||"Failed to get tmux status")}return t.json()}async function KA(t){const e=t.trim();if(!e)throw new Error("tmux session name is required");const n=await Y(),r=await fetch(`/api/terminal/tmux/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":n}});if(!r.ok){const s=await r.json().catch(()=>({error:"Failed to kill tmux session"}));throw new Error(s.error||"Failed to kill tmux session")}const o=await r.json();return{cleanedSessions:Array.isArray(o.cleanedSessions)?o.cleanedSessions:[],alreadyGone:!!o.alreadyGone}}async function zA(){const t=await Y(),e=await fetch("/api/terminal/tmux/recovery/restore-all",{method:"POST",headers:{"X-XSRF-TOKEN":t}}),n=await e.json().catch(()=>({}));if(!e.ok)throw new Ae(n.error||"Failed to restore tmux Agent sessions",e.status);return n}async function WA(){const t=await Y(),e=await fetch("/api/terminal/tmux/recovery",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Ae("Failed to dismiss tmux recovery",e.status)}const Ho=new Map;function VA(t){return JSON.stringify({preferredFrontendSessionId:t.preferredFrontendSessionId??null,mode:t.mode??null,tmuxSessionName:t.tmuxSessionName??null,cwd:t.cwd??null,termType:t.termType??null,createIfEmpty:t.createIfEmpty===!0,requireExisting:t.requireExisting===!0})}async function yg(){const t=await fetch("/api/terminal/session-inventory",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to load session inventory"}));throw new Error(e.error||"Failed to load session inventory")}return t.json()}async function bg(t){const e=VA(t),n=Ho.get(e);if(n)return n;const r=await Y(),o=pe("/api/terminal/session-inventory/open",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(t)},hg,"Terminal session open request timed out").then(async s=>{if(!s.ok){const i=await hr(s,fr,"Terminal session open error response timed out").catch(()=>({error:"Failed to open session"}));throw new Ae(i.error||"Failed to open session",s.status,typeof i.code=="string"?i.code:void 0)}return hr(s,fr,"Terminal session open response timed out")}).finally(()=>{Ho.get(e)===o&&Ho.delete(e)});return Ho.set(e,o),o}async function ts(t,e){const n=await Y(),r=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:"Failed to update session"}));throw new Error(o.error||"Failed to update session")}return r.json()}async function vg(t){const e=await Y(),n=await fetch("/api/terminal/session-inventory/reorder",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({sessionIds:t})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to reorder sessions"}));throw new Error(r.error||"Failed to reorder sessions")}return n.json()}async function Sg(t){const e=await Y(),n=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to remove session"}));throw new Error(r.error||"Failed to remove session")}}async function xg(){const t=await Y(),e=await fetch("/api/terminal/session-inventory/sessions",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to clear sessions"}));throw new Error(n.error||"Failed to clear sessions")}}async function GA(){const t=await fetch("/api/terminal/toolbar-presets",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to load toolbar presets"}));throw new Error(e.error||"Failed to load toolbar presets")}return t.json()}async function XA(t){const e=await Y(),n=await fetch("/api/terminal/toolbar-presets",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to save toolbar presets"})),o=new Error(r.error||"Failed to save toolbar presets");throw o.current=r.current,o.code=r.code,o}return n.json()}let Lr=null,Hr=null;const Eg=1500;function rr(){return Hr&&Date.now()-Hr.readAt<Eg?Promise.resolve(Hr.value):Lr||(Lr=(async()=>{const t=await fetch("/api/terminal/settings",{method:"GET"});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to load settings"}));throw new Error(n.error||"Failed to load settings")}const e=await t.json();return Hr={value:e,readAt:Date.now()},e})().finally(()=>{Lr=null}),Lr)}async function vt(t){const e=await Y(),n=await fetch("/api/terminal/settings",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to update settings"}));throw new Error(o.error||"Failed to update settings")}const r=await n.json();return Hr={value:r,readAt:Date.now()},r}async function YA(t=!1){const e=await fetch(`/api/terminal/auto-title/catalog${t?"?refresh=1":""}`);if(!e.ok)throw new Error("Failed to discover title models");const n=await e.json();return Array.isArray(n?.namers)?n.namers:[]}let Br=null,qr=null;function ZA(){return qr&&Date.now()-qr.readAt<Eg?Promise.resolve(qr.value):Br||(Br=(async()=>{const t=await fetch("/api/terminal/context-draft",{method:"GET"});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to load context draft"}));throw new Error(n.error||"Failed to load context draft")}const e=await t.json();return qr={value:e,readAt:Date.now()},e})().finally(()=>{Br=null}),Br)}async function JA(t,e){const n=await Y(),r=await fetch("/api/terminal/context-draft",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify({text:t,origin:e})});if(!r.ok){const s=await r.json().catch(()=>({error:"Failed to update context draft"}));throw new Error(s.error||"Failed to update context draft")}const o=await r.json();return qr={value:o,readAt:Date.now()},o}async function Ag(t){const e=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:t})});if(e.ok)return wl(),{ok:!0};const n=await e.json().catch(()=>null);return e.status===429?{ok:!1,rateLimited:!0,retryAfterMs:typeof n?.retryAfterMs=="number"?n.retryAfterMs:void 0,error:n?.error||"Too many failed attempts. Please wait and try again."}:{ok:!1,error:n?.error||"Login failed"}}async function QA(){pl(),ag();const t=await Y();await fetch("/api/auth/logout",{method:"POST",headers:{"X-XSRF-TOKEN":t}}),wl()}async function ek(){const t=await fetch("/api/terminal/agent-launchers");if(!t.ok)throw new Error("Failed to detect agent launchers");const e=await t.json();return Array.isArray(e?.agents)?e.agents:[]}async function tk(){const t=await fetch("/api/terminal/agent-hooks");if(!t.ok)throw new Error("Failed to get agent hooks");const e=await t.json();return Array.isArray(e?.agents)?e.agents:[]}async function nk(t){const e=await Y(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(t)}/install`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to install agent hooks");return{summary:r.summary??"Installed",devMode:r.devMode===!0}}async function rk(t){const e=await Y(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(t)}/uninstall`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to uninstall agent hooks");return r.summary??"Removed"}class bl extends Error{constructor(e,n,r){super(e),this.code=n,this.migration=r,this.name="AgentPluginManifestError"}code;migration}async function ok(){const t=await fetch("/api/terminal/agent-plugins");if(!t.ok)throw new Error("Failed to get agent plugins");return await t.json()}async function sk(t){const e=await Y(),n=await fetch("/api/terminal/agent-plugins",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok)throw new bl(r.error||"Failed to create agent plugin",r.code,r.migration);return r}async function ik(t){const e=await Y(),n=await fetch("/api/terminal/agent-plugins/install",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({source:t})}),r=await n.json().catch(()=>({}));if(!n.ok)throw new bl(r.error||"Failed to install agent plugin",r.code,r.migration);return r}async function ak(t){const e=await Y(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/check-update`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to check plugin updates");return r}async function ck(t){const e=await Y(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/update`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to update plugin");return r}async function lk(t){const e=await Y(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/doctor`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to diagnose plugin");return r}async function dk(t){const e=await Y(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||"Failed to delete agent plugin")}}async function uk(t){const e=await Y(),n=await fetch(`/api/terminal/${encodeURIComponent(t)}/agent-resume`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Ae(r.error||"Failed to resume agent session",n.status,typeof r.code=="string"?r.code:void 0);return{command:r.command??""}}async function fk(){const t=await fetch("/api/terminal/agent-resume-history",{method:"GET"});if(!t.ok)throw new Error("Failed to load Agent resume history");const e=await t.json().catch(()=>({entries:[]}));return Array.isArray(e.entries)?e.entries:[]}async function hk(t){const e=await Y(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(t)}/prepare`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Ae(r.error||"Failed to prepare Agent session resume",n.status,typeof r.code=="string"?r.code:void 0);return r}async function pk(t){const e=await Y(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!n.ok&&n.status!==404)throw new Error("Failed to remove Agent resume history")}async function gk(t){const e=await Y(),n=await fetch("/api/terminal/program-rules",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to update program rules"}));throw new Error(r.error||"Failed to update program rules")}return n.json()}async function mk(){const t=await Y(),e=await fetch("/api/terminal/program-rules",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Error("Failed to reset program rules");return e.json()}async function wk(){const t=await fetch("/api/terminal/program-detection");if(!t.ok)throw new Error("Failed to get program detection config");return t.json()}async function yk(t){const e=await Y(),n=await fetch("/api/terminal/program-detection",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!n.ok)throw new Error("Failed to save program detection config");return n.json()}async function bk(){const t=await Y(),e=await fetch("/api/terminal/program-detection",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Error("Failed to reset program detection config");return e.json()}const vk={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".bmp":"image/bmp",".ico":"image/x-icon",".svg":"image/svg+xml",".heic":"image/heic",".heif":"image/heif"};function si(t){const e=t.lastIndexOf(".");return e<0?null:vk[t.slice(e).toLowerCase()]??null}function Sk(t){return si(t)!==null}function kg(t){const e=si(t);return e==="image/heic"||e==="image/heif"}const xk={".mp4":"video/mp4",".m4v":"video/x-m4v",".webm":"video/webm",".mov":"video/quicktime",".ogv":"video/ogg",".mpeg":"video/mpeg",".mpg":"video/mpeg"};function Cg(t){const e=t.lastIndexOf(".");return e<0?null:xk[t.slice(e).toLowerCase()]??null}function Ek(t){return Cg(t)!==null}function Ak(t){return`/api/terminal/fs/video?path=${encodeURIComponent(t)}&action=view_file`}const Ig=[".stl",".glb",".gltf"];function vl(t){const e=t.lastIndexOf(".");if(e<0)return null;const n=t.slice(e).toLowerCase();return Ig.includes(n)?n:null}function kk(t){return vl(t)!==null}function Sl(t){const e=t.toLowerCase();return e.endsWith(".kicad_sch")?".kicad_sch":e.endsWith(".kicad_pcb")?".kicad_pcb":null}function Ck(t){return Sl(t)!==null}function Ik(t){return Sl(t)===".kicad_pcb"?"pcb-front":"schematic"}const Rg=[".html",".htm"];function Rk(t){const e=t.lastIndexOf(".");if(e<0)return!1;const n=t.slice(e).toLowerCase();return Rg.includes(n)}function Tk(t){return`/api/terminal/fs/preview/${t.split(/[\\/]+/).filter(Boolean).map(n=>encodeURIComponent(n)).join("/")}`}const Pk={".stl":"model/stl",".glb":"model/gltf-binary",".gltf":"model/gltf+json"};async function Nk(t,e,n,r="list_directory",o,s="name"){const i=new URLSearchParams({path:t});n&&i.set("showHidden","true"),s!=="name"&&i.set("sort",s),i.set("action",r),o&&i.set("requestSlotId",o);const a=await pe(`/api/terminal/fs/list?${i}`,{signal:e},Cn,"Directory listing took too long. The folder may be on slow storage or blocked by another process.");if(!a.ok){const c=await a.json().catch(()=>({error:"Failed to list directory"}));throw new Error(c.error||"Failed to list directory")}return a.json()}async function Lk(t,e,n,r,o,s="name",i,a={}){const c=new URLSearchParams({path:t,query:e,stream:"true"});o&&c.set("showHidden","true"),s==="content"&&c.set("mode","content"),i&&c.set("requestSlotId",i);for(const g of a.excludePatterns??[])c.append("exclude",g);a.caseSensitive&&c.set("caseSensitive","true"),a.wholeWord&&c.set("wholeWord","true"),a.regex&&c.set("regex","true");const l=await fetch(`/api/terminal/fs/search?${c}`,{signal:r});if(!l.ok||!l.body){const g=await l.json().catch(()=>({error:"Failed to search files"}));throw new Error(g.error||"Failed to search files")}const d=l.body.getReader(),u=new TextDecoder;let f="";const h=g=>{if(!g.trim())return;const m=JSON.parse(g);if(m.type==="meta")n({path:m.path,query:m.query,engine:m.engine,mode:m.mode,limited:m.limited});else if(m.type==="batch")n({entries:m.entries??[]});else if(m.type==="content-batch")n({contentEntries:m.contentEntries??[]});else{if(m.type==="error")throw new Error(m.message||"Search failed");m.type==="done"&&n({total:m.total,truncated:m.truncated,limited:m.limited,engine:m.engine,mode:m.mode,done:!0})}};for(;;){const{value:g,done:m}=await d.read();if(m)break;f+=u.decode(g,{stream:!0});let b=f.indexOf(`
8
+ `);const D=y(T,E,C),A=t.getSymbolSize(T),x=new r(A);return h(x,T),g(x),m(x,T),w(x,E,0),T>=7&&b(x,T),I(x,D),isNaN(S)&&(S=i.getBestMask(x,w.bind(null,x,E))),i.applyMask(S,x),w(x,E,S),{modules:x,version:T,errorCorrectionLevel:E,maskPattern:S,segments:C}}return zi.create=function(T,E){if(typeof T>"u"||T==="")throw new Error("No input text");let S=e.M,C,N;return typeof E<"u"&&(S=e.from(E.errorCorrectionLevel,e.M),C=l.from(E.version),N=i.from(E.maskPattern),E.toSJISFunc&&t.setToSJISFunction(E.toSJISFunc)),L(T,C,S,N)},zi}var da={},ua={},$u;function sg(){return $u||($u=1,(function(t){function e(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let r=n.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+n);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(s){return[s,s]}))),r.length===6&&r.push("F","F");const o=parseInt(r.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+r.slice(0,6).join("")}}t.getOptions=function(r){r||(r={}),r.color||(r.color={});const o=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,s=r.width&&r.width>=21?r.width:void 0,i=r.scale||4;return{width:s,scale:s?4:i,margin:o,color:{dark:e(r.color.dark||"#000000ff"),light:e(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},t.getScale=function(r,o){return o.width&&o.width>=r+o.margin*2?o.width/(r+o.margin*2):o.scale},t.getImageWidth=function(r,o){const s=t.getScale(r,o);return Math.floor((r+o.margin*2)*s)},t.qrToImageData=function(r,o,s){const i=o.modules.size,a=o.modules.data,c=t.getScale(i,s),l=Math.floor((i+s.margin*2)*c),d=s.margin*c,u=[s.color.light,s.color.dark];for(let f=0;f<l;f++)for(let h=0;h<l;h++){let g=(f*l+h)*4,m=s.color.light;if(f>=d&&h>=d&&f<l-d&&h<l-d){const b=Math.floor((f-d)/c),w=Math.floor((h-d)/c);m=u[a[b*i+w]?1:0]}r[g++]=m.r,r[g++]=m.g,r[g++]=m.b,r[g]=m.a}}})(ua)),ua}var Hu;function j1(){return Hu||(Hu=1,(function(t){const e=sg();function n(o,s,i){o.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=i,s.width=i,s.style.height=i+"px",s.style.width=i+"px"}function r(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}t.render=function(s,i,a){let c=a,l=i;typeof c>"u"&&(!i||!i.getContext)&&(c=i,i=void 0),i||(l=r()),c=e.getOptions(c);const d=e.getImageWidth(s.modules.size,c),u=l.getContext("2d"),f=u.createImageData(d,d);return e.qrToImageData(f.data,s,c),n(u,l,d),u.putImageData(f,0,0),l},t.renderToDataURL=function(s,i,a){let c=a;typeof c>"u"&&(!i||!i.getContext)&&(c=i,i=void 0),c||(c={});const l=t.render(s,i,c),d=c.type||"image/png",u=c.rendererOpts||{};return l.toDataURL(d,u.quality)}})(da)),da}var fa={},qu;function U1(){if(qu)return fa;qu=1;const t=sg();function e(o,s){const i=o.a/255,a=s+'="'+o.hex+'"';return i<1?a+" "+s+'-opacity="'+i.toFixed(2).slice(1)+'"':a}function n(o,s,i){let a=o+s;return typeof i<"u"&&(a+=" "+i),a}function r(o,s,i){let a="",c=0,l=!1,d=0;for(let u=0;u<o.length;u++){const f=Math.floor(u%s),h=Math.floor(u/s);!f&&!l&&(l=!0),o[u]?(d++,u>0&&f>0&&o[u-1]||(a+=l?n("M",f+i,.5+h+i):n("m",c,0),c=0,l=!1),f+1<s&&o[u+1]||(a+=n("h",d),d=0)):c++}return a}return fa.render=function(s,i,a){const c=t.getOptions(i),l=s.modules.size,d=s.modules.data,u=l+c.margin*2,f=c.color.light.a?"<path "+e(c.color.light,"fill")+' d="M0 0h'+u+"v"+u+'H0z"/>':"",h="<path "+e(c.color.dark,"stroke")+' d="'+r(d,l,c.margin)+'"/>',g='viewBox="0 0 '+u+" "+u+'"',b='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+g+' shape-rendering="crispEdges">'+f+h+`</svg>
9
+ `;return typeof a=="function"&&a(null,b),b},fa}var Ku;function $1(){if(Ku)return _n;Ku=1;const t=S1(),e=M1(),n=j1(),r=U1();function o(s,i,a,c,l){const d=[].slice.call(arguments,1),u=d.length,f=typeof d[u-1]=="function";if(!f&&!t())throw new Error("Callback required as last argument");if(f){if(u<2)throw new Error("Too few arguments provided");u===2?(l=a,a=i,i=c=void 0):u===3&&(i.getContext&&typeof l>"u"?(l=c,c=void 0):(l=c,c=a,a=i,i=void 0))}else{if(u<1)throw new Error("Too few arguments provided");return u===1?(a=i,i=c=void 0):u===2&&!i.getContext&&(c=a,a=i,i=void 0),new Promise(function(h,g){try{const m=e.create(a,c);h(s(m,i,c))}catch(m){g(m)}})}try{const h=e.create(a,c);l(null,s(h,i,c))}catch(h){l(h)}}return _n.create=e.create,_n.toCanvas=o.bind(null,n.render),_n.toDataURL=o.bind(null,n.renderToDataURL),_n.toString=o.bind(null,function(s,i,a){return r.render(s,a)}),_n}var H1=$1();const $o="w-full rounded-lg border border-border bg-background px-3 py-2.5 text-base text-foreground focus:outline-none focus:ring-2 focus:ring-ring sm:text-sm",Ge="appearance-none min-h-11 rounded-lg px-3 py-2 text-sm hover:bg-hover focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",On=`${Ge} bg-primary text-primary-foreground hover:opacity-90`;function q1(t){return t.serviceName||new URL(t.url).hostname}function zu(t){return t.includes("service:*")?"完整权限":t.includes("session.input")?"可操作":t.includes("session.view")?"只读":t.includes("route.use")?"仅中转":"自定义权限"}function K1({profile:t,subjectId:e}){return p.jsxs("details",{className:"mt-2 text-xs text-muted-foreground",children:[p.jsx("summary",{className:"cursor-pointer leading-relaxed",children:[t?.model||t?.hostname||t?.system,t?.route,`ID ${e.slice(-8)}`].filter(Boolean).join(" · ")}),p.jsxs("dl",{className:"mt-2 space-y-2 rounded-lg bg-surface-2 p-3",children:[[["设备型号",t?.model],["主机名称",t?.hostname],["操作系统",t?.system],["客户端",t?.client],["打开方式",t?.mode],["处理器",t?.cpu],["架构",t?.arch],["最近连接路径",t?.route],["首次记录",t?.firstSeenAt?new Date(t.firstSeenAt).toLocaleString():void 0],["最近连接",t?.lastSeenAt?new Date(t.lastSeenAt).toLocaleString():void 0],["设备标识",e]].filter(([,n])=>n).map(([n,r])=>p.jsxs("div",{children:[p.jsx("dt",{children:n}),p.jsx("dd",{className:"mt-0.5 select-text break-all text-foreground",children:r})]},n)),p.jsx("p",{className:"leading-relaxed",children:t?"系统、硬件与路径由设备报告;连接时间由服务记录。":"此设备尚未报告详情,更新客户端并重新连接后可补齐。"})]})]})}function z1(){const t=getComputedStyle(document.documentElement),e=t.getPropertyValue("--background").trim(),n=t.getPropertyValue("--foreground").trim(),r=o=>{const s=o.replace("#","");return parseInt(s.slice(0,2),16)*.299+parseInt(s.slice(2,4),16)*.587+parseInt(s.slice(4,6),16)*.114};if(!e||!n)throw new Error("Theme unavailable");return r(e)<r(n)?{dark:e,light:n}:{dark:n,light:e}}function W1({onConnect:t,onClose:e,onConnectWithPassword:n,onAddService:r,onOpenService:o,currentIdentity:s,currentServiceName:i,currentServiceId:a,currentServiceOrigin:c,hasBackup:l=!1,paired:d=!1,initialInvite:u,sessions:f=[],grants:h=[],onCreateInvite:g,onRevoke:m,onRename:b,loading:w=!1,loadError:I,onRetry:y}){const[v,L]=_.useState(!1),[k,T]=_.useState(""),[E,S]=_.useState({}),[C,N]=_.useState(""),[D,A]=_.useState(""),[x,P]=_.useState(!1),[R,O]=_.useState(!1),[j,M]=_.useState(!d),[B,F]=_.useState(!0),[U,H]=_.useState("read"),[q,K]=_.useState("all"),[W,V]=_.useState([]),[G,X]=_.useState(!1),[Z,ce]=_.useState(""),[Ie,Me]=_.useState(""),[ne,Ve]=_.useState(),[Yt,Zt]=_.useState(""),[je,Jt]=_.useState("services"),[Qt,Rn]=_.useState(),[ui,Bl]=_.useState(""),[yr,_l]=_.useState(!1),[Ol,br]=_.useState(),[pt,So]=_.useState(!1),[Tn,Dl]=_.useState([]),fi=h.filter($=>$.revokedAt===void 0&&(!$.expiresAt||$.expiresAt>Date.now())),hi=h.filter($=>!fi.includes($)),vr=[...new Set(fi.map($=>$.subjectId))].map($=>{const z=fi.filter(ue=>ue.subjectId===$);return{subjectId:$,grants:z,name:$===s?"此设备":z.find(ue=>ue.label)?.label||"未命名设备"}}).sort(($,z)=>+(z.subjectId===s)-+($.subjectId===s)),Pn=!Qt&&!yr&&d&&!j&&!R&&!u,lm=()=>{Rn(void 0),_l(!1),M(!1),O(!1),Ve(void 0),X(!1),N(""),A(""),br(void 0)},Fl=()=>{O(!0),M(!1),X(!1),N(""),A("")},dm=$=>$.subjectId===s?"此设备":$.label||"未命名设备",pi=()=>{pt?So(!1):e()},Sr=_.useRef(null);_.useEffect(()=>{const $=document.activeElement;return Sr.current?.focus(),()=>{$?.focus()}},[]),_.useEffect(()=>{let $=!1;if(Zt(""),ne)try{H1.toDataURL(ne.url,{width:220,margin:3,errorCorrectionLevel:"M",color:z1()}).then(z=>{$||Zt(z)}).catch(()=>{})}catch{}return()=>{$=!0}},[ne]);async function gi($){P(!0),N(""),A("");try{await t($);const{url:z,targetPeerId:ue,serviceName:qe,serviceOrigin:mi}=$;await Ct({id:ue,url:z,targetPeerId:ue,label:qe||new URL(z).host,serviceOrigin:mi,entryServiceId:$.entryServiceId}),M(!1),A("已连接。")}catch(z){$.routeOnly&&z instanceof Je?L(!0):N("暂时无法连接,请检查网络,或确认邀请是否仍然有效。")}finally{P(!1)}}async function um($){if($.preventDefault(),!g)return;N(""),A("");const z=W.filter(qe=>f.some(mi=>mi.sessionId===qe));if(U!=="full"&&q==="selected"&&!z.length){N("请选择至少一个 Session。");return}const ue=Ie?new Date(Ie).getTime():void 0;if(ue!==void 0&&(!Number.isFinite(ue)||ue<=Date.now())){N("授权到期时间必须晚于现在。");return}P(!0);try{const qe=await g({...l?{includeBackup:B}:{},scope:U==="full"||q==="all"?{kind:"service"}:{kind:"sessions",sessionIds:z},actions:U==="full"?["service:*"]:U==="write"?["session.view","session.input","session.resize"]:["session.view"],...Z.trim()?{label:Z.trim()}:{},...ue===void 0?{}:{expiresAt:ue}});Ve(qe)}catch(qe){N(qe instanceof Error&&qe.message.startsWith("无法分享备用连接:")?"无法分享备用连接:需要入口管理员授权。你也可以关闭“包含备用连接”,生成直连邀请。":"暂时无法生成邀请,请确认当前设备有授权管理权限。")}finally{P(!1)}}async function fm(){if(ne)try{await navigator.clipboard.writeText(ne.url),A("邀请链接已复制。")}catch{N("浏览器未允许复制,请长按下方链接复制。")}}const hm=E.title||(Qt?"设备名称":yr?je==="devices"?"授权详情":"连接详情":pt?"选择终端":R?"邀请设备":j&&d?"添加服务":d?"服务与设备":"连接 Termdock"),pm=!!E.back||!!Qt||yr||pt||d&&(j||R),gm=()=>{if(E.back){E.back();return}pt?So(!1):lm()},Ml=$=>$.every(z=>z.routeTargetServiceId)?`${new Set($.map(z=>z.routeTargetServiceId)).size} 台服务`:$.some(z=>z.scope.kind==="service")?"全部终端":`${new Set($.flatMap(z=>z.scope.kind==="sessions"?z.scope.sessionIds:[])).size} 个终端`;return Tc.createPortal(p.jsx("div",{className:"fixed inset-0 z-modal-backdrop flex items-end justify-center bg-[var(--app-backdrop)] backdrop-blur-sm sm:items-center sm:p-6","data-sidebar-gesture-ignore":!0,onMouseDown:$=>{$.target===$.currentTarget&&!x&&pi()},children:p.jsxs("div",{ref:Sr,tabIndex:-1,role:"dialog","aria-modal":"true","aria-labelledby":"federation-title",className:"z-modal-panel flex max-h-[calc(100dvh-env(safe-area-inset-top)-12px)] w-full max-w-lg flex-col overflow-hidden rounded-t-2xl border border-border bg-surface font-sans text-foreground shadow-xl outline-none sm:max-h-[min(720px,90dvh)] sm:rounded-2xl",onKeyDown:$=>{if($.key==="Escape"&&!x&&($.stopPropagation(),pi()),$.key!=="Tab")return;const z=Sr.current?.querySelectorAll('button:not(:disabled), input:not(:disabled), textarea:not(:disabled), select:not(:disabled), [tabindex="0"], summary');if(!z?.length){$.preventDefault();return}const ue=z[0],qe=z[z.length-1];$.shiftKey&&(document.activeElement===ue||document.activeElement===Sr.current)?($.preventDefault(),qe.focus()):!$.shiftKey&&(document.activeElement===qe||document.activeElement===Sr.current)&&($.preventDefault(),ue.focus())},children:[p.jsxs("header",{className:"shrink-0 border-b border-border px-5 pt-3",children:[p.jsxs("div",{className:"flex min-h-12 items-center gap-2 pb-2",children:[pm&&p.jsx("button",{type:"button",className:`${Ge} -ml-3 inline-flex w-11 items-center justify-center text-muted-foreground`,disabled:x,onClick:gm,"aria-label":pt?"取消选择终端":je==="devices"?"返回设备":"返回服务",children:p.jsx(qp,{size:20})}),p.jsx("h2",{id:"federation-title",className:"min-w-0 flex-1 text-base font-semibold",children:hm}),p.jsx("button",{type:"button",className:`${Ge} -mr-3 inline-flex w-11 items-center justify-center text-muted-foreground`,disabled:x,onClick:pi,"aria-label":"关闭",children:p.jsx(Yp,{size:20})})]}),Pn&&!E.title&&p.jsx("div",{className:"flex gap-6",role:"tablist","aria-label":"管理内容",children:[["services","服务"],["devices","设备"]].map(([$,z])=>p.jsxs("button",{type:"button",role:"tab","aria-selected":je===$,"aria-controls":`federation-${$}`,id:`federation-tab-${$}`,className:`min-h-11 border-b-2 px-1 text-sm transition ${je===$?"border-primary font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"}`,onClick:()=>{Jt($),X(!1),br(void 0),N(""),A("")},children:[z,$==="devices"&&vr.length>0&&p.jsx("span",{className:"ml-1.5 text-xs text-muted-foreground",children:vr.length})]},$))})]}),p.jsxs("div",{className:"min-h-0 overflow-y-auto overscroll-contain px-5 py-4 pb-[max(20px,env(safe-area-inset-bottom))]",children:[(Pn&&je==="services"||j&&!R&&!u)&&p.jsx(y1,{renderRelayServices:($,z)=>p.jsx(m1,{service:$,onBusyChange:z,onConnect:t,onConnectWithPassword:n}),renderRoutes:($,z)=>p.jsx(w1,{service:$,onBusyChange:z}),hideHeader:!0,initiallyAdding:j,current:a?{id:a,targetPeerId:a,url:c||location.origin,label:i||"当前服务"}:void 0,onNavigation:S,onBusyChange:P,onInvite:g?Fl:void 0,onOpen:async $=>{if(o)return o($);$.targetPeerId?await gi({...$,targetPeerId:$.targetPeerId,serviceName:$.label}):r&&await r($.url)},onAdd:async($,z)=>{if(r)return r($,z);await gi(Ls($))}}),Pn&&je==="devices"&&p.jsxs("section",{role:"tabpanel",id:"federation-devices","aria-labelledby":"federation-tab-devices",children:[p.jsx("p",{className:"mb-2 text-xs leading-relaxed text-muted-foreground",children:"可访问此服务的设备"}),w?p.jsxs("p",{role:"status",className:"flex items-center gap-2 py-5 text-sm text-muted-foreground",children:[p.jsx(De,{size:16,className:"animate-spin"}),"正在读取设备…"]}):p.jsxs("div",{className:"divide-y divide-border",children:[vr.map($=>p.jsxs("div",{className:"py-3",children:[p.jsxs("div",{className:"flex items-center gap-3",children:[p.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-surface-2 text-muted-foreground",children:/iPhone|iPad|Android|手机|平板/i.test($.grants.find(z=>z.label)?.label||($.subjectId===s?navigator.userAgent:""))?p.jsx(Xp,{size:19}):p.jsx(HE,{size:19})}),p.jsxs("div",{className:"min-w-0 flex-1",children:[p.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[p.jsx("p",{className:"truncate text-sm font-medium",children:$.name}),b&&(m||$.subjectId===s)&&p.jsx("button",{type:"button","aria-label":`重命名 ${$.name}`,className:"inline-flex h-9 w-9 shrink-0 appearance-none items-center justify-center rounded-lg bg-transparent text-muted-foreground hover:bg-surface-2",onClick:()=>{Rn($.subjectId),Bl($.grants.find(z=>z.label)?.label||"")},children:p.jsx(KE,{size:14})})]}),$.subjectId===s&&$.grants.find(z=>z.label)?.label&&p.jsx("p",{className:"truncate text-xs text-muted-foreground",children:$.grants.find(z=>z.label)?.label}),p.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[zu($.grants.flatMap(z=>z.actions))," · ",Ml($.grants)]})]}),m&&$.subjectId!==s&&Ol!==$.subjectId&&p.jsx("button",{type:"button",className:`${Ge} -mr-2 text-xs text-muted-foreground hover:text-destructive`,disabled:x,"aria-label":`撤销 ${$.name} 的访问权限`,onClick:()=>br($.subjectId),children:"撤销"})]}),p.jsx(K1,{profile:$.grants.find(z=>z.deviceProfile)?.deviceProfile,subjectId:$.subjectId}),Ol===$.subjectId&&p.jsxs("div",{className:"mt-3 rounded-lg border border-border bg-background p-3",children:[p.jsx("p",{className:"text-xs leading-relaxed",children:"撤销后,这台设备将断开连接,需重新邀请才能访问。"}),p.jsxs("div",{className:"mt-2 flex justify-end gap-2",children:[p.jsx("button",{type:"button",className:`${Ge} text-xs text-muted-foreground`,disabled:x,onClick:()=>br(void 0),children:"取消"}),p.jsx("button",{type:"button",className:`${Ge} text-xs text-destructive`,disabled:x,onClick:async()=>{P(!0),N("");try{for(const z of $.grants)await m?.(z.id);br(void 0),A("设备访问权限已撤销。")}catch{N("暂时无法撤销,请重试。")}finally{P(!1)}},children:"确认撤销"})]})]})]},$.subjectId)),vr.length===0&&!I&&p.jsxs("p",{className:"py-5 text-sm text-muted-foreground",children:["暂无设备授权。",g?"可通过邀请添加设备。":""]})]}),g&&p.jsxs("button",{type:"button",className:`${Ge} mt-4 inline-flex w-full items-center justify-center gap-2 border border-border text-sm`,disabled:x,onClick:Fl,children:[p.jsx(Gp,{size:16}),"邀请设备"]}),hi.length>0&&p.jsxs("details",{className:"mt-4 text-xs text-muted-foreground",children:[p.jsxs("summary",{className:"cursor-pointer py-2",children:["已失效的授权(",hi.length,")"]}),p.jsx("div",{className:"mt-1 space-y-2 border-l border-border pl-3",children:hi.map($=>p.jsxs("p",{className:"flex gap-3",children:[p.jsx("span",{className:"min-w-0 flex-1 truncate",children:dm($)}),p.jsx("span",{className:"shrink-0",children:$.revokedAt!==void 0?"已撤销":"已到期"})]},$.id))})]})]}),Qt&&p.jsxs("form",{className:"space-y-4",onSubmit:async $=>{$.preventDefault(),P(!0),N("");try{await b?.(Qt,ui.trim()),Rn(void 0)}catch{N("暂时无法保存设备名称,请重试。")}finally{P(!1)}},children:[p.jsxs("label",{className:"block space-y-2 text-sm",children:[p.jsx("span",{children:"设备名称"}),p.jsx("input",{autoFocus:!0,className:$o,maxLength:80,required:!0,value:ui,onChange:$=>Bl($.target.value),placeholder:"例如:我的 iPhone、办公室电脑"})]}),p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"为设备起一个容易辨认的名字,会同步显示在此服务的设备列表中。"}),p.jsx("button",{type:"submit",className:`${On} w-full`,disabled:x||!ui.trim(),children:x?"正在保存…":"保存名称"})]}),yr&&p.jsx("section",{className:"space-y-5",children:je==="devices"?vr.map($=>p.jsxs("div",{className:"space-y-3",children:[p.jsx("h3",{className:"text-sm font-medium",children:$.name}),p.jsxs("dl",{className:"space-y-3 rounded-xl bg-surface-2 p-3 text-xs",children:[p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"访问权限"}),p.jsxs("dd",{className:"mt-1",children:[zu($.grants.flatMap(z=>z.actions))," · ",Ml($.grants)]})]}),$.grants.map(z=>p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:z.routeTargetServiceId?"允许经此入口访问":z.scope.kind==="sessions"?"可访问终端":"有效期"}),p.jsx("dd",{className:"mt-1 leading-relaxed",children:z.routeTargetServiceId?z.routeTargetName||"指定服务":z.scope.kind==="sessions"?z.scope.sessionIds.map(ue=>f.find(qe=>qe.sessionId===ue)?.name||ue).join("、"):z.expiresAt?new Date(z.expiresAt).toLocaleString():"保留至撤销"}),z.routeTargetServiceId&&m&&p.jsx("button",{type:"button",className:`${Ge} mt-1 -ml-3 text-xs text-destructive`,disabled:x,onClick:async()=>{P(!0),N("");try{await m(z.id)}catch{N("暂时无法撤销,请重试。")}finally{P(!1)}},children:"撤销此中转权限"})]},z.id)),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"设备标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed text-muted-foreground select-text",children:$.subjectId})]})]})]},$.subjectId)):p.jsxs("dl",{className:"space-y-4 text-xs",children:[p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"当前服务"}),p.jsx("dd",{className:"mt-1 text-sm",children:i||"当前服务"})]}),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"服务标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed select-text",children:a})]}),p.jsxs("div",{children:[p.jsx("dt",{className:"text-muted-foreground",children:"本设备标识"}),p.jsx("dd",{className:"mt-1 break-all font-mono leading-relaxed select-text",children:s})]})]})}),u&&!R&&p.jsxs("section",{className:"space-y-5 py-1",children:[p.jsxs("div",{className:"flex items-center gap-3",children:[p.jsx("span",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-surface-2 text-muted-foreground",children:p.jsx(ri,{size:22})}),p.jsxs("div",{className:"min-w-0",children:[p.jsx("p",{className:"text-xs text-muted-foreground",children:"你受邀连接"}),p.jsx("p",{className:"mt-1 break-words text-base font-medium",children:q1(u)})]})]}),u.routeOnly&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"此邀请提供备用连接,目标服务仍会验证你的访问权限。"}),v?p.jsxs("form",{className:"space-y-3",onSubmit:async $=>{$.preventDefault(),P(!0),N("");try{await n?.(u,k)}catch(z){N(z instanceof Error?z.message:"暂时无法登录,请重试。")}finally{T(""),P(!1)}},children:[p.jsxs("label",{className:"block space-y-2 text-sm",children:[p.jsx("span",{children:"目标服务密码"}),p.jsx("input",{className:$o,type:"password",required:!0,autoFocus:!0,autoComplete:"current-password",value:k,onChange:$=>T($.target.value)})]}),p.jsx("button",{className:`${On} w-full`,disabled:x||!k,children:x?"正在登录…":"登录并连接"})]}):p.jsx("button",{type:"button",className:`${On} w-full text-sm`,disabled:x,onClick:()=>{gi(u)},children:x?"正在连接…":"接受邀请"})]}),R&&!pt&&p.jsx("section",{children:ne?p.jsxs("div",{className:"space-y-4 text-center",children:[p.jsx("p",{className:"text-sm font-medium",children:"用另一台设备扫描二维码"}),Yt?p.jsx("img",{src:Yt,width:220,height:220,className:"mx-auto max-w-full rounded-xl",alt:"设备邀请二维码"}):p.jsx("div",{className:"mx-auto flex h-48 w-48 items-center justify-center",children:p.jsx(De,{size:22,className:"animate-spin text-muted-foreground"})}),p.jsxs("p",{className:"text-xs leading-relaxed text-muted-foreground",children:["仅限一台设备使用 · ",new Date(ne.expiresAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," 前有效"]}),p.jsxs("button",{type:"button",className:`${On} inline-flex w-full items-center justify-center gap-2 text-sm`,onClick:()=>{fm()},children:[p.jsx(Wp,{size:16}),"复制邀请链接"]}),p.jsxs("details",{className:"text-left text-xs text-muted-foreground",children:[p.jsx("summary",{className:"cursor-pointer py-2",children:"查看链接"}),p.jsx("p",{className:"mt-2 select-all break-all",children:ne.url})]})]}):p.jsxs("form",{className:"space-y-5",onSubmit:um,children:[p.jsxs("fieldset",{children:[p.jsx("legend",{className:"mb-2 text-sm font-medium",children:"访问权限"}),p.jsx("div",{className:"space-y-2",children:[["read","仅查看","查看终端画面,不可输入命令"],["write","可操作","查看终端画面,并输入命令"],["full","完整访问","包括文件、设置和权限管理"]].map(([$,z,ue])=>p.jsxs("label",{className:`flex cursor-pointer items-center gap-3 rounded-xl border px-3 py-2.5 transition focus-within:ring-2 focus-within:ring-ring ${U===$?"border-primary bg-primary/10":"border-border hover:bg-surface-2"}`,children:[p.jsx("input",{type:"radio",name:"federation-permission",value:$,checked:U===$,onChange:()=>H($),className:"sr-only"}),p.jsx("span",{"aria-hidden":"true",className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border ${U===$?"border-primary bg-primary text-primary-foreground":"border-border bg-background"}`,children:U===$&&p.jsx(dl,{size:13,strokeWidth:3})}),p.jsxs("span",{className:"min-w-0",children:[p.jsx("span",{className:"block text-sm font-medium text-foreground",children:z}),p.jsx("span",{className:"mt-0.5 block text-xs leading-relaxed text-muted-foreground",children:ue})]})]},$))})]}),U!=="full"&&p.jsxs("fieldset",{children:[p.jsx("legend",{className:"mb-2 text-sm font-medium",children:"可访问的终端"}),p.jsxs("div",{className:"flex gap-2",children:[p.jsx("button",{type:"button","aria-pressed":q==="all",className:`${Ge} flex-1 appearance-none border text-sm ${q==="all"?"border-primary bg-primary/10 text-foreground":"border-border text-muted-foreground"}`,onClick:()=>K("all"),children:"全部终端"}),p.jsxs("button",{type:"button","aria-pressed":q==="selected",className:`${Ge} inline-flex flex-1 appearance-none items-center justify-center gap-1 border text-sm ${q==="selected"?"border-primary bg-primary/10 text-foreground":"border-border text-muted-foreground"}`,onClick:()=>{Dl(W),So(!0)},children:[q==="selected"?`已选 ${W.length} 个`:"选择终端",p.jsx(vn,{size:14})]})]}),q==="all"&&p.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"包括之后新建的终端。"})]}),U==="write"&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"终端命令可读写该系统用户有权访问的文件。"}),U==="full"&&p.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"拥有此服务的全部当前及未来权限。仅授予你完全信任的设备。"}),l&&p.jsxs("label",{className:"flex items-start gap-3 text-sm",children:[p.jsx("input",{type:"checkbox",className:"mt-0.5 h-4 w-4 accent-primary",checked:B,onChange:$=>F($.target.checked)}),p.jsxs("span",{children:["让新设备也能使用备用连接",p.jsx("span",{className:"mt-1 block text-xs leading-relaxed text-muted-foreground",children:"需要入口管理员授权;关闭后生成直接连接邀请。"})]})]}),p.jsxs("div",{children:[p.jsxs("button",{className:`${On} inline-flex w-full items-center justify-center gap-2 text-sm`,type:"submit",disabled:x||w,children:[x&&p.jsx(De,{size:16,className:"animate-spin"}),x?"正在生成…":"生成邀请"]}),p.jsxs("p",{className:"mt-2 text-center text-xs leading-relaxed text-muted-foreground",children:["链接 10 分钟内有效 · 访问权限",Ie?"按设定时间到期":"保留至撤销"]})]})]})}),pt&&p.jsxs("section",{children:[p.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"仅允许访问勾选的终端。"}),p.jsxs("div",{className:"space-y-1",children:[f.map($=>p.jsxs("label",{className:"flex min-h-12 cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm hover:bg-surface-2",children:[p.jsx("input",{type:"checkbox",className:"h-4 w-4 accent-primary",checked:Tn.includes($.sessionId),onChange:z=>Dl(z.target.checked?[...Tn,$.sessionId]:Tn.filter(ue=>ue!==$.sessionId))}),p.jsx("span",{className:"min-w-0 break-words",children:$.name})]},$.sessionId)),!f.length&&p.jsx("p",{className:"py-4 text-sm text-muted-foreground",children:"当前没有可共享的终端。"})]})]}),I&&p.jsxs("p",{role:"alert",className:"mt-4 text-sm text-destructive",children:[I,y&&p.jsx("button",{type:"button",className:`${Ge} ml-1 text-sm underline`,onClick:y,children:"重试"})]}),!E.title&&!j&&!Qt&&!yr&&!pt&&!ne&&p.jsxs("div",{className:"mt-4 border-t border-border pt-2",children:[p.jsxs("button",{type:"button",className:`${Ge} -ml-3 inline-flex items-center gap-1 bg-transparent text-xs text-muted-foreground`,"aria-expanded":Pn?void 0:G,onClick:()=>Pn?_l(!0):X($=>!$),children:[R?"有效期与备注":j?"手动连接":je==="devices"?"授权详情":"连接详情",Pn?p.jsx(vn,{size:14}):p.jsx(zp,{size:13,className:G?"rotate-180":""})]}),G&&p.jsxs("section",{className:"space-y-3 pb-1 pt-2",children:[R&&p.jsxs(p.Fragment,{children:[p.jsxs("label",{className:"block space-y-1 text-sm",children:[p.jsx("span",{children:"设备备注(可选)"}),p.jsx("input",{className:$o,value:Z,onChange:$=>ce($.target.value),placeholder:"例如:工作电脑"})]}),p.jsxs("label",{className:"block space-y-1 text-sm",children:[p.jsx("span",{children:"授权到期时间"}),p.jsx("input",{type:"datetime-local",className:$o,value:Ie,onChange:$=>Me($.target.value)})]})]}),!R&&s&&p.jsxs("p",{className:"break-all text-xs leading-relaxed text-muted-foreground",children:["本设备身份:",s]})]})]}),C&&p.jsx("p",{role:"alert",className:"mt-3 text-sm text-destructive",children:C}),D&&p.jsx("p",{role:"status",className:"mt-3 text-sm text-muted-foreground",children:D})]}),pt&&p.jsx("footer",{className:"shrink-0 border-t border-border px-5 pt-3 pb-[max(16px,env(safe-area-inset-bottom))]",children:p.jsxs("button",{type:"button",className:`${On} w-full text-sm`,disabled:!Tn.length,onClick:()=>{V(Tn),K("selected"),So(!1)},children:["使用所选终端(",Tn.length,")"]})})]})}),document.body)}const V1={background:"#1C1B1A",foreground:"#CECDC3",cursor:"#CECDC3",cursorAccent:"#1C1B1A",selectionBackground:"#403E3C",selectionForeground:"#CECDC3",selectionInactiveBackground:"#403E3C50",black:"#6F6E69",red:"#AF3029",green:"#66800B",yellow:"#AD8301",blue:"#205EA6",magenta:"#A02F6F",cyan:"#24837B",white:"#CECDC3",brightBlack:"#6F6E69",brightRed:"#D14D41",brightGreen:"#879A39",brightYellow:"#D0A215",brightBlue:"#4385BE",brightMagenta:"#CE5D97",brightCyan:"#3AA99F",brightWhite:"#FFFCF0"},G1={background:"#FFFCF0",foreground:"#100F0F",cursor:"#100F0F",cursorAccent:"#FFFCF0",selectionBackground:"#CECDC3",selectionForeground:"#100F0F",selectionInactiveBackground:"#CECDC350",black:"#100F0F",red:"#AF3029",green:"#66800B",yellow:"#AD8301",blue:"#205EA6",magenta:"#A02F6F",cyan:"#24837B",white:"#575653",brightBlack:"#6F6E69",brightRed:"#D14D41",brightGreen:"#879A39",brightYellow:"#D0A215",brightBlue:"#4385BE",brightMagenta:"#CE5D97",brightCyan:"#3AA99F",brightWhite:"#100F0F"};function X1(t){return t==="light"?G1:V1}const nc="termdock:open-services";function ig(){window.dispatchEvent(new Event(nc))}function Y1({client:t,initialSessionId:e}){const[n,r]=_.useState([]),[o,s]=_.useState(),i=_.useRef();_.useEffect(()=>{if(!e||i.current===e)return;const f=n.find(h=>h.sessionId===e||h.sourceSessionId===e);f&&(i.current=e,s(f))},[n,e]);const[a,c]=_.useState("正在读取已授权 Session"),[l,d]=_.useState(()=>document.documentElement.dataset.theme==="light"?"light":"dark");_.useEffect(()=>{const f=new MutationObserver(()=>d(document.documentElement.dataset.theme==="light"?"light":"dark"));return f.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>f.disconnect()},[]);const u=_.useRef(null);return _.useEffect(()=>{let f=!0;const h=async()=>{try{const m=await t.request({type:"session-list"});if(f){const b=m.items;r(b),s(w=>{if(!w)return c(b.length?"选择一个已授权 Session":"暂无已授权的在线 Session"),w;const I=b.find(y=>y.sessionId===w.sessionId);if(!I){c("Session 已移除或授权失效");return}return I.canWrite===w.canWrite&&I.canResize===w.canResize?w:I})}}catch{f&&c("目标不可达或授权已失效")}};h();const g=setInterval(()=>{h()},15e3);return()=>{f=!1,clearInterval(g)}},[t]),_.useEffect(()=>{if(!o||!u.current)return;let f=!1,h=0,g;const m=new wm({theme:X1(l),cursorBlink:o.canWrite,disableStdin:!o.canWrite,convertEol:!1}),b=new ym;m.loadAddon(b),m.open(u.current),o.canResize&&b.fit(),c("正在建立加密终端连接");const w=t.openSocket(`/api/terminal/${encodeURIComponent(o.sessionId)}/ws?flow=2`),I=()=>{f||!o.canResize||(b.fit(),w.readyState===1&&w.send(JSON.stringify({type:"resize",cols:m.cols,rows:m.rows})))};w.onopen=()=>c(o.canWrite?"读写":"只读"),w.onmessage=k=>{try{const T=JSON.parse(k.data);if(f)return;if(T.type==="connected"){g=typeof T.streamEpoch=="string"?T.streamEpoch:void 0,h=Number.isSafeInteger(T.replayLastSeq)?T.replayLastSeq:0,!o.canResize&&Number.isSafeInteger(T.cols)&&Number.isSafeInteger(T.rows)&&T.cols>0&&T.rows>0&&m.resize(T.cols,T.rows);const E=Array.isArray(T.replayChunks)?T.replayChunks.filter(S=>typeof S=="string").join(""):"";m.write((T.replayOutOfWindow?"\x1Bc":"")+E,I)}else T.type==="data"&&typeof T.data=="string"?m.write(T.data,()=>{f||(Number.isSafeInteger(T.seq)&&(h=Math.max(h,T.seq)),w.readyState===1&&Number.isSafeInteger(T.flowSeq)&&w.send(JSON.stringify({type:"output-ack",flowSeq:T.flowSeq,since:h,epoch:g})))}):T.type==="pty-size"&&!o.canResize&&Number.isSafeInteger(T.cols)&&Number.isSafeInteger(T.rows)&&T.cols>0&&T.rows>0?m.resize(T.cols,T.rows):T.type==="error"&&c("目标拒绝终端操作,请检查有效授权")}catch{c("终端数据无效"),w.close()}},w.onclose=()=>c("连接已断开;画面已过期,重新选择 Session 可重连"),w.onerror=()=>c("目标不可达或授权不足");const y=m.onData(k=>{o.canWrite&&w.readyState===1&&w.send(JSON.stringify({type:"input",data:k}))}),v=setInterval(()=>{w.readyState===1&&w.send(JSON.stringify({type:"ping"}))},2e4),L=new ResizeObserver(I);return L.observe(u.current),()=>{f=!0,clearInterval(v),L.disconnect(),y.dispose(),w.onclose=null,w.onerror=null,w.close(),m.dispose()}},[t,o,l]),p.jsxs("div",{className:"flex h-dvh flex-col bg-background text-foreground",children:[p.jsxs("div",{className:"flex items-center gap-3 border-b border-border p-3 text-sm",children:[p.jsxs("span",{className:"min-w-0 flex-1",children:["已授权 Session · ",a]}),p.jsx("button",{type:"button",onClick:ig,className:"min-h-11 shrink-0 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2",children:"服务与设备"})]}),p.jsx("div",{className:"flex flex-wrap gap-2 p-2",children:n.map(f=>p.jsxs("button",{className:"rounded border border-border px-3 py-2 text-sm hover:bg-surface-2",onClick:()=>s({...f}),children:[f.name," · ",f.canWrite?"读写":"只读"]},`${t.targetPeerId}:${f.sessionId}`))}),p.jsx("div",{ref:u,className:"min-h-0 flex-1 overflow-auto p-2"})]})}function Z1(t){const e=t.serviceLabel?.trim();if(!e||/^https?:\/\//i.test(e)||e===t.serviceOrigin)return"远端服务";try{const n=new URL(t.serviceOrigin??"");if(e===n.host||e===n.hostname)return"远端服务"}catch{}return e}function rc(t){if(!t.startsWith("remote:"))return null;const e=t.slice(7).split(":");if(e.length!==2)return null;try{const n=decodeURIComponent(e[0]),r=decodeURIComponent(e[1]);return!r||new URL(n).origin!==n||!/^https?:/.test(n)?null:{origin:n,id:r}}catch{return null}}class J1{constructor(e){this.source=e,this.peers={state:e.peerProtocol==="unsupported"?"unsupported":e.readPeers?"loading":"unavailable",checkedAt:null}}source;local=null;remote=[];peers;localInFlight=null;peerInFlight=null;listeners=new Set;disposed=!1;peerTimer;lastPeerAttempt=-1/0;generation=0;localHealthy=!1;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}snapshot(){if(!this.local)return null;const e=new Map;for(const n of this.local.groups)for(const r of n.remoteSessions??[]){const o=rc(r.sessionId);o&&o.origin!==this.source.origin&&o.origin!==this.source.peerOrigin&&e.set(r.sessionId,{...r,status:"offline",serviceConnected:!1})}for(const n of this.remote)e.set(n.sessionId,n);for(const n of this.local.sessions)e.set(n.sessionId,n);return{groups:this.local.groups.map(n=>({...n,remoteSessions:n.remoteSessions?.map(r=>e.get(r.sessionId)??r)})),sessions:[...e.values()],peers:this.peers,capabilities:this.local.capabilities}}emit(){if(this.disposed||!this.localHealthy)return;const e=this.snapshot();if(e)for(const n of this.listeners)n(e)}load(){if(this.disposed)return Promise.reject(new Error("协作连接已切换,请重新加载"));if(this.localInFlight)return this.localInFlight;this.refreshPeers();const e=this.generation,n=Promise.resolve().then(()=>this.source.readLocal()).then(r=>{if(this.disposed)throw new Error("协作连接已切换,请重新加载");if(e!==this.generation)return this.load();if(!Array.isArray(r.groups)||!Array.isArray(r.sessions))throw new Error("协作会话响应无效,请更新服务后重试");return this.local=r,this.localHealthy=!0,this.emit(),this.snapshot()}).catch(r=>{throw e===this.generation&&(this.localHealthy=!1),r}).finally(()=>{this.localInFlight===n&&(this.localInFlight=null)});return this.localInFlight=n,n}invalidate(){this.generation++,this.localInFlight=null,this.localHealthy=!1}refreshPeers(e=!1){if(this.disposed||!this.source.readPeers||this.peerInFlight||!e&&Date.now()-this.lastPeerAttempt<2e3)return;this.lastPeerAttempt=Date.now(),this.peers.checkedAt||(this.peers={state:"loading",checkedAt:null}),this.emit();const n=this.source.readPeers;this.peerInFlight=Promise.race([Promise.resolve().then(()=>n()),new Promise((r,o)=>{this.peerTimer=setTimeout(()=>o(new Error("服务端协作目录加载超时,请检查服务连接")),2e4)})]).then(r=>{if(this.disposed)return;const o=r.origin===this.source.origin||!!this.source.peerOrigin&&r.origin===this.source.peerOrigin;if(!Array.isArray(r.sessions)||this.source.peerProtocol==="v2"&&(r.protocolVersion!==2||!o)||r.origin&&!o||r.protocolVersion!==void 0&&r.protocolVersion!==2)throw new Error("协作目录响应与当前服务不匹配,请升级服务后重试");this.remote=r.sessions.filter(i=>{const a=rc(i.sessionId);return a&&a.origin!==this.source.origin&&a.origin!==this.source.peerOrigin});const s=r.services?.filter(i=>i.origin!==this.source.origin&&i.origin!==this.source.peerOrigin);this.peers={state:s?.some(i=>!i.connected)?"partial":"ready",checkedAt:Date.now(),services:s}}).catch(r=>{this.disposed||(this.remote=this.remote.map(o=>({...o,status:"offline",serviceConnected:!1})),this.peers={state:"error",checkedAt:Date.now(),error:r instanceof Error?r.message:"跨服务会话加载失败"})}).finally(()=>{clearTimeout(this.peerTimer),this.peerInFlight=null,this.emit()})}dispose(){this.disposed=!0,clearTimeout(this.peerTimer),this.listeners.clear(),this.local=null,this.remote=[]}}async function Q1(t,e){const n=navigator.serviceWorker?.controller;if(!n)return null;const r=new MessageChannel;return new Promise(o=>{const s=a=>{clearTimeout(i),r.port1.close(),o(a)},i=setTimeout(()=>s(null),5e3);r.port1.onmessage=a=>{try{const c=new URL(a.data.url,location.origin);s(c.origin===location.origin&&/^\/__termdock-download\/[a-f0-9-]{36}$/.test(c.pathname)?c.href:null)}catch{s(null)}},r.port1.onmessageerror=()=>s(null);try{n.postMessage({type:"termdock:prepare-download",blob:t,filename:e},[r.port2])}catch{s(null)}})}const eA=4*1024*1024,tA=256*1024,nA=1440*6e4;let tr=0,Wu;function hl(){return typeof indexedDB>"u"?Promise.resolve(null):Wu??=new Promise(t=>{const e=indexedDB.open(`termdock-terminal-snapshots:${Kn}`,1);e.onupgradeneeded=()=>e.result.createObjectStore("snapshots",{keyPath:"id"}),e.onerror=()=>t(null),e.onblocked=()=>t(null),e.onsuccess=()=>{e.result.onversionchange=()=>{e.result.close(),Wu=void 0},t(e.result)}})}function oc(t){return!!t&&t.version===1&&typeof t.epoch=="string"&&t.epoch.length>0&&Number.isSafeInteger(t.cols)&&t.cols>0&&Number.isSafeInteger(t.rows)&&t.rows>0&&Number.isSafeInteger(t.seq)&&t.seq>0&&typeof t.data=="string"&&t.data.length*2<=tA&&t.savedAt<=Date.now()&&Date.now()-t.savedAt<nA}async function ZI(t){const e=tr;try{const n=await hl();return!n||e!==tr?null:await new Promise(r=>{const o=n.transaction("snapshots").objectStore("snapshots").get(t);o.onerror=()=>r(null),o.onsuccess=()=>r(e===tr&&oc(o.result)?o.result:null)})}catch{return null}}async function JI(t){const e=tr;if(oc(t))try{const n=await hl();if(!n||e!==tr)return;await new Promise(r=>{const o=n.transaction("snapshots","readwrite"),s=o.objectStore("snapshots");s.put(t);const i=s.getAll();i.onsuccess=()=>{let a=0,c=0;for(const l of i.result.sort((d,u)=>u.savedAt-d.savedAt))a+=l.data.length*2,(++c>32||a>eA||!oc(l))&&s.delete(l.id)},o.oncomplete=()=>r(),o.onerror=o.onabort=()=>r()})}catch{}}async function ag(){tr+=1;try{(await hl())?.transaction("snapshots","readwrite").objectStore("snapshots").clear()}catch{}}typeof window<"u"&&window.addEventListener("auth:unauthorized",()=>{ag()});const wt=new Map,Ht=new Map,rA=32*1024*1024,oA=8*1024*1024,sA=48;let $r=0,sc=0;function pl(){sc+=1,wt.clear(),$r=0;for(const t of Ht.values())t.controller.abort();Ht.clear()}typeof window<"u"&&window.addEventListener("auth:unauthorized",pl);function iA(t,e){const n=wt.get(t);if(n&&($r-=n.blob.size,wt.delete(t)),!(e.blob.size>oA))for(wt.set(t,e),$r+=e.blob.size;wt.size>sA||$r>rA;){const r=wt.keys().next().value;$r-=wt.get(r).blob.size,wt.delete(r)}}async function cg(t,e={}){const n=new URL(t,typeof location<"u"?location.origin:"http://localhost");if(!/^\/api\/terminal\/fs\/(read|blob)$/.test(n.pathname))return fetch(t,{signal:e.signal});if(e.signal?.aborted)throw e.signal.reason??new DOMException("Aborted","AbortError");n.searchParams.delete("requestSlotId"),n.searchParams.delete("action"),n.searchParams.sort();const r=n.href;let o=Ht.get(r);if(!o){const i=new AbortController,a=sc,c=wt.get(r),l=new Headers,d=c?.headers.get("ETag");d&&l.set("If-None-Match",d);const u=setTimeout(()=>i.abort(new DOMException("File preview timed out. Please retry.","TimeoutError")),e.timeoutMs??15e3),f={controller:i,readers:0,promise:Promise.resolve(null)};f.promise=(async()=>{const h=await fetch(r,{headers:l,signal:i.signal,cache:"no-cache"});let g;return h.status===304&&c?g=c:g={blob:await h.blob(),headers:new Headers(h.headers),status:h.status},sc===a&&!i.signal.aborted&&g.status===200&&g.headers.has("ETag")&&iA(r,g),h.status===401&&pl(),g})().finally(()=>{clearTimeout(u),Ht.get(r)===f&&Ht.delete(r)}),o=f,Ht.set(r,o)}const s=o;return s.readers+=1,new Promise((i,a)=>{let c=!1;const l=()=>c?!1:(c=!0,e.signal?.removeEventListener("abort",d),s.readers-=1,s.readers===0&&Ht.get(r)===s&&(Ht.delete(r),s.controller.abort()),!0),d=()=>{l()&&a(e.signal?.reason??new DOMException("Aborted","AbortError"))};if(e.signal?.addEventListener("abort",d,{once:!0}),e.signal?.aborted){d();return}s.promise.then(u=>{l()&&i(new Response(u.blob,{status:u.status,headers:u.headers}))},u=>{l()&&a(u)})})}const gl="auth:unauthorized";let Hn=null;class Ae extends Error{constructor(e,n,r){super(e),this.status=n,this.code=r,this.name="TerminalApiError"}status;code}async function aA(){const t=await fetch("/api/terminal/update");if(!t.ok)throw new Ae("Failed to load update state",t.status);return t.json()}async function cA(){const t=await Y(),e=await fetch("/api/terminal/update/check",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Ae("Failed to check for updates",e.status);return e.json()}async function lA(){const t=await Y(),e=await fetch("/api/terminal/update/restart",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to restart Termdock"}));throw new Ae(n.error||"Failed to restart Termdock",e.status)}return e.json()}async function dA(){const t=await fetch("/api/terminal/quota");if(!t.ok)throw new Ae("Failed to fetch quota",t.status);return t.json()}async function uA(){const t=await Y(),e=await fetch("/api/terminal/quota/refresh",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Ae("Failed to refresh quota",e.status);return e.json()}const Cn=8e3,lg=6e4,fA=32e3,dg=125e3,ft=1e4,nr=45e3,ug=8e3,fg=8e3,hg=15e3,hA=1e4,fr=5e3;let pA=0;const es=[];let ha=!1;function Mt(t,e={}){if(typeof window>"u")return;const n=JSON.stringify({level:t==="error"||t==="timeout_or_abort"||t==="response_body_timeout"||t==="response_body_parse_error"?"warn":"info",message:`DIFF_API ${t}`,data:{seq:++pA,ts:Date.now(),...e}});es.push(n),gA()}async function gA(){if(!ha){ha=!0;try{for(;es.length>0;){const t=es[0];try{await fetch("/api/client-log",{method:"POST",headers:{"Content-Type":"application/json"},body:t,keepalive:!0}),es.shift()}catch{break}}}finally{ha=!1}}}function ml(t,e,n){const r=new AbortController;let o=setTimeout(()=>{r.abort(new DOMException(n,"TimeoutError"))},e);const s=()=>r.abort(t?.reason);return t&&(t.aborted?s():t.addEventListener("abort",s,{once:!0})),{signal:r.signal,cleanup:()=>{o&&(clearTimeout(o),o=null),t?.removeEventListener("abort",s)}}}async function pe(t,e,n,r){const{signal:o,cleanup:s}=ml(e?.signal??void 0,n,r);try{return await fetch(t,{...e,signal:o})}catch(i){throw i instanceof DOMException&&i.name==="TimeoutError"?new Error(r):i}finally{s()}}async function pg(t,e,n){let r=null;const o=new Promise((s,i)=>{r=setTimeout(()=>i(new Error(n)),e)});try{return await Promise.race([t.text(),o])}finally{r&&clearTimeout(r)}}async function hr(t,e,n){const r=await pg(t,e,n);return JSON.parse(r)}if(typeof window<"u"&&!window.__termdockFetchPatched){window.__termdockFetchPatched=!0;const t=window.fetch.bind(window);window.fetch=async(...e)=>{const n=await t(...e);if(n.status===401){Hn=null,Al();try{window.dispatchEvent(new CustomEvent(gl))}catch{}}return n}}async function Y(){if(Hn)return Hn;const t=await pe("/api/csrf-token",void 0,ug,"CSRF token request timed out");if(!t.ok)throw new Error("Failed to get CSRF token");const e=await hr(t,fr,"CSRF token response timed out");if(!e.csrfToken)throw new Error("Invalid CSRF token response");return Hn=e.csrfToken,Hn}function wl(){Al(),Hn=null}const mA=2e4,Vu=8e3,wA=1500,gg=250,me=new Map,yl=new Map,yA=24,bA=40,vA=40;function SA(t){return t.retryState.retryCount>=2||t.pendingInputs.length>=vA?"congested":t.retryState.retryCount>=1||t.pendingInputs.length>=8?"degraded":"good"}function Gu(t){if(t.pendingInputs.length===0||t.ws.readyState!==WebSocket.OPEN)return;const e=t.pendingInputs.splice(0);for(const n of e)try{t.ws.send(JSON.stringify({type:"input",data:n}))}catch{}}function mg(t){if(t.ws.readyState!==WebSocket.OPEN)return;const e=SA(t);if(e==="good"){Gu(t);return}if(t.inputFlushTimer)return;const n=e==="congested"?bA:yA;t.inputFlushTimer=setTimeout(()=>{t.inputFlushTimer=null,Gu(t)},n)}const Zr=new Map;function xA(t,e,n,r){const o=Zr.get(t);o&&(Zr.delete(t),e?o.resolve({success:!0,layout:n}):o.reject(new Error(r||"Tmux action failed")))}const Un=new Map;function EA(t,e,n,r){const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/terminal/${t}/ws`,i=new URLSearchParams({flow:"2",transport:"tmux-client",active:yl.get(t)===!1?"0":"1"});e>0&&i.set("since",String(e)),n&&i.set("epoch",n);const a=r??Un.get(t);return a&&(i.set("cols",String(a.cols)),i.set("rows",String(a.rows))),`${s}?${i}`}const ic=new Map,ac=new Map;function AA(t,e,n){ic.set(t,e),ac.set(t,n)}function kA(t){const e=me.get(t);return e?.streamEpoch&&e.appliedSeq===e.lastSeq&&e.lastSeq>0?{seq:e.lastSeq,epoch:e.streamEpoch}:null}async function CA(t){const e=await Y(),n=await fetch("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({cols:t.cols||80,rows:t.rows||24,mode:t.mode||"shell",tmuxSessionName:t.tmuxSessionName,cwd:t.cwd,termType:t.termType})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to create terminal"}));throw new Error(r.error||"Failed to create terminal session")}return n.json()}function IA(t,e,n,r={}){const{maxRetries:o=10,initialRetryDelay:s=1e3,maxRetryDelay:i=2e4,connectionTimeout:a=15e3}=r,c={maxRetries:o,initialDelayMs:s,maxDelayMs:i,connectionTimeoutMs:a,retryCount:0,retryTimeout:null,connectionTimeoutId:null,isClosed:!1,isSuspended:!1};let l=null,d=ic.get(t)??0,u=ac.get(t);ac.delete(t),ic.delete(t);const f=[];let h=!1,g=null;const m=new WeakSet,b=()=>{c.retryTimeout&&(clearTimeout(c.retryTimeout),c.retryTimeout=null),c.connectionTimeoutId&&(clearTimeout(c.connectionTimeoutId),c.connectionTimeoutId=null),g&&(clearTimeout(g),g=null)},w=k=>{k.wakeProbe&&(clearTimeout(k.wakeProbe.timer),k.wakeProbe=void 0),k.heartbeatTimer&&(clearInterval(k.heartbeatTimer),k.heartbeatTimer=null),k.pongTimer&&(clearTimeout(k.pongTimer),k.pongTimer=null),k.inputFlushTimer&&(clearTimeout(k.inputFlushTimer),k.inputFlushTimer=null)},I=k=>{w(k),k.heartbeatTimer=setInterval(()=>{if(k.ws.readyState===WebSocket.OPEN){try{k.ws.send(JSON.stringify({type:"ping"}))}catch{}k.pongTimer&&clearTimeout(k.pongTimer),k.pongTimer=setTimeout(()=>{if(Date.now()-k.lastInboundAt>=Vu){h=!0,w(k);try{k.ws.close()}catch{}L(new Error("WebSocket heartbeat timeout"),!1)}},Vu)}},mA)},y=()=>{if(c.isClosed=!0,b(),l){w(l),me.delete(t);try{l.ws.close()}catch{}l=null}},v=()=>{if(c.isClosed)return;if(l){m.add(l.ws),w(l);try{l.ws.close()}catch{}}const k=EA(t,d,u,r.getDimensions?.()),T=Up(k);h=!1,c.connectionTimeoutId=setTimeout(()=>{T.readyState!==WebSocket.OPEN&&(h=!0,T.close(),L(new Error("WebSocket connection timeout"),!1))},a);const E={ws:T,onEvent:e,onError:n,reconnectNow:S=>{if(!c.isClosed&&(c.isSuspended=!1,!g)){if(b(),l){m.add(l.ws),w(l);try{l.ws.close()}catch{}}S?.silent||e({type:"reconnecting",attempt:Math.min(c.retryCount+1,o),maxAttempts:o}),c.retryCount=Math.min(c.retryCount+1,o),h=!0,g=setTimeout(()=>{g=null,h=!1,v()},0)}},suspendReconnect:()=>{c.isClosed||(c.isSuspended=!0,c.retryTimeout&&(clearTimeout(c.retryTimeout),c.retryTimeout=null))},retryState:c,lastSeq:d,pendingInputs:f,inputFlushTimer:null,heartbeatTimer:null,pongTimer:null,lastInboundAt:Date.now(),inboundSequence:0};T.onopen=()=>{c.isClosed||m.has(T)||h||(b(),c.retryCount=0,E.lastInboundAt=Date.now(),E.inboundSequence+=1,I(E),mg(E))},T.onmessage=S=>{if(!(c.isClosed||m.has(T)||h)){E.lastInboundAt=Date.now(),E.inboundSequence+=1;try{const C=JSON.parse(S.data);if(E.wakeProbe&&me.get(t)===E){const D=E.wakeProbe;E.wakeProbe=void 0,clearTimeout(D.timer);for(const A of D.listeners)A()}if(C.type==="pong"){E.pongTimer&&(clearTimeout(E.pongTimer),E.pongTimer=null);return}if(C.type==="tmux-result"&&C.reqId){xA(C.reqId,C.success!==!1,C.layout,C.error);return}if(C.type==="tmux-layout"&&C.layout){e({type:"tmux-layout",layout:C.layout});return}if(C.type==="tmux-screen-sync"&&Array.isArray(C.chunks)){e({type:"tmux-screen-sync",chunks:C.chunks.filter(D=>typeof D=="string"),cols:typeof C.cols=="number"?C.cols:void 0,rows:typeof C.rows=="number"?C.rows:void 0,generation:typeof C.generation=="number"?C.generation:void 0});return}if(C.type==="active-program"){e({type:"active-program",activeProgram:C.activeProgram,activeProgramRaw:C.activeProgramRaw,activeProgramSource:C.activeProgramSource});return}if(C.type==="cwd"){e({type:"cwd",cwd:C.cwd});return}if(C.type==="agent-status"){e({type:"agent-status",agentStatus:C.agentStatus??null,agentIndicator:C.agentIndicator??null,agentStatusDetail:C.agentStatusDetail??null,agent:C.agent??null,agentMessage:C.agentMessage??null,agentNativeSessionId:C.agentNativeSessionId??null,agentResumeRecovered:C.agentResumeRecovered===!0,agentRich:C.agentRich===!0,agentActivity:typeof C.agentActivity=="number"?C.agentActivity:0,agentCwd:C.agentCwd??null,reviewed:typeof C.reviewed=="boolean"?C.reviewed:null});return}if(C.type==="git-status"){e({type:"git-status",gitStatus:C.gitStatus??null});return}if(C.type==="quota-status"&&Array.isArray(C.providers)){window.dispatchEvent(new CustomEvent("termdock:quota-update",{detail:C.providers}));return}if(C.type==="focus-mode"){e({type:"focus-mode",focusTrackingRequested:C.focusTrackingRequested===!0});return}if(C.type==="resize-ack"){e({type:"resize-ack",seq:typeof C.seq=="number"?C.seq:void 0,cols:typeof C.cols=="number"?C.cols:void 0,rows:typeof C.rows=="number"?C.rows:void 0,ok:C.ok!==!1,error:typeof C.error=="string"?C.error:void 0,screenSyncPending:C.screenSyncPending===!0,screenSyncGeneration:typeof C.screenSyncGeneration=="number"?C.screenSyncGeneration:void 0});return}if(C.type==="pty-size"){e({type:"pty-size",cols:typeof C.cols=="number"?C.cols:void 0,rows:typeof C.rows=="number"?C.rows:void 0,source:typeof C.source=="string"?C.source:void 0});return}if(C.type==="shell-title"){e({type:"shell-title",title:typeof C.title=="string"?C.title:""});return}if(C.type==="prompt-state"){e({type:"prompt-state",state:C.state==="running"?"running":"idle",exitCode:typeof C.exitCode=="number"?C.exitCode:void 0});return}const N=C;if(N.type==="connected"){E.appliedSeq=void 0,u=N.streamEpoch,E.streamEpoch=u,E.outputProtocol=N.outputProtocol,typeof N.replayLastSeq=="number"&&N.replayLastSeq>=0&&(d=N.replayLastSeq,E.lastSeq=d),e(N),wg(t,yl.get(t)??!0);return}if(N.type==="exit"){y(),e(N);return}if(N.type==="data"){if(E.appliedSeq=void 0,typeof N.seq=="number"&&N.seq<=d)return;typeof N.flowSeq=="number"&&(E.flowSeq=N.flowSeq)}e(N),N.type==="data"&&typeof N.seq=="number"&&Number.isFinite(N.seq)&&N.seq>d&&(d=N.seq,E.lastSeq=d)}catch(C){n?.(C,!1)}}},T.onerror=()=>{c.isClosed||m.has(T)||h||(b(),w(E),h||(h=!0,L(new Error("WebSocket connection error"),!1)))},T.onclose=S=>{if(!(c.isClosed||m.has(T)||h)){if(S.code===Ep&&S.reason===Ap){E.reconnectNow({silent:!0});return}if(b(),w(E),h=!0,S.code===4001){console.warn("[Terminal] WS 4001: Session not found on server",{code:S.code,reason:S.reason,stack:new Error().stack}),L(new Error("Session not found on server"),!0);return}if(S.code===4003||S.code===4401){try{window.dispatchEvent(new CustomEvent(gl))}catch{}L(new Error("Authentication required"),!0);return}L(new Error("WebSocket connection closed"),!1)}},l=E,me.set(t,l)},L=(k,T)=>{if(!c.isClosed)if(T)n?.(k,!0),y();else{c.retryCount=Math.min(c.retryCount+1,Math.max(1,o));const E=Math.min(s*Math.pow(2,c.retryCount-1),i);if(e({type:"reconnecting",attempt:c.retryCount,maxAttempts:o}),c.isSuspended)return;c.retryTimeout=setTimeout(()=>{c.isClosed||v()},E)}};return v(),y}async function RA(t,e){const n=me.get(t);if(n){if(n.ws.readyState===WebSocket.OPEN){n.pendingInputs.push(e),mg(n);return}if(n.ws.readyState===WebSocket.CONNECTING){n.pendingInputs.push(e);return}}const r=await Y(),o=await fetch(`/api/terminal/${t}/input`,{method:"POST",headers:{"Content-Type":"text/plain","X-XSRF-TOKEN":r},body:e});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to send input"}));throw new Error(s.error||"Failed to send terminal input")}}function TA(t,e,n={}){const r=me.get(t);if(!r)return!1;if(r.retryState.isSuspended=!1,r.ws.readyState!==WebSocket.OPEN)return r.reconnectNow(),!0;const o=n.visible?gg:wA,s=Date.now()+o,i=r.wakeProbe,a=i?.listeners??new Set;if(e&&a.add(e),i&&i.deadline<=s)return!0;i&&clearTimeout(i.timer);const c=setTimeout(()=>{me.get(t)!==r||r.retryState.isClosed||(r.wakeProbe=void 0,r.reconnectNow())},o);if(r.wakeProbe={timer:c,listeners:a,deadline:s},i)return!0;try{r.ws.send(JSON.stringify({type:"ping"}))}catch{clearTimeout(c),r.wakeProbe=void 0,r.reconnectNow()}return!0}function PA(t){const e=me.get(t);return e?(e.reconnectNow(),!0):!1}function NA(){for(const t of me.values())t.suspendReconnect()}function LA(t,e,n){const r=me.get(t);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"focus",focused:e,reason:n}))}catch{}}function wg(t,e){yl.set(t,e);const n=me.get(t);!n||n.ws.readyState!==WebSocket.OPEN||n.outputProtocol!==2||n.ws.send(JSON.stringify({type:"output-subscription",active:e,since:n.lastSeq,epoch:n.streamEpoch}))}function BA(t){const e=me.get(t);!e||e.ws.readyState!==WebSocket.OPEN||e.outputProtocol!==2||(e.appliedSeq=e.lastSeq,!(!e.flowSeq||e.flowSeq===e.acknowledgedFlowSeq)&&(e.acknowledgedFlowSeq=e.flowSeq,e.ws.send(JSON.stringify({type:"output-ack",flowSeq:e.flowSeq,since:e.appliedSeq,epoch:e.streamEpoch}))))}function _A(t,e,n){const r=me.get(t);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"viewing",viewing:e,reason:n}))}catch{}}function cc(t){const e=me.get(t);if(!(!e||e.ws.readyState!==WebSocket.OPEN))try{e.ws.send(JSON.stringify({type:"agent-review-ack"}))}catch{}}function OA(t,e,n){const r=me.get(t);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"flow-control",paused:e,reason:n}))}catch{}}async function DA(t,e,n,r){Number.isFinite(e)&&Number.isFinite(n)&&e>=1&&n>=1&&(Un.delete(t),Un.set(t,{cols:Math.floor(e),rows:Math.floor(n)}),Un.size>256&&Un.delete(Un.keys().next().value));const o=me.get(t);if(o&&o.ws.readyState===WebSocket.OPEN)try{o.ws.send(JSON.stringify({type:"resize",cols:e,rows:n,seq:r}));return}catch{}const s=await Y(),i=await fetch(`/api/terminal/${t}/resize`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":s},body:JSON.stringify({cols:e,rows:n,seq:r})});if(!i.ok){const c=await i.json().catch(()=>({error:"Failed to resize terminal"}));throw new Error(c.error||"Failed to resize terminal")}const a=await i.json().catch(()=>({success:!0}));if(a?.success===!1||a?.ok===!1)throw new Error(a?.error||"Failed to resize terminal")}async function FA(t,e){const n=me.get(t);if(n&&n.ws.readyState===WebSocket.OPEN)return e.action==="scroll"?(n.ws.send(JSON.stringify({type:"tmux",...e})),{success:!0}):new Promise((s,i)=>{const a=Math.random().toString(36).substring(7);Zr.set(a,{resolve:s,reject:i}),n.ws.send(JSON.stringify({type:"tmux",reqId:a,...e})),setTimeout(()=>{Zr.has(a)&&(Zr.delete(a),i(new Error("Tmux action timed out")))},3e4)});const r=await Y(),o=await fetch(`/api/terminal/${t}/tmux`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(e)});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to execute tmux action"}));throw new Error(s.error||"Failed to execute tmux action")}return o.json()}async function MA(t){const e=me.get(t);if(e){e.retryState.isClosed=!0;try{e.ws.close()}catch{}me.delete(t)}const n=await Y(),r=await fetch(`/api/terminal/${t}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":n}});if(r.status!==404&&!r.ok){const o=await r.json().catch(()=>({error:"Failed to close terminal"}));throw new Error(o.error||"Failed to close terminal")}}async function jA(t,e){const n=me.get(t);if(n){n.retryState.isClosed=!0;try{n.ws.close()}catch{}me.delete(t)}const r=await Y(),o=await fetch(`/api/terminal/${t}/restart`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify({...e.cwd?{cwd:e.cwd}:{},cols:e.cols??80,rows:e.rows??24,mode:e.mode,tmuxSessionName:e.tmuxSessionName})});if(!o.ok){const s=await o.json().catch(()=>({error:"Failed to restart terminal"}));throw new Error(s.error||"Failed to restart terminal session")}return o.json()}async function UA(t){const e=await pe(`/api/terminal/${t}/health`,{method:"GET"},fg,"Terminal health check timed out");if(!e.ok){if(e.status===404)return{healthy:!1,sessionId:t};const n=await hr(e,fr,"Terminal health error response timed out").catch(()=>({error:"Failed to check terminal health"}));throw new Error(n.error||"Failed to check terminal health")}return hr(e,fr,"Terminal health response timed out")}async function $A(t){const e=await Y(),n=await pe("/api/terminal/force-kill",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)},hA,"Terminal force-kill request timed out");if(!n.ok){const r=await hr(n,fr,"Terminal force-kill error response timed out").catch(()=>({error:"Failed to force kill terminal"}));throw new Error(r.error||"Failed to force kill terminal")}}async function HA(){const t=await fetch("/api/terminal/tmux/sessions",{method:"GET"});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to list tmux sessions"}));throw new Error(n.error||"Failed to list tmux sessions")}const e=await t.json();return Array.isArray(e.sessions)?e.sessions:[]}async function qA(){const t=await fetch("/api/terminal/tmux/status",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to get tmux status"}));throw new Error(e.error||"Failed to get tmux status")}return t.json()}async function KA(t){const e=t.trim();if(!e)throw new Error("tmux session name is required");const n=await Y(),r=await fetch(`/api/terminal/tmux/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":n}});if(!r.ok){const s=await r.json().catch(()=>({error:"Failed to kill tmux session"}));throw new Error(s.error||"Failed to kill tmux session")}const o=await r.json();return{cleanedSessions:Array.isArray(o.cleanedSessions)?o.cleanedSessions:[],alreadyGone:!!o.alreadyGone}}async function zA(){const t=await Y(),e=await fetch("/api/terminal/tmux/recovery/restore-all",{method:"POST",headers:{"X-XSRF-TOKEN":t}}),n=await e.json().catch(()=>({}));if(!e.ok)throw new Ae(n.error||"Failed to restore tmux Agent sessions",e.status);return n}async function WA(){const t=await Y(),e=await fetch("/api/terminal/tmux/recovery",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Ae("Failed to dismiss tmux recovery",e.status)}const Ho=new Map;function VA(t){return JSON.stringify({preferredFrontendSessionId:t.preferredFrontendSessionId??null,mode:t.mode??null,tmuxSessionName:t.tmuxSessionName??null,cwd:t.cwd??null,termType:t.termType??null,createIfEmpty:t.createIfEmpty===!0,requireExisting:t.requireExisting===!0})}async function yg(){const t=await fetch("/api/terminal/session-inventory",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to load session inventory"}));throw new Error(e.error||"Failed to load session inventory")}return t.json()}async function bg(t){const e=VA(t),n=Ho.get(e);if(n)return n;const r=await Y(),o=pe("/api/terminal/session-inventory/open",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(t)},hg,"Terminal session open request timed out").then(async s=>{if(!s.ok){const i=await hr(s,fr,"Terminal session open error response timed out").catch(()=>({error:"Failed to open session"}));throw new Ae(i.error||"Failed to open session",s.status,typeof i.code=="string"?i.code:void 0)}return hr(s,fr,"Terminal session open response timed out")}).finally(()=>{Ho.get(e)===o&&Ho.delete(e)});return Ho.set(e,o),o}async function ts(t,e){const n=await Y(),r=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify(e)});if(!r.ok){const o=await r.json().catch(()=>({error:"Failed to update session"}));throw new Error(o.error||"Failed to update session")}return r.json()}async function vg(t){const e=await Y(),n=await fetch("/api/terminal/session-inventory/reorder",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({sessionIds:t})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to reorder sessions"}));throw new Error(r.error||"Failed to reorder sessions")}return n.json()}async function Sg(t){const e=await Y(),n=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to remove session"}));throw new Error(r.error||"Failed to remove session")}}async function xg(){const t=await Y(),e=await fetch("/api/terminal/session-inventory/sessions",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to clear sessions"}));throw new Error(n.error||"Failed to clear sessions")}}async function GA(){const t=await fetch("/api/terminal/toolbar-presets",{method:"GET"});if(!t.ok){const e=await t.json().catch(()=>({error:"Failed to load toolbar presets"}));throw new Error(e.error||"Failed to load toolbar presets")}return t.json()}async function XA(t){const e=await Y(),n=await fetch("/api/terminal/toolbar-presets",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to save toolbar presets"})),o=new Error(r.error||"Failed to save toolbar presets");throw o.current=r.current,o.code=r.code,o}return n.json()}let Lr=null,Hr=null;const Eg=1500;function rr(){return Hr&&Date.now()-Hr.readAt<Eg?Promise.resolve(Hr.value):Lr||(Lr=(async()=>{const t=await fetch("/api/terminal/settings",{method:"GET"});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to load settings"}));throw new Error(n.error||"Failed to load settings")}const e=await t.json();return Hr={value:e,readAt:Date.now()},e})().finally(()=>{Lr=null}),Lr)}async function vt(t){const e=await Y(),n=await fetch("/api/terminal/settings",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to update settings"}));throw new Error(o.error||"Failed to update settings")}const r=await n.json();return Hr={value:r,readAt:Date.now()},r}async function YA(t=!1){const e=await fetch(`/api/terminal/auto-title/catalog${t?"?refresh=1":""}`);if(!e.ok)throw new Error("Failed to discover title models");const n=await e.json();return Array.isArray(n?.namers)?n.namers:[]}let Br=null,qr=null;function ZA(){return qr&&Date.now()-qr.readAt<Eg?Promise.resolve(qr.value):Br||(Br=(async()=>{const t=await fetch("/api/terminal/context-draft",{method:"GET"});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to load context draft"}));throw new Error(n.error||"Failed to load context draft")}const e=await t.json();return qr={value:e,readAt:Date.now()},e})().finally(()=>{Br=null}),Br)}async function JA(t,e){const n=await Y(),r=await fetch("/api/terminal/context-draft",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify({text:t,origin:e})});if(!r.ok){const s=await r.json().catch(()=>({error:"Failed to update context draft"}));throw new Error(s.error||"Failed to update context draft")}const o=await r.json();return qr={value:o,readAt:Date.now()},o}async function Ag(t){const e=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:t})});if(e.ok)return wl(),{ok:!0};const n=await e.json().catch(()=>null);return e.status===429?{ok:!1,rateLimited:!0,retryAfterMs:typeof n?.retryAfterMs=="number"?n.retryAfterMs:void 0,error:n?.error||"Too many failed attempts. Please wait and try again."}:{ok:!1,error:n?.error||"Login failed"}}async function QA(){pl(),ag();const t=await Y();await fetch("/api/auth/logout",{method:"POST",headers:{"X-XSRF-TOKEN":t}}),wl()}async function ek(){const t=await fetch("/api/terminal/agent-launchers");if(!t.ok)throw new Error("Failed to detect agent launchers");const e=await t.json();return Array.isArray(e?.agents)?e.agents:[]}async function tk(){const t=await fetch("/api/terminal/agent-hooks");if(!t.ok)throw new Error("Failed to get agent hooks");const e=await t.json();return Array.isArray(e?.agents)?e.agents:[]}async function nk(t){const e=await Y(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(t)}/install`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to install agent hooks");return{summary:r.summary??"Installed",devMode:r.devMode===!0}}async function rk(t){const e=await Y(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(t)}/uninstall`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to uninstall agent hooks");return r.summary??"Removed"}class bl extends Error{constructor(e,n,r){super(e),this.code=n,this.migration=r,this.name="AgentPluginManifestError"}code;migration}async function ok(){const t=await fetch("/api/terminal/agent-plugins");if(!t.ok)throw new Error("Failed to get agent plugins");return await t.json()}async function sk(t){const e=await Y(),n=await fetch("/api/terminal/agent-plugins",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok)throw new bl(r.error||"Failed to create agent plugin",r.code,r.migration);return r}async function ik(t){const e=await Y(),n=await fetch("/api/terminal/agent-plugins/install",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify({source:t})}),r=await n.json().catch(()=>({}));if(!n.ok)throw new bl(r.error||"Failed to install agent plugin",r.code,r.migration);return r}async function ak(t){const e=await Y(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/check-update`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to check plugin updates");return r}async function ck(t){const e=await Y(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/update`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to update plugin");return r}async function lk(t){const e=await Y(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}/doctor`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to diagnose plugin");return r}async function dk(t){const e=await Y(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||"Failed to delete agent plugin")}}async function uk(t){const e=await Y(),n=await fetch(`/api/terminal/${encodeURIComponent(t)}/agent-resume`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Ae(r.error||"Failed to resume agent session",n.status,typeof r.code=="string"?r.code:void 0);return{command:r.command??""}}async function fk(){const t=await fetch("/api/terminal/agent-resume-history",{method:"GET"});if(!t.ok)throw new Error("Failed to load Agent resume history");const e=await t.json().catch(()=>({entries:[]}));return Array.isArray(e.entries)?e.entries:[]}async function hk(t){const e=await Y(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(t)}/prepare`,{method:"POST",headers:{"X-XSRF-TOKEN":e}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Ae(r.error||"Failed to prepare Agent session resume",n.status,typeof r.code=="string"?r.code:void 0);return r}async function pk(t){const e=await Y(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!n.ok&&n.status!==404)throw new Error("Failed to remove Agent resume history")}async function gk(t){const e=await Y(),n=await fetch("/api/terminal/program-rules",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to update program rules"}));throw new Error(r.error||"Failed to update program rules")}return n.json()}async function mk(){const t=await Y(),e=await fetch("/api/terminal/program-rules",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Error("Failed to reset program rules");return e.json()}async function wk(){const t=await fetch("/api/terminal/program-detection");if(!t.ok)throw new Error("Failed to get program detection config");return t.json()}async function yk(t){const e=await Y(),n=await fetch("/api/terminal/program-detection",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":e},body:JSON.stringify(t)});if(!n.ok)throw new Error("Failed to save program detection config");return n.json()}async function bk(){const t=await Y(),e=await fetch("/api/terminal/program-detection",{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!e.ok)throw new Error("Failed to reset program detection config");return e.json()}const vk={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".bmp":"image/bmp",".ico":"image/x-icon",".svg":"image/svg+xml",".heic":"image/heic",".heif":"image/heif"};function si(t){const e=t.lastIndexOf(".");return e<0?null:vk[t.slice(e).toLowerCase()]??null}function Sk(t){return si(t)!==null}function kg(t){const e=si(t);return e==="image/heic"||e==="image/heif"}const xk={".mp4":"video/mp4",".m4v":"video/x-m4v",".webm":"video/webm",".mov":"video/quicktime",".ogv":"video/ogg",".mpeg":"video/mpeg",".mpg":"video/mpeg"};function Cg(t){const e=t.lastIndexOf(".");return e<0?null:xk[t.slice(e).toLowerCase()]??null}function Ek(t){return Cg(t)!==null}function Ak(t){return`/api/terminal/fs/video?path=${encodeURIComponent(t)}&action=view_file`}const Ig=[".stl",".glb",".gltf"];function vl(t){const e=t.lastIndexOf(".");if(e<0)return null;const n=t.slice(e).toLowerCase();return Ig.includes(n)?n:null}function kk(t){return vl(t)!==null}function Sl(t){const e=t.toLowerCase();return e.endsWith(".kicad_sch")?".kicad_sch":e.endsWith(".kicad_pcb")?".kicad_pcb":null}function Ck(t){return Sl(t)!==null}function Ik(t){return Sl(t)===".kicad_pcb"?"pcb-front":"schematic"}const Rg=[".html",".htm"];function Rk(t){const e=t.lastIndexOf(".");if(e<0)return!1;const n=t.slice(e).toLowerCase();return Rg.includes(n)}function Tk(t){return`/api/terminal/fs/preview/${t.split(/[\\/]+/).filter(Boolean).map(n=>encodeURIComponent(n)).join("/")}`}const Pk={".stl":"model/stl",".glb":"model/gltf-binary",".gltf":"model/gltf+json"};async function Nk(t,e,n,r="list_directory",o,s="name"){const i=new URLSearchParams({path:t});n&&i.set("showHidden","true"),s!=="name"&&i.set("sort",s),i.set("action",r),o&&i.set("requestSlotId",o);const a=await pe(`/api/terminal/fs/list?${i}`,{signal:e},Cn,"Directory listing took too long. The folder may be on slow storage or blocked by another process.");if(!a.ok){const c=await a.json().catch(()=>({error:"Failed to list directory"}));throw new Error(c.error||"Failed to list directory")}return a.json()}async function Lk(t,e,n,r,o,s="name",i,a={}){const c=new URLSearchParams({path:t,query:e,stream:"true"});o&&c.set("showHidden","true"),s==="content"&&c.set("mode","content"),i&&c.set("requestSlotId",i);for(const g of a.excludePatterns??[])c.append("exclude",g);a.caseSensitive&&c.set("caseSensitive","true"),a.wholeWord&&c.set("wholeWord","true"),a.regex&&c.set("regex","true");const l=await fetch(`/api/terminal/fs/search?${c}`,{signal:r});if(!l.ok||!l.body){const g=await l.json().catch(()=>({error:"Failed to search files"}));throw new Error(g.error||"Failed to search files")}const d=l.body.getReader(),u=new TextDecoder;let f="";const h=g=>{if(!g.trim())return;const m=JSON.parse(g);if(m.type==="meta")n({path:m.path,query:m.query,engine:m.engine,mode:m.mode,limited:m.limited});else if(m.type==="batch")n({entries:m.entries??[]});else if(m.type==="content-batch")n({contentEntries:m.contentEntries??[]});else{if(m.type==="error")throw new Error(m.message||"Search failed");m.type==="done"&&n({total:m.total,truncated:m.truncated,limited:m.limited,engine:m.engine,mode:m.mode,done:!0})}};for(;;){const{value:g,done:m}=await d.read();if(m)break;f+=u.decode(g,{stream:!0});let b=f.indexOf(`
10
10
  `);for(;b>=0;)h(f.slice(0,b)),f=f.slice(b+1),b=f.indexOf(`
11
11
  `)}f+=u.decode(),h(f)}async function Bk(t,e,n){const r=new URLSearchParams;for(const d of t)r.append("root",d);const o=await fetch(`/api/terminal/fs/watch?${r}`,{signal:n});if(!o.ok||!o.body){const d=await o.json().catch(()=>({error:"Failed to watch files"}));throw new Error(d.error||"Failed to watch files")}const s=o.body.getReader(),i=new TextDecoder;let a="",c=null;const l=d=>{if(!d.trim())return;const u=JSON.parse(d);if(u.type==="events"&&u.events?.length){e(u.events);const f=u.events.find(h=>h.type==="rescan-required"&&h.reason!=="event-storm"&&h.reason!=="reconnected"&&h.reason!=="directory-rescan"&&h.reason!=="polling-fallback");f?.reason&&(c=f.reason)}};for(;;){const{value:d,done:u}=await s.read();if(u)break;a+=i.decode(d,{stream:!0});let f=a.indexOf(`
12
12
  `);for(;f>=0;)l(a.slice(0,f)),a=a.slice(f+1),f=a.indexOf(`
@@ -26,10 +26,10 @@ Minimum version required to store current data is: `+N+`.
26
26
  animation: terminal-blink 1.05s steps(1, end) infinite;
27
27
  color: var(--primary);
28
28
  }
29
- `})]})}const L2={activeKey:"root",items:[]},B2=()=>()=>{},_2=()=>L2,hc="termdock:open-saved-service";function O2(t,e){try{const n=new URL(t.serviceOrigin||t.url);return t.label!==n.host&&t.label!==n.origin?t.label:!e.some(o=>{const s=new URL(o.serviceOrigin||o.url);return s.hostname===n.hostname&&s.port!==n.port})&&n.port==="9834"?n.hostname:n.host}catch{return t.label}}function QI(t,e,n){_.useEffect(()=>{window.termdockDesktop?.reportServiceActivity?.({runningCount:t,reviewCount:e})},[t,e]),_.useEffect(()=>{Mn({runningCount:t,reviewCount:e,attentionSessions:n})},[t,e,n])}function D2({onReselect:t}){return window.termdockDesktop?null:p.jsx(F2,{onReselect:t})}function F2({onReselect:t}){const[e,n]=_.useState([]),[r,o]=_.useState([]),[s,i]=_.useState(re()?.targetPeerId),[a,c]=_.useState(""),[l,d]=_.useState(!1),[u,f]=_.useState(!1),h=_.useRef(0),g=_.useRef(!1);_.useEffect(()=>{let C=!1;const T=()=>{const E=h.current;rr().then(S=>{!C&&!g.current&&E===h.current&&d(S.serviceSwitcherExpanded===!0)}).catch(()=>{})};return T(),window.addEventListener(Ye,T),()=>{C=!0,window.removeEventListener(Ye,T)}},[]);const m=async()=>{if(g.current)return;const C=l;h.current+=1,g.current=!0,f(!0),d(!C),c("");try{const T=await vt({serviceSwitcherExpanded:!C});d(T.serviceSwitcherExpanded===!0)}catch{d(C),c("展开状态保存失败,请重试")}finally{g.current=!1,f(!1)}},b=_.useRef(null),w=ut(),I=_.useSyncExternalStore(w?.subscribe||B2,w?.snapshot||_2);_.useEffect(()=>{let C=!1,T=0;const E=()=>{const N=++T;i(re()?.targetPeerId),He().then(D=>{if(!(C||N!==T)){try{const A="termdock-secure-service-order",x=JSON.parse(localStorage.getItem(A)||"[]"),P=Array.isArray(x)?x.filter(M=>typeof M=="string"):[],R=M=>M.targetPeerId||M.id,O=[...P.filter(M=>D.some(B=>R(B)===M)),...D.map(R).filter(M=>!P.includes(M))];D.sort((M,B)=>O.indexOf(R(M))-O.indexOf(R(B)));const j=JSON.stringify(O);j!==localStorage.getItem(A)&&localStorage.setItem(A,j)}catch{}n(D)}}).catch(()=>{})};E();const S=Hs(E),k=window.termdockDesktop?.onServiceActivity?.(o);return window.addEventListener(Ye,E),()=>{C=!0,S(),k?.(),window.removeEventListener(Ye,E)}},[]),_.useEffect(()=>{const C=b.current,T=C?.querySelector('[aria-current="page"]');if(!C||!T)return;const E=T.offsetLeft,S=E+T.offsetWidth;E<C.scrollLeft?C.scrollLeft=E:S>C.scrollLeft+C.clientWidth&&(C.scrollLeft=S-C.clientWidth)},[s,e,l]);const y=async C=>{if(c(""),C.targetPeerId&&C.targetPeerId===s){t?.();return}try{const T=window.termdockDesktop;if(T?.openServiceConnection){const E=await T.openServiceConnection(C);if(!E.ok)throw new Error(E.error||"暂时无法打开服务")}else Ns(C)||window.dispatchEvent(new CustomEvent(hc,{detail:C}))}catch(T){c(T instanceof Error?T.message:"暂时无法切换服务")}},v=C=>{const T=I.items.find(S=>S.service?.targetPeerId===C.targetPeerId),E=r.find(S=>S.targetPeerId&&S.targetPeerId===C.targetPeerId||S.origin===(C.serviceOrigin||C.url));return{phase:T?.phase,running:T?.runningCount??E?.runningCount??0,review:T?.reviewCount??E?.reviewCount??0}},L=C=>{const T=v(C);return T.review?p.jsxs("span",{className:"inline-flex shrink-0 items-center gap-0.5 text-[color:var(--warning)]",title:"等待处理",children:[p.jsx(Kp,{size:11}),T.review]}):T.phase==="connecting"||T.phase==="reconnecting"?p.jsx(De,{size:12,className:"shrink-0 animate-spin","aria-label":"正在连接"}):T.phase==="offline"||T.phase==="login"?p.jsx("span",{className:"shrink-0 text-[color:var(--warning)]",title:T.phase==="login"?"需要登录":"连接已断开",children:"!"}):T.running?p.jsx("span",{className:"shrink-0 text-[color:var(--success)]",title:"运行中",children:T.running}):null};return e.length<=1?null:p.jsxs("div",{className:"min-w-0 shrink-0 bg-[var(--chrome-bg)] px-3 pb-1 md:order-first md:bg-transparent md:pb-0 md:pt-1","data-sidebar-gesture-ignore":!0,children:[p.jsx("button",{type:"button",onClick:()=>{m()},disabled:u,"aria-expanded":l,"aria-label":l?"收起服务切换":"展开服务切换",title:l?"收起服务切换":"展开服务切换",className:"flex h-6 w-full items-center justify-center rounded-lg text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary disabled:opacity-60",children:l?p.jsx(zp,{size:16}):p.jsx(FE,{size:16})}),l&&p.jsxs("div",{className:"flex w-full items-center gap-1 md:gap-0 md:rounded-xl md:bg-surface md:p-1",children:[p.jsx("nav",{ref:b,"aria-label":"切换服务",className:"relative flex min-w-0 flex-1 gap-0.5 overflow-x-auto overscroll-x-contain md:gap-1 md:rounded-lg [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:e.map(C=>p.jsx("button",{type:"button",onClick:()=>{y(C)},"aria-current":C.targetPeerId===s?"page":void 0,"aria-label":C.label,title:C.label,className:`inline-flex min-h-11 min-w-0 flex-[1_0_auto] items-center justify-center rounded-lg text-[11px] leading-4 transition-colors motion-reduce:transition-none md:min-h-8 ${e.length>3?"md:flex-[0_0_30%]":"md:flex-[1_1_0%]"} focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary ${C.targetPeerId===s?"font-medium text-foreground md:bg-surface-elevated":"text-muted-foreground hover:bg-surface hover:text-foreground md:hover:bg-surface-2"}`,children:p.jsxs("span",{className:`inline-flex min-w-0 items-center justify-center gap-1 rounded-lg px-2 py-1.5 ${C.targetPeerId===s?"bg-surface-elevated md:bg-transparent":""}`,children:[p.jsx("span",{className:"max-w-[11rem] truncate md:hidden",children:O2(C,e)}),p.jsx("span",{className:"hidden truncate md:inline",children:C.label}),L(C)]})},C.id))}),p.jsx("button",{type:"button",onClick:ig,"aria-label":"管理服务",title:"管理服务",className:"inline-flex h-11 w-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-surface hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary md:hidden",children:p.jsx(Vp,{size:18})})]}),a&&p.jsx("p",{role:"alert",className:"mt-1 text-[11px] text-[color:var(--warning)]",children:a})]})}function qo(t,e,n=new Set){for(const r of t.keys()){if(t.size<=e)break;n.has(r)||t.delete(r)}return t}function ht(t,e){if(typeof window>"u")return null;try{const n=window.localStorage.getItem(t);if(n===null||n==="")return null;const r=JSON.parse(n);return e(r)?r:null}catch{return null}}function We(t,e){if(!(typeof window>"u"))try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}function _r(t){if(!(typeof window>"u"))try{window.localStorage.removeItem(t)}catch{}}const Jr=new Map,or=new Map,rs=new Map;function eR(t,e,n){if(typeof window>"u")return;const r=Date.now(),o=rs.get(t)??0,s=r-o;if(s>=n){rs.set(t,r),We(t,e);return}if(or.set(t,e),Jr.has(t))return;const i=n-s,a=setTimeout(()=>{Jr.delete(t);const c=or.get(t);or.delete(t),rs.set(t,Date.now()),c!==void 0&&We(t,c)},i);Jr.set(t,a)}function M2(t){const e=Jr.get(t);e&&(clearTimeout(e),Jr.delete(t));const n=or.get(t);n!==void 0&&(or.delete(t),rs.set(t,Date.now()),We(t,n))}function tR(t,e){if(t===e)return!0;try{return JSON.stringify(t)===JSON.stringify(e)}catch{return!1}}if(typeof window<"u"){const t=()=>{for(const e of or.keys())M2(e)};window.addEventListener("pagehide",t),window.addEventListener("termdock:before-update",t),document.addEventListener("visibilitychange",()=>{document.hidden&&t()})}const j2=600,co=320,U2=280,$2=5;function nR(t,e,n=0){const r=Math.max(co,e-Math.max(0,n)-$2*(n>0?2:1)-U2);return Math.min(r,Math.max(co,t))}const Ng="termdock:right-sidebar:tabs-by-session:v2",Lg="termdock:right-sidebar:explorer-roots-by-session:v2",kl="termdock:right-sidebar:pinned-explorer-roots:v1",Bg="termdock:right-sidebar:selected-files-by-session:v2",_g="termdock:right-sidebar:show-hidden-files:v1",pc="termdock:right-sidebar:file-sort-modes:v1",gc="termdock:right-sidebar:nested-git-scan-roots:v1",Zu="termdock-sidebar-group-by-folder",Og="termdock-sidebar-collapsed-folder-groups",Dg="termdock-left-sidebar-pinned",Fg="termdock-left-sidebar-width",Mg="termdock-right-sidebar-pinned",Cl="termdock:right-sidebar:pinned-by-session:v1",jg="termdock-right-sidebar-width",Il="termdock:right-sidebar:widths-by-session:v1",Ug="termdock:right-sidebar:split-state-initialized:v1",$g="termdock-right-sidebar-layout-preference";function H2(){if(typeof window>"u")return!0;try{const t=window.localStorage.getItem(Dg);return t===null?!0:t==="1"}catch{return!0}}function Ju(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Dg,t?"1":"0")}catch{}}function q2(){if(typeof window>"u")return 300;try{const t=window.localStorage.getItem(Fg);if(!t)return 300;const e=parseInt(t,10);return Number.isFinite(e)&&e>=200&&e<=500?e:300}catch{return 300}}function K2(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Fg,String(t))}catch{}}function os(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Mg)==="1"}catch{return!1}}function z2(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Mg,t?"1":"0")}catch{}}function Bs(){return ht(Cl,t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.values(t).every(e=>typeof e=="boolean"))??{}}function pa(t,e){if(!t){z2(e);return}We(Cl,{...Bs(),[t]:e})}function ss(){if(typeof window>"u")return 760;try{const t=window.localStorage.getItem(jg);if(!t)return 760;const e=parseInt(t,10);return Number.isFinite(e)&&e>=co?e:760}catch{return 760}}function W2(t){if(!(typeof window>"u"))try{window.localStorage.setItem(jg,String(t))}catch{}}function V2(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="number"&&Number.isFinite(e)&&e>=co)}function _s(){return ht(Il,V2)??{}}function Qu(t,e){if(!t){W2(e);return}We(Il,{..._s(),[t]:e})}function G2(){if(typeof window>"u")return"auto";try{const t=window.localStorage.getItem($g);return t==="narrow"||t==="wide"?t:"auto"}catch{return"auto"}}function X2(t){if(!(typeof window>"u"))try{window.localStorage.setItem($g,t)}catch{}}function rR(t,e,n){return!e||n==="auto"?t<j2:n==="narrow"}function Y2(){return!0}function ef(t){if(!(typeof window>"u"))try{t?window.localStorage.setItem(Zu,"1"):window.localStorage.setItem(Zu,"0")}catch{}}function Z2(){if(typeof window>"u")return new Set;try{const t=window.localStorage.getItem(Og);if(!t)return new Set;const e=JSON.parse(t);return Array.isArray(e)?new Set(e.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function J2(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Og,JSON.stringify([...t]))}catch{}}function Q2(t){return t==="git"||t==="files"||t==="diff"}function eC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(Q2)}function mc(){return ht(Ng,eC)??{}}function ga(t,e){t&&We(Ng,{...mc(),[t]:e})}function tC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string")}function tf(){return ht(Lg,tC)??{}}function Ko(t){We(Lg,t)}function nC(t){return t!==null&&typeof t=="object"&&typeof t.path=="string"&&(t.kind==="file"||t.kind==="directory")}function rC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>Array.isArray(e)&&e.every(n=>typeof n=="string"||nC(n)))}function Hg(t){const e=new Set,n=[];for(const r of t){const o=typeof r=="string"?{path:r,kind:"directory"}:r;!o.path||e.has(o.path)||(e.add(o.path),n.push(o))}return n}function oC(){const t=ht(kl,rC)??{},e={};for(const[n,r]of Object.entries(t))e[n]=Hg(r);return e}function nf(t){We(kl,t)}function sC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string")}function wc(){return ht(Bg,sC)??{}}function Or(t,e){if(!t)return;const n={...wc()};e?n[t]=e:delete n[t],We(Bg,n)}function lo(t,e){return e?t?`${t}\0${e}`:e:null}function Os(t,e,n){return n?`split-workspace\0${n}`:lo(t,e)}function oR(t,e,n){const r=_s(),o=Os(t,e,n);if(o&&r[o]!==void 0)return r[o];if(n){const s=lo(t,e);if(s&&r[s]!==void 0)return r[s]}return ss()}function sR(t,e,n){const r=Bs(),o=Os(t,e,n);if(o&&r[o]!==void 0)return r[o];if(n){const s=lo(t,e);if(s&&r[s]!==void 0)return r[s]}return os()}function qg(){const t=ht(Ug,e=>Array.isArray(e)&&e.every(n=>typeof n=="string"));return new Set(t??[])}function iC(t){const e=qg();e.has(t)||(e.add(t),We(Ug,[...e]))}function aC(t){return typeof t=="boolean"}function cC(){return ht(_g,aC)??!1}function lC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>e==="modified")}function dC(){return ht(pc,lC)??{}}function uC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>e===!0)}function fC(){return ht(gc,uC)??{}}let Dr=null;const ma=new Map;let Fr=null;const zo=new Map;let Mr=null;const wa=globalThis.crypto?.randomUUID?.()??`pins-${Math.random().toString(36).slice(2)}`;function hC(t){const e=t.replace(/\/+$/,"")||"/";return e==="/"?"/":e.slice(0,e.lastIndexOf("/"))||"/"}function Dn(t,e){const n=t.replace(/\/+$/,"")||"/";return e===n||e.startsWith(`${n}/`)}function rf(t,e="name"){return[...t].sort((n,r)=>{if(n.type==="directory"&&r.type!=="directory")return-1;if(n.type!=="directory"&&r.type==="directory")return 1;if(e==="modified"){const o=Date.parse(r.modified??"")-Date.parse(n.modified??"");if(Number.isFinite(o)&&o!==0)return o}return n.name.localeCompare(r.name)})}function pC(t){return t.entry?{name:t.entry.name,path:t.entry.path,type:t.entry.type,isSymlink:t.entry.isSymlink,modified:t.entry.modified,expanded:!1,loaded:!1,children:t.entry.type==="directory"?[]:void 0}:null}const Le=oi(t=>({leftOpen:!1,rightOpen:!1,leftPinned:H2(),leftSidebarWidth:q2(),rightPinned:os(),rightSidebarWidth:ss(),rightSidebarLayoutPreference:G2(),rightTab:"files",rightSearchOpen:!1,rootPath:null,contextKey:null,rightSidebarWidthContextKey:null,explorerRoot:null,explorerRootCache:tf(),pinnedExplorerRootsCache:oC(),pinnedExplorerRootsHydrated:!1,expandedPaths:new Set,selectedFilePath:null,directoryCache:new Map,fileSortModes:dC(),fileSortModesHydrated:!1,nestedGitScanRoots:fC(),nestedGitScanRootsHydrated:!1,showHiddenFiles:cC(),groupByFolder:Y2(),collapsedGroups:Z2(),changedFiles:new Map,fileChangeVersions:new Map,fileWatchEpoch:0,gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null,gitBundleError:null,gitBundleLastLoadedAt:null,gitBundleCacheInfo:null,projectStateCache:new Map,rootDataCache:new Map,openLeft:()=>t({leftOpen:!0}),closeLeft:()=>t({leftOpen:!1}),toggleLeft:()=>t(e=>({leftOpen:!e.leftOpen,rightOpen:e.leftOpen?e.rightOpen:!1})),toggleLeftPinned:()=>t(e=>{const n=!e.leftPinned;return Ju(n),{leftPinned:n,leftOpen:!0}}),setLeftPinned:e=>t(()=>(Ju(e),{leftPinned:e})),setLeftSidebarWidth:e=>t(n=>{const r=Math.min(Math.max(e,200),500);return n.leftSidebarWidth===r?n:(K2(r),{leftSidebarWidth:r})}),toggleRightPinned:()=>t(e=>{const n=!e.rightPinned;return pa(e.rightSidebarWidthContextKey,n),{rightPinned:n,rightOpen:!0}}),setRightPinned:e=>t(n=>(pa(n.rightSidebarWidthContextKey,e),{rightPinned:e})),setRightSidebarWidth:e=>t(n=>{const r=Math.max(e,co);return n.rightSidebarWidth===r?n:(Qu(n.rightSidebarWidthContextKey,r),{rightSidebarWidth:r})}),setRightSidebarLayoutPreference:e=>t(n=>n.rightSidebarLayoutPreference===e?n:(X2(e),{rightSidebarLayoutPreference:e})),openRight:()=>t({rightOpen:!0}),closeRight:()=>t({rightOpen:!1,rightSearchOpen:!1}),toggleRight:()=>t(e=>({rightOpen:!e.rightOpen,rightSearchOpen:e.rightOpen?!1:e.rightSearchOpen,leftOpen:e.rightOpen?e.leftOpen:!1})),closeAll:()=>t({leftOpen:!1,rightOpen:!1,rightSearchOpen:!1}),setRightTab:e=>t(n=>(ga(n.contextKey,e),{rightTab:e})),openRightSearch:()=>t({rightSearchOpen:!0}),closeRightSearch:()=>t({rightSearchOpen:!1}),setRightSearchOpen:e=>t({rightSearchOpen:e}),setRootPath:(e,n=null,r=null)=>t(o=>{const s=lo(n,e),i=Os(n,e,r),a=r?i:s;if(o.contextKey===a&&o.rightSidebarWidthContextKey===i)return e===o.rootPath?o:{rootPath:e};const c=new Map(o.rootDataCache);o.rootPath&&c.set(o.rootPath,{directoryCache:o.directoryCache,changedFiles:o.changedFiles,gitBundleError:o.gitBundleError,gitBundleLastLoadedAt:o.gitBundleLastLoadedAt,gitBundleCacheInfo:o.gitBundleCacheInfo}),qo(c,12,new Set(e?[e]:[]));const l=e?c.get(e):void 0,d=e===o.rootPath,u=new Map(o.projectStateCache);o.contextKey&&u.set(o.contextKey,{rightTab:o.rightTab,explorerRoot:o.explorerRoot,expandedPaths:new Set(o.expandedPaths),selectedFilePath:o.selectedFilePath,directoryCache:new Map(o.directoryCache),changedFiles:new Map(o.changedFiles),gitBundleError:o.gitBundleError,gitBundleLastLoadedAt:o.gitBundleLastLoadedAt,gitBundleCacheInfo:o.gitBundleCacheInfo});const f=r?qg().has(r):!1;let h={...tf(),...o.explorerRootCache};const g=!!r&&!f,m=g&&s?o.contextKey===s?{rightTab:o.rightTab,explorerRoot:o.explorerRoot,expandedPaths:new Set(o.expandedPaths),selectedFilePath:o.selectedFilePath,directoryCache:new Map(o.directoryCache),changedFiles:new Map(o.changedFiles),gitBundleError:o.gitBundleError,gitBundleLastLoadedAt:o.gitBundleLastLoadedAt,gitBundleCacheInfo:o.gitBundleCacheInfo}:u.get(s):void 0;if(g&&r){const E=m?.rightTab??(s?mc()[s]:void 0)??"files",S=m?.explorerRoot??(s?o.explorerRootCache[s]:void 0)??e,k=m?.selectedFilePath??(s?wc()[s]:void 0)??null,N={rightTab:E,explorerRoot:S,expandedPaths:new Set(m?.expandedPaths??[]),selectedFilePath:k,directoryCache:new Map(m?.directoryCache??[]),changedFiles:new Map(m?.changedFiles??[]),gitBundleError:m?.gitBundleError??null,gitBundleLastLoadedAt:m?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:m?.gitBundleCacheInfo??null};a&&(u.set(a,N),ga(a,E),Or(a,k),S&&(h={...h,[a]:S},Ko(h))),iC(r)}qo(u,12,new Set(a?[a]:[]));const b=a?u.get(a):void 0,w=a?mc()[a]:void 0,I=_s();let y=i?I[i]:void 0;r&&i&&y===void 0&&(y=(s?I[s]:void 0)??ss(),Qu(i,y));const v=a?h[a]:void 0,L=Bs();let C=i?L[i]:void 0;r&&i&&C===void 0&&(C=(s?L[s]:void 0)??os(),pa(i,C));const T=a?wc()[a]:void 0;return{rootPath:e,contextKey:a,rightSidebarWidthContextKey:i,rightSidebarWidth:y??ss(),rightPinned:C??os(),rightOpen:o.rightSidebarWidthContextKey===i?o.rightOpen:!1,rightTab:b?.rightTab??w??"files",explorerRoot:b?.explorerRoot??v??e,expandedPaths:b?new Set(b.expandedPaths):new Set,selectedFilePath:b?.selectedFilePath??T??null,explorerRootCache:h,directoryCache:l?.directoryCache??new Map,changedFiles:l?.changedFiles??new Map,gitBundleLoading:d?o.gitBundleLoading:!1,gitBundleSlow:d?o.gitBundleSlow:!1,gitBundleLoadingOwner:d?o.gitBundleLoadingOwner:null,gitBundleError:l?.gitBundleError??null,gitBundleLastLoadedAt:l?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:l?.gitBundleCacheInfo??null,rootDataCache:c,projectStateCache:u}}),inheritRightSidebarStateFromSplitWorkspace:(e,n)=>t(r=>{if(!e||n.length===0)return r;const o=_s(),s=Os(null,null,e);if(!s)return r;const i=o[s]??(r.rightSidebarWidthContextKey===s?r.rightSidebarWidth:void 0),a=Bs(),c=a[s]??(r.rightSidebarWidthContextKey===s?r.rightPinned:void 0),l=r.contextKey===s?{rightTab:r.rightTab,explorerRoot:r.explorerRoot,expandedPaths:new Set(r.expandedPaths),selectedFilePath:r.selectedFilePath,directoryCache:new Map(r.directoryCache),changedFiles:new Map(r.changedFiles),gitBundleError:r.gitBundleError,gitBundleLastLoadedAt:r.gitBundleLastLoadedAt,gitBundleCacheInfo:r.gitBundleCacheInfo}:r.projectStateCache.get(s);if(i===void 0&&c===void 0&&!l)return r;const d={...o},u=new Map(r.projectStateCache),f={...r.explorerRootCache};for(const h of n){const g=lo(h.sessionId,h.rootPath);g&&(i!==void 0&&(d[g]=i),c!==void 0&&(a[g]=c),l&&(u.set(g,{...l,expandedPaths:new Set(l.expandedPaths),directoryCache:new Map(l.directoryCache),changedFiles:new Map(l.changedFiles)}),ga(g,l.rightTab),Or(g,l.selectedFilePath),l.explorerRoot?f[g]=l.explorerRoot:delete f[g]))}return i!==void 0&&We(Il,d),l&&Ko(f),c!==void 0&&We(Cl,a),qo(u,12,new Set(r.contextKey?[r.contextKey]:[])),{projectStateCache:u,explorerRootCache:f}}),setExplorerRoot:e=>t(n=>{if(n.explorerRoot===e)return n;const r={...n.explorerRootCache};return n.contextKey&&e&&(r[n.contextKey]=e,Ko(r)),{explorerRoot:e,explorerRootCache:r}}),resetExplorerToProject:()=>t(e=>{if(e.explorerRoot===e.rootPath)return e;const n={...e.explorerRootCache};return e.contextKey&&e.rootPath&&(n[e.contextKey]=e.rootPath,Ko(n)),{explorerRoot:e.rootPath,explorerRootCache:n}}),pinExplorerRoot:(e,n="directory")=>t(r=>{if(!r.rootPath||!e)return r;const o=r.rootPath,s=r.pinnedExplorerRootsCache[r.rootPath]??[];if(s.some(a=>a.path===e))return r;const i={...r.pinnedExplorerRootsCache,[r.rootPath]:[{path:e,kind:n},...s].slice(0,12)};return nf(i),(async()=>{try{await Le.getState().hydratePinnedExplorerRoots();const a=await vt({pinnedExplorerRoot:{rootPath:o,path:e,kind:n,pinned:!0},pinnedExplorerRootsOrigin:wa});Le.getState().syncPinnedExplorerRoots(a.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:i}}),unpinExplorerRoot:e=>t(n=>{if(!n.rootPath||!e)return n;const r=n.rootPath,o=n.pinnedExplorerRootsCache[n.rootPath]??[],s=o.find(c=>c.path===e);if(!o.some(c=>c.path===e))return n;const i=o.filter(c=>c.path!==e),a={...n.pinnedExplorerRootsCache};return i.length>0?a[n.rootPath]=i:delete a[n.rootPath],nf(a),(async()=>{try{await Le.getState().hydratePinnedExplorerRoots();const c=await vt({pinnedExplorerRoot:{rootPath:r,path:e,kind:s?.kind??"directory",pinned:!1},pinnedExplorerRootsOrigin:wa});Le.getState().syncPinnedExplorerRoots(c.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:a}}),hydratePinnedExplorerRoots:async()=>{if(!Le.getState().pinnedExplorerRootsHydrated)return Mr||(Mr=(async()=>{const e=Le.getState().pinnedExplorerRootsCache;let r=(await rr()).pinnedExplorerRoots??{};Object.keys(r).length===0&&Object.keys(e).length>0&&(r=(await vt({pinnedExplorerRoots:e,pinnedExplorerRootsOrigin:wa})).pinnedExplorerRoots??e),Le.getState().syncPinnedExplorerRoots(r)})().finally(()=>{Mr=null}),Mr)},syncPinnedExplorerRoots:e=>t(()=>{const n={};for(const[r,o]of Object.entries(e)){const s=Hg(o);s.length>0&&(n[r]=s.slice(0,12))}return _r(kl),{pinnedExplorerRootsCache:n,pinnedExplorerRootsHydrated:!0}}),toggleExpanded:e=>t(n=>{const r=new Set(n.expandedPaths);return r.has(e)?r.delete(e):r.add(e),{expandedPaths:r}}),selectFile:e=>t(n=>(Or(n.contextKey,e),{selectedFilePath:e})),toggleShowHiddenFiles:()=>t(e=>{const n=!e.showHiddenFiles;We(_g,n);const r=new Map(e.projectStateCache);for(const[o,s]of r)r.set(o,{...s,directoryCache:new Map});return{showHiddenFiles:n,directoryCache:new Map,projectStateCache:r}}),toggleGroupByFolder:()=>t(e=>{const n=!e.groupByFolder;return ef(n),{groupByFolder:n}}),setGroupByFolder:e=>t(n=>n.groupByFolder===e?n:(ef(e),{groupByFolder:e})),toggleGroupCollapsed:e=>t(n=>{const r=new Set(n.collapsedGroups);return r.has(e)?r.delete(e):r.add(e),J2(r),{collapsedGroups:r}}),setDirectoryCache:(e,n)=>t(r=>{const o=new Map(r.directoryCache);return o.delete(e),o.set(e,n),qo(o,128,new Set([...r.expandedPaths,e,r.explorerRoot??r.rootPath??""])),{directoryCache:o}}),reconcileDirectoryCache:(e,n)=>t(r=>{const o=r.directoryCache.get(e);if(!o)return r;const s=new Map(o.map(d=>[d.path,d])),i=new Set(n.map(d=>d.path)),a=new Map(r.directoryCache),c=n.map(d=>{const u=s.get(d.path);return{name:d.name,path:d.path,type:d.type,isSymlink:d.isSymlink,modified:d.modified,expanded:u?.expanded??!1,loaded:u?.loaded??!1,children:d.type==="directory"?u?.children??[]:void 0}});a.set(e,rf(c,r.fileSortModes[e]??"name"));for(const d of o)if(!i.has(d.path))for(const u of a.keys())Dn(d.path,u)&&a.delete(u);let l=r.selectedFilePath;return l&&o.find(u=>!i.has(u.path)&&Dn(u.path,l))&&(l=null,Or(r.rootPath,null)),{directoryCache:a,selectedFilePath:l}}),hydrateFileSortModes:async()=>{if(!Le.getState().fileSortModesHydrated)return Dr||(Dr=(async()=>{const e=Le.getState().fileSortModes;let r=(await rr()).fileSortModes??{};Object.keys(r).length===0&&Object.keys(e).length>0&&(r=(await vt({fileSortModes:e})).fileSortModes??e),_r(pc),t({fileSortModes:r,fileSortModesHydrated:!0,directoryCache:new Map})})().finally(()=>{Dr=null}),Dr)},setDirectorySortMode:async(e,n)=>{try{await Le.getState().hydrateFileSortModes()}catch{}const r=Le.getState().fileSortModes[e]??"name",o=(ma.get(e)??0)+1;ma.set(e,o),t(s=>{const i={...s.fileSortModes};n==="modified"?i[e]=n:delete i[e];const a=new Map(s.directoryCache);return a.delete(e),{fileSortModes:i,fileSortModesHydrated:!0,directoryCache:a}});try{await vt({fileSortMode:{path:e,mode:n}}),_r(pc)}catch{if(ma.get(e)!==o)return;t(s=>{const i={...s.fileSortModes};r==="modified"?i[e]=r:delete i[e];const a=new Map(s.directoryCache);return a.delete(e),{fileSortModes:i,directoryCache:a}})}},hydrateNestedGitScanRoots:async()=>{if(!Le.getState().nestedGitScanRootsHydrated)return Fr||(Fr=(async()=>{const n=(await rr()).nestedGitScanRoots??{};_r(gc),t({nestedGitScanRoots:n,nestedGitScanRootsHydrated:!0})})().finally(()=>{Fr=null}),Fr)},setNestedGitScanRoot:async(e,n)=>{try{await Le.getState().hydrateNestedGitScanRoots()}catch{}const r=!!Le.getState().nestedGitScanRoots[e],o=(zo.get(e)??0)+1;zo.set(e,o),t(s=>{const i={...s.nestedGitScanRoots};return n?i[e]=!0:delete i[e],{nestedGitScanRoots:i,nestedGitScanRootsHydrated:!0}});try{const s=await vt({nestedGitScanRoot:{rootPath:e,enabled:n}});if(zo.get(e)!==o)return;t({nestedGitScanRoots:s.nestedGitScanRoots??{}}),_r(gc)}catch{if(zo.get(e)!==o)return;t(s=>{const i={...s.nestedGitScanRoots};return r?i[e]=!0:delete i[e],{nestedGitScanRoots:i}})}},invalidateDirectoryCache:(e,n=!1)=>t(r=>{const o=new Map(r.directoryCache);for(const s of o.keys())(s===e||n&&Dn(e,s))&&o.delete(s);return{directoryCache:o}}),applyFileWatchEvents:e=>t(n=>{if(e.length===0)return n;const r=new Map(n.directoryCache),o=new Map(n.fileChangeVersions);let s=n.selectedFilePath,i=!1,a=!1,c=!1;const l=d=>{o.set(d,(o.get(d)??0)+1),a=!0};for(const d of e){if(d.type==="rescan-required"){c=!0,s&&Dn(d.path,s)&&l(s);continue}const u=hC(d.path),f=r.get(u);if(d.type==="deleted"){if(l(d.path),s&&Dn(d.path,s)&&(s=null,Or(n.rootPath,null)),f){const b=f.filter(w=>w.path!==d.path);b.length!==f.length&&(r.set(u,b),i=!0)}for(const b of r.keys())Dn(d.path,b)&&(r.delete(b),i=!0);continue}l(d.path);const h=pC(d);if(!h||!f)continue;const g=f.find(b=>b.path===h.path),m=rf(g?f.map(b=>b.path===h.path?{...b,...h,children:b.children}:b):[...f,h],n.fileSortModes[u]??"name");r.set(u,m),i=!0}return!i&&!a&&!c?n:{directoryCache:i?r:n.directoryCache,selectedFilePath:s,fileChangeVersions:a?o:n.fileChangeVersions,fileWatchEpoch:c?n.fileWatchEpoch+1:n.fileWatchEpoch}}),bumpFileWatchEpoch:()=>t(e=>({fileWatchEpoch:e.fileWatchEpoch+1})),setChangedFiles:e=>t({changedFiles:e}),beginGitBundleLoading:e=>t({gitBundleLoading:!0,gitBundleSlow:!1,gitBundleLoadingOwner:e}),setGitBundleSlowFor:(e,n)=>t(r=>r.gitBundleLoadingOwner===e?{gitBundleSlow:n}:r),finishGitBundleLoading:e=>t(n=>n.gitBundleLoadingOwner===e?{gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}:n),resetGitBundleLoading:()=>t({gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}),setGitBundleError:e=>t({gitBundleError:e}),markGitBundleLoaded:(e=null)=>t({gitBundleLastLoadedAt:Date.now(),gitBundleCacheInfo:e})})),ya=(()=>{if(location.hash.startsWith("#termdock-invite="))try{return Ls(location.href)}catch{return}finally{history.replaceState(null,"",location.pathname+location.search)}})(),yc="termdock-secure-open-session";let ba,jr;function gC(){try{const t=JSON.parse(sessionStorage.getItem(yc)??"null");return t?.serviceId===re()?.targetPeerId?t.sessionId:void 0}catch{return}}function mC({children:t}){const[e,n]=_.useState(ya),[r,o]=_.useState(!1),[s,i]=_.useState(!!ya),[a,c]=_.useState(!ya),[l,d]=_.useState(!1),[u,f]=_.useState("正在连接服务…"),[h,g]=_.useState([]),[m,b]=_.useState([]),[w,I]=_.useState(!1),[y,v]=_.useState(!1),[L,C]=_.useState(""),[T,E]=_.useState(!1),[S,k]=_.useState(""),[N,D]=_.useState(re()?.serviceName??location.hostname),[A,x]=_.useState(gC);_.useEffect(()=>{(!r&&!a||r&&(!w||A))&&Mn({rendered:!0})},[r,a,w,A]),_.useEffect(()=>{Qe().then(F=>C(F.peerId)).catch(()=>d(!0))},[]),_.useEffect(()=>{const F=U=>{const{origin:H,sessionId:q}=U.detail;try{const W=JSON.parse(localStorage.getItem("termdock.federation.connections.v1")??"[]").find(V=>wr(V).some(G=>new URL(G).origin===new URL(H).origin));if(!W){i(!0);return}if(ut()?.focusSession(W.targetPeerId,q))return;sessionStorage.setItem(yc,JSON.stringify({serviceId:W.targetPeerId,sessionId:q})),Ze(W).then(()=>{x(q),o(!0)}).catch(()=>{d(!0),i(!0)})}catch{i(!0)}};return window.addEventListener("termdock:open-remote-session",F),()=>window.removeEventListener("termdock:open-remote-session",F)},[]);const P=async(F=5e3)=>{const U=await dt(),H=await mr(U,{timeoutMs:F}),q=cE(),K=eE()?.targetPeerId;Promise.all([g1(),He()]).then(([V,G])=>{const X=G.find(ce=>ce.targetPeerId===K),Z=q==="relay"?`经 ${X?.label||K?.slice(-12)||"入口服务"} 中转`:"直连";return U.request({type:"device-name",name:eg(),onlyIfMissing:!0,profile:{...V,route:Z}})}).catch(()=>{}),I(H.fullService),v(H.canManage),o(!0),c(!1),d(!1);const W=re();Mn({phase:"ready",...W?{service:{...W,id:W.targetPeerId,label:W.serviceName||location.host}}:{}}),Yo()&&aE()};_.useEffect(()=>{let F=!1,U=!1,H=0,q;const K=async()=>{if(F||U||H&&(document.hidden||!Yo()))return;if(!navigator.onLine){c(!0),d(!0),f("网络已断开,恢复后会自动连接"),Mn({phase:"offline"});return}U=!0,clearTimeout(q);const Ie=performance.now(),Me=nn();try{if(Ms&&!re())throw new Error("工作区的服务记录已移除,请重新添加服务。");jr??=window.termdockDesktop?.getServiceConnection?.();const ne=await jr;if(ne?.invitation){n(Ls(ne.invitation)),i(!0),c(!1);return}if(!re()){if(e){c(!1);return}if(ba??=(async()=>{if(ne?.targetPeerId){await Ze({...ne,targetPeerId:ne.targetPeerId,serviceName:ne.label});return}const Ve=await window.termdockDesktop?.getLocalInvite?.();Ve?await Ze(Ve):await tE()})(),await ba,!re()){F||(o(!1),c(!1),d(!1));return}}F||await P(Me?.canSwitchTransport?2500:5e3),H=0,performance.measure("termdock:connection-ready",{start:Ie,end:performance.now()})}catch(ne){if(F)return;ne instanceof Je?(o(!1),c(!1),i(!1),d(!1),Mn({phase:"login"})):(Me&&nn()===Me&&Mp(),d(!0),c(!0),ba=void 0,f("连接暂未恢复,正在重试…"),Mn({phase:"reconnecting"}),H++,q=setTimeout(()=>{K()},Math.min(5e3,300*2**Math.min(H-1,5))),console.debug("[connection] retry",{elapsedMs:Math.round(performance.now()-Ie),attempt:H,reason:ne instanceof Error?ne.message:"unknown"}))}finally{U=!1}},W=()=>{document.visibilityState==="visible"&&Yo()&&K()},V=W,G=()=>{H=0,W()},X=()=>{Le.getState().openLeft(),W()};window.addEventListener(ao,W),window.addEventListener(Ja,X),ut()?.attach(ni(),window),K(),document.addEventListener("visibilitychange",V),window.addEventListener("focus",W),window.addEventListener("online",G);const Z=navigator.connection;Z?.addEventListener("change",G),window.addEventListener("auth:unauthorized",W),window.addEventListener(Ye,W);const ce=setInterval(W,3e4);return()=>{F=!0,clearTimeout(q),clearInterval(ce),window.removeEventListener(ao,W),window.removeEventListener(Ja,X),document.removeEventListener("visibilitychange",V),window.removeEventListener("focus",W),window.removeEventListener("online",G),Z?.removeEventListener("change",G),window.removeEventListener("auth:unauthorized",W),window.removeEventListener(Ye,W)}},[]);const R=async()=>{const F=nn();if(F){E(!0),k("");try{const U=await F.request({type:"session-list"});b(U.items)}catch{k("暂时无法读取终端列表,请重试。")}try{if(y){const U=await F.request({type:"grants-list"}),H=U.subjectLabels??{},q=await F.request({type:"route-access"}),K=await He(),W=(Array.isArray(q.grants)?q.grants:[]).map(V=>({id:`route:${V.id}`,subjectId:V.subjectId,scope:{kind:"service"},actions:["route.use"],routeTargetServiceId:V.targetServiceId,routeTargetName:K.find(G=>G.targetPeerId===V.targetServiceId)?.label||"指定服务",...V.active?{}:{revokedAt:V.revokedAt??0}}));g([...U.grants,...W].map(V=>({...V,label:H[V.subjectId],deviceProfile:U.deviceProfiles?.[V.subjectId]})))}else{const U=await F.request({type:"permissions"});g(U.grants??[])}}catch{k("暂时无法读取设备权限,请重试。")}finally{E(!1)}}};_.useEffect(()=>{const F=()=>{i(!0),r&&R()};return window.addEventListener(nc,F),()=>window.removeEventListener(nc,F)},[r,y]);const O=async F=>{if(!F.pairingCode&&!F.routeCode&&re()?.targetPeerId!==F.targetPeerId&&ut()){const U={...F,id:F.targetPeerId,label:F.serviceName||new URL(F.serviceOrigin||F.url).host};if(await Ct(U),Ns(U)){i(!1);return}}await Ze(F),jr&&(jr=jr.then(U=>U?{...U,invitation:void 0}:null)),n(void 0),x(void 0),sessionStorage.removeItem(yc),D(F.serviceName??new URL(F.url).hostname),await P(),i(!1),d(!1)},j=async F=>{const U=window.termdockDesktop;if(U?.openServiceConnection){const H=await U.openServiceConnection(F);if(!H.ok)throw new Error(H.error||"暂时无法打开这台服务。");i(!1);return}if(Ns(F)){i(!1);return}if(F.targetPeerId)try{await O({...F,targetPeerId:F.targetPeerId,serviceName:F.label});return}catch(H){if(!(H instanceof Je))throw H}return su(F.serviceOrigin||F.url)};_.useEffect(()=>{const F=U=>{j(U.detail).catch(H=>{i(!0),k(H instanceof Error?H.message:"暂时无法打开服务")})};return window.addEventListener(hc,F),()=>window.removeEventListener(hc,F)});const M=async(F,U)=>{if(F.includes("#termdock-invite=")){const q=Ls(F);if(window.termdockDesktop?.openServiceConnection){const K=await window.termdockDesktop.openServiceConnection({id:q.targetPeerId,url:q.url,label:q.serviceName||new URL(q.serviceOrigin||q.url).host,targetPeerId:q.targetPeerId,serviceOrigin:q.serviceOrigin,entryServiceId:q.entryServiceId},F);if(!K.ok)throw new Error(K.error||"暂时无法打开邀请。");i(!1);return}if(U!==void 0&&q.routeOnly){await iu(q,U),await P(),i(!1);return}try{await O(q)}catch(K){if(q.routeOnly&&K instanceof Je)return{passwordRequired:!0};throw K}return}const H=Oe(F);return window.termdockDesktop?.openServiceConnection?j({id:H,url:H,label:new URL(H).host}):su(H,U)},B=async F=>{const U=await dt(),{includeBackup:H=!0,...q}=F,K=re(),W=K?Vt(K):[];let V;if(H&&W.length){for(const Z of W)try{const ce=await $p({...K,targetPeerId:U.targetPeerId},Z);V={...Z,routeCode:ce.routeCode};break}catch{}if(!V)throw new Error("无法分享备用连接:需要入口管理员授权。也可以关闭此选项,生成直接连接邀请。")}let G=K?.serviceOrigin||location.origin;if(["localhost","127.0.0.1","[::1]"].includes(new URL(G).hostname)){const ce=await(await U.fetch("/api/terminal/settings")).json();typeof ce.localAccess?.url=="string"&&(G=ce.localAccess.url)}const X=await U.request({type:"invite-create",...q});if(typeof X.code!="string"||typeof X.expiresAt!="number")throw new Error("暂时无法生成邀请。");return{url:tg({v:1,serviceId:U.targetPeerId,code:X.code,entryUrl:V?.url||G,serviceUrl:G,name:N,entryServiceId:V?.targetPeerId,routeCode:V?.routeCode}),expiresAt:X.expiresAt}};return p.jsxs(p.Fragment,{children:[r?w&&!A?t:p.jsx(Y1,{client:nn(),initialSessionId:A}):a?p.jsx("div",{className:"flex h-full min-h-0 flex-col items-center justify-center bg-[var(--chrome-bg)] px-6 text-foreground",children:p.jsxs("div",{className:"flex w-full max-w-xs flex-col items-center text-center",children:[p.jsx("div",{className:"mb-5 flex h-12 w-12 items-center justify-center rounded-2xl bg-surface-2 text-muted-foreground","aria-hidden":"true",children:p.jsx(XE,{size:24,strokeWidth:1.5})}),p.jsx("h1",{className:"max-w-full truncate text-base font-medium tracking-tight",title:N,children:N}),p.jsxs("div",{role:"status",className:"mt-2 flex max-w-full items-center justify-center gap-2 text-xs leading-5 text-muted-foreground",children:[!l&&p.jsx(De,{size:13,className:"shrink-0 animate-spin motion-reduce:animate-none","aria-hidden":"true"}),p.jsx("span",{children:u})]}),l&&p.jsx("p",{className:"mt-2 text-xs leading-5 text-muted-foreground",children:"登录信息已保留"}),p.jsx("button",{type:"button",className:"mt-6 min-h-11 rounded-lg px-4 text-xs text-muted-foreground transition-colors hover:bg-surface-2 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>i(!0),children:"管理服务"})]})}):p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"fixed left-0 right-0 top-[var(--safe-top-inset)] z-chrome sm:right-auto sm:w-72",children:p.jsx(D2,{})}),p.jsx(N2,{onLoginSuccess:()=>{P().catch(()=>d(!0))}})]}),s&&p.jsx(W1,{onConnect:O,onClose:()=>i(!1),onAddService:M,onOpenService:j,onConnectWithPassword:async(F,U)=>{await iu(F,U),await P(),i(!1)},paired:r||!!re(),initialInvite:e,currentServiceName:N,currentServiceId:nn()?.targetPeerId||re()?.targetPeerId,currentServiceOrigin:re()?.serviceOrigin,currentIdentity:L,grants:h,sessions:m,loading:T,loadError:S,onRetry:()=>{R()},onRename:async(F,U)=>{await(await dt()).request({type:"device-name",subjectId:F,name:U}),await R()},hasBackup:!!re()&&Vt(re()).length>0,onCreateInvite:y?B:void 0,onRevoke:y?async F=>{await(await dt()).request(F.startsWith("route:")?{type:"route-revoke",grantId:F.slice(6)}:{type:"revoke",grantId:F}),await R()}:void 0})]})}function wC(t,e,n){const r=t?.name||"Error",o=t?.message||"Unexpected error";return["Termdock error report",`Time: ${n.capturedAt}`,`URL: ${n.url}`,`User agent: ${n.userAgent}`,"",`${r}: ${o}`,t?.stack?`
29
+ `})]})}const L2={activeKey:"root",items:[]},B2=()=>()=>{},_2=()=>L2,hc="termdock:open-saved-service";function O2(t,e){try{const n=new URL(t.serviceOrigin||t.url);return t.label!==n.host&&t.label!==n.origin?t.label:!e.some(o=>{const s=new URL(o.serviceOrigin||o.url);return s.hostname===n.hostname&&s.port!==n.port})&&n.port==="9834"?n.hostname:n.host}catch{return t.label}}function QI(t,e,n){_.useEffect(()=>{window.termdockDesktop?.reportServiceActivity?.({runningCount:t,reviewCount:e})},[t,e]),_.useEffect(()=>{Mn({runningCount:t,reviewCount:e,attentionSessions:n})},[t,e,n])}function D2({onReselect:t}){return window.termdockDesktop?null:p.jsx(F2,{onReselect:t})}function F2({onReselect:t}){const[e,n]=_.useState([]),[r,o]=_.useState([]),[s,i]=_.useState(re()?.targetPeerId),[a,c]=_.useState(""),[l,d]=_.useState(!1),[u,f]=_.useState(!1),h=_.useRef(0),g=_.useRef(!1);_.useEffect(()=>{let k=!1;const T=()=>{const E=h.current;rr().then(S=>{!k&&!g.current&&E===h.current&&d(S.serviceSwitcherExpanded===!0)}).catch(()=>{})};return T(),window.addEventListener(Ye,T),()=>{k=!0,window.removeEventListener(Ye,T)}},[]);const m=async()=>{if(g.current)return;const k=l;h.current+=1,g.current=!0,f(!0),d(!k),c("");try{const T=await vt({serviceSwitcherExpanded:!k});d(T.serviceSwitcherExpanded===!0)}catch{d(k),c("展开状态保存失败,请重试")}finally{g.current=!1,f(!1)}},b=_.useRef(null),w=ut(),I=_.useSyncExternalStore(w?.subscribe||B2,w?.snapshot||_2);_.useEffect(()=>{let k=!1,T=0;const E=()=>{const N=++T;i(re()?.targetPeerId),He().then(D=>{if(!(k||N!==T)){try{const A="termdock-secure-service-order",x=JSON.parse(localStorage.getItem(A)||"[]"),P=Array.isArray(x)?x.filter(M=>typeof M=="string"):[],R=M=>M.targetPeerId||M.id,O=[...P.filter(M=>D.some(B=>R(B)===M)),...D.map(R).filter(M=>!P.includes(M))];D.sort((M,B)=>O.indexOf(R(M))-O.indexOf(R(B)));const j=JSON.stringify(O);j!==localStorage.getItem(A)&&localStorage.setItem(A,j)}catch{}n(D)}}).catch(()=>{})};E();const S=Hs(E),C=window.termdockDesktop?.onServiceActivity?.(o);return window.addEventListener(Ye,E),()=>{k=!0,S(),C?.(),window.removeEventListener(Ye,E)}},[]),_.useEffect(()=>{const k=b.current,T=k?.querySelector('[aria-current="page"]');if(!k||!T)return;const E=T.offsetLeft,S=E+T.offsetWidth;E<k.scrollLeft?k.scrollLeft=E:S>k.scrollLeft+k.clientWidth&&(k.scrollLeft=S-k.clientWidth)},[s,e,l]);const y=async k=>{if(c(""),k.targetPeerId&&k.targetPeerId===s){t?.();return}try{const T=window.termdockDesktop;if(T?.openServiceConnection){const E=await T.openServiceConnection(k);if(!E.ok)throw new Error(E.error||"暂时无法打开服务")}else Ns(k)||window.dispatchEvent(new CustomEvent(hc,{detail:k}))}catch(T){c(T instanceof Error?T.message:"暂时无法切换服务")}},v=k=>{const T=I.items.find(S=>S.service?.targetPeerId===k.targetPeerId),E=r.find(S=>S.targetPeerId&&S.targetPeerId===k.targetPeerId||S.origin===(k.serviceOrigin||k.url));return{phase:T?.phase,running:T?.runningCount??E?.runningCount??0,review:T?.reviewCount??E?.reviewCount??0}},L=k=>{const T=v(k);return T.review?p.jsxs("span",{className:"inline-flex shrink-0 items-center gap-0.5 text-[color:var(--warning)]",title:"等待处理",children:[p.jsx(Kp,{size:11}),T.review]}):T.phase==="connecting"||T.phase==="reconnecting"?p.jsx(De,{size:12,className:"shrink-0 animate-spin","aria-label":"正在连接"}):T.phase==="offline"||T.phase==="login"?p.jsx("span",{className:"shrink-0 text-[color:var(--warning)]",title:T.phase==="login"?"需要登录":"连接已断开",children:"!"}):T.running?p.jsx("span",{className:"shrink-0 text-[color:var(--success)]",title:"运行中",children:T.running}):null};return e.length<=1?null:p.jsxs("div",{className:"min-w-0 shrink-0 bg-[var(--chrome-bg)] px-3 pb-1 md:order-first md:bg-transparent md:pb-0 md:pt-1","data-sidebar-gesture-ignore":!0,children:[p.jsx("button",{type:"button",onClick:()=>{m()},disabled:u,"aria-expanded":l,"aria-label":l?"收起服务切换":"展开服务切换",title:l?"收起服务切换":"展开服务切换",className:"flex h-6 w-full items-center justify-center rounded-lg text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary disabled:opacity-60",children:l?p.jsx(zp,{size:16}):p.jsx(FE,{size:16})}),l&&p.jsxs("div",{className:"flex w-full items-center gap-1 md:gap-0 md:rounded-xl md:bg-surface md:p-1",children:[p.jsx("nav",{ref:b,"aria-label":"切换服务",className:"relative flex min-w-0 flex-1 gap-0.5 overflow-x-auto overscroll-x-contain md:gap-1 md:rounded-lg [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:e.map(k=>p.jsx("button",{type:"button",onClick:()=>{y(k)},"aria-current":k.targetPeerId===s?"page":void 0,"aria-label":k.label,title:k.label,className:`inline-flex min-h-11 min-w-0 flex-[1_0_auto] items-center justify-center rounded-lg text-[11px] leading-4 transition-colors motion-reduce:transition-none md:min-h-8 ${e.length>3?"md:flex-[0_0_30%]":"md:flex-[1_1_0%]"} focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary ${k.targetPeerId===s?"font-medium text-foreground md:bg-surface-elevated":"text-muted-foreground hover:bg-surface hover:text-foreground md:hover:bg-surface-2"}`,children:p.jsxs("span",{className:`inline-flex min-w-0 items-center justify-center gap-1 rounded-lg px-2 py-1.5 ${k.targetPeerId===s?"bg-surface-elevated md:bg-transparent":""}`,children:[p.jsx("span",{className:"max-w-[11rem] truncate md:hidden",children:O2(k,e)}),p.jsx("span",{className:"hidden truncate md:inline",children:k.label}),L(k)]})},k.id))}),p.jsx("button",{type:"button",onClick:ig,"aria-label":"管理服务",title:"管理服务",className:"inline-flex h-11 w-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-surface hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary md:hidden",children:p.jsx(Vp,{size:18})})]}),a&&p.jsx("p",{role:"alert",className:"mt-1 text-[11px] text-[color:var(--warning)]",children:a})]})}function qo(t,e,n=new Set){for(const r of t.keys()){if(t.size<=e)break;n.has(r)||t.delete(r)}return t}function ht(t,e){if(typeof window>"u")return null;try{const n=window.localStorage.getItem(t);if(n===null||n==="")return null;const r=JSON.parse(n);return e(r)?r:null}catch{return null}}function We(t,e){if(!(typeof window>"u"))try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}function _r(t){if(!(typeof window>"u"))try{window.localStorage.removeItem(t)}catch{}}const Jr=new Map,or=new Map,rs=new Map;function eR(t,e,n){if(typeof window>"u")return;const r=Date.now(),o=rs.get(t)??0,s=r-o;if(s>=n){rs.set(t,r),We(t,e);return}if(or.set(t,e),Jr.has(t))return;const i=n-s,a=setTimeout(()=>{Jr.delete(t);const c=or.get(t);or.delete(t),rs.set(t,Date.now()),c!==void 0&&We(t,c)},i);Jr.set(t,a)}function M2(t){const e=Jr.get(t);e&&(clearTimeout(e),Jr.delete(t));const n=or.get(t);n!==void 0&&(or.delete(t),rs.set(t,Date.now()),We(t,n))}function tR(t,e){if(t===e)return!0;try{return JSON.stringify(t)===JSON.stringify(e)}catch{return!1}}if(typeof window<"u"){const t=()=>{for(const e of or.keys())M2(e)};window.addEventListener("pagehide",t),window.addEventListener("termdock:before-update",t),document.addEventListener("visibilitychange",()=>{document.hidden&&t()})}const j2=600,co=320,U2=280,$2=5;function nR(t,e,n=0){const r=Math.max(co,e-Math.max(0,n)-$2*(n>0?2:1)-U2);return Math.min(r,Math.max(co,t))}const Ng="termdock:right-sidebar:tabs-by-session:v2",Lg="termdock:right-sidebar:explorer-roots-by-session:v2",kl="termdock:right-sidebar:pinned-explorer-roots:v1",Bg="termdock:right-sidebar:selected-files-by-session:v2",_g="termdock:right-sidebar:show-hidden-files:v1",pc="termdock:right-sidebar:file-sort-modes:v1",gc="termdock:right-sidebar:nested-git-scan-roots:v1",Zu="termdock-sidebar-group-by-folder",Og="termdock-sidebar-collapsed-folder-groups",Dg="termdock-left-sidebar-pinned",Fg="termdock-left-sidebar-width",Mg="termdock-right-sidebar-pinned",Cl="termdock:right-sidebar:pinned-by-session:v1",jg="termdock-right-sidebar-width",Il="termdock:right-sidebar:widths-by-session:v1",Ug="termdock:right-sidebar:split-state-initialized:v1",$g="termdock-right-sidebar-layout-preference";function H2(){if(typeof window>"u")return!0;try{const t=window.localStorage.getItem(Dg);return t===null?!0:t==="1"}catch{return!0}}function Ju(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Dg,t?"1":"0")}catch{}}function q2(){if(typeof window>"u")return 300;try{const t=window.localStorage.getItem(Fg);if(!t)return 300;const e=parseInt(t,10);return Number.isFinite(e)&&e>=200&&e<=500?e:300}catch{return 300}}function K2(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Fg,String(t))}catch{}}function os(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Mg)==="1"}catch{return!1}}function z2(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Mg,t?"1":"0")}catch{}}function Bs(){return ht(Cl,t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.values(t).every(e=>typeof e=="boolean"))??{}}function pa(t,e){if(!t){z2(e);return}We(Cl,{...Bs(),[t]:e})}function ss(){if(typeof window>"u")return 760;try{const t=window.localStorage.getItem(jg);if(!t)return 760;const e=parseInt(t,10);return Number.isFinite(e)&&e>=co?e:760}catch{return 760}}function W2(t){if(!(typeof window>"u"))try{window.localStorage.setItem(jg,String(t))}catch{}}function V2(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="number"&&Number.isFinite(e)&&e>=co)}function _s(){return ht(Il,V2)??{}}function Qu(t,e){if(!t){W2(e);return}We(Il,{..._s(),[t]:e})}function G2(){if(typeof window>"u")return"auto";try{const t=window.localStorage.getItem($g);return t==="narrow"||t==="wide"?t:"auto"}catch{return"auto"}}function X2(t){if(!(typeof window>"u"))try{window.localStorage.setItem($g,t)}catch{}}function rR(t,e,n){return!e||n==="auto"?t<j2:n==="narrow"}function Y2(){return!0}function ef(t){if(!(typeof window>"u"))try{t?window.localStorage.setItem(Zu,"1"):window.localStorage.setItem(Zu,"0")}catch{}}function Z2(){if(typeof window>"u")return new Set;try{const t=window.localStorage.getItem(Og);if(!t)return new Set;const e=JSON.parse(t);return Array.isArray(e)?new Set(e.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function J2(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Og,JSON.stringify([...t]))}catch{}}function Q2(t){return t==="git"||t==="files"||t==="diff"}function eC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(Q2)}function mc(){return ht(Ng,eC)??{}}function ga(t,e){t&&We(Ng,{...mc(),[t]:e})}function tC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string")}function tf(){return ht(Lg,tC)??{}}function Ko(t){We(Lg,t)}function nC(t){return t!==null&&typeof t=="object"&&typeof t.path=="string"&&(t.kind==="file"||t.kind==="directory")}function rC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>Array.isArray(e)&&e.every(n=>typeof n=="string"||nC(n)))}function Hg(t){const e=new Set,n=[];for(const r of t){const o=typeof r=="string"?{path:r,kind:"directory"}:r;!o.path||e.has(o.path)||(e.add(o.path),n.push(o))}return n}function oC(){const t=ht(kl,rC)??{},e={};for(const[n,r]of Object.entries(t))e[n]=Hg(r);return e}function nf(t){We(kl,t)}function sC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string")}function wc(){return ht(Bg,sC)??{}}function Or(t,e){if(!t)return;const n={...wc()};e?n[t]=e:delete n[t],We(Bg,n)}function lo(t,e){return e?t?`${t}\0${e}`:e:null}function Os(t,e,n){return n?`split-workspace\0${n}`:lo(t,e)}function oR(t,e,n){const r=_s(),o=Os(t,e,n);if(o&&r[o]!==void 0)return r[o];if(n){const s=lo(t,e);if(s&&r[s]!==void 0)return r[s]}return ss()}function sR(t,e,n){const r=Bs(),o=Os(t,e,n);if(o&&r[o]!==void 0)return r[o];if(n){const s=lo(t,e);if(s&&r[s]!==void 0)return r[s]}return os()}function qg(){const t=ht(Ug,e=>Array.isArray(e)&&e.every(n=>typeof n=="string"));return new Set(t??[])}function iC(t){const e=qg();e.has(t)||(e.add(t),We(Ug,[...e]))}function aC(t){return typeof t=="boolean"}function cC(){return ht(_g,aC)??!1}function lC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>e==="modified")}function dC(){return ht(pc,lC)??{}}function uC(t){return!t||typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(e=>e===!0)}function fC(){return ht(gc,uC)??{}}let Dr=null;const ma=new Map;let Fr=null;const zo=new Map;let Mr=null;const wa=globalThis.crypto?.randomUUID?.()??`pins-${Math.random().toString(36).slice(2)}`;function hC(t){const e=t.replace(/\/+$/,"")||"/";return e==="/"?"/":e.slice(0,e.lastIndexOf("/"))||"/"}function Dn(t,e){const n=t.replace(/\/+$/,"")||"/";return e===n||e.startsWith(`${n}/`)}function rf(t,e="name"){return[...t].sort((n,r)=>{if(n.type==="directory"&&r.type!=="directory")return-1;if(n.type!=="directory"&&r.type==="directory")return 1;if(e==="modified"){const o=Date.parse(r.modified??"")-Date.parse(n.modified??"");if(Number.isFinite(o)&&o!==0)return o}return n.name.localeCompare(r.name)})}function pC(t){return t.entry?{name:t.entry.name,path:t.entry.path,type:t.entry.type,isSymlink:t.entry.isSymlink,modified:t.entry.modified,expanded:!1,loaded:!1,children:t.entry.type==="directory"?[]:void 0}:null}const Le=oi(t=>({leftOpen:!1,rightOpen:!1,leftPinned:H2(),leftSidebarWidth:q2(),rightPinned:os(),rightSidebarWidth:ss(),rightSidebarLayoutPreference:G2(),rightTab:"files",rightSearchOpen:!1,rootPath:null,contextKey:null,rightSidebarWidthContextKey:null,explorerRoot:null,explorerRootCache:tf(),pinnedExplorerRootsCache:oC(),pinnedExplorerRootsHydrated:!1,expandedPaths:new Set,selectedFilePath:null,directoryCache:new Map,fileSortModes:dC(),fileSortModesHydrated:!1,nestedGitScanRoots:fC(),nestedGitScanRootsHydrated:!1,showHiddenFiles:cC(),groupByFolder:Y2(),collapsedGroups:Z2(),changedFiles:new Map,fileChangeVersions:new Map,fileWatchEpoch:0,gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null,gitBundleError:null,gitBundleLastLoadedAt:null,gitBundleCacheInfo:null,projectStateCache:new Map,rootDataCache:new Map,openLeft:()=>t({leftOpen:!0}),closeLeft:()=>t({leftOpen:!1}),toggleLeft:()=>t(e=>({leftOpen:!e.leftOpen,rightOpen:e.leftOpen?e.rightOpen:!1})),toggleLeftPinned:()=>t(e=>{const n=!e.leftPinned;return Ju(n),{leftPinned:n,leftOpen:!0}}),setLeftPinned:e=>t(()=>(Ju(e),{leftPinned:e})),setLeftSidebarWidth:e=>t(n=>{const r=Math.min(Math.max(e,200),500);return n.leftSidebarWidth===r?n:(K2(r),{leftSidebarWidth:r})}),toggleRightPinned:()=>t(e=>{const n=!e.rightPinned;return pa(e.rightSidebarWidthContextKey,n),{rightPinned:n,rightOpen:!0}}),setRightPinned:e=>t(n=>(pa(n.rightSidebarWidthContextKey,e),{rightPinned:e})),setRightSidebarWidth:e=>t(n=>{const r=Math.max(e,co);return n.rightSidebarWidth===r?n:(Qu(n.rightSidebarWidthContextKey,r),{rightSidebarWidth:r})}),setRightSidebarLayoutPreference:e=>t(n=>n.rightSidebarLayoutPreference===e?n:(X2(e),{rightSidebarLayoutPreference:e})),openRight:()=>t({rightOpen:!0}),closeRight:()=>t({rightOpen:!1,rightSearchOpen:!1}),toggleRight:()=>t(e=>({rightOpen:!e.rightOpen,rightSearchOpen:e.rightOpen?!1:e.rightSearchOpen,leftOpen:e.rightOpen?e.leftOpen:!1})),closeAll:()=>t({leftOpen:!1,rightOpen:!1,rightSearchOpen:!1}),setRightTab:e=>t(n=>(ga(n.contextKey,e),{rightTab:e})),openRightSearch:()=>t({rightSearchOpen:!0}),closeRightSearch:()=>t({rightSearchOpen:!1}),setRightSearchOpen:e=>t({rightSearchOpen:e}),setRootPath:(e,n=null,r=null)=>t(o=>{const s=lo(n,e),i=Os(n,e,r),a=r?i:s;if(o.contextKey===a&&o.rightSidebarWidthContextKey===i)return e===o.rootPath?o:{rootPath:e};const c=new Map(o.rootDataCache);o.rootPath&&c.set(o.rootPath,{directoryCache:o.directoryCache,changedFiles:o.changedFiles,gitBundleError:o.gitBundleError,gitBundleLastLoadedAt:o.gitBundleLastLoadedAt,gitBundleCacheInfo:o.gitBundleCacheInfo}),qo(c,12,new Set(e?[e]:[]));const l=e?c.get(e):void 0,d=e===o.rootPath,u=new Map(o.projectStateCache);o.contextKey&&u.set(o.contextKey,{rightTab:o.rightTab,explorerRoot:o.explorerRoot,expandedPaths:new Set(o.expandedPaths),selectedFilePath:o.selectedFilePath,directoryCache:new Map(o.directoryCache),changedFiles:new Map(o.changedFiles),gitBundleError:o.gitBundleError,gitBundleLastLoadedAt:o.gitBundleLastLoadedAt,gitBundleCacheInfo:o.gitBundleCacheInfo});const f=r?qg().has(r):!1;let h={...tf(),...o.explorerRootCache};const g=!!r&&!f,m=g&&s?o.contextKey===s?{rightTab:o.rightTab,explorerRoot:o.explorerRoot,expandedPaths:new Set(o.expandedPaths),selectedFilePath:o.selectedFilePath,directoryCache:new Map(o.directoryCache),changedFiles:new Map(o.changedFiles),gitBundleError:o.gitBundleError,gitBundleLastLoadedAt:o.gitBundleLastLoadedAt,gitBundleCacheInfo:o.gitBundleCacheInfo}:u.get(s):void 0;if(g&&r){const E=m?.rightTab??(s?mc()[s]:void 0)??"files",S=m?.explorerRoot??(s?o.explorerRootCache[s]:void 0)??e,C=m?.selectedFilePath??(s?wc()[s]:void 0)??null,N={rightTab:E,explorerRoot:S,expandedPaths:new Set(m?.expandedPaths??[]),selectedFilePath:C,directoryCache:new Map(m?.directoryCache??[]),changedFiles:new Map(m?.changedFiles??[]),gitBundleError:m?.gitBundleError??null,gitBundleLastLoadedAt:m?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:m?.gitBundleCacheInfo??null};a&&(u.set(a,N),ga(a,E),Or(a,C),S&&(h={...h,[a]:S},Ko(h))),iC(r)}qo(u,12,new Set(a?[a]:[]));const b=a?u.get(a):void 0,w=a?mc()[a]:void 0,I=_s();let y=i?I[i]:void 0;r&&i&&y===void 0&&(y=(s?I[s]:void 0)??ss(),Qu(i,y));const v=a?h[a]:void 0,L=Bs();let k=i?L[i]:void 0;r&&i&&k===void 0&&(k=(s?L[s]:void 0)??os(),pa(i,k));const T=a?wc()[a]:void 0;return{rootPath:e,contextKey:a,rightSidebarWidthContextKey:i,rightSidebarWidth:y??ss(),rightPinned:k??os(),rightOpen:o.rightSidebarWidthContextKey===i?o.rightOpen:!1,rightTab:b?.rightTab??w??"files",explorerRoot:b?.explorerRoot??v??e,expandedPaths:b?new Set(b.expandedPaths):new Set,selectedFilePath:b?.selectedFilePath??T??null,explorerRootCache:h,directoryCache:l?.directoryCache??new Map,changedFiles:l?.changedFiles??new Map,gitBundleLoading:d?o.gitBundleLoading:!1,gitBundleSlow:d?o.gitBundleSlow:!1,gitBundleLoadingOwner:d?o.gitBundleLoadingOwner:null,gitBundleError:l?.gitBundleError??null,gitBundleLastLoadedAt:l?.gitBundleLastLoadedAt??null,gitBundleCacheInfo:l?.gitBundleCacheInfo??null,rootDataCache:c,projectStateCache:u}}),inheritRightSidebarStateFromSplitWorkspace:(e,n)=>t(r=>{if(!e||n.length===0)return r;const o=_s(),s=Os(null,null,e);if(!s)return r;const i=o[s]??(r.rightSidebarWidthContextKey===s?r.rightSidebarWidth:void 0),a=Bs(),c=a[s]??(r.rightSidebarWidthContextKey===s?r.rightPinned:void 0),l=r.contextKey===s?{rightTab:r.rightTab,explorerRoot:r.explorerRoot,expandedPaths:new Set(r.expandedPaths),selectedFilePath:r.selectedFilePath,directoryCache:new Map(r.directoryCache),changedFiles:new Map(r.changedFiles),gitBundleError:r.gitBundleError,gitBundleLastLoadedAt:r.gitBundleLastLoadedAt,gitBundleCacheInfo:r.gitBundleCacheInfo}:r.projectStateCache.get(s);if(i===void 0&&c===void 0&&!l)return r;const d={...o},u=new Map(r.projectStateCache),f={...r.explorerRootCache};for(const h of n){const g=lo(h.sessionId,h.rootPath);g&&(i!==void 0&&(d[g]=i),c!==void 0&&(a[g]=c),l&&(u.set(g,{...l,expandedPaths:new Set(l.expandedPaths),directoryCache:new Map(l.directoryCache),changedFiles:new Map(l.changedFiles)}),ga(g,l.rightTab),Or(g,l.selectedFilePath),l.explorerRoot?f[g]=l.explorerRoot:delete f[g]))}return i!==void 0&&We(Il,d),l&&Ko(f),c!==void 0&&We(Cl,a),qo(u,12,new Set(r.contextKey?[r.contextKey]:[])),{projectStateCache:u,explorerRootCache:f}}),setExplorerRoot:e=>t(n=>{if(n.explorerRoot===e)return n;const r={...n.explorerRootCache};return n.contextKey&&e&&(r[n.contextKey]=e,Ko(r)),{explorerRoot:e,explorerRootCache:r}}),resetExplorerToProject:()=>t(e=>{if(e.explorerRoot===e.rootPath)return e;const n={...e.explorerRootCache};return e.contextKey&&e.rootPath&&(n[e.contextKey]=e.rootPath,Ko(n)),{explorerRoot:e.rootPath,explorerRootCache:n}}),pinExplorerRoot:(e,n="directory")=>t(r=>{if(!r.rootPath||!e)return r;const o=r.rootPath,s=r.pinnedExplorerRootsCache[r.rootPath]??[];if(s.some(a=>a.path===e))return r;const i={...r.pinnedExplorerRootsCache,[r.rootPath]:[{path:e,kind:n},...s].slice(0,12)};return nf(i),(async()=>{try{await Le.getState().hydratePinnedExplorerRoots();const a=await vt({pinnedExplorerRoot:{rootPath:o,path:e,kind:n,pinned:!0},pinnedExplorerRootsOrigin:wa});Le.getState().syncPinnedExplorerRoots(a.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:i}}),unpinExplorerRoot:e=>t(n=>{if(!n.rootPath||!e)return n;const r=n.rootPath,o=n.pinnedExplorerRootsCache[n.rootPath]??[],s=o.find(c=>c.path===e);if(!o.some(c=>c.path===e))return n;const i=o.filter(c=>c.path!==e),a={...n.pinnedExplorerRootsCache};return i.length>0?a[n.rootPath]=i:delete a[n.rootPath],nf(a),(async()=>{try{await Le.getState().hydratePinnedExplorerRoots();const c=await vt({pinnedExplorerRoot:{rootPath:r,path:e,kind:s?.kind??"directory",pinned:!1},pinnedExplorerRootsOrigin:wa});Le.getState().syncPinnedExplorerRoots(c.pinnedExplorerRoots??{})}catch{}})(),{pinnedExplorerRootsCache:a}}),hydratePinnedExplorerRoots:async()=>{if(!Le.getState().pinnedExplorerRootsHydrated)return Mr||(Mr=(async()=>{const e=Le.getState().pinnedExplorerRootsCache;let r=(await rr()).pinnedExplorerRoots??{};Object.keys(r).length===0&&Object.keys(e).length>0&&(r=(await vt({pinnedExplorerRoots:e,pinnedExplorerRootsOrigin:wa})).pinnedExplorerRoots??e),Le.getState().syncPinnedExplorerRoots(r)})().finally(()=>{Mr=null}),Mr)},syncPinnedExplorerRoots:e=>t(()=>{const n={};for(const[r,o]of Object.entries(e)){const s=Hg(o);s.length>0&&(n[r]=s.slice(0,12))}return _r(kl),{pinnedExplorerRootsCache:n,pinnedExplorerRootsHydrated:!0}}),toggleExpanded:e=>t(n=>{const r=new Set(n.expandedPaths);return r.has(e)?r.delete(e):r.add(e),{expandedPaths:r}}),selectFile:e=>t(n=>(Or(n.contextKey,e),{selectedFilePath:e})),toggleShowHiddenFiles:()=>t(e=>{const n=!e.showHiddenFiles;We(_g,n);const r=new Map(e.projectStateCache);for(const[o,s]of r)r.set(o,{...s,directoryCache:new Map});return{showHiddenFiles:n,directoryCache:new Map,projectStateCache:r}}),toggleGroupByFolder:()=>t(e=>{const n=!e.groupByFolder;return ef(n),{groupByFolder:n}}),setGroupByFolder:e=>t(n=>n.groupByFolder===e?n:(ef(e),{groupByFolder:e})),toggleGroupCollapsed:e=>t(n=>{const r=new Set(n.collapsedGroups);return r.has(e)?r.delete(e):r.add(e),J2(r),{collapsedGroups:r}}),setDirectoryCache:(e,n)=>t(r=>{const o=new Map(r.directoryCache);return o.delete(e),o.set(e,n),qo(o,128,new Set([...r.expandedPaths,e,r.explorerRoot??r.rootPath??""])),{directoryCache:o}}),reconcileDirectoryCache:(e,n)=>t(r=>{const o=r.directoryCache.get(e);if(!o)return r;const s=new Map(o.map(d=>[d.path,d])),i=new Set(n.map(d=>d.path)),a=new Map(r.directoryCache),c=n.map(d=>{const u=s.get(d.path);return{name:d.name,path:d.path,type:d.type,isSymlink:d.isSymlink,modified:d.modified,expanded:u?.expanded??!1,loaded:u?.loaded??!1,children:d.type==="directory"?u?.children??[]:void 0}});a.set(e,rf(c,r.fileSortModes[e]??"name"));for(const d of o)if(!i.has(d.path))for(const u of a.keys())Dn(d.path,u)&&a.delete(u);let l=r.selectedFilePath;return l&&o.find(u=>!i.has(u.path)&&Dn(u.path,l))&&(l=null,Or(r.rootPath,null)),{directoryCache:a,selectedFilePath:l}}),hydrateFileSortModes:async()=>{if(!Le.getState().fileSortModesHydrated)return Dr||(Dr=(async()=>{const e=Le.getState().fileSortModes;let r=(await rr()).fileSortModes??{};Object.keys(r).length===0&&Object.keys(e).length>0&&(r=(await vt({fileSortModes:e})).fileSortModes??e),_r(pc),t({fileSortModes:r,fileSortModesHydrated:!0,directoryCache:new Map})})().finally(()=>{Dr=null}),Dr)},setDirectorySortMode:async(e,n)=>{try{await Le.getState().hydrateFileSortModes()}catch{}const r=Le.getState().fileSortModes[e]??"name",o=(ma.get(e)??0)+1;ma.set(e,o),t(s=>{const i={...s.fileSortModes};n==="modified"?i[e]=n:delete i[e];const a=new Map(s.directoryCache);return a.delete(e),{fileSortModes:i,fileSortModesHydrated:!0,directoryCache:a}});try{await vt({fileSortMode:{path:e,mode:n}}),_r(pc)}catch{if(ma.get(e)!==o)return;t(s=>{const i={...s.fileSortModes};r==="modified"?i[e]=r:delete i[e];const a=new Map(s.directoryCache);return a.delete(e),{fileSortModes:i,directoryCache:a}})}},hydrateNestedGitScanRoots:async()=>{if(!Le.getState().nestedGitScanRootsHydrated)return Fr||(Fr=(async()=>{const n=(await rr()).nestedGitScanRoots??{};_r(gc),t({nestedGitScanRoots:n,nestedGitScanRootsHydrated:!0})})().finally(()=>{Fr=null}),Fr)},setNestedGitScanRoot:async(e,n)=>{try{await Le.getState().hydrateNestedGitScanRoots()}catch{}const r=!!Le.getState().nestedGitScanRoots[e],o=(zo.get(e)??0)+1;zo.set(e,o),t(s=>{const i={...s.nestedGitScanRoots};return n?i[e]=!0:delete i[e],{nestedGitScanRoots:i,nestedGitScanRootsHydrated:!0}});try{const s=await vt({nestedGitScanRoot:{rootPath:e,enabled:n}});if(zo.get(e)!==o)return;t({nestedGitScanRoots:s.nestedGitScanRoots??{}}),_r(gc)}catch{if(zo.get(e)!==o)return;t(s=>{const i={...s.nestedGitScanRoots};return r?i[e]=!0:delete i[e],{nestedGitScanRoots:i}})}},invalidateDirectoryCache:(e,n=!1)=>t(r=>{const o=new Map(r.directoryCache);for(const s of o.keys())(s===e||n&&Dn(e,s))&&o.delete(s);return{directoryCache:o}}),applyFileWatchEvents:e=>t(n=>{if(e.length===0)return n;const r=new Map(n.directoryCache),o=new Map(n.fileChangeVersions);let s=n.selectedFilePath,i=!1,a=!1,c=!1;const l=d=>{o.set(d,(o.get(d)??0)+1),a=!0};for(const d of e){if(d.type==="rescan-required"){c=!0,s&&Dn(d.path,s)&&l(s);continue}const u=hC(d.path),f=r.get(u);if(d.type==="deleted"){if(l(d.path),s&&Dn(d.path,s)&&(s=null,Or(n.rootPath,null)),f){const b=f.filter(w=>w.path!==d.path);b.length!==f.length&&(r.set(u,b),i=!0)}for(const b of r.keys())Dn(d.path,b)&&(r.delete(b),i=!0);continue}l(d.path);const h=pC(d);if(!h||!f)continue;const g=f.find(b=>b.path===h.path),m=rf(g?f.map(b=>b.path===h.path?{...b,...h,children:b.children}:b):[...f,h],n.fileSortModes[u]??"name");r.set(u,m),i=!0}return!i&&!a&&!c?n:{directoryCache:i?r:n.directoryCache,selectedFilePath:s,fileChangeVersions:a?o:n.fileChangeVersions,fileWatchEpoch:c?n.fileWatchEpoch+1:n.fileWatchEpoch}}),bumpFileWatchEpoch:()=>t(e=>({fileWatchEpoch:e.fileWatchEpoch+1})),setChangedFiles:e=>t({changedFiles:e}),beginGitBundleLoading:e=>t({gitBundleLoading:!0,gitBundleSlow:!1,gitBundleLoadingOwner:e}),setGitBundleSlowFor:(e,n)=>t(r=>r.gitBundleLoadingOwner===e?{gitBundleSlow:n}:r),finishGitBundleLoading:e=>t(n=>n.gitBundleLoadingOwner===e?{gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}:n),resetGitBundleLoading:()=>t({gitBundleLoading:!1,gitBundleSlow:!1,gitBundleLoadingOwner:null}),setGitBundleError:e=>t({gitBundleError:e}),markGitBundleLoaded:(e=null)=>t({gitBundleLastLoadedAt:Date.now(),gitBundleCacheInfo:e})})),ya=(()=>{if(location.hash.startsWith("#termdock-invite="))try{return Ls(location.href)}catch{return}finally{history.replaceState(null,"",location.pathname+location.search)}})(),yc="termdock-secure-open-session";let ba,jr;function gC(){try{const t=JSON.parse(sessionStorage.getItem(yc)??"null");return t?.serviceId===re()?.targetPeerId?t.sessionId:void 0}catch{return}}function mC({children:t}){const[e,n]=_.useState(ya),[r,o]=_.useState(!1),[s,i]=_.useState(!!ya),[a,c]=_.useState(!ya),[l,d]=_.useState(!1),[u,f]=_.useState("正在连接服务…"),[h,g]=_.useState([]),[m,b]=_.useState([]),[w,I]=_.useState(!1),[y,v]=_.useState(!1),[L,k]=_.useState(""),[T,E]=_.useState(!1),[S,C]=_.useState(""),[N,D]=_.useState(re()?.serviceName??location.hostname),[A,x]=_.useState(gC);_.useEffect(()=>{(!r&&!a||r&&(!w||A))&&Mn({rendered:!0})},[r,a,w,A]),_.useEffect(()=>{Qe().then(F=>k(F.peerId)).catch(()=>d(!0))},[]),_.useEffect(()=>{const F=U=>{const{origin:H,sessionId:q}=U.detail;try{const W=JSON.parse(localStorage.getItem("termdock.federation.connections.v1")??"[]").find(V=>wr(V).some(G=>new URL(G).origin===new URL(H).origin));if(!W){i(!0);return}if(ut()?.focusSession(W.targetPeerId,q))return;sessionStorage.setItem(yc,JSON.stringify({serviceId:W.targetPeerId,sessionId:q})),Ze(W).then(()=>{x(q),o(!0)}).catch(()=>{d(!0),i(!0)})}catch{i(!0)}};return window.addEventListener("termdock:open-remote-session",F),()=>window.removeEventListener("termdock:open-remote-session",F)},[]);const P=async(F=5e3)=>{const U=await dt(),H=await mr(U,{timeoutMs:F}),q=cE(),K=eE()?.targetPeerId;Promise.all([g1(),He()]).then(([V,G])=>{const X=G.find(ce=>ce.targetPeerId===K),Z=q==="relay"?`经 ${X?.label||K?.slice(-12)||"入口服务"} 中转`:"直连";return U.request({type:"device-name",name:eg(),onlyIfMissing:!0,profile:{...V,route:Z}})}).catch(()=>{}),I(H.fullService),v(H.canManage),o(!0),c(!1),d(!1);const W=re();Mn({phase:"ready",...W?{service:{...W,id:W.targetPeerId,label:W.serviceName||location.host}}:{}}),Yo()&&aE()};_.useEffect(()=>{let F=!1,U=!1,H=0,q;const K=async()=>{if(F||U||H&&(document.hidden||!Yo()))return;if(!navigator.onLine){c(!0),d(!0),f("网络已断开,恢复后会自动连接"),Mn({phase:"offline"});return}U=!0,clearTimeout(q);const Ie=performance.now(),Me=nn();try{if(Ms&&!re())throw new Error("工作区的服务记录已移除,请重新添加服务。");jr??=window.termdockDesktop?.getServiceConnection?.();const ne=await jr;if(ne?.invitation){n(Ls(ne.invitation)),i(!0),c(!1);return}if(!re()){if(e){c(!1);return}if(ba??=(async()=>{if(ne?.targetPeerId){await Ze({...ne,targetPeerId:ne.targetPeerId,serviceName:ne.label});return}const Ve=await window.termdockDesktop?.getLocalInvite?.();Ve?await Ze(Ve):await tE()})(),await ba,!re()){F||(o(!1),c(!1),d(!1));return}}F||await P(Me?.canSwitchTransport?2500:5e3),H=0,performance.measure("termdock:connection-ready",{start:Ie,end:performance.now()})}catch(ne){if(F)return;ne instanceof Je?(o(!1),c(!1),i(!1),d(!1),Mn({phase:"login"})):(Me&&nn()===Me&&Mp(),d(!0),c(!0),ba=void 0,f("连接暂未恢复,正在重试…"),Mn({phase:"reconnecting"}),H++,q=setTimeout(()=>{K()},Math.min(5e3,300*2**Math.min(H-1,5))),console.debug("[connection] retry",{elapsedMs:Math.round(performance.now()-Ie),attempt:H,reason:ne instanceof Error?ne.message:"unknown"}))}finally{U=!1}},W=()=>{document.visibilityState==="visible"&&Yo()&&K()},V=W,G=()=>{H=0,W()},X=()=>{Le.getState().openLeft(),W()};window.addEventListener(ao,W),window.addEventListener(Ja,X),ut()?.attach(ni(),window),K(),document.addEventListener("visibilitychange",V),window.addEventListener("focus",W),window.addEventListener("online",G);const Z=navigator.connection;Z?.addEventListener("change",G),window.addEventListener("auth:unauthorized",W),window.addEventListener(Ye,W);const ce=setInterval(W,3e4);return()=>{F=!0,clearTimeout(q),clearInterval(ce),window.removeEventListener(ao,W),window.removeEventListener(Ja,X),document.removeEventListener("visibilitychange",V),window.removeEventListener("focus",W),window.removeEventListener("online",G),Z?.removeEventListener("change",G),window.removeEventListener("auth:unauthorized",W),window.removeEventListener(Ye,W)}},[]);const R=async()=>{const F=nn();if(F){E(!0),C("");try{const U=await F.request({type:"session-list"});b(U.items)}catch{C("暂时无法读取终端列表,请重试。")}try{if(y){const U=await F.request({type:"grants-list"}),H=U.subjectLabels??{},q=await F.request({type:"route-access"}),K=await He(),W=(Array.isArray(q.grants)?q.grants:[]).map(V=>({id:`route:${V.id}`,subjectId:V.subjectId,scope:{kind:"service"},actions:["route.use"],routeTargetServiceId:V.targetServiceId,routeTargetName:K.find(G=>G.targetPeerId===V.targetServiceId)?.label||"指定服务",...V.active?{}:{revokedAt:V.revokedAt??0}}));g([...U.grants,...W].map(V=>({...V,label:H[V.subjectId],deviceProfile:U.deviceProfiles?.[V.subjectId]})))}else{const U=await F.request({type:"permissions"});g(U.grants??[])}}catch{C("暂时无法读取设备权限,请重试。")}finally{E(!1)}}};_.useEffect(()=>{const F=()=>{i(!0),r&&R()};return window.addEventListener(nc,F),()=>window.removeEventListener(nc,F)},[r,y]);const O=async F=>{if(!F.pairingCode&&!F.routeCode&&re()?.targetPeerId!==F.targetPeerId&&ut()){const U={...F,id:F.targetPeerId,label:F.serviceName||new URL(F.serviceOrigin||F.url).host};if(await Ct(U),Ns(U)){i(!1);return}}await Ze(F),jr&&(jr=jr.then(U=>U?{...U,invitation:void 0}:null)),n(void 0),x(void 0),sessionStorage.removeItem(yc),D(F.serviceName??new URL(F.url).hostname),await P(),i(!1),d(!1)},j=async F=>{const U=window.termdockDesktop;if(U?.openServiceConnection){const H=await U.openServiceConnection(F);if(!H.ok)throw new Error(H.error||"暂时无法打开这台服务。");i(!1);return}if(Ns(F)){i(!1);return}if(F.targetPeerId)try{await O({...F,targetPeerId:F.targetPeerId,serviceName:F.label});return}catch(H){if(!(H instanceof Je))throw H}return su(F.serviceOrigin||F.url)};_.useEffect(()=>{const F=U=>{j(U.detail).catch(H=>{i(!0),C(H instanceof Error?H.message:"暂时无法打开服务")})};return window.addEventListener(hc,F),()=>window.removeEventListener(hc,F)});const M=async(F,U)=>{if(F.includes("#termdock-invite=")){const q=Ls(F);if(window.termdockDesktop?.openServiceConnection){const K=await window.termdockDesktop.openServiceConnection({id:q.targetPeerId,url:q.url,label:q.serviceName||new URL(q.serviceOrigin||q.url).host,targetPeerId:q.targetPeerId,serviceOrigin:q.serviceOrigin,entryServiceId:q.entryServiceId},F);if(!K.ok)throw new Error(K.error||"暂时无法打开邀请。");i(!1);return}if(U!==void 0&&q.routeOnly){await iu(q,U),await P(),i(!1);return}try{await O(q)}catch(K){if(q.routeOnly&&K instanceof Je)return{passwordRequired:!0};throw K}return}const H=Oe(F);return window.termdockDesktop?.openServiceConnection?j({id:H,url:H,label:new URL(H).host}):su(H,U)},B=async F=>{const U=await dt(),{includeBackup:H=!0,...q}=F,K=re(),W=K?Vt(K):[];let V;if(H&&W.length){for(const Z of W)try{const ce=await $p({...K,targetPeerId:U.targetPeerId},Z);V={...Z,routeCode:ce.routeCode};break}catch{}if(!V)throw new Error("无法分享备用连接:需要入口管理员授权。也可以关闭此选项,生成直接连接邀请。")}let G=K?.serviceOrigin||location.origin;if(["localhost","127.0.0.1","[::1]"].includes(new URL(G).hostname)){const ce=await(await U.fetch("/api/terminal/settings")).json();typeof ce.localAccess?.url=="string"&&(G=ce.localAccess.url)}const X=await U.request({type:"invite-create",...q});if(typeof X.code!="string"||typeof X.expiresAt!="number")throw new Error("暂时无法生成邀请。");return{url:tg({v:1,serviceId:U.targetPeerId,code:X.code,entryUrl:V?.url||G,serviceUrl:G,name:N,entryServiceId:V?.targetPeerId,routeCode:V?.routeCode}),expiresAt:X.expiresAt}};return p.jsxs(p.Fragment,{children:[r?w&&!A?t:p.jsx(Y1,{client:nn(),initialSessionId:A}):a?p.jsx("div",{className:"flex h-full min-h-0 flex-col items-center justify-center bg-[var(--chrome-bg)] px-6 text-foreground",children:p.jsxs("div",{className:"flex w-full max-w-xs flex-col items-center text-center",children:[p.jsx("div",{className:"mb-5 flex h-12 w-12 items-center justify-center rounded-2xl bg-surface-2 text-muted-foreground","aria-hidden":"true",children:p.jsx(XE,{size:24,strokeWidth:1.5})}),p.jsx("h1",{className:"max-w-full truncate text-base font-medium tracking-tight",title:N,children:N}),p.jsxs("div",{role:"status",className:"mt-2 flex max-w-full items-center justify-center gap-2 text-xs leading-5 text-muted-foreground",children:[!l&&p.jsx(De,{size:13,className:"shrink-0 animate-spin motion-reduce:animate-none","aria-hidden":"true"}),p.jsx("span",{children:u})]}),l&&p.jsx("p",{className:"mt-2 text-xs leading-5 text-muted-foreground",children:"登录信息已保留"}),p.jsx("button",{type:"button",className:"mt-6 min-h-11 rounded-lg px-4 text-xs text-muted-foreground transition-colors hover:bg-surface-2 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>i(!0),children:"管理服务"})]})}):p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"fixed left-0 right-0 top-[var(--safe-top-inset)] z-chrome sm:right-auto sm:w-72",children:p.jsx(D2,{})}),p.jsx(N2,{onLoginSuccess:()=>{P().catch(()=>d(!0))}})]}),s&&p.jsx(W1,{onConnect:O,onClose:()=>i(!1),onAddService:M,onOpenService:j,onConnectWithPassword:async(F,U)=>{await iu(F,U),await P(),i(!1)},paired:r||!!re(),initialInvite:e,currentServiceName:N,currentServiceId:nn()?.targetPeerId||re()?.targetPeerId,currentServiceOrigin:re()?.serviceOrigin,currentIdentity:L,grants:h,sessions:m,loading:T,loadError:S,onRetry:()=>{R()},onRename:async(F,U)=>{await(await dt()).request({type:"device-name",subjectId:F,name:U}),await R()},hasBackup:!!re()&&Vt(re()).length>0,onCreateInvite:y?B:void 0,onRevoke:y?async F=>{await(await dt()).request(F.startsWith("route:")?{type:"route-revoke",grantId:F.slice(6)}:{type:"revoke",grantId:F}),await R()}:void 0})]})}function wC(t,e,n){const r=t?.name||"Error",o=t?.message||"Unexpected error";return["Termdock error report",`Time: ${n.capturedAt}`,`URL: ${n.url}`,`User agent: ${n.userAgent}`,"",`${r}: ${o}`,t?.stack?`
30
30
  Stack:
31
31
  ${t.stack}`:"",e?`
32
32
  React component stack:
33
33
  ${e.trim()}`:""].filter(Boolean).join(`
34
- `)}async function yC(t){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(t),!0}catch{}const e=document.createElement("textarea");e.value=t,e.setAttribute("readonly",""),e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select();try{return document.execCommand("copy")}catch{return!1}finally{e.remove()}}function bC({error:t,componentStack:e}){const{t:n}=ii(),[r,o]=ze.useState("idle"),s=async()=>{const i=wC(t,e,{url:window.location.href,userAgent:navigator.userAgent,capturedAt:new Date().toISOString()});o(await yC(i)?"copied":"failed")};return p.jsx("div",{className:"flex h-full items-center justify-center p-4",children:p.jsxs("div",{className:"flex flex-col items-center gap-3 text-center max-w-md",children:[p.jsx("div",{className:"w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center",children:p.jsx("svg",{className:"w-6 h-6 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:p.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),p.jsxs("div",{className:"space-y-1",children:[p.jsx("h3",{className:"font-medium text-foreground",children:n("errorBoundary.title")}),p.jsx("p",{className:"text-sm text-muted-foreground",children:t?.message||n("errorBoundary.unexpected")})]}),p.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-center gap-2",children:[p.jsx("button",{type:"button",onClick:()=>{s()},className:"rounded-full bg-surface-2 px-5 py-2.5 text-sm font-medium text-foreground ring-1 ring-border/15 transition hover:bg-surface-elevated active:scale-[0.97]",children:n(r==="copied"?"errorBoundary.copied":r==="failed"?"errorBoundary.copyFailed":"errorBoundary.copyDetails")}),p.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"rounded-full bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground shadow-sm transition-all hover:bg-primary/90 active:scale-[0.97]",children:n("errorBoundary.retry")})]})]})})}class vC extends ze.Component{state={hasError:!1,error:null,componentStack:""};static getDerivedStateFromError(e){return{hasError:!0,error:e,componentStack:""}}componentDidCatch(e,n){console.error("Terminal error caught by boundary:",e,n),this.setState({componentStack:n.componentStack??""})}render(){return this.state.hasError?this.props.fallback?this.props.fallback:p.jsx(bC,{error:this.state.error,componentStack:this.state.componentStack}):this.props.children}}function ge(){try{if(window.parent!==window&&location.pathname==="/workspace.html"&&window.parent.location.origin===location.origin&&window.parent.__termdockWorkspaceHost)return window.parent}catch{}return window}const SC="debug",xC="termdock:debug";function of(t){return t?new Set(t.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean)):new Set}function EC(){if(typeof window>"u")return new Set;const t=of(new URLSearchParams(window.location.search).get(SC));let e=new Set;try{e=of(window.localStorage.getItem(xC))}catch{e=new Set}const n=new Set([...t,...e]);return n.has("1")||n.has("true")||n.has("*")||n.has("all")?new Set(["*"]):n}function AC(t){const e=EC();return e.has("*")||e.has(t)}function kC(t){const e=AC(t);return(...n)=>{e&&console.log(`[debug:${t}]`,...n)}}const sf=80,CC=60,IC="termdock:viewport-keyboard-change",RC="termdock:viewport-layout-change",At=240,af=640,cf=360,TC=1500;function PC({measuredHeight:t,documentVisible:e,editableFocused:n}){return e&&n&&t>0}function va(){if(typeof document>"u")return!1;const t=document.activeElement;return t instanceof HTMLElement&&t.matches('input:not([type="hidden"]), textarea, select, [contenteditable]:not([contenteditable="false"])')}const Ds=t=>{const e=typeof t=="number"?t:Number.parseFloat(typeof t=="string"?t:"0");return Number.isFinite(e)&&e>0?Math.round(e):0},Kg=(t,e)=>{const n=t.map(Ds).filter(r=>r>0);return n.find(r=>r>=At)??n[0]??e},Qr=()=>typeof window>"u"?af:Kg([ge().innerHeight,document.documentElement?.clientHeight,document.body?.clientHeight,ge().visualViewport?.height,window.screen?.availHeight,window.screen?.height],af),zg=()=>typeof window>"u"?cf:Kg([ge().innerWidth,document.documentElement?.clientWidth,document.body?.clientWidth,ge().visualViewport?.width,window.screen?.availWidth,window.screen?.width],cf),jt=t=>{const e=Number.parseFloat(t||"0");return Number.isFinite(e)?Math.max(0,Math.round(e)):0},Wg=()=>typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,NC=()=>typeof window>"u"?!1:ge().navigator.standalone===!0||ge().matchMedia?.("(display-mode: standalone)").matches===!0,Vg=()=>{if(typeof window>"u"||!Wg()||!NC())return{top:0,right:0,bottom:0,left:0};if(!(Qr()>=zg()))return{top:0,right:0,bottom:0,left:0};const e=window.screen?.width||window.innerWidth,n=window.screen?.height||window.innerHeight,r=Math.min(e,n),o=Math.max(e,n);return r>=700?{top:20,right:0,bottom:20,left:0}:o<780?{top:20,right:0,bottom:0,left:0}:{top:o>=852?59:o>=844?47:44,right:0,bottom:34,left:0}};function LC(t="--app-vh"){if(typeof window>"u"||typeof document>"u")return;const e=Ds(ge().visualViewport?.height),n=Math.max(0,Math.round(ge().visualViewport?.offsetTop??0)),r=Qr(),s=e>=At?Math.min(r,e+n):r,i=Math.max(r,s),a=document.documentElement.style;a.setProperty(t,`${Math.max(s,At)}px`),a.setProperty("--app-base-vh",`${Math.max(i,At)}px`),a.setProperty("--app-visible-vh",`${Math.max(s,At)}px`),a.setProperty("--app-vv-offset-top",`${n}px`),a.setProperty("--kb-translate-y","0px"),a.setProperty("--kb-margin-top","0px"),a.setProperty("--kb-height","0px");const c=Vg();c.top>0&&a.setProperty("--safe-top-inset",`${c.top}px`),c.right>0&&a.setProperty("--safe-right-inset",`${c.right}px`),c.bottom>0&&a.setProperty("--safe-bottom-inset",`${c.bottom}px`),c.left>0&&a.setProperty("--safe-left-inset",`${c.left}px`)}function iR(t={}){const{cssVarName:e="--app-vh"}=t,n=ze.useMemo(()=>kC("viewport"),[]),r=ze.useCallback(()=>{if(typeof window>"u")return 0;const d=ge().visualViewport,u=Qr();if(!d)return u;const f=Ds(d.height);if(f<At&&u>=At)return u;const h=d.offsetTop,m=f<u-1&&h>0&&h<=96?f+h:f,b=Math.max(0,Math.min(u,m));return b>0?Math.round(b):u},[]),[o,s]=ze.useState(r),i=ze.useRef(0),a=ze.useRef(0),c=ze.useRef(0),l=ze.useRef(!1);return ze.useEffect(()=>{if(typeof window>"u")return;let d=null,u=0,f=null,h="",g=null;const m=()=>{if(g?.isConnected)return g;try{return g=document.createElement("div"),g.setAttribute("aria-hidden","true"),g.style.cssText=["position:fixed","top:0","left:0","width:0","height:0","visibility:hidden","pointer-events:none","padding-top:constant(safe-area-inset-top)","padding-top:env(safe-area-inset-top,0px)","padding-right:constant(safe-area-inset-right)","padding-right:env(safe-area-inset-right,0px)","padding-bottom:constant(safe-area-inset-bottom)","padding-bottom:env(safe-area-inset-bottom,0px)","padding-left:constant(safe-area-inset-left)","padding-left:env(safe-area-inset-left,0px)"].join(";"),(document.body||document.documentElement).appendChild(g),g}catch{}return null},b=()=>{let R={top:0,right:0,bottom:0,left:0};try{const B=m();if(B){const F=getComputedStyle(B);R={top:jt(F.paddingTop),right:jt(F.paddingRight),bottom:jt(F.paddingBottom),left:jt(F.paddingLeft)}}}catch{}const O=ge();if(O!==window){const B=O.getComputedStyle(O.document.documentElement);R={top:Math.max(R.top,jt(B.getPropertyValue("--safe-top-inset"))),right:Math.max(R.right,jt(B.getPropertyValue("--safe-right-inset"))),bottom:Math.max(R.bottom,jt(B.getPropertyValue("--safe-bottom-inset"))),left:Math.max(R.left,jt(B.getPropertyValue("--safe-left-inset")))}}const j=Vg(),M={top:Math.max(R.top,j.top),right:Math.max(R.right,j.right),bottom:Math.max(R.bottom,j.bottom),left:Math.max(R.left,j.left)};return document.documentElement.style.setProperty("--safe-top-inset",`${M.top}px`),document.documentElement.style.setProperty("--safe-right-inset",`${M.right}px`),document.documentElement.style.setProperty("--safe-bottom-inset",`${M.bottom}px`),document.documentElement.style.setProperty("--safe-left-inset",`${M.left}px`),M},w=(R,O,j,M)=>{const B=Math.max(O,j);if(i.current===0){i.current=B,a.current=R,document.documentElement.style.setProperty("--app-base-vh",`${B}px`);return}const F=Math.abs(R-a.current),U=M<=sf;(F>CC||U)&&(i.current=B,a.current=R,document.documentElement.style.setProperty("--app-base-vh",`${B}px`))},I=(R="event")=>{d=null;const O=r(),j=Math.round(ge().visualViewport?.offsetTop??0),M=Ds(ge().visualViewport?.height),B=M>=At?M:O,F=Qr(),U=zg(),H=Math.max(0,B+j),q=b(),K=q.bottom,W=Math.max(0,i.current-H-K);w(U,F,H,W),s(Rn=>Rn===O?Rn:O);const V=Number.parseInt(document.documentElement.style.getPropertyValue(e)||"0",10);document.documentElement.style.setProperty(e,`${O}px`),document.documentElement.style.setProperty("--app-vv-offset-top",`${j}px`);const G=i.current,X=Math.min(O,B),Z=Math.max(0,Math.min(G,H)),ce=Math.max(0,Math.round(G-X-K)),Ie=va(),Me=PC({measuredHeight:ce,documentVisible:document.visibilityState==="visible",editableFocused:Ie}),ne=Me?ce:0,Ve=ne>=sf,Yt=-ne,Zt=ne;document.documentElement.style.setProperty("--kb-translate-y",`${Yt}px`),document.documentElement.style.setProperty("--kb-margin-top",`${Zt}px`),document.documentElement.style.setProperty("--kb-height",`${ne}px`),document.documentElement.style.setProperty("--app-visible-vh",`${Z}px`);const je=Math.abs(ne-c.current)>1,Jt=Ve!==l.current;(je||Jt)&&(c.current=ne,l.current=Ve,document.dispatchEvent(new CustomEvent(IC,{detail:{baseHeight:G,visibleHeight:Z,visualViewportHeight:B,offsetTop:j,keyboardHeight:ne,isOpen:Ve,source:R}}))),(V!==O||j>0||je||Jt)&&n("sync",{cssVarName:e,innerHeight:F,baseHeight:G,rawViewportHeight:B,offsetTop:j,visibleHeight:Z,rawHeight:O,appliedHeight:O,keyboardViewportHeight:X,measuredKeyboardHeight:ce,editableFocused:Ie,applyKeyboardInset:Me,keyboardHeight:ne,isKeyboardOpen:Ve,safeAreaInsets:q,source:R}),document.dispatchEvent(new CustomEvent(RC,{detail:{height:O,baseHeight:G,visibleHeight:Z,offsetTop:j,source:R}}))},y=()=>{d===null&&(d=window.requestAnimationFrame(()=>{d=null;const R=ge(),O=R.visualViewport,j=[R.innerWidth,R.innerHeight,O?.width,O?.height,O?.offsetTop,O?.offsetLeft,document.visibilityState,va()].join(":"),M=f;f=null,(M||j!==h)&&(h=j,I(M||"viewport.settle")),performance.now()<u&&y()}))},v=(R="event")=>{(R.includes("visibilitychange")||R.includes("pageshow"))&&n("schedule",{source:R}),f=R,Wg()&&document.visibilityState==="visible"&&(u=performance.now()+TC),y()};v("mount");const L=()=>v("resize"),C=()=>v("orientationchange"),T=()=>v("visualViewport.resize"),E=()=>v("visualViewport.scroll"),S=()=>v("focusin"),k=()=>v("focusout"),N=R=>{u=0;const O=document.activeElement;O instanceof HTMLElement&&va()&&O.blur(),c.current=0,l.current=!1;const j=Math.max(i.current,Qr(),At),M=document.documentElement.style;M.setProperty(e,`${j}px`),M.setProperty("--app-visible-vh",`${j}px`),M.setProperty("--app-vv-offset-top","0px"),M.setProperty("--kb-translate-y","0px"),M.setProperty("--kb-margin-top","0px"),M.setProperty("--kb-height","0px"),s(B=>B===j?B:j),n("keyboard session reset",{source:R,baseHeight:j})};window.addEventListener("resize",L),window.addEventListener("orientationchange",C),ge().visualViewport?.addEventListener("resize",T),ge().visualViewport?.addEventListener("scroll",E),document.addEventListener("focusin",S),document.addEventListener("focusout",k);const D=R=>{n("resume",{source:R,innerHeight:Math.round(window.innerHeight),visualViewport:ge().visualViewport?{width:Math.round(ge().visualViewport.width),height:Math.round(ge().visualViewport.height),offsetTop:Math.round(ge().visualViewport.offsetTop)}:null,hidden:document.hidden}),v(R)},A=()=>{document.hidden?N("visibilitychange:hidden"):D("visibilitychange")},x=()=>D("pageshow"),P=()=>N("pagehide");return document.addEventListener("visibilitychange",A),window.addEventListener("pageshow",x),window.addEventListener("pagehide",P),()=>{window.removeEventListener("resize",L),window.removeEventListener("orientationchange",C),ge().visualViewport?.removeEventListener("resize",T),ge().visualViewport?.removeEventListener("scroll",E),document.removeEventListener("focusin",S),document.removeEventListener("focusout",k),document.removeEventListener("visibilitychange",A),window.removeEventListener("pageshow",x),window.removeEventListener("pagehide",P),d!==null&&window.cancelAnimationFrame(d),g?.remove()}},[e,n,r]),o}const BC=1e3,_C=2e4,OC=9e4,DC=5e3,Q={ws:null,listeners:new Set,reconnectAttempt:0,reconnectTimer:null,idleCloseTimer:null,closing:!1};let Wo=0,sr=null;function FC(){return typeof window>"u"?null:`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/control/ws`}function Gg(){Q.idleCloseTimer&&(clearTimeout(Q.idleCloseTimer),Q.idleCloseTimer=null)}function MC(){Gg(),!(Q.ws&&Q.ws.readyState===WebSocket.OPEN)&&(Q.idleCloseTimer=setTimeout(()=>{Q.idleCloseTimer=null,Q.listeners.size===0&&jC()},DC))}function jC(){if(Q.ws){try{Q.ws.close()}catch{}Q.ws=null}sr&&(clearInterval(sr),sr=null)}function lf(){if(Q.reconnectTimer)return;const t=Math.min(BC*Math.pow(2,Q.reconnectAttempt),_C);Q.reconnectAttempt+=1,Q.reconnectTimer=setTimeout(()=>{Q.reconnectTimer=null,Xg()},t)}function Xg(){const t=FC();if(!t||Q.ws&&Q.ws.readyState===WebSocket.OPEN)return;let e;try{e=Up(t)}catch{lf();return}Q.ws=e,e.onopen=()=>{Q.reconnectAttempt=0,Wo=Date.now(),sr||(sr=setInterval(()=>{if(!(!Q.ws||Q.ws.readyState!==WebSocket.OPEN)&&Wo>0&&Date.now()-Wo>OC)try{Q.ws.close()}catch{}},3e4),sr.unref?.())},e.onmessage=n=>{Wo=Date.now();let r=null;try{r=JSON.parse(n.data)}catch{return}if(!r)return;if(r.type==="session-notice"){if(typeof r.id!="string"||typeof r.sessionId!="string"||typeof r.sessionName!="string"||typeof r.message!="string"||!r.message.trim()||r.message.length>4e3||r.title!==void 0&&(typeof r.title!="string"||r.title.length>120)||typeof r.createdAt!="number")return;const i=r;for(const a of Q.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type==="update-state"){const i=r.state;if(!i||typeof i.status!="string"||typeof i.currentVersion!="string")return;const a={type:"update-state",state:i};for(const c of Q.listeners)try{c(a)}catch(l){console.error("[clientStateSync] listener threw:",l)}return}if(r.type==="context-draft"){if(typeof r.text!="string")return;const i={type:"context-draft",text:r.text,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const a of Q.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type==="pinned-explorer-roots"){if(!r.pinnedExplorerRoots||typeof r.pinnedExplorerRoots!="object"||Array.isArray(r.pinnedExplorerRoots))return;const i={type:"pinned-explorer-roots",pinnedExplorerRoots:r.pinnedExplorerRoots,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const a of Q.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type==="config-updated"){if(r.key!=="toolbar-presets"&&r.key!=="agent-rules"&&r.key!=="program-detection")return;const i={type:"config-updated",key:r.key,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0};for(const a of Q.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type!=="client-state"||!r.state)return;const o=r.state,s={type:"client-state",clientState:{sessions:Array.isArray(o.sessions)?o.sessions:[],updatedAt:typeof o.updatedAt=="number"?o.updatedAt:Date.now()},inventory:r.inventory,seq:typeof r.seq=="number"?r.seq:void 0};for(const i of Q.listeners)try{i(s)}catch(a){console.error("[clientStateSync] listener threw:",a)}},e.onclose=()=>{Q.ws===e&&(Q.ws=null),Q.listeners.size>0&&lf()},e.onerror=()=>{}}function Yg(t){return Q.listeners.add(t),Gg(),Q.ws||Xg(),()=>{Q.listeners.delete(t),Q.listeners.size===0&&MC()}}const Sa=oi(t=>({unread:{},viewing:null,receive:(e,n)=>t(r=>{const o=r.unread[e]??[];return r.viewing===e||o.includes(n)?r:{unread:{...r.unread,[e]:[...o,n]}}}),view:e=>t(n=>{if(!e||!n.unread[e])return n.viewing===e?n:{viewing:e};const r={...n.unread};return delete r[e],{viewing:e,unread:r}})})),Zg=new Set(["bash","zsh","fish","sh","dash","ksh","tcsh","csh","nu"]);function qn(t){if(!t)return null;if(t==="/")return"/";const e=t.replace(/\/+$/,"").split("/");return e[e.length-1]||t}function UC(t,e,n,r=Zg,o=null,s=null){if(t.customName)return{primary:t.name,secondary:qn(n)};if(o){const a=qn(n),c=o===n||o===a;if(s!=="idle"&&!r.has(o)&&!c)return{primary:o,secondary:a}}if(e&&!r.has(e))return{primary:e,secondary:qn(n)};const i=qn(n);return i?{primary:i,secondary:null}:{primary:t.name,secondary:null}}function $C(t,e,n,r=Zg,o=null,s=null){return UC(t,e,n,r,o,s).primary}function HC(t,e,n){const r=[],o=new Map;for(const s of t){const i=e(s),a=i&&i.trim().length>0?i:"";let c=o.get(a);c||(c={key:a,label:a?qn(a)??a:n,sessions:[]},o.set(a,c),r.push(c)),c.sessions.push(s)}return r.sort((s,i)=>(s.key===""?1:0)-(i.key===""?1:0))}function aR(t){return t&&t.trim().length>0?t:""}function cR(t,e,n){const r=[...t],[o]=r.splice(e,1);return o?(r.splice(n,0,o),r.flatMap(s=>s.sessions.map(i=>i.id))):t.flatMap(s=>s.sessions.map(i=>i.id))}function qC(t,e){const n=new Set;return t.flatMap(r=>{const o=[...new Set(r.sessionIds)].filter(s=>e.has(s)&&!n.has(s));return o.length<(r.federated?1:2)?[]:(o.forEach(s=>n.add(s)),[{...r,sessionIds:o}])})}function lR(t,e,n,r,o=[],s=[]){const i=new Map(t.map(g=>[g.id,g])),a=qC(s,new Set(i.keys())),c=new Map,l=new Map,d=o.filter(g=>g.sessionIds.length>=2&&g.sessionIds.every(m=>i.has(m))),u=(g,m)=>{const b=i.get(m);g.forEach(w=>{c.set(w,g),l.set(w,b)})};for(const g of a){const m=new Set(g.sessionIds),b=new Map;for(const y of d)y.sessionIds.every(v=>m.has(v))&&y.sessionIds.forEach(v=>b.set(v,y.sessionIds));const w=new Set,I=g.sessionIds.flatMap(y=>{if(w.has(y))return[];const v=b.get(y)??[y];return v.forEach(L=>w.add(L)),v});u(I,g.sessionIds[0])}for(const g of d)g.sessionIds.some(m=>c.has(m))||u(g.sessionIds,g.sessionIds[0]);const f=g=>{const m=new Set;return g.flatMap(b=>{if(m.has(b.id))return[];const w=c.get(b.id)??[b.id];return w.forEach(I=>m.add(I)),w.map(I=>i.get(I))})};if(!n)return{arranged:f(t),groups:[]};const h=HC(t,g=>e(l.get(g.id)??g),r).map(g=>({...g,sessions:f(g.sessions)}));return{arranged:h.flatMap(g=>g.sessions),groups:h}}function KC(t,e,n){const r=t.findIndex(o=>n(o)===e);return r<0?null:t[r+1]?n(t[r+1]):r>0?n(t[r-1]):null}const xa="termdock-sessions",bc="termdock-active-session",Rl="termdock-sessions-cache";function vc(){try{const t=localStorage.getItem(bc);return t&&t.trim().length>0?t:null}catch{return null}}function Fn(t){try{t?localStorage.setItem(bc,t):localStorage.removeItem(bc)}catch{}}function Jg(){if(typeof window>"u")return null;try{const t=localStorage.getItem(Rl);if(!t)return null;const e=JSON.parse(t);return Array.isArray(e)?e.filter(n=>typeof n=="object"&&n!==null&&typeof n.sessionId=="string"&&typeof n.name=="string"):null}catch{return null}}function tn(t){if(!(typeof window>"u"))try{localStorage.setItem(Rl,JSON.stringify(t))}catch{}}function df(){if(!(typeof window>"u"))try{localStorage.removeItem(Rl)}catch{}}function Qg(t){return t.map(e=>({...e,mode:e.mode==="tmux"?"tmux":"shell",tmuxSessionName:e.tmuxSessionName??null,customName:e.customName===!0}))}function uf(t){return Qg(t.map(e=>({sessionId:e.sessionId,name:e.name,customName:e.customName===!0,backendSessionId:e.backendSessionId,mode:e.mode,tmuxSessionName:e.tmuxSessionName,createdAt:e.createdAt,lastActivity:e.lastActivity}))).map((e,n)=>({...e,activeProgram:t[n]?.activeProgram??null,cwd:t[n]?.cwd??null}))}function ff(t){return t.map(e=>`${e.sessionId}:${e.name}:${e.customName}:${e.backendSessionId}:${e.mode}:${e.tmuxSessionName}:${e.lastActivity}:${e.activeProgram??""}:${e.cwd??""}`).join("|")}function Sc(t,e){return t.length===0?null:e&&t.some(n=>n.sessionId===e)?e:t[0]?.sessionId??null}function zC(){const t=Jg()??[];return{sessions:t,activeSessionId:Sc(t,vc())}}function dR(){const t=_.useRef(Jg()).current,e=_.useRef(vc()).current,[n,r]=_.useState(t??[]),[o,s]=_.useState(null),[i,a]=_.useState(t&&t.length>0?Sc(t,e):e),[c,l]=_.useState(t===null),d=_.useRef(!1),u=_.useRef(null),f=_.useRef(t===null),h=_.useRef(0),g=_.useRef(new Set),m=_.useRef(0);_.useEffect(()=>{f.current=c},[c]),_.useEffect(()=>{u.current=i},[i]);const b=_.useCallback(x=>{const P=Sc(x,u.current??vc());return a(R=>R===P?R:P),Fn(P),u.current=P,P},[]),w=_.useCallback((x,P)=>{const R=x.filter(O=>!g.current.has(O.sessionId));r(O=>ff(O)===ff(R)?O:R),tn(R),P?.reconcileActive&&b(R)},[b]),I=_.useCallback((x,P)=>{const R=g.current.size===0?x:{...x,clientSessions:x.clientSessions.filter(O=>!g.current.has(O.sessionId))};s(R),w(uf(R.clientSessions),P)},[w]),y=_.useCallback(()=>typeof window>"u"?[]:localStorage.getItem(xa)?(localStorage.removeItem(xa),df(),Fn(null),r([]),a(null),console.info("[session-persist] discarded legacy local session cache"),[]):[],[]),v=_.useCallback(async()=>{if(typeof window>"u")return[];const x=m.current;try{const P=await yg(),R=uf(P.clientSessions);return x!==m.current?(console.info("[session-inventory] ignored restore snapshot superseded by a local mutation"),R.filter(O=>!g.current.has(O.sessionId))):(I(P,{reconcileActive:!0}),R.length>0?R:y())}catch(P){console.error("Failed to restore sessions from server:",P);try{return y()}catch(R){console.error("Failed to discard legacy local sessions:",R)}}finally{l(!1)}return[]},[I,y]),L=_.useCallback(async x=>{const P=++m.current,R=await bg(x);return P===m.current&&(I(R.inventory),a(R.session.sessionId),Fn(R.session.sessionId)),R},[I]),C=_.useCallback(async(x,P)=>{++m.current,g.current.add(x),r(R=>{const O=R.filter(B=>B.sessionId!==x),j=P!=null&&O.some(B=>B.sessionId===P),M=u.current===x?j?P:KC(R,x,B=>B.sessionId):u.current;return a(M),Fn(M),tn(O),O});try{await Sg(x)}catch(R){console.error("Failed to remove session from inventory:",R)}},[]),T=_.useCallback(x=>{const P=Date.now();r(R=>{const O=R.map(j=>j.sessionId===x?{...j,lastActivity:P}:j);return tn(O),O})},[]),E=_.useCallback(x=>{a(x),Fn(x)},[]),S=_.useCallback(async(x,P)=>{const R=P.trim();if(!R)return;const O=++m.current;r(j=>{const M=j.map(B=>B.sessionId===x?{...B,name:R,customName:!0}:B);return tn(M),M});try{const j=await ts(x,{name:R,customName:!0});O===m.current&&I(j)}catch(j){console.error("Failed to rename session in inventory:",j)}},[I]),k=_.useCallback(async x=>{const P=++m.current;r(R=>{const O=R.map(j=>j.sessionId===x?{...j,customName:!1}:j);return tn(O),O});try{const R=await ts(x,{customName:!1});P===m.current&&I(R)}catch(R){console.error("Failed to reset session name in inventory:",R)}},[I]),N=_.useCallback(async x=>{const P=++m.current;r(R=>{const O=new Map(R.map(U=>[U.sessionId,U])),j=x.map(U=>O.get(U)).filter(U=>U!==void 0),M=new Set(x),B=R.filter(U=>!M.has(U.sessionId)),F=[...j,...B];return tn(F),F});try{const R=await vg(x);P===m.current&&I(R)}catch(R){console.error("Failed to reorder sessions in inventory:",R)}},[I]),D=_.useCallback(async()=>{++m.current;for(const x of n)g.current.add(x.sessionId);r([]),s(null),a(null),Fn(null),df(),typeof window<"u"&&localStorage.removeItem(xa);try{await xg()}catch(x){console.error("Failed to clear session inventory:",x)}},[n]),A=_.useCallback(async(x,P)=>{const R=++m.current;r(O=>{const j=O.map(M=>M.sessionId===x?{...M,backendSessionId:P}:M);return tn(j),j});try{const O=await ts(x,{backendSessionId:P});R===m.current&&I(O)}catch(O){console.error("Failed to update session backend in inventory:",O)}},[I]);return _.useEffect(()=>{d.current||(d.current=!0,v())},[v]),_.useEffect(()=>Yg(P=>{if(P.type!=="client-state"||f.current)return;const R=typeof P.seq=="number"?P.seq:null;if(R!==null){if(R<h.current){console.warn("[session-inventory] ignored stale control snapshot",{seq:R,latestSeq:h.current});return}h.current=R}if(P.inventory){I(P.inventory,{reconcileActive:!0});return}const O=Qg(P.clientState.sessions||[]);w(O,{reconcileActive:!0})}),[I,w]),{sessions:n,inventory:o,activeSessionId:i,isLoading:c,openSession:L,removeSession:C,updateSessionActivity:T,setActiveSession:E,updateSessionBackendId:A,renameSession:S,resetSessionCustomName:k,reorderSessions:N,clearAllSessions:D,restoreSessions:v}}const WC=256*1024,VC=256*1024,GC=128;function hf(t,e=WC){if(!t)return[];if(t.length<=e)return[t];const n=[];let r=0;for(;r<t.length;){let o=Math.min(r+e,t.length);if(o<t.length){const s=t.lastIndexOf(`
35
- `,o);s>r&&(o=s+1)}n.push(t.slice(r,o)),r=o}return n}function XC(t,e=VC,n=GC){const r=new Map;let o=0,s=0;for(const i of[...t.keys()]){const a=t.get(i);if(!a||a.length===0){t.delete(i);continue}const c=[];for(;a.length>0;){const l=a[0];if(s>0&&(s>=n||o+l.length>e))break;a.shift(),c.push(l),o+=l.length,s+=1}if(c.length>0&&r.set(i,c),t.delete(i),a.length>0&&t.set(i,a),s>=n||o>=e)break}return r}async function em(t,e=!1,n="termdock-encrypted-background"){const r=await new Promise((o,s)=>{const i=indexedDB.open(n,1);i.onupgradeneeded=()=>i.result.createObjectStore("state"),i.onsuccess=()=>o(i.result),i.onerror=()=>s(i.error)});try{return await new Promise((o,s)=>{const i=r.transaction("state",e?"readwrite":"readonly"),a=t(i.objectStore("state"));i.oncomplete=()=>o(a.result),i.onabort=i.onerror=()=>s(i.error)})}finally{r.close()}}const YC=t=>em(e=>e.put(t,t.targetPeerId),!0),ZC=t=>em(e=>e.delete(t),!0),tm="termdock-pwa-notifications-enabled",nm="termdock-pwa-ai-notifications-enabled",rm="termdock-pwa-exit-notifications-enabled",om="termdock-pwa-notification-alert-style",JC="termdock-notification-claim:",xc=5e3,QC=1500,Ec="termdock-push-last-sync",pf=360*60*1e3,eI=10080*60*1e3,eo=new Map;function Tl(){return et()?!0:typeof window<"u"&&typeof Notification<"u"&&"serviceWorker"in navigator&&window.isSecureContext}function tI(){if(typeof navigator>"u")return!1;const t=navigator.userAgent;return/iPad|iPhone|iPod/.test(t)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}function nI(){return typeof window>"u"?!1:!!(window.matchMedia("(display-mode: standalone)").matches||"standalone"in navigator&&navigator.standalone===!0)}function rI(){return et()?!0:!(!Tl()||tI()&&!nI())}function uR(){return et()?"granted":typeof Notification>"u"?"unsupported":Notification.permission}function Pl(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(tm)==="true"}catch{return!1}}function fR(t){if(!(typeof window>"u"))try{window.localStorage.setItem(tm,String(t))}catch{}}function Fs(){if(typeof window>"u")return!0;try{const t=window.localStorage.getItem(nm);return t===null?!0:t==="true"}catch{return!0}}function hR(t){if(!(typeof window>"u"))try{window.localStorage.setItem(nm,String(t))}catch{}}function Ac(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(rm)==="true"}catch{return!1}}function pR(t){if(!(typeof window>"u"))try{window.localStorage.setItem(rm,String(t))}catch{}}function uo(){if(typeof window>"u")return"normal";try{const t=window.localStorage.getItem(om);if(t==="quiet"||t==="persistent")return t}catch{}return"normal"}function gR(t){if(!(typeof window>"u"))try{window.localStorage.setItem(om,t)}catch{}}async function mR(){return et()?"granted":Tl()?Notification.permission==="default"?Notification.requestPermission():Notification.permission:"unsupported"}function oI(){return typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus()}function sI(t){for(const[e,n]of eo)t-n>xc&&eo.delete(e)}function iI(t){return t.dedupKey?.trim()?t.dedupKey.trim():t.tag?.trim()?t.tag.trim():[t.data?.sessionId,t.title,t.body].filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()).join("|")}function aI(t){const e=iI(t);if(!e)return!0;const n=Date.now();sI(n);const r=eo.get(e)??0;if(n-r<xc)return!1;try{if(typeof window<"u"&&window.localStorage){const o=`${JC}${e}`,s=Number(window.localStorage.getItem(o)??"0");if(Number.isFinite(s)&&n-s<xc)return eo.set(e,s),!1;Number.isFinite(s)&&s>0&&window.localStorage.removeItem(o),window.localStorage.setItem(o,String(n))}}catch{}return eo.set(e,n),!0}async function ai(){if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;try{const t=await navigator.serviceWorker.getRegistration()??null;return t?.active?t:await Promise.race([navigator.serviceWorker.ready,new Promise(n=>{window.setTimeout(()=>n(null),QC)})])??t}catch{return null}}function cI(t){const e="=".repeat((4-t.length%4)%4),n=(t+e).replace(/-/g,"+").replace(/_/g,"/"),r=window.atob(n),o=new Uint8Array(new ArrayBuffer(r.length));for(let s=0;s<r.length;s+=1)o[s]=r.charCodeAt(s);return o}async function Nl(t,e){const n=await fetch("/api/csrf-token");if(!n.ok)throw new Error("Unable to get notification security token");const{csrfToken:r}=await n.json();return fetch(`/api/notifications/${t}`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(e)})}async function lI(t=!1,e=!1){if(et())return!0;if(!Pl()||!rI()||Notification.permission!=="granted")return!1;const n=await ai();if(!n?.pushManager)return!1;try{const r=await fetch("/api/notifications/status");if(!r.ok)return!1;const o=await r.json();let s=await n.pushManager.getSubscription();const i=!!(s?.expirationTime&&s.expirationTime-Date.now()<eI);if(!s)try{s=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:cI(o.publicKey)})}catch(d){return console.warn(`[PWA notifications] Push subscription missing; re-subscribe failed${e?" (user gesture)":""}:`,d),!1}const a=Number(window.localStorage.getItem(Ec)??"0"),c=!o.subscription||o.subscription.endpoint!==s.endpoint||Date.now()-(o.subscription.updatedAt??0)>=pf;if(t||c||Date.now()-a>=pf||i){if(!(await Nl("subscribe",{subscription:s.toJSON(),aiEnabled:Fs(),exitEnabled:Ac(),alertStyle:uo(),locale:navigator.language})).ok)return!1;window.localStorage.setItem(Ec,String(Date.now()))}const l=re();return l&&await YC({targetPeerId:l.targetPeerId,addresses:wr(l),routes:Vt(l),publicKey:o.publicKey,preferences:{aiEnabled:Fs(),exitEnabled:Ac(),alertStyle:uo(),locale:navigator.language}}),!0}catch(r){return console.warn("[PWA notifications] Push subscription sync failed:",r),!1}}async function wR(){if(et())return;const e=await(await ai())?.pushManager?.getSubscription();try{await Nl("unsubscribe",{endpoint:e?.endpoint})}finally{const n=re();n&&await ZC(n.targetPeerId),await e?.unsubscribe();try{window.localStorage.removeItem(Ec)}catch{}}}async function yR(){if(et()||!Pl())return;(await Nl("preferences",{aiEnabled:Fs(),exitEnabled:Ac(),alertStyle:uo(),locale:navigator.language})).status===404&&await lI(!0)}async function bR(){if(!et())try{const t=navigator;typeof t.clearAppBadge=="function"&&await t.clearAppBadge()}catch{}}async function vR(t){if(!et())try{const e=await ai();if(!e||typeof e.getNotifications!="function")return;const n=`agent:${t}`,r=await e.getNotifications({tag:n});for(const s of r)s.close();const o=navigator;if(typeof o.setAppBadge=="function"){const s=await e.getNotifications();await o.setAppBadge(s.length)}}catch{}}async function Ea(t){if(!Pl()||!Tl())return!1;if(t.requireHidden!==!1&&oI())return!0;const e=et();if(e){const s=t.alertStyle??uo(),i=await e.showNotification({title:t.title,body:t.body,tag:t.tag,sessionId:t.data?.sessionId,silent:s==="quiet",persistent:s==="persistent"});return e.notificationDeliveryConfirmation===!0&&i}if(Notification.permission!=="granted")return!1;const n=await ai();if(t.deferToPush&&await n?.pushManager?.getSubscription())return!0;if(t.requireHidden!==!1){if(await n?.pushManager?.getSubscription())return!0}if(!aI(t))return!0;const r=t.alertStyle??uo(),o={body:t.body,tag:t.tag,icon:"/pwa-192x192.png",badge:"/maskable-icon-512x512.png",requireInteraction:r==="persistent",renotify:r==="persistent"?!!t.tag:!1,silent:r==="quiet",vibrate:r==="quiet"?[]:[80,40,80],data:{url:t.data?.url??"/",sessionId:t.data?.sessionId}};try{if(n&&typeof n.showNotification=="function")return await n.showNotification(t.title,o),!0;const s=new Notification(t.title,o);return s.onclick=()=>{window.focus(),t.data?.url&&window.location.href!==t.data.url&&window.location.assign(t.data.url),s.close()},!0}catch(s){if(s instanceof DOMException&&s.name==="NotSupportedError"&&o.renotify)try{const i={...o,renotify:!1};return n&&typeof n.showNotification=="function"?await n.showNotification(t.title,i):new Notification(t.title,i),!0}catch(i){return console.warn("[PWA notifications] Failed to show notification (renotify fallback):",i),!1}return console.warn("[PWA notifications] Failed to show notification:",s),!1}}function dI(){try{return localStorage.getItem("termdock:locale")||"en"}catch{return"en"}}function uI(t,e){return t==="zh"?{waitingTitle:`${e} 需要你的处理`,waitingBody:`${e} 需要你的处理。`,doneTitle:`${e} 已完成`,doneBody:`${e} 已完成,点按查看结果。`,exitedTitle:`${e} 已退出`,exitedBody:`${e} 已退出,点按查看结果。`}:{waitingTitle:`${e} needs your input`,waitingBody:`${e} is waiting for your input.`,doneTitle:`${e} finished`,doneBody:"Tap to see the result.",exitedTitle:`${e} exited`,exitedBody:"Tap to see the result."}}const gf=1e6;function Ut(t){return{sessionId:t,directory:"",terminalSessionId:null,mode:"shell",tmuxSessionName:null,activeProgram:null,activeProgramRaw:null,activeProgramSource:null,cwd:null,inCopyMode:!1,isConnecting:!1,agentStatus:null,agentIndicator:null,agentStatusDetail:null,agent:null,agentMessage:null,agentNativeSessionId:null,agentResumeRecovered:!1,agentRich:!1,agentActivity:0,agentCwd:null,agentNeedsReview:!1,shellTitle:null,promptState:null,shellExitCode:null,tuiProgress:null,gitStatus:null,bufferChunks:[],bufferLength:0,lastOutputAt:null,updatedAt:Date.now()}}const ci="termdock-shell-titles-v1";function li(){if(typeof window>"u")return{};try{const t=localStorage.getItem(ci);if(!t)return{};const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:{}}catch{return{}}}function fI(t){return li()[t]??null}function hI(t,e){if(!(typeof window>"u"))try{const n=li();e?n[t]=e:delete n[t],localStorage.setItem(ci,JSON.stringify(n))}catch{}}function pI(t){if(!(typeof window>"u"))try{const e=li();delete e[t],localStorage.setItem(ci,JSON.stringify(e))}catch{}}const di="termdock-agent-cache-v1";function Ll(){if(typeof window>"u")return{};try{const t=localStorage.getItem(di);if(!t)return{};const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:{}}catch{return{}}}function gI(t,e){if(!(typeof window>"u"))try{const n=Ll();e?n[t]=e:delete n[t],localStorage.setItem(di,JSON.stringify(n))}catch{}}function mI(t){if(!(typeof window>"u"))try{const e=Ll();delete e[t],localStorage.setItem(di,JSON.stringify(e))}catch{}}function wI(){if(!(typeof window>"u"))try{localStorage.removeItem(di)}catch{}}function SR(t){return Ll()[t]??null}function yI(){if(!(typeof window>"u"))try{localStorage.removeItem(ci)}catch{}}const Aa=oi((t,e)=>{const n={pendingChunksBySession:new Map,activitySessionIds:new Set,batchFlushRafRef:null},r=(i,a)=>{const c=new Map;return t(l=>{const d=new Map(l.sessions);let u=l.nextChunkId;const f=Date.now();for(const[h,g]of i){const m=d.get(h)??Ut(h);let b=m.bufferChunks.length>0?[...m.bufferChunks]:[],w=m.bufferLength;for(const I of g){const y=u++;b.push({id:y,data:I}),c.set(h,y),w+=I.length}for(;w>gf&&b.length>1;){const I=b.shift();if(!I)break;w-=I.data.length}d.set(h,{...m,bufferChunks:b,bufferLength:w,lastOutputAt:a.has(h)?f:m.lastOutputAt,updatedAt:f})}return{sessions:d,nextChunkId:u}}),c},o=()=>{if(n.batchFlushRafRef===null){if(typeof window>"u"){s();return}n.batchFlushRafRef=window.requestAnimationFrame(()=>{n.batchFlushRafRef=null,s()})}},s=()=>{if(n.pendingChunksBySession.size===0)return;const i=XC(n.pendingChunksBySession),a=new Set([...i.keys()].filter(c=>n.activitySessionIds.has(c)));for(const c of i.keys())n.pendingChunksBySession.has(c)||n.activitySessionIds.delete(c);r(i,a),n.pendingChunksBySession.size>0&&o()};return{sessions:new Map,nextChunkId:1,activeSessionId:null,getTerminalSession:i=>e().sessions.get(i),setActiveSessionId:i=>{if(t({activeSessionId:i}),i){const a=e().sessions.get(i);if(a?.agentNeedsReview){const c=new Map(e().sessions);c.set(i,{...a,agentNeedsReview:!1,updatedAt:Date.now()}),t({sessions:c}),a.terminalSessionId&&cc(a.terminalSessionId)}}},setTerminalSession:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i),f=!d||d.terminalSessionId!==a.sessionId?Ut(i):d??Ut(i),h=a.history??d?.history??[];return l.set(i,{...f,terminalSessionId:a.sessionId,mode:a.mode??f.mode,tmuxSessionName:a.tmuxSessionName??f.tmuxSessionName,activeProgram:a.activeProgram??d?.activeProgram??f.activeProgram,activeProgramRaw:a.activeProgramRaw??d?.activeProgramRaw??f.activeProgramRaw,activeProgramSource:a.activeProgramSource??d?.activeProgramSource??f.activeProgramSource,cwd:a.cwd??d?.cwd??f.cwd,agentResumeRecovered:d?.agentResumeRecovered??f.agentResumeRecovered,shellTitle:d?.shellTitle??li()[i]??f.shellTitle,sessionId:i,isConnecting:!1,history:h,updatedAt:Date.now()}),{sessions:l}})},setSessionHistory:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??Ut(i);return l.set(i,{...d,history:a,updatedAt:Date.now()}),{sessions:l}})},setSessionActiveProgram:(i,a,c=null,l=null)=>{t(d=>{const u=new Map(d.sessions),f=u.get(i)??Ut(i);return u.set(i,{...f,activeProgram:a,activeProgramRaw:l,activeProgramSource:c,updatedAt:Date.now()}),{sessions:u}})},setSessionCwd:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??Ut(i);return l.set(i,{...d,cwd:a,updatedAt:Date.now()}),{sessions:l}})},setSessionShellTitle:(i,a)=>{t(c=>{const l=c.sessions.get(i);if(!l||l.shellTitle===a)return c;const d=new Map(c.sessions);return d.set(i,{...l,shellTitle:a,updatedAt:Date.now()}),{sessions:d}}),hI(i,a)},setSessionPromptState:(i,a,c)=>{t(l=>{const d=l.sessions.get(i);if(!d||d.promptState===a)return l;const u=new Map(l.sessions);return u.set(i,{...d,promptState:a,shellExitCode:c??d.shellExitCode,updatedAt:Date.now()}),{sessions:u}})},setSessionTuiProgress:(i,a)=>{t(c=>{const l=c.sessions.get(i);if(!l)return c;const d=a?.state==="remove"?null:a;if(l.tuiProgress?.state===d?.state&&l.tuiProgress?.progress===d?.progress)return c;const u=new Map(c.sessions);return u.set(i,{...l,tuiProgress:d,updatedAt:Date.now()}),{sessions:u}})},setSessionGitStatus:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i);return!d||JSON.stringify(d.gitStatus)===JSON.stringify(a)?c:(l.set(i,{...d,gitStatus:a,updatedAt:Date.now()}),{sessions:l})})},setSessionCopyMode:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i);return!d||d.inCopyMode===a?c:(l.set(i,{...d,inCopyMode:a,updatedAt:Date.now()}),{sessions:l})})},setSessionAgentStatus:(i,a)=>{const c=e(),l=c.sessions.get(i);if(!l)return;const d=a.agentStatus??null,u=d&&d!=="idle"?a.agentIndicator??l.agentIndicator??null:null,f=d&&d!=="idle"?a.agentStatusDetail??null:null,h=a.agent!==void 0?a.agent:l.agent,g=a.agentMessage!==void 0?a.agentMessage:d?l.agentMessage:null,m=a.agentNativeSessionId!==void 0?a.agentNativeSessionId:l.agentNativeSessionId,b=a.agentResumeRecovered!==void 0?a.agentResumeRecovered:l.agentResumeRecovered,w=a.agentRich??l.agentRich,I=a.agentActivity??l.agentActivity,y=a.agentCwd!==void 0?a.agentCwd:l.agentCwd,v=c.activeSessionId!==i,L=l.agentStatus==="working"||l.agentStatus==="waiting"||l.agentStatus==="done",C=a.reviewed===!1||a.reviewed===null&&d===null&&L&&v;if(l.agentStatus===d&&l.agentIndicator===u&&l.agentStatusDetail===f&&l.agent===h&&l.agentMessage===g&&l.agentNativeSessionId===m&&l.agentResumeRecovered===b&&l.agentRich===w&&l.agentActivity===I&&l.agentCwd===y&&l.agentNeedsReview===C)return;const T=new Map(c.sessions);if(T.set(i,{...l,agentStatus:d,agentIndicator:u,agentStatusDetail:f,agent:h,agentMessage:g,agentNativeSessionId:m,agentResumeRecovered:b,agentRich:w,agentActivity:I,agentCwd:y,agentNeedsReview:C,updatedAt:Date.now()}),t({sessions:T}),h&&gI(i,h),!Fs())return;const E=h?.displayName??l.agent?.displayName??"Agent",S=dI(),k=uI(S,E);if(d==="waiting"&&l.agentStatus!=="waiting"&&v){Ea({title:k.waitingTitle,body:g??k.waitingBody,tag:`agent:${i}`,dedupKey:`agent:${i}:waiting:${I}`,data:{url:"/",sessionId:i},deferToPush:!0});return}if(d==="done"&&l.agentStatus!=="done"&&v){Ea({title:k.doneTitle,body:k.doneBody,tag:`agent:${i}`,dedupKey:`agent:${i}:done:${I}`,data:{url:"/",sessionId:i},deferToPush:!0});return}d===null&&(l.agentStatus==="working"||l.agentStatus==="waiting")&&v&&Ea({title:k.exitedTitle,body:k.exitedBody,tag:`agent:${i}`,dedupKey:`agent:${i}:exited:${I}`,data:{url:"/",sessionId:i},deferToPush:!0})},setAgentResumeRecovered:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??Ut(i);return d.agentResumeRecovered===a?c:(l.set(i,{...d,agentResumeRecovered:a,updatedAt:Date.now()}),{sessions:l})})},clearAgentNeedsReview:i=>{const a=e().sessions.get(i);a?.agentNeedsReview&&(t(c=>{const l=new Map(c.sessions),d=l.get(i);return!d||!d.agentNeedsReview?c:(l.set(i,{...d,agentNeedsReview:!1,updatedAt:Date.now()}),{sessions:l})}),a.terminalSessionId&&cc(a.terminalSessionId))},setConnecting:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??Ut(i);return l.set(i,{...d,isConnecting:a,updatedAt:Date.now()}),{sessions:l}})},appendToBuffer:(i,a,c)=>{if(!a)return;let l=n.pendingChunksBySession.get(i);l||(l=[],n.pendingChunksBySession.set(i,l)),l.push(...hf(a)),c?.markActivity!==!1&&n.activitySessionIds.add(i),o()},hasPendingBufferWrites:i=>(n.pendingChunksBySession.get(i)?.length??0)>0,flushPendingBufferWrites:i=>{const a=n.pendingChunksBySession.get(i);if(!a?.length)return e().sessions.get(i)?.bufferChunks.at(-1)?.id??null;n.pendingChunksBySession.delete(i);const c=n.activitySessionIds.delete(i);return n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),r(new Map([[i,a]]),c?new Set([i]):new Set).get(i)??null},replaceBuffer:(i,a)=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null);let c=null;return t(l=>{const d=new Map(l.sessions),u=d.get(i);if(!u)return l;if(!a||a.length===0)return d.set(i,{...u,bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:d};let f=l.nextChunkId;const h=[];let g=0;for(const m of a)if(m)for(const b of hf(m)){const w=f++;h.push({id:w,data:b}),c=w,g+=b.length}for(;g>gf&&h.length>1;){const m=h.shift();if(!m)break;g-=m.data.length}return d.set(i,{...u,bufferChunks:h,bufferLength:g,updatedAt:Date.now()}),{sessions:d,nextChunkId:f}}),c},clearTerminalSession:i=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),t(a=>{const c=new Map(a.sessions),l=c.get(i);return l&&c.set(i,{...l,terminalSessionId:null,isConnecting:!1,agentStatus:null,agentIndicator:null,agentStatusDetail:null,agent:null,agentMessage:null,agentNeedsReview:!1,updatedAt:Date.now()}),{sessions:c}})},clearBuffer:i=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),t(a=>{const c=new Map(a.sessions),l=c.get(i);return l?(c.set(i,{...l,bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:c}):a})},removeTerminalSession:i=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),t(a=>{const c=new Map(a.sessions);return c.delete(i),{sessions:c}}),pI(i),mI(i)},clearAllTerminalSessions:()=>{n.pendingChunksBySession.clear(),n.activitySessionIds.clear(),n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),t({sessions:new Map,nextChunkId:1}),yI(),wI()}}}),kc="termdock:session-notice";function bI(){return _.useEffect(()=>{const t=()=>Sa.getState().view(!document.hidden&&Yo()?Aa.getState().activeSessionId:null);t();const e=Aa.subscribe((n,r)=>{n.activeSessionId!==r.activeSessionId&&t()});return document.addEventListener("visibilitychange",t),window.addEventListener(ao,t),()=>{e(),document.removeEventListener("visibilitychange",t),window.removeEventListener(ao,t),Sa.getState().view(null)}},[]),_.useEffect(()=>Yg(t=>{if(t.type!=="session-notice")return;Sa.getState().receive(t.sessionId,t.id);const e=re()?.targetPeerId,n=ut(),r=window.parent,o=zC().sessions.find(u=>u.sessionId===t.sessionId),s=Aa.getState().sessions.get(t.sessionId),i=s?.shellTitle??fI(t.sessionId),a=i===s?.cwd||i===qn(s?.cwd??null)?null:i,c=$C(o??{name:t.sessionName},s?.activeProgram??null,null,void 0,a,s?.promptState??null),l={...t,sessionName:c,key:`${e??"local"}:${t.id}`,open:()=>e&&n?n.focusSession(e,t.sessionId):(window.dispatchEvent(new CustomEvent("termdock:focus-session",{detail:t.sessionId})),!0)},d=r.document.createEvent("CustomEvent");d.initCustomEvent(kc,!1,!1,l),r.dispatchEvent(d)}),[]),null}function vI(){const{locale:t}=ii(),e=t==="zh",[n,r]=_.useState([]);_.useEffect(()=>{const i=a=>{const c=a.detail;r(l=>l.some(d=>d.key===c.key)?l:[...l,c])};return window.addEventListener(kc,i),()=>window.removeEventListener(kc,i)},[]);const o=_.useCallback(i=>{r(a=>a.filter(c=>c.key!==i))},[]),s=n[0];return s?Tc.createPortal(p.jsx(SI,{notice:s,remaining:n.length-1,chinese:e,onDismiss:o},s.key),document.body):null}function SI({notice:t,remaining:e,chinese:n,onDismiss:r}){const[o,s]=_.useState(!1);return p.jsxs("section",{"aria-label":n?"关键进展提醒":"Progress reminder",className:"fixed left-3 right-3 top-[calc(var(--safe-top-inset,0px)+0.75rem)] z-toast overflow-hidden rounded-xl bg-surface text-foreground shadow-lg ring-1 ring-inset ring-border/15 animate-fade-in md:left-auto md:right-4 md:w-[360px]",children:[p.jsxs("button",{type:"button","aria-label":n?"查看 Session":"Open session",className:"group flex w-full items-start gap-2.5 p-3.5 pr-11 text-left transition-colors hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",onClick:()=>{t.open()?r(t.key):s(!0)},children:[p.jsx(Kp,{size:16,className:"mt-0.5 shrink-0 text-primary","aria-hidden":"true"}),p.jsxs("span",{className:"min-w-0 flex-1",role:"status","aria-live":"polite","aria-atomic":"true",children:[p.jsxs("span",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium",title:t.sessionName,children:t.sessionName}),p.jsx(NE,{size:13,className:"shrink-0 text-muted-foreground/60 transition-colors group-hover:text-primary","aria-hidden":"true"})]}),t.title&&p.jsx("span",{className:"mt-1 block truncate text-[11px] text-muted-foreground",children:t.title}),p.jsx("span",{className:"mt-1.5 line-clamp-3 whitespace-pre-wrap break-words text-[13px] leading-relaxed text-foreground/85",title:t.message,children:t.message}),e>0&&p.jsx("span",{className:"mt-2 block text-[10px] text-muted-foreground",children:n?`还有 ${e} 条`:`${e} more`}),o&&p.jsx("span",{role:"alert",className:"mt-2 block text-xs text-warning",children:n?"暂时无法打开该服务,请重试。":"Unable to open the service. Please retry."})]})]}),p.jsx("button",{type:"button","aria-label":n?"关闭提醒":"Dismiss reminder",className:"absolute right-0 top-0 flex h-11 w-11 items-center justify-center rounded-tr-xl text-muted-foreground/60 transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",onClick:()=>r(t.key),children:p.jsx(Yp,{size:14})})]})}const mf=5*6e4;let Cc,sm=!1,im=!1,wf=!1;const Ic=new Set;function yf(){sm=!0,Ic.forEach(t=>t())}function xI(){return _.useSyncExternalStore(t=>(Ic.add(t),()=>{Ic.delete(t)}),()=>sm,()=>!1)}function EI(){window.dispatchEvent(new Event("termdock:before-update")),im=!0,Cc?.waiting?Cc.waiting.postMessage({type:"SKIP_WAITING"}):window.location.reload()}function AI(t,e){let n=t;return()=>{if(!n){n=!0;return}e()}}function kI(){if(wf||typeof window>"u"||!("serviceWorker"in navigator))return;wf=!0,navigator.serviceWorker.addEventListener("controllerchange",AI(!!navigator.serviceWorker.controller,()=>{im?window.location.reload():yf()}));const t=()=>{navigator.serviceWorker.register("/sw.js",{scope:"/",updateViaCache:"none"}).then(e=>{Cc=e;const n=()=>{e.waiting&&yf()},r=()=>{const i=e.installing;i?.addEventListener("statechange",()=>{i.state==="installed"&&navigator.serviceWorker.controller&&n()})};e.addEventListener("updatefound",r),r(),n();let o=0;const s=()=>{document.visibilityState!=="visible"||Date.now()-o<mf||(o=Date.now(),e.update().then(n).catch(()=>{}))};s(),window.setInterval(s,mf),document.addEventListener("visibilitychange",s)}).catch(()=>{})};document.readyState==="complete"?t():window.addEventListener("load",t,{once:!0})}function CI(){const t=xI(),[e,n]=_.useState(!1),{locale:r}=ii();if(!t||e)return null;const o=r==="zh";return p.jsxs("div",{role:"status",className:"fixed bottom-16 left-1/2 z-toast flex max-w-[calc(100%-2rem)] -translate-x-1/2 items-center gap-3 rounded-lg border border-border bg-background px-4 py-3 text-sm text-foreground shadow-lg",children:[p.jsx("span",{children:o?"新版本已就绪":"An update is ready"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-primary",onClick:EI,children:o?"重新加载":"Reload"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-muted-foreground",onClick:()=>n(!0),children:o?"稍后":"Later"})]})}function am(t){const e=document.querySelector('meta[name="theme-color"]');e&&e.setAttribute("content",t==="light"?"#FFFCF0":"#1C1B1A")}const cm=_.createContext(void 0);function xR({children:t}){const e=_.useContext(cm),n=e===void 0?typeof document>"u"?null:document.body:e;return n?Tc.createPortal(t,n):null}const II={activeKey:"root",items:[]},RI=()=>()=>{},TI=()=>II;function PI({host:t,item:e,visible:n,active:r}){const o=_.useRef(null);return _.useEffect(()=>{o.current?.toggleAttribute("inert",!r)},[r]),_.useLayoutEffect(()=>{const s=o.current;return()=>{try{const i=s?.contentWindow,a=i?.document.createEvent("Event");a&&(a.initEvent("termdock:before-update",!1,!1),i?.dispatchEvent(a))}catch{}t.attach(e.key,null)}},[t,e.key]),p.jsx("iframe",{ref:o,title:e.service?.label||"服务工作区","data-workspace-key":e.key,src:`/workspace.html?${Dp}=${encodeURIComponent(e.key)}`,className:"fixed inset-0 w-full border-0 bg-[var(--chrome-bg)]",style:{height:"var(--app-base-vh, 100%)",visibility:n?"visible":"hidden",pointerEvents:r?"auto":"none"},"aria-hidden":!r,tabIndex:r?0:-1,allow:"clipboard-read; clipboard-write; fullscreen"})}function NI({children:t}){const e=window.parent===window?ut():void 0,n=_.useSyncExternalStore(e?.subscribe||RI,e?.snapshot||TI),[r,o]=_.useState(null),[s,i]=_.useState(()=>n.activeKey==="root"?"root":null),[a,c]=_.useState(),[l,d]=_.useState(!1),[u,f]=_.useState(),h=n.items.find(y=>y.key===n.activeKey),g=h?.rendered||a===n.activeKey?n.activeKey:s,m=g!==n.activeKey,b=m&&s===null;_.useLayoutEffect(()=>{if(!m||b){f(void 0);return}const y=()=>{const v=Array.from(document.querySelectorAll("iframe[data-workspace-key]")).find(N=>N.dataset.workspaceKey===s),E=(s==="root"?r:v?.contentDocument)?.querySelector('nav[aria-label="切换服务"]')?.closest("[data-sidebar-gesture-ignore]")?.getBoundingClientRect();if(!E||E.width===0||E.right<=0){f(void 0);return}const S=v?.getBoundingClientRect(),k=E.top+(S?.top??0)>=160;f({left:E.left+(S?.left??0)+12,top:(k?E.top-8:E.bottom+8)+(S?.top??0),width:Math.max(0,E.width-24),transform:k?"translateY(-100%)":"none"})};return y(),window.addEventListener("resize",y),()=>window.removeEventListener("resize",y)},[m,b,s,r]),_.useLayoutEffect(()=>{e?.present(g),m||i(g),r?.toggleAttribute("inert",g!=="root"||m)},[e,r,g,m]),_.useEffect(()=>{if(d(!1),!m)return;const y=setTimeout(()=>d(!0),8e3);return()=>clearTimeout(y)},[n.activeKey,m]),_.useEffect(()=>{c(void 0)},[n.activeKey]);const w=n.items.find(y=>y.key===s),I=h?.phase==="offline"?"网络已断开,等待恢复…":h?.phase==="reconnecting"?"连接暂未恢复,正在重试…":l?"连接时间较长,仍在等待服务…":b?"正在恢复服务…":"正在切换服务…";return _.useEffect(()=>{if(!e)return;const y=()=>{try{const v=JSON.parse(localStorage.getItem("termdock-color-theme")||"null");(v==="dark"||v==="light")&&(document.documentElement.dataset.theme=v,am(v))}catch{}};return window.addEventListener("storage",y),()=>window.removeEventListener("storage",y)},[e]),_.useEffect(()=>{if(!e||!("serviceWorker"in navigator))return;const y=C=>{if(C.source!==navigator.serviceWorker.controller)return;const T=C.data;T?.type==="termdock:focus-session"&&typeof T.targetPeerId=="string"&&typeof T.sessionId=="string"&&e.focusSession(T.targetPeerId,T.sessionId)&&(C.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),C.stopImmediatePropagation())},v=async()=>{if("caches"in window)try{const C=await caches.open("termdock-notification-target-v1"),T=await C.match("/__termdock-notification-target");if(!T)return;const E=await T.json();typeof E.targetPeerId=="string"&&typeof E.sessionId=="string"&&Date.now()-E.clickedAt<3e4&&e.focusSession(E.targetPeerId,E.sessionId)&&await C.delete("/__termdock-notification-target")}catch{}},L=()=>{document.hidden||v()};return navigator.serviceWorker.addEventListener("message",y),document.addEventListener("visibilitychange",L),v(),()=>{navigator.serviceWorker.removeEventListener("message",y),document.removeEventListener("visibilitychange",L)}},[e]),e?p.jsxs("div",{className:"relative h-full w-full overflow-hidden bg-[var(--chrome-bg)]",children:[p.jsx("div",{ref:o,className:"isolate h-full w-full","aria-hidden":g!=="root"||m,style:{visibility:g==="root"?"visible":"hidden"},children:p.jsx(cm.Provider,{value:r,children:t})}),n.items.filter(y=>y.key!=="root").map(y=>p.jsx(PI,{host:e,item:y,visible:g===y.key,active:!m&&g===y.key},y.key)),b&&p.jsx("div",{className:"termdock-boot z-modal-panel",role:"status","aria-live":"polite",children:l||h?.phase==="offline"||h?.phase==="reconnecting"?p.jsxs("div",{className:"flex max-w-xs flex-col items-center gap-3 text-center",children:[p.jsx(De,{size:16,className:"animate-spin motion-reduce:animate-none","aria-hidden":"true"}),p.jsx("div",{className:"max-w-full truncate text-sm",children:h?.service?.label||"Termdock"}),p.jsx("div",{className:"text-xs text-muted-foreground",children:I}),p.jsx("button",{type:"button",className:"min-h-11 rounded-lg bg-surface-2 px-4 text-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>c(n.activeKey),children:"查看连接页面"})]}):p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"termdock-boot-spinner","aria-hidden":"true"}),p.jsx("span",{children:"Loading Termdock"})]})}),m&&!b&&p.jsx("div",{className:"fixed inset-0 z-modal-panel flex items-end justify-center px-3 pb-[calc(env(safe-area-inset-bottom)+96px)]",role:"dialog","aria-modal":"true","aria-label":"切换服务",onKeyDown:y=>{if(y.key==="Escape"&&w?.service&&(y.preventDefault(),e.activate(w.service)),y.key==="Tab"){const v=Array.from(y.currentTarget.querySelectorAll("button")),L=v[0],C=v[v.length-1];y.shiftKey&&document.activeElement===L?(y.preventDefault(),C?.focus()):!y.shiftKey&&document.activeElement===C&&(y.preventDefault(),L?.focus())}},children:p.jsxs("div",{style:u?{position:"absolute",...u}:void 0,className:"flex w-full max-w-sm flex-wrap items-center gap-x-2 gap-y-1 rounded-xl border border-border bg-surface-elevated px-3 py-1.5 text-foreground shadow-lg",children:[p.jsxs("div",{role:"status","aria-live":"polite",className:"flex min-w-0 flex-1 items-center gap-2",children:[p.jsx(De,{size:16,className:"shrink-0 animate-spin text-primary motion-reduce:animate-none","aria-hidden":"true"}),p.jsxs("div",{className:"min-w-0",children:[p.jsx("div",{className:"truncate text-sm font-medium",children:h?.service?.label||"服务工作区"}),p.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:I})]})]}),p.jsxs("div",{className:"flex items-center justify-end gap-1",children:[l&&p.jsx("button",{type:"button",className:"min-h-11 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2",onClick:()=>c(n.activeKey),children:"查看连接页面"}),w?.service&&p.jsx("button",{type:"button",autoFocus:!0,"aria-label":"取消切换",className:"min-h-11 shrink-0 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>e.activate(w.service),children:"取消"})]})]})})]}):t}const LI=_.lazy(()=>Gt(()=>import("./App-CmlGDKDj.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,3,7,8]))),BI=_.lazy(()=>Gt(()=>import("./DagPlayground-y80OTTQj.js"),__vite__mapDeps([9,10,2,1,11,7,3])).then(t=>({default:t.DagPlayground}))),_I=_.lazy(()=>Gt(()=>import("./DiffLab-BY2wbRtg.js"),__vite__mapDeps([12,2,1,13,8,14,3])).then(t=>({default:t.DiffLab}))),OI=_.lazy(()=>Gt(()=>import("./DiffReviewLab-CEpa_B8I.js"),__vite__mapDeps([15,2,1,16,5,6,11,13,8,14,3])).then(t=>({default:t.DiffReviewLab})));LC();dE();wE();window.parent===window&&kI();const Kr=re();Kr&&Gt(()=>import("./App-CmlGDKDj.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,3,7,8])).catch(()=>{});!new URLSearchParams(location.search).has("dag-playground")&&!new URLSearchParams(location.search).has("diff-lab")&&!new URLSearchParams(location.search).has("diff-review-lab")&&Qx(Kr?{...Kr,id:Kr.targetPeerId,label:Kr.serviceName||location.host}:void 0);try{const t=JSON.parse(window.localStorage.getItem("termdock-color-theme")||"null");(t==="dark"||t==="light")&&(document.documentElement.dataset.theme=t,am(t))}catch{}vE.createRoot(document.getElementById("root")).render(p.jsx(ze.StrictMode,{children:p.jsxs(T2,{children:[window.parent===window&&p.jsxs(p.Fragment,{children:[p.jsx(CI,{}),p.jsx(vI,{})]}),p.jsx(vC,{children:p.jsx(_.Suspense,{fallback:p.jsx("div",{className:"termdock-boot",role:"status",children:"Loading Termdock"}),children:(()=>{const t=new URLSearchParams(window.location.search);return t.get("dag-playground")==="1"?p.jsx(BI,{}):t.get("diff-review-lab")==="1"?p.jsx(OI,{}):t.get("diff-lab")==="1"?p.jsx(_I,{}):p.jsx(NI,{children:p.jsxs(mC,{children:[p.jsx(bI,{}),p.jsx(LI,{})]})})})()})})]})}));export{VI as $,bl as A,Kp as B,dl as C,Zg as D,dg as E,pv as F,cA as G,UA as H,nR as I,fn as J,t2 as K,De as L,Gx as M,e2 as N,bR as O,$2 as P,MA as Q,ul as R,ri as S,XE as T,Z1 as U,RC as V,ao as W,Yp as X,lA as Y,IA as Z,Gt as _,qp as a,jk as a$,oi as a0,sk as a1,kC as a2,xe as a3,CA as a4,Pi as a5,dk as a6,Hk as a7,lR as a8,vR as a9,Dk as aA,r2 as aB,Gk as aC,Kk as aD,wk as aE,uR as aF,Jk as aG,Os as aH,UC as aI,$C as aJ,rr as aK,Fs as aL,Ac as aM,uo as aN,Pl as aO,et as aP,aA as aQ,X1 as aR,YA as aS,qA as aT,GA as aU,n2 as aV,Cg as aW,ut as aX,va as aY,$h as aZ,ap as a_,WA as aa,lk as ab,$k as ac,u1 as ad,cg as ae,dA as af,M2 as ag,GI as ah,aR as ai,$A as aj,dt as ak,tk as al,ek as am,ok as an,kA as ao,Qk as ap,Yk as aq,SR as ar,fI as as,Xk as at,Zk as au,ZA as av,qn as aw,Ik as ax,Vk as ay,s2 as az,TE as b,c2 as b$,nk as b0,ik as b1,kg as b2,Ck as b3,Rk as b4,Sk as b5,kk as b6,Ek as b7,rI as b8,Tl as b9,oR as bA,ZI as bB,PA as bC,uA as bD,XI as bE,rc as bF,u2 as bG,pk as bH,b2 as bI,cR as bJ,yk as bK,gk as bL,XA as bM,Mn as bN,mR as bO,bk as bP,mk as bQ,DA as bR,rR as bS,jA as bT,zA as bU,uk as bV,h2 as bW,qI as bX,l1 as bY,l2 as bZ,o2 as b_,Yo as ba,p as bb,WI as bc,KA as bd,a2 as be,fk as bf,p2 as bg,v2 as bh,Nk as bi,HA as bj,QA as bk,m2 as bl,qC as bm,zk as bn,ig as bo,bg as bp,KC as bq,hk as br,TA as bs,ht as bt,zC as bu,Mk as bv,Ok as bw,Fk as bx,Uk as by,sR as bz,zp as c,g2 as c0,re as c1,Lk as c2,x2 as c3,S2 as c4,OA as c5,LA as c6,RA as c7,_A as c8,FA as c9,vt as cA,qk as cB,Jp as cC,ii as cD,QI as cE,Sa as cF,dR as cG,Le as cH,Aa as cI,iR as cJ,ge as cK,Bk as cL,ni as cM,We as cN,eR as cO,JI as cP,d2 as ca,y2 as cb,hR as cc,pR as cd,gR as ce,fR as cf,wg as cg,AA as ch,Ni as ci,tR as cj,Ea as ck,w2 as cl,Yg as cm,f2 as cn,YI as co,NA as cp,KI as cq,yR as cr,lI as cs,am as ct,HI as cu,rk as cv,wR as cw,ck as cx,JA as cy,ts as cz,vn as d,FE as e,Wp as f,Vp as g,vC as h,lg as i,KE as j,Gp as k,D2 as l,Ae as m,xR as n,BA as o,Jc as p,Tt as q,i2 as r,zI as s,HC as t,Tk as u,Ak as v,Qc as w,_k as x,Hx as y,ak as z};
34
+ `)}async function yC(t){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(t),!0}catch{}const e=document.createElement("textarea");e.value=t,e.setAttribute("readonly",""),e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select();try{return document.execCommand("copy")}catch{return!1}finally{e.remove()}}function bC({error:t,componentStack:e}){const{t:n}=ii(),[r,o]=ze.useState("idle"),s=async()=>{const i=wC(t,e,{url:window.location.href,userAgent:navigator.userAgent,capturedAt:new Date().toISOString()});o(await yC(i)?"copied":"failed")};return p.jsx("div",{className:"flex h-full items-center justify-center p-4",children:p.jsxs("div",{className:"flex flex-col items-center gap-3 text-center max-w-md",children:[p.jsx("div",{className:"w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center",children:p.jsx("svg",{className:"w-6 h-6 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:p.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),p.jsxs("div",{className:"space-y-1",children:[p.jsx("h3",{className:"font-medium text-foreground",children:n("errorBoundary.title")}),p.jsx("p",{className:"text-sm text-muted-foreground",children:t?.message||n("errorBoundary.unexpected")})]}),p.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-center gap-2",children:[p.jsx("button",{type:"button",onClick:()=>{s()},className:"rounded-full bg-surface-2 px-5 py-2.5 text-sm font-medium text-foreground ring-1 ring-border/15 transition hover:bg-surface-elevated active:scale-[0.97]",children:n(r==="copied"?"errorBoundary.copied":r==="failed"?"errorBoundary.copyFailed":"errorBoundary.copyDetails")}),p.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"rounded-full bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground shadow-sm transition-all hover:bg-primary/90 active:scale-[0.97]",children:n("errorBoundary.retry")})]})]})})}class vC extends ze.Component{state={hasError:!1,error:null,componentStack:""};static getDerivedStateFromError(e){return{hasError:!0,error:e,componentStack:""}}componentDidCatch(e,n){console.error("Terminal error caught by boundary:",e,n),this.setState({componentStack:n.componentStack??""})}render(){return this.state.hasError?this.props.fallback?this.props.fallback:p.jsx(bC,{error:this.state.error,componentStack:this.state.componentStack}):this.props.children}}function ge(){try{if(window.parent!==window&&location.pathname==="/workspace.html"&&window.parent.location.origin===location.origin&&window.parent.__termdockWorkspaceHost)return window.parent}catch{}return window}const SC="debug",xC="termdock:debug";function of(t){return t?new Set(t.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean)):new Set}function EC(){if(typeof window>"u")return new Set;const t=of(new URLSearchParams(window.location.search).get(SC));let e=new Set;try{e=of(window.localStorage.getItem(xC))}catch{e=new Set}const n=new Set([...t,...e]);return n.has("1")||n.has("true")||n.has("*")||n.has("all")?new Set(["*"]):n}function AC(t){const e=EC();return e.has("*")||e.has(t)}function kC(t){const e=AC(t);return(...n)=>{e&&console.log(`[debug:${t}]`,...n)}}const sf=80,CC=60,IC="termdock:viewport-keyboard-change",RC="termdock:viewport-layout-change",At=240,af=640,cf=360,TC=1500;function PC({measuredHeight:t,documentVisible:e,editableFocused:n}){return e&&n&&t>0}function va(){if(typeof document>"u")return!1;const t=document.activeElement;return t instanceof HTMLElement&&t.matches('input:not([type="hidden"]), textarea, select, [contenteditable]:not([contenteditable="false"])')}const Ds=t=>{const e=typeof t=="number"?t:Number.parseFloat(typeof t=="string"?t:"0");return Number.isFinite(e)&&e>0?Math.round(e):0},Kg=(t,e)=>{const n=t.map(Ds).filter(r=>r>0);return n.find(r=>r>=At)??n[0]??e},Qr=()=>typeof window>"u"?af:Kg([ge().innerHeight,document.documentElement?.clientHeight,document.body?.clientHeight,ge().visualViewport?.height,window.screen?.availHeight,window.screen?.height],af),zg=()=>typeof window>"u"?cf:Kg([ge().innerWidth,document.documentElement?.clientWidth,document.body?.clientWidth,ge().visualViewport?.width,window.screen?.availWidth,window.screen?.width],cf),jt=t=>{const e=Number.parseFloat(t||"0");return Number.isFinite(e)?Math.max(0,Math.round(e)):0},Wg=()=>typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,NC=()=>typeof window>"u"?!1:ge().navigator.standalone===!0||ge().matchMedia?.("(display-mode: standalone)").matches===!0,Vg=()=>{if(typeof window>"u"||!Wg()||!NC())return{top:0,right:0,bottom:0,left:0};if(!(Qr()>=zg()))return{top:0,right:0,bottom:0,left:0};const e=window.screen?.width||window.innerWidth,n=window.screen?.height||window.innerHeight,r=Math.min(e,n),o=Math.max(e,n);return r>=700?{top:20,right:0,bottom:20,left:0}:o<780?{top:20,right:0,bottom:0,left:0}:{top:o>=852?59:o>=844?47:44,right:0,bottom:34,left:0}};function LC(t="--app-vh"){if(typeof window>"u"||typeof document>"u")return;const e=Ds(ge().visualViewport?.height),n=Math.max(0,Math.round(ge().visualViewport?.offsetTop??0)),r=Qr(),s=e>=At?Math.min(r,e+n):r,i=Math.max(r,s),a=document.documentElement.style;a.setProperty(t,`${Math.max(s,At)}px`),a.setProperty("--app-base-vh",`${Math.max(i,At)}px`),a.setProperty("--app-visible-vh",`${Math.max(s,At)}px`),a.setProperty("--app-vv-offset-top",`${n}px`),a.setProperty("--kb-translate-y","0px"),a.setProperty("--kb-margin-top","0px"),a.setProperty("--kb-height","0px");const c=Vg();c.top>0&&a.setProperty("--safe-top-inset",`${c.top}px`),c.right>0&&a.setProperty("--safe-right-inset",`${c.right}px`),c.bottom>0&&a.setProperty("--safe-bottom-inset",`${c.bottom}px`),c.left>0&&a.setProperty("--safe-left-inset",`${c.left}px`)}function iR(t={}){const{cssVarName:e="--app-vh"}=t,n=ze.useMemo(()=>kC("viewport"),[]),r=ze.useCallback(()=>{if(typeof window>"u")return 0;const d=ge().visualViewport,u=Qr();if(!d)return u;const f=Ds(d.height);if(f<At&&u>=At)return u;const h=d.offsetTop,m=f<u-1&&h>0&&h<=96?f+h:f,b=Math.max(0,Math.min(u,m));return b>0?Math.round(b):u},[]),[o,s]=ze.useState(r),i=ze.useRef(0),a=ze.useRef(0),c=ze.useRef(0),l=ze.useRef(!1);return ze.useEffect(()=>{if(typeof window>"u")return;let d=null,u=0,f=null,h="",g=null;const m=()=>{if(g?.isConnected)return g;try{return g=document.createElement("div"),g.setAttribute("aria-hidden","true"),g.style.cssText=["position:fixed","top:0","left:0","width:0","height:0","visibility:hidden","pointer-events:none","padding-top:constant(safe-area-inset-top)","padding-top:env(safe-area-inset-top,0px)","padding-right:constant(safe-area-inset-right)","padding-right:env(safe-area-inset-right,0px)","padding-bottom:constant(safe-area-inset-bottom)","padding-bottom:env(safe-area-inset-bottom,0px)","padding-left:constant(safe-area-inset-left)","padding-left:env(safe-area-inset-left,0px)"].join(";"),(document.body||document.documentElement).appendChild(g),g}catch{}return null},b=()=>{let R={top:0,right:0,bottom:0,left:0};try{const B=m();if(B){const F=getComputedStyle(B);R={top:jt(F.paddingTop),right:jt(F.paddingRight),bottom:jt(F.paddingBottom),left:jt(F.paddingLeft)}}}catch{}const O=ge();if(O!==window){const B=O.getComputedStyle(O.document.documentElement);R={top:Math.max(R.top,jt(B.getPropertyValue("--safe-top-inset"))),right:Math.max(R.right,jt(B.getPropertyValue("--safe-right-inset"))),bottom:Math.max(R.bottom,jt(B.getPropertyValue("--safe-bottom-inset"))),left:Math.max(R.left,jt(B.getPropertyValue("--safe-left-inset")))}}const j=Vg(),M={top:Math.max(R.top,j.top),right:Math.max(R.right,j.right),bottom:Math.max(R.bottom,j.bottom),left:Math.max(R.left,j.left)};return document.documentElement.style.setProperty("--safe-top-inset",`${M.top}px`),document.documentElement.style.setProperty("--safe-right-inset",`${M.right}px`),document.documentElement.style.setProperty("--safe-bottom-inset",`${M.bottom}px`),document.documentElement.style.setProperty("--safe-left-inset",`${M.left}px`),M},w=(R,O,j,M)=>{const B=Math.max(O,j);if(i.current===0){i.current=B,a.current=R,document.documentElement.style.setProperty("--app-base-vh",`${B}px`);return}const F=Math.abs(R-a.current),U=M<=sf;(F>CC||U)&&(i.current=B,a.current=R,document.documentElement.style.setProperty("--app-base-vh",`${B}px`))},I=(R="event")=>{d=null;const O=r(),j=Math.round(ge().visualViewport?.offsetTop??0),M=Ds(ge().visualViewport?.height),B=M>=At?M:O,F=Qr(),U=zg(),H=Math.max(0,B+j),q=b(),K=q.bottom,W=Math.max(0,i.current-H-K);w(U,F,H,W),s(Rn=>Rn===O?Rn:O);const V=Number.parseInt(document.documentElement.style.getPropertyValue(e)||"0",10);document.documentElement.style.setProperty(e,`${O}px`),document.documentElement.style.setProperty("--app-vv-offset-top",`${j}px`);const G=i.current,X=Math.min(O,B),Z=Math.max(0,Math.min(G,H)),ce=Math.max(0,Math.round(G-X-K)),Ie=va(),Me=PC({measuredHeight:ce,documentVisible:document.visibilityState==="visible",editableFocused:Ie}),ne=Me?ce:0,Ve=ne>=sf,Yt=-ne,Zt=ne;document.documentElement.style.setProperty("--kb-translate-y",`${Yt}px`),document.documentElement.style.setProperty("--kb-margin-top",`${Zt}px`),document.documentElement.style.setProperty("--kb-height",`${ne}px`),document.documentElement.style.setProperty("--app-visible-vh",`${Z}px`);const je=Math.abs(ne-c.current)>1,Jt=Ve!==l.current;(je||Jt)&&(c.current=ne,l.current=Ve,document.dispatchEvent(new CustomEvent(IC,{detail:{baseHeight:G,visibleHeight:Z,visualViewportHeight:B,offsetTop:j,keyboardHeight:ne,isOpen:Ve,source:R}}))),(V!==O||j>0||je||Jt)&&n("sync",{cssVarName:e,innerHeight:F,baseHeight:G,rawViewportHeight:B,offsetTop:j,visibleHeight:Z,rawHeight:O,appliedHeight:O,keyboardViewportHeight:X,measuredKeyboardHeight:ce,editableFocused:Ie,applyKeyboardInset:Me,keyboardHeight:ne,isKeyboardOpen:Ve,safeAreaInsets:q,source:R}),document.dispatchEvent(new CustomEvent(RC,{detail:{height:O,baseHeight:G,visibleHeight:Z,offsetTop:j,source:R}}))},y=()=>{d===null&&(d=window.requestAnimationFrame(()=>{d=null;const R=ge(),O=R.visualViewport,j=[R.innerWidth,R.innerHeight,O?.width,O?.height,O?.offsetTop,O?.offsetLeft,document.visibilityState,va()].join(":"),M=f;f=null,(M||j!==h)&&(h=j,I(M||"viewport.settle")),performance.now()<u&&y()}))},v=(R="event")=>{(R.includes("visibilitychange")||R.includes("pageshow"))&&n("schedule",{source:R}),f=R,Wg()&&document.visibilityState==="visible"&&(u=performance.now()+TC),y()};v("mount");const L=()=>v("resize"),k=()=>v("orientationchange"),T=()=>v("visualViewport.resize"),E=()=>v("visualViewport.scroll"),S=()=>v("focusin"),C=()=>v("focusout"),N=R=>{u=0;const O=document.activeElement;O instanceof HTMLElement&&va()&&O.blur(),c.current=0,l.current=!1;const j=Math.max(i.current,Qr(),At),M=document.documentElement.style;M.setProperty(e,`${j}px`),M.setProperty("--app-visible-vh",`${j}px`),M.setProperty("--app-vv-offset-top","0px"),M.setProperty("--kb-translate-y","0px"),M.setProperty("--kb-margin-top","0px"),M.setProperty("--kb-height","0px"),s(B=>B===j?B:j),n("keyboard session reset",{source:R,baseHeight:j})};window.addEventListener("resize",L),window.addEventListener("orientationchange",k),ge().visualViewport?.addEventListener("resize",T),ge().visualViewport?.addEventListener("scroll",E),document.addEventListener("focusin",S),document.addEventListener("focusout",C);const D=R=>{n("resume",{source:R,innerHeight:Math.round(window.innerHeight),visualViewport:ge().visualViewport?{width:Math.round(ge().visualViewport.width),height:Math.round(ge().visualViewport.height),offsetTop:Math.round(ge().visualViewport.offsetTop)}:null,hidden:document.hidden}),v(R)},A=()=>{document.hidden?N("visibilitychange:hidden"):D("visibilitychange")},x=()=>D("pageshow"),P=()=>N("pagehide");return document.addEventListener("visibilitychange",A),window.addEventListener("pageshow",x),window.addEventListener("pagehide",P),()=>{window.removeEventListener("resize",L),window.removeEventListener("orientationchange",k),ge().visualViewport?.removeEventListener("resize",T),ge().visualViewport?.removeEventListener("scroll",E),document.removeEventListener("focusin",S),document.removeEventListener("focusout",C),document.removeEventListener("visibilitychange",A),window.removeEventListener("pageshow",x),window.removeEventListener("pagehide",P),d!==null&&window.cancelAnimationFrame(d),g?.remove()}},[e,n,r]),o}const BC=1e3,_C=2e4,OC=9e4,DC=5e3,Q={ws:null,listeners:new Set,reconnectAttempt:0,reconnectTimer:null,idleCloseTimer:null,closing:!1};let Wo=0,sr=null;function FC(){return typeof window>"u"?null:`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/control/ws`}function Gg(){Q.idleCloseTimer&&(clearTimeout(Q.idleCloseTimer),Q.idleCloseTimer=null)}function MC(){Gg(),!(Q.ws&&Q.ws.readyState===WebSocket.OPEN)&&(Q.idleCloseTimer=setTimeout(()=>{Q.idleCloseTimer=null,Q.listeners.size===0&&jC()},DC))}function jC(){if(Q.ws){try{Q.ws.close()}catch{}Q.ws=null}sr&&(clearInterval(sr),sr=null)}function lf(){if(Q.reconnectTimer)return;const t=Math.min(BC*Math.pow(2,Q.reconnectAttempt),_C);Q.reconnectAttempt+=1,Q.reconnectTimer=setTimeout(()=>{Q.reconnectTimer=null,Xg()},t)}function Xg(){const t=FC();if(!t||Q.ws&&Q.ws.readyState===WebSocket.OPEN)return;let e;try{e=Up(t)}catch{lf();return}Q.ws=e,e.onopen=()=>{Q.reconnectAttempt=0,Wo=Date.now(),sr||(sr=setInterval(()=>{if(!(!Q.ws||Q.ws.readyState!==WebSocket.OPEN)&&Wo>0&&Date.now()-Wo>OC)try{Q.ws.close()}catch{}},3e4),sr.unref?.())},e.onmessage=n=>{Wo=Date.now();let r=null;try{r=JSON.parse(n.data)}catch{return}if(!r)return;if(r.type==="session-notice"){if(typeof r.id!="string"||typeof r.sessionId!="string"||typeof r.sessionName!="string"||typeof r.message!="string"||!r.message.trim()||r.message.length>4e3||r.title!==void 0&&(typeof r.title!="string"||r.title.length>120)||typeof r.createdAt!="number")return;const i=r;for(const a of Q.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type==="update-state"){const i=r.state;if(!i||typeof i.status!="string"||typeof i.currentVersion!="string")return;const a={type:"update-state",state:i};for(const c of Q.listeners)try{c(a)}catch(l){console.error("[clientStateSync] listener threw:",l)}return}if(r.type==="context-draft"){if(typeof r.text!="string")return;const i={type:"context-draft",text:r.text,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const a of Q.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type==="pinned-explorer-roots"){if(!r.pinnedExplorerRoots||typeof r.pinnedExplorerRoots!="object"||Array.isArray(r.pinnedExplorerRoots))return;const i={type:"pinned-explorer-roots",pinnedExplorerRoots:r.pinnedExplorerRoots,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const a of Q.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type==="config-updated"){if(r.key!=="toolbar-presets"&&r.key!=="agent-rules"&&r.key!=="program-detection")return;const i={type:"config-updated",key:r.key,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0};for(const a of Q.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type!=="client-state"||!r.state)return;const o=r.state,s={type:"client-state",clientState:{sessions:Array.isArray(o.sessions)?o.sessions:[],updatedAt:typeof o.updatedAt=="number"?o.updatedAt:Date.now()},inventory:r.inventory,seq:typeof r.seq=="number"?r.seq:void 0};for(const i of Q.listeners)try{i(s)}catch(a){console.error("[clientStateSync] listener threw:",a)}},e.onclose=()=>{Q.ws===e&&(Q.ws=null),Q.listeners.size>0&&lf()},e.onerror=()=>{}}function Yg(t){return Q.listeners.add(t),Gg(),Q.ws||Xg(),()=>{Q.listeners.delete(t),Q.listeners.size===0&&MC()}}const Sa=oi(t=>({unread:{},viewing:null,receive:(e,n)=>t(r=>{const o=r.unread[e]??[];return r.viewing===e||o.includes(n)?r:{unread:{...r.unread,[e]:[...o,n]}}}),view:e=>t(n=>{if(!e||!n.unread[e])return n.viewing===e?n:{viewing:e};const r={...n.unread};return delete r[e],{viewing:e,unread:r}})})),Zg=new Set(["bash","zsh","fish","sh","dash","ksh","tcsh","csh","nu"]);function qn(t){if(!t)return null;if(t==="/")return"/";const e=t.replace(/\/+$/,"").split("/");return e[e.length-1]||t}function UC(t,e,n,r=Zg,o=null,s=null){if(t.customName)return{primary:t.name,secondary:qn(n)};if(o){const a=qn(n),c=o===n||o===a;if(s!=="idle"&&!r.has(o)&&!c)return{primary:o,secondary:a}}if(e&&!r.has(e))return{primary:e,secondary:qn(n)};const i=qn(n);return i?{primary:i,secondary:null}:{primary:t.name,secondary:null}}function $C(t,e,n,r=Zg,o=null,s=null){return UC(t,e,n,r,o,s).primary}function HC(t,e,n){const r=[],o=new Map;for(const s of t){const i=e(s),a=i&&i.trim().length>0?i:"";let c=o.get(a);c||(c={key:a,label:a?qn(a)??a:n,sessions:[]},o.set(a,c),r.push(c)),c.sessions.push(s)}return r.sort((s,i)=>(s.key===""?1:0)-(i.key===""?1:0))}function aR(t){return t&&t.trim().length>0?t:""}function cR(t,e,n){const r=[...t],[o]=r.splice(e,1);return o?(r.splice(n,0,o),r.flatMap(s=>s.sessions.map(i=>i.id))):t.flatMap(s=>s.sessions.map(i=>i.id))}function qC(t,e){const n=new Set;return t.flatMap(r=>{const o=[...new Set(r.sessionIds)].filter(s=>e.has(s)&&!n.has(s));return o.length<(r.federated?1:2)?[]:(o.forEach(s=>n.add(s)),[{...r,sessionIds:o}])})}function lR(t,e,n,r,o=[],s=[]){const i=new Map(t.map(g=>[g.id,g])),a=qC(s,new Set(i.keys())),c=new Map,l=new Map,d=o.filter(g=>g.sessionIds.length>=2&&g.sessionIds.every(m=>i.has(m))),u=(g,m)=>{const b=i.get(m);g.forEach(w=>{c.set(w,g),l.set(w,b)})};for(const g of a){const m=new Set(g.sessionIds),b=new Map;for(const y of d)y.sessionIds.every(v=>m.has(v))&&y.sessionIds.forEach(v=>b.set(v,y.sessionIds));const w=new Set,I=g.sessionIds.flatMap(y=>{if(w.has(y))return[];const v=b.get(y)??[y];return v.forEach(L=>w.add(L)),v});u(I,g.sessionIds[0])}for(const g of d)g.sessionIds.some(m=>c.has(m))||u(g.sessionIds,g.sessionIds[0]);const f=g=>{const m=new Set;return g.flatMap(b=>{if(m.has(b.id))return[];const w=c.get(b.id)??[b.id];return w.forEach(I=>m.add(I)),w.map(I=>i.get(I))})};if(!n)return{arranged:f(t),groups:[]};const h=HC(t,g=>e(l.get(g.id)??g),r).map(g=>({...g,sessions:f(g.sessions)}));return{arranged:h.flatMap(g=>g.sessions),groups:h}}function KC(t,e,n){const r=t.findIndex(o=>n(o)===e);return r<0?null:t[r+1]?n(t[r+1]):r>0?n(t[r-1]):null}const xa="termdock-sessions",bc="termdock-active-session",Rl="termdock-sessions-cache";function vc(){try{const t=localStorage.getItem(bc);return t&&t.trim().length>0?t:null}catch{return null}}function Fn(t){try{t?localStorage.setItem(bc,t):localStorage.removeItem(bc)}catch{}}function Jg(){if(typeof window>"u")return null;try{const t=localStorage.getItem(Rl);if(!t)return null;const e=JSON.parse(t);return Array.isArray(e)?e.filter(n=>typeof n=="object"&&n!==null&&typeof n.sessionId=="string"&&typeof n.name=="string"):null}catch{return null}}function tn(t){if(!(typeof window>"u"))try{localStorage.setItem(Rl,JSON.stringify(t))}catch{}}function df(){if(!(typeof window>"u"))try{localStorage.removeItem(Rl)}catch{}}function Qg(t){return t.map(e=>({...e,mode:e.mode==="tmux"?"tmux":"shell",tmuxSessionName:e.tmuxSessionName??null,customName:e.customName===!0}))}function uf(t){return Qg(t.map(e=>({sessionId:e.sessionId,name:e.name,customName:e.customName===!0,backendSessionId:e.backendSessionId,mode:e.mode,tmuxSessionName:e.tmuxSessionName,createdAt:e.createdAt,lastActivity:e.lastActivity}))).map((e,n)=>({...e,activeProgram:t[n]?.activeProgram??null,cwd:t[n]?.cwd??null}))}function ff(t){return t.map(e=>`${e.sessionId}:${e.name}:${e.customName}:${e.backendSessionId}:${e.mode}:${e.tmuxSessionName}:${e.lastActivity}:${e.activeProgram??""}:${e.cwd??""}`).join("|")}function Sc(t,e){return t.length===0?null:e&&t.some(n=>n.sessionId===e)?e:t[0]?.sessionId??null}function zC(){const t=Jg()??[];return{sessions:t,activeSessionId:Sc(t,vc())}}function dR(){const t=_.useRef(Jg()).current,e=_.useRef(vc()).current,[n,r]=_.useState(t??[]),[o,s]=_.useState(null),[i,a]=_.useState(t&&t.length>0?Sc(t,e):e),[c,l]=_.useState(t===null),d=_.useRef(!1),u=_.useRef(null),f=_.useRef(t===null),h=_.useRef(0),g=_.useRef(new Set),m=_.useRef(0);_.useEffect(()=>{f.current=c},[c]),_.useEffect(()=>{u.current=i},[i]);const b=_.useCallback(x=>{const P=Sc(x,u.current??vc());return a(R=>R===P?R:P),Fn(P),u.current=P,P},[]),w=_.useCallback((x,P)=>{const R=x.filter(O=>!g.current.has(O.sessionId));r(O=>ff(O)===ff(R)?O:R),tn(R),P?.reconcileActive&&b(R)},[b]),I=_.useCallback((x,P)=>{const R=g.current.size===0?x:{...x,clientSessions:x.clientSessions.filter(O=>!g.current.has(O.sessionId))};s(R),w(uf(R.clientSessions),P)},[w]),y=_.useCallback(()=>typeof window>"u"?[]:localStorage.getItem(xa)?(localStorage.removeItem(xa),df(),Fn(null),r([]),a(null),console.info("[session-persist] discarded legacy local session cache"),[]):[],[]),v=_.useCallback(async()=>{if(typeof window>"u")return[];const x=m.current;try{const P=await yg(),R=uf(P.clientSessions);return x!==m.current?(console.info("[session-inventory] ignored restore snapshot superseded by a local mutation"),R.filter(O=>!g.current.has(O.sessionId))):(I(P,{reconcileActive:!0}),R.length>0?R:y())}catch(P){console.error("Failed to restore sessions from server:",P);try{return y()}catch(R){console.error("Failed to discard legacy local sessions:",R)}}finally{l(!1)}return[]},[I,y]),L=_.useCallback(async x=>{const P=++m.current,R=await bg(x);return P===m.current&&(I(R.inventory),a(R.session.sessionId),Fn(R.session.sessionId)),R},[I]),k=_.useCallback(async(x,P)=>{++m.current,g.current.add(x),r(R=>{const O=R.filter(B=>B.sessionId!==x),j=P!=null&&O.some(B=>B.sessionId===P),M=u.current===x?j?P:KC(R,x,B=>B.sessionId):u.current;return a(M),Fn(M),tn(O),O});try{await Sg(x)}catch(R){console.error("Failed to remove session from inventory:",R)}},[]),T=_.useCallback(x=>{const P=Date.now();r(R=>{const O=R.map(j=>j.sessionId===x?{...j,lastActivity:P}:j);return tn(O),O})},[]),E=_.useCallback(x=>{a(x),Fn(x)},[]),S=_.useCallback(async(x,P)=>{const R=P.trim();if(!R)return;const O=++m.current;r(j=>{const M=j.map(B=>B.sessionId===x?{...B,name:R,customName:!0}:B);return tn(M),M});try{const j=await ts(x,{name:R,customName:!0});O===m.current&&I(j)}catch(j){console.error("Failed to rename session in inventory:",j)}},[I]),C=_.useCallback(async x=>{const P=++m.current;r(R=>{const O=R.map(j=>j.sessionId===x?{...j,customName:!1}:j);return tn(O),O});try{const R=await ts(x,{customName:!1});P===m.current&&I(R)}catch(R){console.error("Failed to reset session name in inventory:",R)}},[I]),N=_.useCallback(async x=>{const P=++m.current;r(R=>{const O=new Map(R.map(U=>[U.sessionId,U])),j=x.map(U=>O.get(U)).filter(U=>U!==void 0),M=new Set(x),B=R.filter(U=>!M.has(U.sessionId)),F=[...j,...B];return tn(F),F});try{const R=await vg(x);P===m.current&&I(R)}catch(R){console.error("Failed to reorder sessions in inventory:",R)}},[I]),D=_.useCallback(async()=>{++m.current;for(const x of n)g.current.add(x.sessionId);r([]),s(null),a(null),Fn(null),df(),typeof window<"u"&&localStorage.removeItem(xa);try{await xg()}catch(x){console.error("Failed to clear session inventory:",x)}},[n]),A=_.useCallback(async(x,P)=>{const R=++m.current;r(O=>{const j=O.map(M=>M.sessionId===x?{...M,backendSessionId:P}:M);return tn(j),j});try{const O=await ts(x,{backendSessionId:P});R===m.current&&I(O)}catch(O){console.error("Failed to update session backend in inventory:",O)}},[I]);return _.useEffect(()=>{d.current||(d.current=!0,v())},[v]),_.useEffect(()=>Yg(P=>{if(P.type!=="client-state"||f.current)return;const R=typeof P.seq=="number"?P.seq:null;if(R!==null){if(R<h.current){console.warn("[session-inventory] ignored stale control snapshot",{seq:R,latestSeq:h.current});return}h.current=R}if(P.inventory){I(P.inventory,{reconcileActive:!0});return}const O=Qg(P.clientState.sessions||[]);w(O,{reconcileActive:!0})}),[I,w]),{sessions:n,inventory:o,activeSessionId:i,isLoading:c,openSession:L,removeSession:k,updateSessionActivity:T,setActiveSession:E,updateSessionBackendId:A,renameSession:S,resetSessionCustomName:C,reorderSessions:N,clearAllSessions:D,restoreSessions:v}}const WC=256*1024,VC=256*1024,GC=128;function hf(t,e=WC){if(!t)return[];if(t.length<=e)return[t];const n=[];let r=0;for(;r<t.length;){let o=Math.min(r+e,t.length);if(o<t.length){const s=t.lastIndexOf(`
35
+ `,o);s>r&&(o=s+1)}n.push(t.slice(r,o)),r=o}return n}function XC(t,e=VC,n=GC){const r=new Map;let o=0,s=0;for(const i of[...t.keys()]){const a=t.get(i);if(!a||a.length===0){t.delete(i);continue}const c=[];for(;a.length>0;){const l=a[0];if(s>0&&(s>=n||o+l.length>e))break;a.shift(),c.push(l),o+=l.length,s+=1}if(c.length>0&&r.set(i,c),t.delete(i),a.length>0&&t.set(i,a),s>=n||o>=e)break}return r}async function em(t,e=!1,n="termdock-encrypted-background"){const r=await new Promise((o,s)=>{const i=indexedDB.open(n,1);i.onupgradeneeded=()=>i.result.createObjectStore("state"),i.onsuccess=()=>o(i.result),i.onerror=()=>s(i.error)});try{return await new Promise((o,s)=>{const i=r.transaction("state",e?"readwrite":"readonly"),a=t(i.objectStore("state"));i.oncomplete=()=>o(a.result),i.onabort=i.onerror=()=>s(i.error)})}finally{r.close()}}const YC=t=>em(e=>e.put(t,t.targetPeerId),!0),ZC=t=>em(e=>e.delete(t),!0),tm="termdock-pwa-notifications-enabled",nm="termdock-pwa-ai-notifications-enabled",rm="termdock-pwa-exit-notifications-enabled",om="termdock-pwa-notification-alert-style",JC="termdock-notification-claim:",xc=5e3,QC=1500,Ec="termdock-push-last-sync",pf=360*60*1e3,eI=10080*60*1e3,eo=new Map;function Tl(){return et()?!0:typeof window<"u"&&typeof Notification<"u"&&"serviceWorker"in navigator&&window.isSecureContext}function tI(){if(typeof navigator>"u")return!1;const t=navigator.userAgent;return/iPad|iPhone|iPod/.test(t)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}function nI(){return typeof window>"u"?!1:!!(window.matchMedia("(display-mode: standalone)").matches||"standalone"in navigator&&navigator.standalone===!0)}function rI(){return et()?!0:!(!Tl()||tI()&&!nI())}function uR(){return et()?"granted":typeof Notification>"u"?"unsupported":Notification.permission}function Pl(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(tm)==="true"}catch{return!1}}function fR(t){if(!(typeof window>"u"))try{window.localStorage.setItem(tm,String(t))}catch{}}function Fs(){if(typeof window>"u")return!0;try{const t=window.localStorage.getItem(nm);return t===null?!0:t==="true"}catch{return!0}}function hR(t){if(!(typeof window>"u"))try{window.localStorage.setItem(nm,String(t))}catch{}}function Ac(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(rm)==="true"}catch{return!1}}function pR(t){if(!(typeof window>"u"))try{window.localStorage.setItem(rm,String(t))}catch{}}function uo(){if(typeof window>"u")return"normal";try{const t=window.localStorage.getItem(om);if(t==="quiet"||t==="persistent")return t}catch{}return"normal"}function gR(t){if(!(typeof window>"u"))try{window.localStorage.setItem(om,t)}catch{}}async function mR(){return et()?"granted":Tl()?Notification.permission==="default"?Notification.requestPermission():Notification.permission:"unsupported"}function oI(){return typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus()}function sI(t){for(const[e,n]of eo)t-n>xc&&eo.delete(e)}function iI(t){return t.dedupKey?.trim()?t.dedupKey.trim():t.tag?.trim()?t.tag.trim():[t.data?.sessionId,t.title,t.body].filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()).join("|")}function aI(t){const e=iI(t);if(!e)return!0;const n=Date.now();sI(n);const r=eo.get(e)??0;if(n-r<xc)return!1;try{if(typeof window<"u"&&window.localStorage){const o=`${JC}${e}`,s=Number(window.localStorage.getItem(o)??"0");if(Number.isFinite(s)&&n-s<xc)return eo.set(e,s),!1;Number.isFinite(s)&&s>0&&window.localStorage.removeItem(o),window.localStorage.setItem(o,String(n))}}catch{}return eo.set(e,n),!0}async function ai(){if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;try{const t=await navigator.serviceWorker.getRegistration()??null;return t?.active?t:await Promise.race([navigator.serviceWorker.ready,new Promise(n=>{window.setTimeout(()=>n(null),QC)})])??t}catch{return null}}function cI(t){const e="=".repeat((4-t.length%4)%4),n=(t+e).replace(/-/g,"+").replace(/_/g,"/"),r=window.atob(n),o=new Uint8Array(new ArrayBuffer(r.length));for(let s=0;s<r.length;s+=1)o[s]=r.charCodeAt(s);return o}async function Nl(t,e){const n=await fetch("/api/csrf-token");if(!n.ok)throw new Error("Unable to get notification security token");const{csrfToken:r}=await n.json();return fetch(`/api/notifications/${t}`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(e)})}async function lI(t=!1,e=!1){if(et())return!0;if(!Pl()||!rI()||Notification.permission!=="granted")return!1;const n=await ai();if(!n?.pushManager)return!1;try{const r=await fetch("/api/notifications/status");if(!r.ok)return!1;const o=await r.json();let s=await n.pushManager.getSubscription();const i=!!(s?.expirationTime&&s.expirationTime-Date.now()<eI);if(!s)try{s=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:cI(o.publicKey)})}catch(d){return console.warn(`[PWA notifications] Push subscription missing; re-subscribe failed${e?" (user gesture)":""}:`,d),!1}const a=Number(window.localStorage.getItem(Ec)??"0"),c=!o.subscription||o.subscription.endpoint!==s.endpoint||Date.now()-(o.subscription.updatedAt??0)>=pf;if(t||c||Date.now()-a>=pf||i){if(!(await Nl("subscribe",{subscription:s.toJSON(),aiEnabled:Fs(),exitEnabled:Ac(),alertStyle:uo(),locale:navigator.language})).ok)return!1;window.localStorage.setItem(Ec,String(Date.now()))}const l=re();return l&&await YC({targetPeerId:l.targetPeerId,addresses:wr(l),routes:Vt(l),publicKey:o.publicKey,preferences:{aiEnabled:Fs(),exitEnabled:Ac(),alertStyle:uo(),locale:navigator.language}}),!0}catch(r){return console.warn("[PWA notifications] Push subscription sync failed:",r),!1}}async function wR(){if(et())return;const e=await(await ai())?.pushManager?.getSubscription();try{await Nl("unsubscribe",{endpoint:e?.endpoint})}finally{const n=re();n&&await ZC(n.targetPeerId),await e?.unsubscribe();try{window.localStorage.removeItem(Ec)}catch{}}}async function yR(){if(et()||!Pl())return;(await Nl("preferences",{aiEnabled:Fs(),exitEnabled:Ac(),alertStyle:uo(),locale:navigator.language})).status===404&&await lI(!0)}async function bR(){if(!et())try{const t=navigator;typeof t.clearAppBadge=="function"&&await t.clearAppBadge()}catch{}}async function vR(t){if(!et())try{const e=await ai();if(!e||typeof e.getNotifications!="function")return;const n=`agent:${t}`,r=await e.getNotifications({tag:n});for(const s of r)s.close();const o=navigator;if(typeof o.setAppBadge=="function"){const s=await e.getNotifications();await o.setAppBadge(s.length)}}catch{}}async function Ea(t){if(!Pl()||!Tl())return!1;if(t.requireHidden!==!1&&oI())return!0;const e=et();if(e){const s=t.alertStyle??uo(),i=await e.showNotification({title:t.title,body:t.body,tag:t.tag,sessionId:t.data?.sessionId,silent:s==="quiet",persistent:s==="persistent"});return e.notificationDeliveryConfirmation===!0&&i}if(Notification.permission!=="granted")return!1;const n=await ai();if(t.deferToPush&&await n?.pushManager?.getSubscription())return!0;if(t.requireHidden!==!1){if(await n?.pushManager?.getSubscription())return!0}if(!aI(t))return!0;const r=t.alertStyle??uo(),o={body:t.body,tag:t.tag,icon:"/pwa-192x192.png",badge:"/maskable-icon-512x512.png",requireInteraction:r==="persistent",renotify:r==="persistent"?!!t.tag:!1,silent:r==="quiet",vibrate:r==="quiet"?[]:[80,40,80],data:{url:t.data?.url??"/",sessionId:t.data?.sessionId}};try{if(n&&typeof n.showNotification=="function")return await n.showNotification(t.title,o),!0;const s=new Notification(t.title,o);return s.onclick=()=>{window.focus(),t.data?.url&&window.location.href!==t.data.url&&window.location.assign(t.data.url),s.close()},!0}catch(s){if(s instanceof DOMException&&s.name==="NotSupportedError"&&o.renotify)try{const i={...o,renotify:!1};return n&&typeof n.showNotification=="function"?await n.showNotification(t.title,i):new Notification(t.title,i),!0}catch(i){return console.warn("[PWA notifications] Failed to show notification (renotify fallback):",i),!1}return console.warn("[PWA notifications] Failed to show notification:",s),!1}}function dI(){try{return localStorage.getItem("termdock:locale")||"en"}catch{return"en"}}function uI(t,e){return t==="zh"?{waitingTitle:`${e} 需要你的处理`,waitingBody:`${e} 需要你的处理。`,doneTitle:`${e} 已完成`,doneBody:`${e} 已完成,点按查看结果。`,exitedTitle:`${e} 已退出`,exitedBody:`${e} 已退出,点按查看结果。`}:{waitingTitle:`${e} needs your input`,waitingBody:`${e} is waiting for your input.`,doneTitle:`${e} finished`,doneBody:"Tap to see the result.",exitedTitle:`${e} exited`,exitedBody:"Tap to see the result."}}const gf=1e6;function Ut(t){return{sessionId:t,directory:"",terminalSessionId:null,mode:"shell",tmuxSessionName:null,activeProgram:null,activeProgramRaw:null,activeProgramSource:null,cwd:null,inCopyMode:!1,isConnecting:!1,agentStatus:null,agentIndicator:null,agentStatusDetail:null,agent:null,agentMessage:null,agentNativeSessionId:null,agentResumeRecovered:!1,agentRich:!1,agentActivity:0,agentCwd:null,agentNeedsReview:!1,shellTitle:null,promptState:null,shellExitCode:null,tuiProgress:null,gitStatus:null,bufferChunks:[],bufferLength:0,lastOutputAt:null,updatedAt:Date.now()}}const ci="termdock-shell-titles-v1";function li(){if(typeof window>"u")return{};try{const t=localStorage.getItem(ci);if(!t)return{};const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:{}}catch{return{}}}function fI(t){return li()[t]??null}function hI(t,e){if(!(typeof window>"u"))try{const n=li();e?n[t]=e:delete n[t],localStorage.setItem(ci,JSON.stringify(n))}catch{}}function pI(t){if(!(typeof window>"u"))try{const e=li();delete e[t],localStorage.setItem(ci,JSON.stringify(e))}catch{}}const di="termdock-agent-cache-v1";function Ll(){if(typeof window>"u")return{};try{const t=localStorage.getItem(di);if(!t)return{};const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:{}}catch{return{}}}function gI(t,e){if(!(typeof window>"u"))try{const n=Ll();e?n[t]=e:delete n[t],localStorage.setItem(di,JSON.stringify(n))}catch{}}function mI(t){if(!(typeof window>"u"))try{const e=Ll();delete e[t],localStorage.setItem(di,JSON.stringify(e))}catch{}}function wI(){if(!(typeof window>"u"))try{localStorage.removeItem(di)}catch{}}function SR(t){return Ll()[t]??null}function yI(){if(!(typeof window>"u"))try{localStorage.removeItem(ci)}catch{}}const Aa=oi((t,e)=>{const n={pendingChunksBySession:new Map,activitySessionIds:new Set,batchFlushRafRef:null},r=(i,a)=>{const c=new Map;return t(l=>{const d=new Map(l.sessions);let u=l.nextChunkId;const f=Date.now();for(const[h,g]of i){const m=d.get(h)??Ut(h);let b=m.bufferChunks.length>0?[...m.bufferChunks]:[],w=m.bufferLength;for(const I of g){const y=u++;b.push({id:y,data:I}),c.set(h,y),w+=I.length}for(;w>gf&&b.length>1;){const I=b.shift();if(!I)break;w-=I.data.length}d.set(h,{...m,bufferChunks:b,bufferLength:w,lastOutputAt:a.has(h)?f:m.lastOutputAt,updatedAt:f})}return{sessions:d,nextChunkId:u}}),c},o=()=>{if(n.batchFlushRafRef===null){if(typeof window>"u"){s();return}n.batchFlushRafRef=window.requestAnimationFrame(()=>{n.batchFlushRafRef=null,s()})}},s=()=>{if(n.pendingChunksBySession.size===0)return;const i=XC(n.pendingChunksBySession),a=new Set([...i.keys()].filter(c=>n.activitySessionIds.has(c)));for(const c of i.keys())n.pendingChunksBySession.has(c)||n.activitySessionIds.delete(c);r(i,a),n.pendingChunksBySession.size>0&&o()};return{sessions:new Map,nextChunkId:1,activeSessionId:null,getTerminalSession:i=>e().sessions.get(i),setActiveSessionId:i=>{if(t({activeSessionId:i}),i){const a=e().sessions.get(i);if(a?.agentNeedsReview){const c=new Map(e().sessions);c.set(i,{...a,agentNeedsReview:!1,updatedAt:Date.now()}),t({sessions:c}),a.terminalSessionId&&cc(a.terminalSessionId)}}},setTerminalSession:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i),f=!d||d.terminalSessionId!==a.sessionId?Ut(i):d??Ut(i),h=a.history??d?.history??[];return l.set(i,{...f,terminalSessionId:a.sessionId,mode:a.mode??f.mode,tmuxSessionName:a.tmuxSessionName??f.tmuxSessionName,activeProgram:a.activeProgram??d?.activeProgram??f.activeProgram,activeProgramRaw:a.activeProgramRaw??d?.activeProgramRaw??f.activeProgramRaw,activeProgramSource:a.activeProgramSource??d?.activeProgramSource??f.activeProgramSource,cwd:a.cwd??d?.cwd??f.cwd,agentResumeRecovered:d?.agentResumeRecovered??f.agentResumeRecovered,shellTitle:d?.shellTitle??li()[i]??f.shellTitle,sessionId:i,isConnecting:!1,history:h,updatedAt:Date.now()}),{sessions:l}})},setSessionHistory:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??Ut(i);return l.set(i,{...d,history:a,updatedAt:Date.now()}),{sessions:l}})},setSessionActiveProgram:(i,a,c=null,l=null)=>{t(d=>{const u=new Map(d.sessions),f=u.get(i)??Ut(i);return u.set(i,{...f,activeProgram:a,activeProgramRaw:l,activeProgramSource:c,updatedAt:Date.now()}),{sessions:u}})},setSessionCwd:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??Ut(i);return l.set(i,{...d,cwd:a,updatedAt:Date.now()}),{sessions:l}})},setSessionShellTitle:(i,a)=>{t(c=>{const l=c.sessions.get(i);if(!l||l.shellTitle===a)return c;const d=new Map(c.sessions);return d.set(i,{...l,shellTitle:a,updatedAt:Date.now()}),{sessions:d}}),hI(i,a)},setSessionPromptState:(i,a,c)=>{t(l=>{const d=l.sessions.get(i);if(!d||d.promptState===a)return l;const u=new Map(l.sessions);return u.set(i,{...d,promptState:a,shellExitCode:c??d.shellExitCode,updatedAt:Date.now()}),{sessions:u}})},setSessionTuiProgress:(i,a)=>{t(c=>{const l=c.sessions.get(i);if(!l)return c;const d=a?.state==="remove"?null:a;if(l.tuiProgress?.state===d?.state&&l.tuiProgress?.progress===d?.progress)return c;const u=new Map(c.sessions);return u.set(i,{...l,tuiProgress:d,updatedAt:Date.now()}),{sessions:u}})},setSessionGitStatus:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i);return!d||JSON.stringify(d.gitStatus)===JSON.stringify(a)?c:(l.set(i,{...d,gitStatus:a,updatedAt:Date.now()}),{sessions:l})})},setSessionCopyMode:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i);return!d||d.inCopyMode===a?c:(l.set(i,{...d,inCopyMode:a,updatedAt:Date.now()}),{sessions:l})})},setSessionAgentStatus:(i,a)=>{const c=e(),l=c.sessions.get(i);if(!l)return;const d=a.agentStatus??null,u=d&&d!=="idle"?a.agentIndicator??l.agentIndicator??null:null,f=d&&d!=="idle"?a.agentStatusDetail??null:null,h=a.agent!==void 0?a.agent:l.agent,g=a.agentMessage!==void 0?a.agentMessage:d?l.agentMessage:null,m=a.agentNativeSessionId!==void 0?a.agentNativeSessionId:l.agentNativeSessionId,b=a.agentResumeRecovered!==void 0?a.agentResumeRecovered:l.agentResumeRecovered,w=a.agentRich??l.agentRich,I=a.agentActivity??l.agentActivity,y=a.agentCwd!==void 0?a.agentCwd:l.agentCwd,v=c.activeSessionId!==i,L=l.agentStatus==="working"||l.agentStatus==="waiting"||l.agentStatus==="done",k=a.reviewed===!1||a.reviewed===null&&d===null&&L&&v;if(l.agentStatus===d&&l.agentIndicator===u&&l.agentStatusDetail===f&&l.agent===h&&l.agentMessage===g&&l.agentNativeSessionId===m&&l.agentResumeRecovered===b&&l.agentRich===w&&l.agentActivity===I&&l.agentCwd===y&&l.agentNeedsReview===k)return;const T=new Map(c.sessions);if(T.set(i,{...l,agentStatus:d,agentIndicator:u,agentStatusDetail:f,agent:h,agentMessage:g,agentNativeSessionId:m,agentResumeRecovered:b,agentRich:w,agentActivity:I,agentCwd:y,agentNeedsReview:k,updatedAt:Date.now()}),t({sessions:T}),h&&gI(i,h),!Fs())return;const E=h?.displayName??l.agent?.displayName??"Agent",S=dI(),C=uI(S,E);if(d==="waiting"&&l.agentStatus!=="waiting"&&v){Ea({title:C.waitingTitle,body:g??C.waitingBody,tag:`agent:${i}`,dedupKey:`agent:${i}:waiting:${I}`,data:{url:"/",sessionId:i},deferToPush:!0});return}if(d==="done"&&l.agentStatus!=="done"&&v){Ea({title:C.doneTitle,body:C.doneBody,tag:`agent:${i}`,dedupKey:`agent:${i}:done:${I}`,data:{url:"/",sessionId:i},deferToPush:!0});return}d===null&&(l.agentStatus==="working"||l.agentStatus==="waiting")&&v&&Ea({title:C.exitedTitle,body:C.exitedBody,tag:`agent:${i}`,dedupKey:`agent:${i}:exited:${I}`,data:{url:"/",sessionId:i},deferToPush:!0})},setAgentResumeRecovered:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??Ut(i);return d.agentResumeRecovered===a?c:(l.set(i,{...d,agentResumeRecovered:a,updatedAt:Date.now()}),{sessions:l})})},clearAgentNeedsReview:i=>{const a=e().sessions.get(i);a?.agentNeedsReview&&(t(c=>{const l=new Map(c.sessions),d=l.get(i);return!d||!d.agentNeedsReview?c:(l.set(i,{...d,agentNeedsReview:!1,updatedAt:Date.now()}),{sessions:l})}),a.terminalSessionId&&cc(a.terminalSessionId))},setConnecting:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??Ut(i);return l.set(i,{...d,isConnecting:a,updatedAt:Date.now()}),{sessions:l}})},appendToBuffer:(i,a,c)=>{if(!a)return;let l=n.pendingChunksBySession.get(i);l||(l=[],n.pendingChunksBySession.set(i,l)),l.push(...hf(a)),c?.markActivity!==!1&&n.activitySessionIds.add(i),o()},hasPendingBufferWrites:i=>(n.pendingChunksBySession.get(i)?.length??0)>0,flushPendingBufferWrites:i=>{const a=n.pendingChunksBySession.get(i);if(!a?.length)return e().sessions.get(i)?.bufferChunks.at(-1)?.id??null;n.pendingChunksBySession.delete(i);const c=n.activitySessionIds.delete(i);return n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),r(new Map([[i,a]]),c?new Set([i]):new Set).get(i)??null},replaceBuffer:(i,a)=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null);let c=null;return t(l=>{const d=new Map(l.sessions),u=d.get(i);if(!u)return l;if(!a||a.length===0)return d.set(i,{...u,bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:d};let f=l.nextChunkId;const h=[];let g=0;for(const m of a)if(m)for(const b of hf(m)){const w=f++;h.push({id:w,data:b}),c=w,g+=b.length}for(;g>gf&&h.length>1;){const m=h.shift();if(!m)break;g-=m.data.length}return d.set(i,{...u,bufferChunks:h,bufferLength:g,updatedAt:Date.now()}),{sessions:d,nextChunkId:f}}),c},clearTerminalSession:i=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),t(a=>{const c=new Map(a.sessions),l=c.get(i);return l&&c.set(i,{...l,terminalSessionId:null,isConnecting:!1,agentStatus:null,agentIndicator:null,agentStatusDetail:null,agent:null,agentMessage:null,agentNeedsReview:!1,updatedAt:Date.now()}),{sessions:c}})},clearBuffer:i=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),t(a=>{const c=new Map(a.sessions),l=c.get(i);return l?(c.set(i,{...l,bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:c}):a})},removeTerminalSession:i=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),t(a=>{const c=new Map(a.sessions);return c.delete(i),{sessions:c}}),pI(i),mI(i)},clearAllTerminalSessions:()=>{n.pendingChunksBySession.clear(),n.activitySessionIds.clear(),n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),t({sessions:new Map,nextChunkId:1}),yI(),wI()}}}),kc="termdock:session-notice";function bI(){return _.useEffect(()=>{const t=()=>Sa.getState().view(!document.hidden&&Yo()?Aa.getState().activeSessionId:null);t();const e=Aa.subscribe((n,r)=>{n.activeSessionId!==r.activeSessionId&&t()});return document.addEventListener("visibilitychange",t),window.addEventListener(ao,t),()=>{e(),document.removeEventListener("visibilitychange",t),window.removeEventListener(ao,t),Sa.getState().view(null)}},[]),_.useEffect(()=>Yg(t=>{if(t.type!=="session-notice")return;Sa.getState().receive(t.sessionId,t.id);const e=re()?.targetPeerId,n=ut(),r=window.parent,o=zC().sessions.find(u=>u.sessionId===t.sessionId),s=Aa.getState().sessions.get(t.sessionId),i=s?.shellTitle??fI(t.sessionId),a=i===s?.cwd||i===qn(s?.cwd??null)?null:i,c=$C(o??{name:t.sessionName},s?.activeProgram??null,null,void 0,a,s?.promptState??null),l={...t,sessionName:c,key:`${e??"local"}:${t.id}`,open:()=>e&&n?n.focusSession(e,t.sessionId):(window.dispatchEvent(new CustomEvent("termdock:focus-session",{detail:t.sessionId})),!0)},d=r.document.createEvent("CustomEvent");d.initCustomEvent(kc,!1,!1,l),r.dispatchEvent(d)}),[]),null}function vI(){const{locale:t}=ii(),e=t==="zh",[n,r]=_.useState([]);_.useEffect(()=>{const i=a=>{const c=a.detail;r(l=>l.some(d=>d.key===c.key)?l:[...l,c])};return window.addEventListener(kc,i),()=>window.removeEventListener(kc,i)},[]);const o=_.useCallback(i=>{r(a=>a.filter(c=>c.key!==i))},[]),s=n[0];return s?Tc.createPortal(p.jsx(SI,{notice:s,remaining:n.length-1,chinese:e,onDismiss:o},s.key),document.body):null}function SI({notice:t,remaining:e,chinese:n,onDismiss:r}){const[o,s]=_.useState(!1);return p.jsxs("section",{"aria-label":n?"关键进展提醒":"Progress reminder",className:"fixed left-3 right-3 top-[calc(var(--safe-top-inset,0px)+0.75rem)] z-toast overflow-hidden rounded-xl bg-surface text-foreground shadow-lg ring-1 ring-inset ring-border/15 animate-fade-in md:left-auto md:right-4 md:w-[360px]",children:[p.jsxs("button",{type:"button","aria-label":n?"查看 Session":"Open session",className:"group flex w-full items-start gap-2.5 p-3.5 pr-11 text-left transition-colors hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",onClick:()=>{t.open()?r(t.key):s(!0)},children:[p.jsx(Kp,{size:16,className:"mt-0.5 shrink-0 text-primary","aria-hidden":"true"}),p.jsxs("span",{className:"min-w-0 flex-1",role:"status","aria-live":"polite","aria-atomic":"true",children:[p.jsxs("span",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium",title:t.sessionName,children:t.sessionName}),p.jsx(NE,{size:13,className:"shrink-0 text-muted-foreground/60 transition-colors group-hover:text-primary","aria-hidden":"true"})]}),t.title&&p.jsx("span",{className:"mt-1 block truncate text-[11px] text-muted-foreground",children:t.title}),p.jsx("span",{className:"mt-1.5 line-clamp-3 whitespace-pre-wrap break-words text-[13px] leading-relaxed text-foreground/85",title:t.message,children:t.message}),e>0&&p.jsx("span",{className:"mt-2 block text-[10px] text-muted-foreground",children:n?`还有 ${e} 条`:`${e} more`}),o&&p.jsx("span",{role:"alert",className:"mt-2 block text-xs text-warning",children:n?"暂时无法打开该服务,请重试。":"Unable to open the service. Please retry."})]})]}),p.jsx("button",{type:"button","aria-label":n?"关闭提醒":"Dismiss reminder",className:"absolute right-0 top-0 flex h-11 w-11 items-center justify-center rounded-tr-xl text-muted-foreground/60 transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",onClick:()=>r(t.key),children:p.jsx(Yp,{size:14})})]})}const mf=5*6e4;let Cc,sm=!1,im=!1,wf=!1;const Ic=new Set;function yf(){sm=!0,Ic.forEach(t=>t())}function xI(){return _.useSyncExternalStore(t=>(Ic.add(t),()=>{Ic.delete(t)}),()=>sm,()=>!1)}function EI(){window.dispatchEvent(new Event("termdock:before-update")),im=!0,Cc?.waiting?Cc.waiting.postMessage({type:"SKIP_WAITING"}):window.location.reload()}function AI(t,e){let n=t;return()=>{if(!n){n=!0;return}e()}}function kI(){if(wf||typeof window>"u"||!("serviceWorker"in navigator))return;wf=!0,navigator.serviceWorker.addEventListener("controllerchange",AI(!!navigator.serviceWorker.controller,()=>{im?window.location.reload():yf()}));const t=()=>{navigator.serviceWorker.register("/sw.js",{scope:"/",updateViaCache:"none"}).then(e=>{Cc=e;const n=()=>{e.waiting&&yf()},r=()=>{const i=e.installing;i?.addEventListener("statechange",()=>{i.state==="installed"&&navigator.serviceWorker.controller&&n()})};e.addEventListener("updatefound",r),r(),n();let o=0;const s=()=>{document.visibilityState!=="visible"||Date.now()-o<mf||(o=Date.now(),e.update().then(n).catch(()=>{}))};s(),window.setInterval(s,mf),document.addEventListener("visibilitychange",s)}).catch(()=>{})};document.readyState==="complete"?t():window.addEventListener("load",t,{once:!0})}function CI(){const t=xI(),[e,n]=_.useState(!1),{locale:r}=ii();if(!t||e)return null;const o=r==="zh";return p.jsxs("div",{role:"status",className:"fixed bottom-16 left-1/2 z-toast flex max-w-[calc(100%-2rem)] -translate-x-1/2 items-center gap-3 rounded-lg border border-border bg-background px-4 py-3 text-sm text-foreground shadow-lg",children:[p.jsx("span",{children:o?"新版本已就绪":"An update is ready"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-primary",onClick:EI,children:o?"重新加载":"Reload"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-muted-foreground",onClick:()=>n(!0),children:o?"稍后":"Later"})]})}function am(t){const e=document.querySelector('meta[name="theme-color"]');e&&e.setAttribute("content",t==="light"?"#FFFCF0":"#1C1B1A")}const cm=_.createContext(void 0);function xR({children:t}){const e=_.useContext(cm),n=e===void 0?typeof document>"u"?null:document.body:e;return n?Tc.createPortal(t,n):null}const II={activeKey:"root",items:[]},RI=()=>()=>{},TI=()=>II;function PI({host:t,item:e,visible:n,active:r}){const o=_.useRef(null);return _.useEffect(()=>{o.current?.toggleAttribute("inert",!r)},[r]),_.useLayoutEffect(()=>{const s=o.current;return()=>{try{const i=s?.contentWindow,a=i?.document.createEvent("Event");a&&(a.initEvent("termdock:before-update",!1,!1),i?.dispatchEvent(a))}catch{}t.attach(e.key,null)}},[t,e.key]),p.jsx("iframe",{ref:o,title:e.service?.label||"服务工作区","data-workspace-key":e.key,src:`/workspace.html?${Dp}=${encodeURIComponent(e.key)}`,className:"fixed inset-0 w-full border-0 bg-[var(--chrome-bg)]",style:{height:"var(--app-base-vh, 100%)",visibility:n?"visible":"hidden",pointerEvents:r?"auto":"none"},"aria-hidden":!r,tabIndex:r?0:-1,allow:"clipboard-read; clipboard-write; fullscreen"})}function NI({children:t}){const e=window.parent===window?ut():void 0,n=_.useSyncExternalStore(e?.subscribe||RI,e?.snapshot||TI),[r,o]=_.useState(null),[s,i]=_.useState(()=>n.activeKey==="root"?"root":null),[a,c]=_.useState(),[l,d]=_.useState(!1),[u,f]=_.useState(),h=n.items.find(y=>y.key===n.activeKey),g=h?.rendered||a===n.activeKey?n.activeKey:s,m=g!==n.activeKey,b=m&&s===null;_.useLayoutEffect(()=>{if(!m||b){f(void 0);return}const y=()=>{const v=Array.from(document.querySelectorAll("iframe[data-workspace-key]")).find(N=>N.dataset.workspaceKey===s),E=(s==="root"?r:v?.contentDocument)?.querySelector('nav[aria-label="切换服务"]')?.closest("[data-sidebar-gesture-ignore]")?.getBoundingClientRect();if(!E||E.width===0||E.right<=0){f(void 0);return}const S=v?.getBoundingClientRect(),C=E.top+(S?.top??0)>=160;f({left:E.left+(S?.left??0)+12,top:(C?E.top-8:E.bottom+8)+(S?.top??0),width:Math.max(0,E.width-24),transform:C?"translateY(-100%)":"none"})};return y(),window.addEventListener("resize",y),()=>window.removeEventListener("resize",y)},[m,b,s,r]),_.useLayoutEffect(()=>{e?.present(g),m||i(g),r?.toggleAttribute("inert",g!=="root"||m)},[e,r,g,m]),_.useEffect(()=>{if(d(!1),!m)return;const y=setTimeout(()=>d(!0),8e3);return()=>clearTimeout(y)},[n.activeKey,m]),_.useEffect(()=>{c(void 0)},[n.activeKey]);const w=n.items.find(y=>y.key===s),I=h?.phase==="offline"?"网络已断开,等待恢复…":h?.phase==="reconnecting"?"连接暂未恢复,正在重试…":l?"连接时间较长,仍在等待服务…":b?"正在恢复服务…":"正在切换服务…";return _.useEffect(()=>{if(!e)return;const y=()=>{try{const v=JSON.parse(localStorage.getItem("termdock-color-theme")||"null");(v==="dark"||v==="light")&&(document.documentElement.dataset.theme=v,am(v))}catch{}};return window.addEventListener("storage",y),()=>window.removeEventListener("storage",y)},[e]),_.useEffect(()=>{if(!e||!("serviceWorker"in navigator))return;const y=k=>{if(k.source!==navigator.serviceWorker.controller)return;const T=k.data;T?.type==="termdock:focus-session"&&typeof T.targetPeerId=="string"&&typeof T.sessionId=="string"&&e.focusSession(T.targetPeerId,T.sessionId)&&(k.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),k.stopImmediatePropagation())},v=async()=>{if("caches"in window)try{const k=await caches.open("termdock-notification-target-v1"),T=await k.match("/__termdock-notification-target");if(!T)return;const E=await T.json();typeof E.targetPeerId=="string"&&typeof E.sessionId=="string"&&Date.now()-E.clickedAt<3e4&&e.focusSession(E.targetPeerId,E.sessionId)&&await k.delete("/__termdock-notification-target")}catch{}},L=()=>{document.hidden||v()};return navigator.serviceWorker.addEventListener("message",y),document.addEventListener("visibilitychange",L),v(),()=>{navigator.serviceWorker.removeEventListener("message",y),document.removeEventListener("visibilitychange",L)}},[e]),e?p.jsxs("div",{className:"relative h-full w-full overflow-hidden bg-[var(--chrome-bg)]",children:[p.jsx("div",{ref:o,className:"isolate h-full w-full","aria-hidden":g!=="root"||m,style:{visibility:g==="root"?"visible":"hidden"},children:p.jsx(cm.Provider,{value:r,children:t})}),n.items.filter(y=>y.key!=="root").map(y=>p.jsx(PI,{host:e,item:y,visible:g===y.key,active:!m&&g===y.key},y.key)),b&&p.jsx("div",{className:"termdock-boot z-modal-panel",role:"status","aria-live":"polite",children:l||h?.phase==="offline"||h?.phase==="reconnecting"?p.jsxs("div",{className:"flex max-w-xs flex-col items-center gap-3 text-center",children:[p.jsx(De,{size:16,className:"animate-spin motion-reduce:animate-none","aria-hidden":"true"}),p.jsx("div",{className:"max-w-full truncate text-sm",children:h?.service?.label||"Termdock"}),p.jsx("div",{className:"text-xs text-muted-foreground",children:I}),p.jsx("button",{type:"button",className:"min-h-11 rounded-lg bg-surface-2 px-4 text-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>c(n.activeKey),children:"查看连接页面"})]}):p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"termdock-boot-spinner","aria-hidden":"true"}),p.jsx("span",{children:"Loading Termdock"})]})}),m&&!b&&p.jsx("div",{className:"fixed inset-0 z-modal-panel flex items-end justify-center px-3 pb-[calc(env(safe-area-inset-bottom)+96px)]",role:"dialog","aria-modal":"true","aria-label":"切换服务",onKeyDown:y=>{if(y.key==="Escape"&&w?.service&&(y.preventDefault(),e.activate(w.service)),y.key==="Tab"){const v=Array.from(y.currentTarget.querySelectorAll("button")),L=v[0],k=v[v.length-1];y.shiftKey&&document.activeElement===L?(y.preventDefault(),k?.focus()):!y.shiftKey&&document.activeElement===k&&(y.preventDefault(),L?.focus())}},children:p.jsxs("div",{style:u?{position:"absolute",...u}:void 0,className:"flex w-full max-w-sm flex-wrap items-center gap-x-2 gap-y-1 rounded-xl border border-border bg-surface-elevated px-3 py-1.5 text-foreground shadow-lg",children:[p.jsxs("div",{role:"status","aria-live":"polite",className:"flex min-w-0 flex-1 items-center gap-2",children:[p.jsx(De,{size:16,className:"shrink-0 animate-spin text-primary motion-reduce:animate-none","aria-hidden":"true"}),p.jsxs("div",{className:"min-w-0",children:[p.jsx("div",{className:"truncate text-sm font-medium",children:h?.service?.label||"服务工作区"}),p.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:I})]})]}),p.jsxs("div",{className:"flex items-center justify-end gap-1",children:[l&&p.jsx("button",{type:"button",className:"min-h-11 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2",onClick:()=>c(n.activeKey),children:"查看连接页面"}),w?.service&&p.jsx("button",{type:"button",autoFocus:!0,"aria-label":"取消切换",className:"min-h-11 shrink-0 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>e.activate(w.service),children:"取消"})]})]})})]}):t}const LI=_.lazy(()=>Gt(()=>import("./App-CVuPbhP4.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,3,7,8]))),BI=_.lazy(()=>Gt(()=>import("./DagPlayground-Yx7XBwmM.js"),__vite__mapDeps([9,10,2,1,11,7,3])).then(t=>({default:t.DagPlayground}))),_I=_.lazy(()=>Gt(()=>import("./DiffLab-Cn1f9iHY.js"),__vite__mapDeps([12,2,1,13,8,14,3])).then(t=>({default:t.DiffLab}))),OI=_.lazy(()=>Gt(()=>import("./DiffReviewLab-CN3a3LhH.js"),__vite__mapDeps([15,2,1,16,5,6,11,13,8,14,3])).then(t=>({default:t.DiffReviewLab})));LC();dE();wE();window.parent===window&&kI();const Kr=re();Kr&&Gt(()=>import("./App-CVuPbhP4.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,3,7,8])).catch(()=>{});!new URLSearchParams(location.search).has("dag-playground")&&!new URLSearchParams(location.search).has("diff-lab")&&!new URLSearchParams(location.search).has("diff-review-lab")&&Qx(Kr?{...Kr,id:Kr.targetPeerId,label:Kr.serviceName||location.host}:void 0);try{const t=JSON.parse(window.localStorage.getItem("termdock-color-theme")||"null");(t==="dark"||t==="light")&&(document.documentElement.dataset.theme=t,am(t))}catch{}vE.createRoot(document.getElementById("root")).render(p.jsx(ze.StrictMode,{children:p.jsxs(T2,{children:[window.parent===window&&p.jsxs(p.Fragment,{children:[p.jsx(CI,{}),p.jsx(vI,{})]}),p.jsx(vC,{children:p.jsx(_.Suspense,{fallback:p.jsx("div",{className:"termdock-boot",role:"status",children:"Loading Termdock"}),children:(()=>{const t=new URLSearchParams(window.location.search);return t.get("dag-playground")==="1"?p.jsx(BI,{}):t.get("diff-review-lab")==="1"?p.jsx(OI,{}):t.get("diff-lab")==="1"?p.jsx(_I,{}):p.jsx(NI,{children:p.jsxs(mC,{children:[p.jsx(bI,{}),p.jsx(LI,{})]})})})()})})]})}));export{VI as $,bl as A,Kp as B,dl as C,Zg as D,dg as E,pv as F,cA as G,UA as H,nR as I,fn as J,t2 as K,De as L,Gx as M,e2 as N,bR as O,$2 as P,MA as Q,ul as R,ri as S,XE as T,Z1 as U,RC as V,ao as W,Yp as X,lA as Y,IA as Z,Gt as _,qp as a,jk as a$,oi as a0,sk as a1,kC as a2,xe as a3,CA as a4,Pi as a5,dk as a6,Hk as a7,lR as a8,vR as a9,Dk as aA,r2 as aB,Gk as aC,Kk as aD,wk as aE,uR as aF,Jk as aG,Os as aH,UC as aI,$C as aJ,rr as aK,Fs as aL,Ac as aM,uo as aN,Pl as aO,et as aP,aA as aQ,X1 as aR,YA as aS,qA as aT,GA as aU,n2 as aV,Cg as aW,ut as aX,va as aY,$h as aZ,ap as a_,WA as aa,lk as ab,$k as ac,u1 as ad,cg as ae,dA as af,M2 as ag,GI as ah,aR as ai,$A as aj,dt as ak,tk as al,ek as am,ok as an,kA as ao,Qk as ap,Yk as aq,SR as ar,fI as as,Xk as at,Zk as au,ZA as av,qn as aw,Ik as ax,Vk as ay,s2 as az,TE as b,c2 as b$,nk as b0,ik as b1,kg as b2,Ck as b3,Rk as b4,Sk as b5,kk as b6,Ek as b7,rI as b8,Tl as b9,oR as bA,ZI as bB,PA as bC,uA as bD,XI as bE,rc as bF,u2 as bG,pk as bH,b2 as bI,cR as bJ,yk as bK,gk as bL,XA as bM,Mn as bN,mR as bO,bk as bP,mk as bQ,DA as bR,rR as bS,jA as bT,zA as bU,uk as bV,h2 as bW,qI as bX,l1 as bY,l2 as bZ,o2 as b_,Yo as ba,p as bb,WI as bc,KA as bd,a2 as be,fk as bf,p2 as bg,v2 as bh,Nk as bi,HA as bj,QA as bk,m2 as bl,qC as bm,zk as bn,ig as bo,bg as bp,KC as bq,hk as br,TA as bs,ht as bt,zC as bu,Mk as bv,Ok as bw,Fk as bx,Uk as by,sR as bz,zp as c,g2 as c0,re as c1,Lk as c2,x2 as c3,S2 as c4,OA as c5,LA as c6,RA as c7,_A as c8,FA as c9,vt as cA,qk as cB,Jp as cC,ii as cD,QI as cE,Sa as cF,dR as cG,Le as cH,Aa as cI,iR as cJ,ge as cK,Bk as cL,ni as cM,We as cN,eR as cO,JI as cP,d2 as ca,y2 as cb,hR as cc,pR as cd,gR as ce,fR as cf,wg as cg,AA as ch,Ni as ci,tR as cj,Ea as ck,w2 as cl,Yg as cm,f2 as cn,YI as co,NA as cp,KI as cq,yR as cr,lI as cs,am as ct,HI as cu,rk as cv,wR as cw,ck as cx,JA as cy,ts as cz,vn as d,FE as e,Wp as f,Vp as g,vC as h,lg as i,KE as j,Gp as k,D2 as l,Ae as m,xR as n,BA as o,Jc as p,Tt as q,i2 as r,zI as s,HC as t,Tk as u,Ak as v,Qc as w,_k as x,Hx as y,ak as z};