termdock 1.4.180 → 1.4.181

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 (308) hide show
  1. package/dist/client/assets/{App-DBds0RoW.js → App-B19QjfSB.js} +4 -4
  2. package/dist/client/assets/App-B19QjfSB.js.br +0 -0
  3. package/dist/client/assets/App-B19QjfSB.js.gz +0 -0
  4. package/dist/client/assets/{ChangeWalkthroughPanel-DonkfMV2.js → ChangeWalkthroughPanel-DYSWa9RT.js} +1 -1
  5. package/dist/client/assets/ChangeWalkthroughPanel-DYSWa9RT.js.br +0 -0
  6. package/dist/client/assets/ChangeWalkthroughPanel-DYSWa9RT.js.gz +0 -0
  7. package/dist/client/assets/{DagPlayground-CYL8vhaU.js → DagPlayground-qziF3toU.js} +1 -1
  8. package/dist/client/assets/DagPlayground-qziF3toU.js.br +0 -0
  9. package/dist/client/assets/DagPlayground-qziF3toU.js.gz +0 -0
  10. package/dist/client/assets/{DiffLab-COUjebir.js → DiffLab-CDUdFYRL.js} +1 -1
  11. package/dist/client/assets/DiffLab-CDUdFYRL.js.br +0 -0
  12. package/dist/client/assets/DiffLab-CDUdFYRL.js.gz +0 -0
  13. package/dist/client/assets/{DiffReview-DqiRXomQ.js → DiffReview-hnUsI_p2.js} +1 -1
  14. package/dist/client/assets/DiffReview-hnUsI_p2.js.br +0 -0
  15. package/dist/client/assets/DiffReview-hnUsI_p2.js.gz +0 -0
  16. package/dist/client/assets/{DiffReviewLab-Aqib8Qr6.js → DiffReviewLab-DUMlD_0N.js} +1 -1
  17. package/dist/client/assets/DiffReviewLab-DUMlD_0N.js.br +0 -0
  18. package/dist/client/assets/DiffReviewLab-DUMlD_0N.js.gz +0 -0
  19. package/dist/client/assets/{DiffViewer-KR2GhX72.js → DiffViewer-Bg272xI5.js} +1 -1
  20. package/dist/client/assets/DiffViewer-Bg272xI5.js.br +0 -0
  21. package/dist/client/assets/DiffViewer-Bg272xI5.js.gz +0 -0
  22. package/dist/client/assets/{ModelPreview-Bo6giTPm.js → ModelPreview-m10n9N9k.js} +1 -1
  23. package/dist/client/assets/ModelPreview-m10n9N9k.js.br +0 -0
  24. package/dist/client/assets/ModelPreview-m10n9N9k.js.gz +0 -0
  25. package/dist/client/assets/{RightSidebar-rROjRuPY.js → RightSidebar-BJYNFofV.js} +4 -4
  26. package/dist/client/assets/RightSidebar-BJYNFofV.js.br +0 -0
  27. package/dist/client/assets/RightSidebar-BJYNFofV.js.gz +0 -0
  28. package/dist/client/assets/{abnfDiagram-VCTEODGH-m85vHRkF.js → abnfDiagram-VCTEODGH-DEiPXXIM.js} +1 -1
  29. package/dist/client/assets/abnfDiagram-VCTEODGH-DEiPXXIM.js.br +0 -0
  30. package/dist/client/assets/abnfDiagram-VCTEODGH-DEiPXXIM.js.gz +0 -0
  31. package/dist/client/assets/{app-Djvvt1Mi.js → app-CLjXX_Fh.js} +3 -3
  32. package/dist/client/assets/app-CLjXX_Fh.js.br +0 -0
  33. package/dist/client/assets/app-CLjXX_Fh.js.gz +0 -0
  34. package/dist/client/assets/{arc-DmZ3EVhj.js → arc-Chxjt8J8.js} +1 -1
  35. package/dist/client/assets/arc-Chxjt8J8.js.br +0 -0
  36. package/dist/client/assets/arc-Chxjt8J8.js.gz +0 -0
  37. package/dist/client/assets/{architectureDiagram-5GKGNRK7-C8yGaNGM.js → architectureDiagram-5GKGNRK7-D1aJIMC2.js} +1 -1
  38. package/dist/client/assets/architectureDiagram-5GKGNRK7-D1aJIMC2.js.br +0 -0
  39. package/dist/client/assets/architectureDiagram-5GKGNRK7-D1aJIMC2.js.gz +0 -0
  40. package/dist/client/assets/{blockDiagram-I7D4REHJ-CZhh__cR.js → blockDiagram-I7D4REHJ-1H3-uTEC.js} +1 -1
  41. package/dist/client/assets/blockDiagram-I7D4REHJ-1H3-uTEC.js.br +0 -0
  42. package/dist/client/assets/blockDiagram-I7D4REHJ-1H3-uTEC.js.gz +0 -0
  43. package/dist/client/assets/{c4Diagram-7LVT6UL2-py7O2OOO.js → c4Diagram-7LVT6UL2-DKjff_SZ.js} +1 -1
  44. package/dist/client/assets/c4Diagram-7LVT6UL2-DKjff_SZ.js.br +0 -0
  45. package/dist/client/assets/c4Diagram-7LVT6UL2-DKjff_SZ.js.gz +0 -0
  46. package/dist/client/assets/channel-CFexxD9Y.js +1 -0
  47. package/dist/client/assets/{chunk-2Q5K7J3B-SXGoQcYW.js → chunk-2Q5K7J3B-zfwHZ_wM.js} +1 -1
  48. package/dist/client/assets/{chunk-5VM5RSS4-1ZVyPSGv.js → chunk-5VM5RSS4-Cs3E--rj.js} +1 -1
  49. package/dist/client/assets/{chunk-F27PBJKO-DkIqnjYj.js → chunk-F27PBJKO-kXOdPWDz.js} +1 -1
  50. package/dist/client/assets/chunk-F27PBJKO-kXOdPWDz.js.br +0 -0
  51. package/dist/client/assets/chunk-F27PBJKO-kXOdPWDz.js.gz +0 -0
  52. package/dist/client/assets/{chunk-IMKFNOWR-CLS_EByq.js → chunk-IMKFNOWR-B6aDhfLx.js} +1 -1
  53. package/dist/client/assets/chunk-IMKFNOWR-B6aDhfLx.js.br +0 -0
  54. package/dist/client/assets/chunk-IMKFNOWR-B6aDhfLx.js.gz +0 -0
  55. package/dist/client/assets/{chunk-JWPE2WC7-8LtK4UYW.js → chunk-JWPE2WC7-DwrHJCDp.js} +1 -1
  56. package/dist/client/assets/{chunk-POPQ4Y6H-D1PhOQEv.js → chunk-POPQ4Y6H-Cow5F_tm.js} +1 -1
  57. package/dist/client/assets/{chunk-SVP7TREG-cVWIfR_4.js → chunk-SVP7TREG-C86kCt7E.js} +1 -1
  58. package/dist/client/assets/chunk-SVP7TREG-C86kCt7E.js.br +0 -0
  59. package/dist/client/assets/chunk-SVP7TREG-C86kCt7E.js.gz +0 -0
  60. package/dist/client/assets/{chunk-TICWLB2K-BiO8AIZ7.js → chunk-TICWLB2K-rhJUhbIr.js} +1 -1
  61. package/dist/client/assets/chunk-TICWLB2K-rhJUhbIr.js.br +0 -0
  62. package/dist/client/assets/chunk-TICWLB2K-rhJUhbIr.js.gz +0 -0
  63. package/dist/client/assets/{chunk-XXDRQBXY-CwP0rAj8.js → chunk-XXDRQBXY-Dg-bkPC1.js} +1 -1
  64. package/dist/client/assets/classDiagram-ZZMXUADV-B1CyI1XV.js +1 -0
  65. package/dist/client/assets/classDiagram-v2-VYDZK3BY-B1CyI1XV.js +1 -0
  66. package/dist/client/assets/{cose-bilkent-JH36ORCC-Dv9GK27H.js → cose-bilkent-JH36ORCC-BAa3feHH.js} +1 -1
  67. package/dist/client/assets/cose-bilkent-JH36ORCC-BAa3feHH.js.br +0 -0
  68. package/dist/client/assets/cose-bilkent-JH36ORCC-BAa3feHH.js.gz +0 -0
  69. package/dist/client/assets/{cynefin-OW5HDTMX-DDI6luT6.js → cynefin-OW5HDTMX-BtgtnvPn.js} +1 -1
  70. package/dist/client/assets/cynefin-OW5HDTMX-BtgtnvPn.js.br +0 -0
  71. package/dist/client/assets/cynefin-OW5HDTMX-BtgtnvPn.js.gz +0 -0
  72. package/dist/client/assets/{cynefinDiagram-5FMLGOSQ-DQpaBQcE.js → cynefinDiagram-5FMLGOSQ-CqDgLFoh.js} +1 -1
  73. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-CqDgLFoh.js.br +0 -0
  74. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-CqDgLFoh.js.gz +0 -0
  75. package/dist/client/assets/{dagre-GXQ25YYZ-CZ-1rzmK.js → dagre-GXQ25YYZ-DapDK3fW.js} +1 -1
  76. package/dist/client/assets/dagre-GXQ25YYZ-DapDK3fW.js.br +0 -0
  77. package/dist/client/assets/dagre-GXQ25YYZ-DapDK3fW.js.gz +0 -0
  78. package/dist/client/assets/{diagram-S7CK7UJ4-DeYvGv1c.js → diagram-S7CK7UJ4-BHw-DI_N.js} +1 -1
  79. package/dist/client/assets/diagram-S7CK7UJ4-BHw-DI_N.js.br +0 -0
  80. package/dist/client/assets/diagram-S7CK7UJ4-BHw-DI_N.js.gz +0 -0
  81. package/dist/client/assets/{diagram-UQ7AKVKN-BaYQC1t6.js → diagram-UQ7AKVKN-LPdnUGtZ.js} +1 -1
  82. package/dist/client/assets/diagram-UQ7AKVKN-LPdnUGtZ.js.br +0 -0
  83. package/dist/client/assets/diagram-UQ7AKVKN-LPdnUGtZ.js.gz +0 -0
  84. package/dist/client/assets/{diagram-VSXAHHWV-B517BnK0.js → diagram-VSXAHHWV-DXrq369c.js} +1 -1
  85. package/dist/client/assets/diagram-VSXAHHWV-DXrq369c.js.br +0 -0
  86. package/dist/client/assets/diagram-VSXAHHWV-DXrq369c.js.gz +0 -0
  87. package/dist/client/assets/{diagram-VX7I27RA-DyjVlDcv.js → diagram-VX7I27RA-BUjfRaI7.js} +1 -1
  88. package/dist/client/assets/diagram-VX7I27RA-BUjfRaI7.js.br +0 -0
  89. package/dist/client/assets/diagram-VX7I27RA-BUjfRaI7.js.gz +0 -0
  90. package/dist/client/assets/{diagram-Z3DM3KII-Cy9JXHOz.js → diagram-Z3DM3KII-DPK8uW8J.js} +1 -1
  91. package/dist/client/assets/diagram-Z3DM3KII-DPK8uW8J.js.br +0 -0
  92. package/dist/client/assets/diagram-Z3DM3KII-DPK8uW8J.js.gz +0 -0
  93. package/dist/client/assets/{ebnfDiagram-PWID7BFC-xvEH045b.js → ebnfDiagram-PWID7BFC-C_kGLf2C.js} +1 -1
  94. package/dist/client/assets/ebnfDiagram-PWID7BFC-C_kGLf2C.js.br +0 -0
  95. package/dist/client/assets/ebnfDiagram-PWID7BFC-C_kGLf2C.js.gz +0 -0
  96. package/dist/client/assets/{erDiagram-RLTQ6QDP-BTJDgwKq.js → erDiagram-RLTQ6QDP-pLyyDHU1.js} +1 -1
  97. package/dist/client/assets/{erDiagram-RLTQ6QDP-BTJDgwKq.js.br → erDiagram-RLTQ6QDP-pLyyDHU1.js.br} +0 -0
  98. package/dist/client/assets/erDiagram-RLTQ6QDP-pLyyDHU1.js.gz +0 -0
  99. package/dist/client/assets/{flowDiagram-HODETNUW-6pq1SF-S.js → flowDiagram-HODETNUW-nKpOA9LA.js} +1 -1
  100. package/dist/client/assets/flowDiagram-HODETNUW-nKpOA9LA.js.br +0 -0
  101. package/dist/client/assets/flowDiagram-HODETNUW-nKpOA9LA.js.gz +0 -0
  102. package/dist/client/assets/{ganttDiagram-EL5Y4UJY-DS_l5v9m.js → ganttDiagram-EL5Y4UJY-oEfUMlu7.js} +1 -1
  103. package/dist/client/assets/ganttDiagram-EL5Y4UJY-oEfUMlu7.js.br +0 -0
  104. package/dist/client/assets/ganttDiagram-EL5Y4UJY-oEfUMlu7.js.gz +0 -0
  105. package/dist/client/assets/{gestureArbiter-FtwbRpdp.js → gestureArbiter--GtaPB1X.js} +1 -1
  106. package/dist/client/assets/gestureArbiter--GtaPB1X.js.br +0 -0
  107. package/dist/client/assets/gestureArbiter--GtaPB1X.js.gz +0 -0
  108. package/dist/client/assets/{gitGraphDiagram-WWUBYQGX-DEGFo3aa.js → gitGraphDiagram-WWUBYQGX-CQaXwIm4.js} +1 -1
  109. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-CQaXwIm4.js.br +0 -0
  110. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-CQaXwIm4.js.gz +0 -0
  111. package/dist/client/assets/{infoDiagram-27XIBGKW-CFVSyJdD.js → infoDiagram-27XIBGKW-Ck632H8_.js} +1 -1
  112. package/dist/client/assets/{ishikawaDiagram-5VMMS53U-_YX0U_wu.js → ishikawaDiagram-5VMMS53U-kt45HKqz.js} +1 -1
  113. package/dist/client/assets/ishikawaDiagram-5VMMS53U-kt45HKqz.js.br +0 -0
  114. package/dist/client/assets/ishikawaDiagram-5VMMS53U-kt45HKqz.js.gz +0 -0
  115. package/dist/client/assets/{journeyDiagram-3NMN7TZE-DCujswss.js → journeyDiagram-3NMN7TZE-Dpgz_gU8.js} +1 -1
  116. package/dist/client/assets/journeyDiagram-3NMN7TZE-Dpgz_gU8.js.br +0 -0
  117. package/dist/client/assets/journeyDiagram-3NMN7TZE-Dpgz_gU8.js.gz +0 -0
  118. package/dist/client/assets/{kanban-definition-UXKFOSKX-DC6lqIBi.js → kanban-definition-UXKFOSKX-CgQHiDm3.js} +1 -1
  119. package/dist/client/assets/kanban-definition-UXKFOSKX-CgQHiDm3.js.br +0 -0
  120. package/dist/client/assets/kanban-definition-UXKFOSKX-CgQHiDm3.js.gz +0 -0
  121. package/dist/client/assets/{layout-D_hlL0MC.js → layout-yJX6dodE.js} +1 -1
  122. package/dist/client/assets/{layout-D_hlL0MC.js.br → layout-yJX6dodE.js.br} +0 -0
  123. package/dist/client/assets/layout-yJX6dodE.js.gz +0 -0
  124. package/dist/client/assets/{linear-BxpjJ2yt.js → linear-BlT3JzJ1.js} +1 -1
  125. package/dist/client/assets/linear-BlT3JzJ1.js.br +0 -0
  126. package/dist/client/assets/linear-BlT3JzJ1.js.gz +0 -0
  127. package/dist/client/assets/{mermaid.core-BRLYB1Uj.js → mermaid.core-DyTiIDnl.js} +5 -5
  128. package/dist/client/assets/mermaid.core-DyTiIDnl.js.br +0 -0
  129. package/dist/client/assets/mermaid.core-DyTiIDnl.js.gz +0 -0
  130. package/dist/client/assets/{mindmap-definition-YA3MSWOX-BF2f-Z54.js → mindmap-definition-YA3MSWOX-DPnGqi6W.js} +1 -1
  131. package/dist/client/assets/mindmap-definition-YA3MSWOX-DPnGqi6W.js.br +0 -0
  132. package/dist/client/assets/mindmap-definition-YA3MSWOX-DPnGqi6W.js.gz +0 -0
  133. package/dist/client/assets/{passwordBootstrap-hj2Lcgoj.js → passwordBootstrap-CppLqzUc.js} +1 -1
  134. package/dist/client/assets/passwordBootstrap-CppLqzUc.js.br +0 -0
  135. package/dist/client/assets/passwordBootstrap-CppLqzUc.js.gz +0 -0
  136. package/dist/client/assets/{pegDiagram-XKGWAZYB-FxHPBhCy.js → pegDiagram-XKGWAZYB-BQw0Qukh.js} +1 -1
  137. package/dist/client/assets/pegDiagram-XKGWAZYB-BQw0Qukh.js.br +0 -0
  138. package/dist/client/assets/pegDiagram-XKGWAZYB-BQw0Qukh.js.gz +0 -0
  139. package/dist/client/assets/{pieDiagram-E7YTZNPT-DqAcArGH.js → pieDiagram-E7YTZNPT-BmRjioxc.js} +1 -1
  140. package/dist/client/assets/pieDiagram-E7YTZNPT-BmRjioxc.js.br +0 -0
  141. package/dist/client/assets/pieDiagram-E7YTZNPT-BmRjioxc.js.gz +0 -0
  142. package/dist/client/assets/{quadrantDiagram-AXDQQJYC-31lk30-Y.js → quadrantDiagram-AXDQQJYC-CZY-hlRM.js} +1 -1
  143. package/dist/client/assets/quadrantDiagram-AXDQQJYC-CZY-hlRM.js.br +0 -0
  144. package/dist/client/assets/quadrantDiagram-AXDQQJYC-CZY-hlRM.js.gz +0 -0
  145. package/dist/client/assets/{railroadDiagram-O6MQD6OU-C-Jt17Wl.js → railroadDiagram-O6MQD6OU-DCsphPWZ.js} +1 -1
  146. package/dist/client/assets/railroadDiagram-O6MQD6OU-DCsphPWZ.js.br +0 -0
  147. package/dist/client/assets/railroadDiagram-O6MQD6OU-DCsphPWZ.js.gz +0 -0
  148. package/dist/client/assets/{referenceLongPress-BPFSnCDQ.js → referenceLongPress-BWY2Jusg.js} +1 -1
  149. package/dist/client/assets/referenceLongPress-BWY2Jusg.js.br +0 -0
  150. package/dist/client/assets/referenceLongPress-BWY2Jusg.js.gz +0 -0
  151. package/dist/client/assets/{requirementDiagram-BXWQKSXE-DdrbsuCJ.js → requirementDiagram-BXWQKSXE-Dfc84Oq5.js} +1 -1
  152. package/dist/client/assets/requirementDiagram-BXWQKSXE-Dfc84Oq5.js.br +0 -0
  153. package/dist/client/assets/requirementDiagram-BXWQKSXE-Dfc84Oq5.js.gz +0 -0
  154. package/dist/client/assets/{sankeyDiagram-P5KCCOFB-CZjs9KFo.js → sankeyDiagram-P5KCCOFB-BBNGYSip.js} +1 -1
  155. package/dist/client/assets/sankeyDiagram-P5KCCOFB-BBNGYSip.js.br +0 -0
  156. package/dist/client/assets/sankeyDiagram-P5KCCOFB-BBNGYSip.js.gz +0 -0
  157. package/dist/client/assets/{sequenceDiagram-WJ2MYXX4-CkD1f6v4.js → sequenceDiagram-WJ2MYXX4-D5sQ5ja0.js} +1 -1
  158. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-D5sQ5ja0.js.br +0 -0
  159. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-D5sQ5ja0.js.gz +0 -0
  160. package/dist/client/assets/{sizeCapture-INFHLROL-BMuKV0gL.js → sizeCapture-INFHLROL-BvKb-SH_.js} +1 -1
  161. package/dist/client/assets/sizeCapture-INFHLROL-BvKb-SH_.js.br +0 -0
  162. package/dist/client/assets/sizeCapture-INFHLROL-BvKb-SH_.js.gz +0 -0
  163. package/dist/client/assets/{sparkles-DuRvUCWG.js → sparkles-C5UxG6SZ.js} +1 -1
  164. package/dist/client/assets/{stateDiagram-D77RDMKH-B1lLo2WA.js → stateDiagram-D77RDMKH-B4wlBUxv.js} +1 -1
  165. package/dist/client/assets/stateDiagram-D77RDMKH-B4wlBUxv.js.br +0 -0
  166. package/dist/client/assets/stateDiagram-D77RDMKH-B4wlBUxv.js.gz +0 -0
  167. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-C3vnVbNn.js +1 -0
  168. package/dist/client/assets/{swimlanes-42K2YHIH-CfC5CNjA.js → swimlanes-42K2YHIH-Bn4G1f4X.js} +1 -1
  169. package/dist/client/assets/swimlanes-42K2YHIH-Bn4G1f4X.js.br +0 -0
  170. package/dist/client/assets/swimlanes-42K2YHIH-Bn4G1f4X.js.gz +0 -0
  171. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-2HE8N4dv.js +8 -0
  172. package/dist/client/assets/{timeline-definition-24CTP7MA-0mM-Skdo.js → timeline-definition-24CTP7MA-CFNL7lOK.js} +1 -1
  173. package/dist/client/assets/timeline-definition-24CTP7MA-CFNL7lOK.js.br +0 -0
  174. package/dist/client/assets/timeline-definition-24CTP7MA-CFNL7lOK.js.gz +0 -0
  175. package/dist/client/assets/{triangle-alert-wyGdnPOg.js → triangle-alert-CLJo8ig-.js} +1 -1
  176. package/dist/client/assets/{vennDiagram-4TSXK5OY-BYsJo_hU.js → vennDiagram-4TSXK5OY-Cg1xsEai.js} +1 -1
  177. package/dist/client/assets/vennDiagram-4TSXK5OY-Cg1xsEai.js.br +0 -0
  178. package/dist/client/assets/vennDiagram-4TSXK5OY-Cg1xsEai.js.gz +0 -0
  179. package/dist/client/assets/{wardleyDiagram-VM6X3IG4-ree3u-pI.js → wardleyDiagram-VM6X3IG4-BPuVwhy2.js} +1 -1
  180. package/dist/client/assets/wardleyDiagram-VM6X3IG4-BPuVwhy2.js.br +0 -0
  181. package/dist/client/assets/wardleyDiagram-VM6X3IG4-BPuVwhy2.js.gz +0 -0
  182. package/dist/client/assets/{xychartDiagram-S5SC5T6Z-DDono4Wc.js → xychartDiagram-S5SC5T6Z-BkkW7b88.js} +1 -1
  183. package/dist/client/assets/{xychartDiagram-S5SC5T6Z-DDono4Wc.js.br → xychartDiagram-S5SC5T6Z-BkkW7b88.js.br} +0 -0
  184. package/dist/client/assets/xychartDiagram-S5SC5T6Z-BkkW7b88.js.gz +0 -0
  185. package/dist/client/index.html +1 -1
  186. package/dist/client/index.html.br +0 -0
  187. package/dist/client/index.html.gz +0 -0
  188. package/dist/client/sw.js +1 -1
  189. package/dist/client/sw.js.br +0 -0
  190. package/dist/client/sw.js.gz +0 -0
  191. package/package.json +1 -1
  192. package/runtime-manifest.json +2 -2
  193. package/dist/client/assets/App-DBds0RoW.js.br +0 -0
  194. package/dist/client/assets/App-DBds0RoW.js.gz +0 -0
  195. package/dist/client/assets/ChangeWalkthroughPanel-DonkfMV2.js.br +0 -0
  196. package/dist/client/assets/ChangeWalkthroughPanel-DonkfMV2.js.gz +0 -0
  197. package/dist/client/assets/DagPlayground-CYL8vhaU.js.br +0 -0
  198. package/dist/client/assets/DagPlayground-CYL8vhaU.js.gz +0 -0
  199. package/dist/client/assets/DiffLab-COUjebir.js.br +0 -0
  200. package/dist/client/assets/DiffLab-COUjebir.js.gz +0 -0
  201. package/dist/client/assets/DiffReview-DqiRXomQ.js.br +0 -0
  202. package/dist/client/assets/DiffReview-DqiRXomQ.js.gz +0 -0
  203. package/dist/client/assets/DiffReviewLab-Aqib8Qr6.js.br +0 -0
  204. package/dist/client/assets/DiffReviewLab-Aqib8Qr6.js.gz +0 -0
  205. package/dist/client/assets/DiffViewer-KR2GhX72.js.br +0 -0
  206. package/dist/client/assets/DiffViewer-KR2GhX72.js.gz +0 -0
  207. package/dist/client/assets/ModelPreview-Bo6giTPm.js.br +0 -0
  208. package/dist/client/assets/ModelPreview-Bo6giTPm.js.gz +0 -0
  209. package/dist/client/assets/RightSidebar-rROjRuPY.js.br +0 -0
  210. package/dist/client/assets/RightSidebar-rROjRuPY.js.gz +0 -0
  211. package/dist/client/assets/abnfDiagram-VCTEODGH-m85vHRkF.js.br +0 -0
  212. package/dist/client/assets/abnfDiagram-VCTEODGH-m85vHRkF.js.gz +0 -0
  213. package/dist/client/assets/app-Djvvt1Mi.js.br +0 -0
  214. package/dist/client/assets/app-Djvvt1Mi.js.gz +0 -0
  215. package/dist/client/assets/arc-DmZ3EVhj.js.br +0 -0
  216. package/dist/client/assets/arc-DmZ3EVhj.js.gz +0 -0
  217. package/dist/client/assets/architectureDiagram-5GKGNRK7-C8yGaNGM.js.br +0 -0
  218. package/dist/client/assets/architectureDiagram-5GKGNRK7-C8yGaNGM.js.gz +0 -0
  219. package/dist/client/assets/blockDiagram-I7D4REHJ-CZhh__cR.js.br +0 -0
  220. package/dist/client/assets/blockDiagram-I7D4REHJ-CZhh__cR.js.gz +0 -0
  221. package/dist/client/assets/c4Diagram-7LVT6UL2-py7O2OOO.js.br +0 -0
  222. package/dist/client/assets/c4Diagram-7LVT6UL2-py7O2OOO.js.gz +0 -0
  223. package/dist/client/assets/channel-BnKOV34C.js +0 -1
  224. package/dist/client/assets/chunk-F27PBJKO-DkIqnjYj.js.br +0 -0
  225. package/dist/client/assets/chunk-F27PBJKO-DkIqnjYj.js.gz +0 -0
  226. package/dist/client/assets/chunk-IMKFNOWR-CLS_EByq.js.br +0 -0
  227. package/dist/client/assets/chunk-IMKFNOWR-CLS_EByq.js.gz +0 -0
  228. package/dist/client/assets/chunk-SVP7TREG-cVWIfR_4.js.br +0 -0
  229. package/dist/client/assets/chunk-SVP7TREG-cVWIfR_4.js.gz +0 -0
  230. package/dist/client/assets/chunk-TICWLB2K-BiO8AIZ7.js.br +0 -0
  231. package/dist/client/assets/chunk-TICWLB2K-BiO8AIZ7.js.gz +0 -0
  232. package/dist/client/assets/classDiagram-ZZMXUADV-CZ5ElqWa.js +0 -1
  233. package/dist/client/assets/classDiagram-v2-VYDZK3BY-CZ5ElqWa.js +0 -1
  234. package/dist/client/assets/cose-bilkent-JH36ORCC-Dv9GK27H.js.br +0 -0
  235. package/dist/client/assets/cose-bilkent-JH36ORCC-Dv9GK27H.js.gz +0 -0
  236. package/dist/client/assets/cynefin-OW5HDTMX-DDI6luT6.js.br +0 -0
  237. package/dist/client/assets/cynefin-OW5HDTMX-DDI6luT6.js.gz +0 -0
  238. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-DQpaBQcE.js.br +0 -0
  239. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-DQpaBQcE.js.gz +0 -0
  240. package/dist/client/assets/dagre-GXQ25YYZ-CZ-1rzmK.js.br +0 -0
  241. package/dist/client/assets/dagre-GXQ25YYZ-CZ-1rzmK.js.gz +0 -0
  242. package/dist/client/assets/diagram-S7CK7UJ4-DeYvGv1c.js.br +0 -0
  243. package/dist/client/assets/diagram-S7CK7UJ4-DeYvGv1c.js.gz +0 -0
  244. package/dist/client/assets/diagram-UQ7AKVKN-BaYQC1t6.js.br +0 -0
  245. package/dist/client/assets/diagram-UQ7AKVKN-BaYQC1t6.js.gz +0 -0
  246. package/dist/client/assets/diagram-VSXAHHWV-B517BnK0.js.br +0 -0
  247. package/dist/client/assets/diagram-VSXAHHWV-B517BnK0.js.gz +0 -0
  248. package/dist/client/assets/diagram-VX7I27RA-DyjVlDcv.js.br +0 -0
  249. package/dist/client/assets/diagram-VX7I27RA-DyjVlDcv.js.gz +0 -0
  250. package/dist/client/assets/diagram-Z3DM3KII-Cy9JXHOz.js.br +0 -0
  251. package/dist/client/assets/diagram-Z3DM3KII-Cy9JXHOz.js.gz +0 -0
  252. package/dist/client/assets/ebnfDiagram-PWID7BFC-xvEH045b.js.br +0 -0
  253. package/dist/client/assets/ebnfDiagram-PWID7BFC-xvEH045b.js.gz +0 -0
  254. package/dist/client/assets/erDiagram-RLTQ6QDP-BTJDgwKq.js.gz +0 -0
  255. package/dist/client/assets/flowDiagram-HODETNUW-6pq1SF-S.js.br +0 -0
  256. package/dist/client/assets/flowDiagram-HODETNUW-6pq1SF-S.js.gz +0 -0
  257. package/dist/client/assets/ganttDiagram-EL5Y4UJY-DS_l5v9m.js.br +0 -0
  258. package/dist/client/assets/ganttDiagram-EL5Y4UJY-DS_l5v9m.js.gz +0 -0
  259. package/dist/client/assets/gestureArbiter-FtwbRpdp.js.br +0 -0
  260. package/dist/client/assets/gestureArbiter-FtwbRpdp.js.gz +0 -0
  261. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-DEGFo3aa.js.br +0 -0
  262. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-DEGFo3aa.js.gz +0 -0
  263. package/dist/client/assets/ishikawaDiagram-5VMMS53U-_YX0U_wu.js.br +0 -0
  264. package/dist/client/assets/ishikawaDiagram-5VMMS53U-_YX0U_wu.js.gz +0 -0
  265. package/dist/client/assets/journeyDiagram-3NMN7TZE-DCujswss.js.br +0 -0
  266. package/dist/client/assets/journeyDiagram-3NMN7TZE-DCujswss.js.gz +0 -0
  267. package/dist/client/assets/kanban-definition-UXKFOSKX-DC6lqIBi.js.br +0 -0
  268. package/dist/client/assets/kanban-definition-UXKFOSKX-DC6lqIBi.js.gz +0 -0
  269. package/dist/client/assets/layout-D_hlL0MC.js.gz +0 -0
  270. package/dist/client/assets/linear-BxpjJ2yt.js.br +0 -0
  271. package/dist/client/assets/linear-BxpjJ2yt.js.gz +0 -0
  272. package/dist/client/assets/mermaid.core-BRLYB1Uj.js.br +0 -0
  273. package/dist/client/assets/mermaid.core-BRLYB1Uj.js.gz +0 -0
  274. package/dist/client/assets/mindmap-definition-YA3MSWOX-BF2f-Z54.js.br +0 -0
  275. package/dist/client/assets/mindmap-definition-YA3MSWOX-BF2f-Z54.js.gz +0 -0
  276. package/dist/client/assets/passwordBootstrap-hj2Lcgoj.js.br +0 -0
  277. package/dist/client/assets/passwordBootstrap-hj2Lcgoj.js.gz +0 -0
  278. package/dist/client/assets/pegDiagram-XKGWAZYB-FxHPBhCy.js.br +0 -0
  279. package/dist/client/assets/pegDiagram-XKGWAZYB-FxHPBhCy.js.gz +0 -0
  280. package/dist/client/assets/pieDiagram-E7YTZNPT-DqAcArGH.js.br +0 -0
  281. package/dist/client/assets/pieDiagram-E7YTZNPT-DqAcArGH.js.gz +0 -0
  282. package/dist/client/assets/quadrantDiagram-AXDQQJYC-31lk30-Y.js.br +0 -0
  283. package/dist/client/assets/quadrantDiagram-AXDQQJYC-31lk30-Y.js.gz +0 -0
  284. package/dist/client/assets/railroadDiagram-O6MQD6OU-C-Jt17Wl.js.br +0 -0
  285. package/dist/client/assets/railroadDiagram-O6MQD6OU-C-Jt17Wl.js.gz +0 -0
  286. package/dist/client/assets/referenceLongPress-BPFSnCDQ.js.br +0 -0
  287. package/dist/client/assets/referenceLongPress-BPFSnCDQ.js.gz +0 -0
  288. package/dist/client/assets/requirementDiagram-BXWQKSXE-DdrbsuCJ.js.br +0 -0
  289. package/dist/client/assets/requirementDiagram-BXWQKSXE-DdrbsuCJ.js.gz +0 -0
  290. package/dist/client/assets/sankeyDiagram-P5KCCOFB-CZjs9KFo.js.br +0 -0
  291. package/dist/client/assets/sankeyDiagram-P5KCCOFB-CZjs9KFo.js.gz +0 -0
  292. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-CkD1f6v4.js.br +0 -0
  293. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-CkD1f6v4.js.gz +0 -0
  294. package/dist/client/assets/sizeCapture-INFHLROL-BMuKV0gL.js.br +0 -0
  295. package/dist/client/assets/sizeCapture-INFHLROL-BMuKV0gL.js.gz +0 -0
  296. package/dist/client/assets/stateDiagram-D77RDMKH-B1lLo2WA.js.br +0 -0
  297. package/dist/client/assets/stateDiagram-D77RDMKH-B1lLo2WA.js.gz +0 -0
  298. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-F5MbngH8.js +0 -1
  299. package/dist/client/assets/swimlanes-42K2YHIH-CfC5CNjA.js.br +0 -0
  300. package/dist/client/assets/swimlanes-42K2YHIH-CfC5CNjA.js.gz +0 -0
  301. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-BqbZwNvL.js +0 -8
  302. package/dist/client/assets/timeline-definition-24CTP7MA-0mM-Skdo.js.br +0 -0
  303. package/dist/client/assets/timeline-definition-24CTP7MA-0mM-Skdo.js.gz +0 -0
  304. package/dist/client/assets/vennDiagram-4TSXK5OY-BYsJo_hU.js.br +0 -0
  305. package/dist/client/assets/vennDiagram-4TSXK5OY-BYsJo_hU.js.gz +0 -0
  306. package/dist/client/assets/wardleyDiagram-VM6X3IG4-ree3u-pI.js.br +0 -0
  307. package/dist/client/assets/wardleyDiagram-VM6X3IG4-ree3u-pI.js.gz +0 -0
  308. package/dist/client/assets/xychartDiagram-S5SC5T6Z-DDono4Wc.js.gz +0 -0
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/passwordBootstrap-hj2Lcgoj.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/App-DBds0RoW.js","assets/gestureArbiter-FtwbRpdp.js","assets/gestureArbiter-C2J0D0kV.css","assets/referenceLongPress-BPFSnCDQ.js","assets/triangle-alert-wyGdnPOg.js","assets/DagPlayground-CYL8vhaU.js","assets/ChangeWalkthroughPanel-DonkfMV2.js","assets/sparkles-DuRvUCWG.js","assets/DiffLab-COUjebir.js","assets/DiffViewer-KR2GhX72.js","assets/DiffViewer-T3uj2-aP.css","assets/DiffReviewLab-Aqib8Qr6.js","assets/DiffReview-DqiRXomQ.js"])))=>i.map(i=>d[i]);
2
- import{r as Yf,a as Zf,g as Jf}from"./react-XDCjal2T.js";import{b as $,r as Qf,R as je}from"./dnd-BCFAPC0L.js";import{L as eh,l as th}from"./terminal-C7X98Amf.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();const nh="modulepreload",rh=function(t){return"/"+t},ja={},Un=function(e,n,r){let s=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");s=c(n.map(l=>{if(l=rh(l),l in ja)return;ja[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":nh,d||(f.as="script"),f.crossOrigin="",f.href=l,a&&f.setAttribute("nonce",a),document.head.appendChild(f),d)return new Promise((p,g)=>{f.addEventListener("load",p),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${l}`)))})}))}function o(i){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=i,window.dispatchEvent(a),!a.defaultPrevented)throw i}return s.then(i=>{for(const a of i||[])a.status==="rejected"&&o(a.reason);return e().catch(o)})};var co={exports:{}},Vn={};var Ua;function sh(){if(Ua)return Vn;Ua=1;var t=Yf(),e=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,s=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,o={key:!0,ref:!0,__self:!0,__source:!0};function i(a,c,l){var d,u={},f=null,p=null;l!==void 0&&(f=""+l),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(p=c.ref);for(d in c)r.call(c,d)&&!o.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:p,props:u,_owner:s.current}}return Vn.Fragment=n,Vn.jsx=i,Vn.jsxs=i,Vn}var $a;function oh(){return $a||($a=1,co.exports=sh()),co.exports}var h=oh();const Vt="termdock-secure-target-v1",qi="termdock-secure-entry-v1",ih=new Set([Vt,qi,"termdock-color-theme","termdock:locale","termdock.federation.connections.v1"]),Dr=typeof Storage>"u"?void 0:Storage.prototype.getItem,lo=typeof Storage>"u"?void 0:Storage.prototype.setItem,Ha="termdock-secure-legacy-owner";function ah(){if(typeof window>"u")return null;try{const t=JSON.parse(sessionStorage.getItem(Vt)??localStorage.getItem(Vt)??"null");return t&&typeof t.url=="string"&&typeof t.targetPeerId=="string"?t:null}catch{return null}}let Ki=ah();const Fs=Ki?.targetPeerId??"unpaired";function ch(){return Ki}function Gl(t){Ki=t;const e=JSON.stringify(t);sessionStorage.setItem(Vt,e),localStorage.setItem(Vt,e)}function ur(t,e=Fs){return ih.has(t)||t.startsWith("termdock-secure-")?t:`termdock-service:${e}:${t}`}function lh(t){if(!(!Dr||!lo))try{if(Dr.call(localStorage,Ha))return;lo.call(localStorage,Ha,t);for(const n of[localStorage,sessionStorage]){const r=Array.from({length:n.length},(s,o)=>n.key(o)).filter(s=>!!s);for(const s of r){if(s.startsWith("termdock-service:")||ur(s,t)===s)continue;const o=ur(s,t),i=Dr.call(n,s);i!==null&&Dr.call(n,o)===null&&lo.call(n,o,i)}}}catch{}}let qa=!1;function dh(){if(qa||typeof Storage>"u")return;qa=!0;const t=Storage.prototype.getItem,e=Storage.prototype.setItem,n=Storage.prototype.removeItem;Storage.prototype.getItem=function(r){return t.call(this,ur(String(r)))},Storage.prototype.setItem=function(r,s){e.call(this,ur(String(r)),s)},Storage.prototype.removeItem=function(r){n.call(this,ur(String(r)))}}dh();var Fr={},Ka;function uh(){if(Ka)return Fr;Ka=1;var t=Zf();return Fr.createRoot=t.createRoot,Fr.hydrateRoot=t.hydrateRoot,Fr}var fh=uh();const hh=Jf(fh),Os="termdock.federation.connections.v1",oi="termdock:services-changed";function Ce(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 Wl(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.url=="string")try{const n=Ce(e.url),r=typeof e.targetPeerId=="string"&&e.targetPeerId?e.targetPeerId:void 0,s=(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:s,...r?{targetPeerId:r}:{},...typeof e.serviceOrigin=="string"?{serviceOrigin:Ce(e.serviceOrigin)}:{},...typeof e.entryServiceId=="string"&&e.entryServiceId?{entryServiceId:e.entryServiceId}:{},...Array.isArray(e.routes)?{routes:e.routes.slice(0,4).flatMap(o=>{try{return o&&typeof o.targetPeerId=="string"&&o.targetPeerId?[{url:Ce(o.url),targetPeerId:o.targetPeerId}]:[]}catch{return[]}})}:{}}}catch{return}}function Pt(t,e){return t.targetPeerId&&e.targetPeerId?t.targetPeerId===e.targetPeerId:(t.serviceOrigin||t.url)===(e.serviceOrigin||e.url)}function Xl(t){const e=[];for(const n of t){const r=e.findIndex(s=>Pt(s,n));r<0?e.push(n):e[r]={...e[r],...n,id:e[r].id}}return e}function Ms(){return typeof window>"u"?void 0:window.termdockDesktop}function cs(){try{const t=JSON.parse(localStorage.getItem(Os)||"[]");return Array.isArray(t)?Xl(t.map(Wl).filter(e=>!!e)):[]}catch{return[]}}function Yl(t){localStorage.setItem(Os,JSON.stringify(t.map(e=>({...e,serviceName:e.label})))),window.dispatchEvent(new Event(oi))}let Gn;async function nt(){const t=Ms();if(!t?.serviceConnections||!t.saveServiceConnection)return cs();if(Gn)return Gn;Gn=(async()=>{let e=await t.serviceConnections();const n=cs();for(const r of n)e.some(s=>Pt(s,r))||(e=await(t.importServiceConnection||t.saveServiceConnection)(r));return n.length&&localStorage.removeItem(Os),e})();try{return await Gn}finally{Gn=void 0}}async function Pn(t){const e=Wl(t);if(!e)throw new Error("服务地址无效。");const n=Ms();if(n?.saveServiceConnection)return n.saveServiceConnection(e);const r=cs(),s=r.find(i=>i.id===e.id||Pt(i,e)),o=Xl([...r.filter(i=>i!==s),{...s,...e,id:s?.id||e.id}]);return Yl(o),o}async function ph(t){const e=Ms();if(e?.removeServiceConnection)return e.removeServiceConnection(t);const n=cs().filter(r=>r.id!==t);return Yl(n),n}function gh(t){const e=r=>{(r.key===Os||r.key===null)&&t()};window.addEventListener(oi,t),window.addEventListener("storage",e);const n=Ms()?.onServiceConnections?.(t);return()=>{window.removeEventListener(oi,t),window.removeEventListener("storage",e),n?.()}}class mh extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}let wh=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},Xe=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};class Zl extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class Jl extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}}class yh extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class bh extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class js extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}const Ql=Symbol.for("@libp2p/peer-id");function xh(t){return typeof t?.handleEvent=="function"}function vh(t){return t===!0||t===!1}function Eh(t){return vh(t)?t:t?.capture??!1}function ii(t){const e={capture:Eh(t),once:!!t?.once};return t?.passive!=null&&(e.passive=t?.passive),t?.signal!=null&&(e.signal=t?.signal),e}function za(t,e){return ii(t).capture===ii(e).capture}class Sh 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 s=ii(r);if(s?.signal?.aborted===!0)return;const o=l=>{s.once&&this.removeEventListener(e,n,s),xh(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:za(l.options,s)))return;super.addEventListener(e,o,s);const c=()=>{this.removeEventListener(e,n,s)};s.signal?.addEventListener("abort",c),i.push({callback:n,wrapper:o,options:s,onAbort:c})}removeEventListener(e,n,r){const s=this.#e.get(e);if(s==null){super.removeEventListener(e,n??null,r);return}this.#e.set(e,s.filter(o=>o.callback===n&&za(o.options,r)?(super.removeEventListener(e,o.wrapper,r),o.options?.signal?.removeEventListener("abort",o.onAbort),!1):!0))}safeDispatchEvent(e,n={}){return this.dispatchEvent(new CustomEvent(e,n))}}const Ah=Symbol.for("@libp2p/service-capabilities");function kh(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 Us(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 Th(t){return new TextEncoder().encode(t)}function Ch(t){return new TextDecoder().decode(t)}function Ih(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 s=0;s<t.length;s++){var o=t.charAt(s),i=o.charCodeAt(0);if(n[i]!==255)throw new TypeError(o+" is ambiguous");n[i]=s}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,x=0,y=0,T=g.length;y!==T&&g[y]===0;)y++,m++;for(var v=(T-y)*d+1>>>0,A=new Uint8Array(v);y!==T;){for(var _=g[y],C=0,L=v-1;(_!==0||C<x)&&L!==-1;L--,C++)_+=256*A[L]>>>0,A[L]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");x=C,y++}for(var R=v-x;R!==v&&A[R]===0;)R++;for(var E=c.repeat(m);R<v;++R)E+=t.charAt(A[R]);return E}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 x=0,y=0;g[m]===c;)x++,m++;for(var T=(g.length-m)*l+1>>>0,v=new Uint8Array(T);g[m];){var A=n[g.charCodeAt(m)];if(A===255)return;for(var _=0,C=T-1;(A!==0||_<y)&&C!==-1;C--,_++)A+=a*v[C]>>>0,v[C]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");y=_,m++}if(g[m]!==" "){for(var L=T-y;L!==T&&v[L]===0;)L++;for(var R=new Uint8Array(x+(T-L)),E=x;L!==T;)R[E++]=v[L++];return R}}}function p(g){var m=f(g);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:p}}var Rh=Ih,Ph=Rh;class Nh{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 Lh{name;prefix;baseDecode;prefixCodePoint;constructor(e,n,r){this.name=e,this.prefix=n;const s=n.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 ed(this,e)}}class Bh{decoders;constructor(e){this.decoders=e}or(e){return ed(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 ed(t,e){return new Bh({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class _h{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,n,r,s){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=s,this.encoder=new Nh(e,n,r),this.decoder=new Lh(e,n,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function $s({name:t,prefix:e,encode:n,decode:r}){return new _h(t,e,n,r)}function kr({name:t,prefix:e,alphabet:n}){const{encode:r,decode:s}=Ph(n,t);return $s({prefix:e,name:t,encode:r,decode:o=>Us(s(o))})}function Dh(t,e,n,r){let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let i=0,a=0,c=0;for(let l=0;l<s;++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,o[c++]=255&a>>i)}if(i>=n||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Fh(t,e,n){const r=e[e.length-1]==="=",s=(1<<n)-1;let o="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>n;)i-=n,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<n-i]),r)for(;(o.length*n&7)!==0;)o+="=";return o}function Oh(t){const e={};for(let n=0;n<t.length;++n)e[t[n]]=n;return e}function xe({name:t,prefix:e,bitsPerChar:n,alphabet:r}){const s=Oh(r);return $s({prefix:e,name:t,encode(o){return Fh(o,r,n)},decode(o){return Dh(o,s,n,t)}})}const Te=kr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Mh=kr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),jh=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Te,base58flickr:Mh},Symbol.toStringTag,{value:"Module"})),fr=xe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Uh=xe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),$h=xe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Hh=xe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),qh=xe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Kh=xe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),zh=xe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Vh=xe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Gh=xe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Wh=Object.freeze(Object.defineProperty({__proto__:null,base32:fr,base32hex:qh,base32hexpad:zh,base32hexpadupper:Vh,base32hexupper:Kh,base32pad:$h,base32padupper:Hh,base32upper:Uh,base32z:Gh},Symbol.toStringTag,{value:"Module"})),ns=kr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Xh=kr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Yh=Object.freeze(Object.defineProperty({__proto__:null,base36:ns,base36upper:Xh},Symbol.toStringTag,{value:"Module"}));var Zh=td,Va=128,Jh=-128,Qh=Math.pow(2,31);function td(t,e,n){e=e||[],n=n||0;for(var r=n;t>=Qh;)e[n++]=t&255|Va,t/=128;for(;t&Jh;)e[n++]=t&255|Va,t>>>=7;return e[n]=t|0,td.bytes=n-r+1,e}var ep=ai,tp=128,Ga=127;function ai(t,r){var n=0,r=r||0,s=0,o=r,i,a=t.length;do{if(o>=a)throw ai.bytes=0,new RangeError("Could not decode varint");i=t[o++],n+=s<28?(i&Ga)<<s:(i&Ga)*Math.pow(2,s),s+=7}while(i>=tp);return ai.bytes=o-r,n}var np=Math.pow(2,7),rp=Math.pow(2,14),sp=Math.pow(2,21),op=Math.pow(2,28),ip=Math.pow(2,35),ap=Math.pow(2,42),cp=Math.pow(2,49),lp=Math.pow(2,56),dp=Math.pow(2,63),up=function(t){return t<np?1:t<rp?2:t<sp?3:t<op?4:t<ip?5:t<ap?6:t<cp?7:t<lp?8:t<dp?9:10},fp={encode:Zh,decode:ep,encodingLength:up},ls=fp;function ci(t,e=0){return[ls.decode(t,e),ls.decode.bytes]}function ds(t,e,n=0){return ls.encode(t,e,n),e}function us(t){return ls.encodingLength(t)}function Tr(t,e){const n=e.byteLength,r=us(t),s=r+us(n),o=new Uint8Array(s+n);return ds(t,o,0),ds(n,o,r),o.set(e,s),new zi(t,n,e,o)}function nd(t){const e=Us(t),[n,r]=ci(e),[s,o]=ci(e.subarray(r)),i=e.subarray(r+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new zi(n,s,i,e)}function hp(t,e){if(t===e)return!0;{const n=e;return t.code===n.code&&t.size===n.size&&n.bytes instanceof Uint8Array&&kh(t.bytes,n.bytes)}}class zi{code;size;digest;bytes;constructor(e,n,r,s){this.code=e,this.size=n,this.digest=r,this.bytes=s}}function Wa(t,e){const{bytes:n,version:r}=t;return r===0?gp(n,li(t),e??Te.encoder):mp(n,li(t),e??fr.encoder)}const Xa=new WeakMap;function li(t){const e=Xa.get(t);if(e==null){const n=new Map;return Xa.set(t,n),n}return e}class oe{code;version;multihash;bytes;"/";constructor(e,n,r,s){this.code=n,this.version=e,this.multihash=r,this.bytes=s,this["/"]=s}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!==Wn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==wp)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return oe.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=Tr(e,n);return oe.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 oe.equals(this,e)}static equals(e,n){const r=n;return r!=null&&e.code===r.code&&e.version===r.version&&hp(e.multihash,r.multihash)}toString(e){return Wa(this,e)}toJSON(){return{"/":Wa(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 oe)return n;if(n["/"]!=null&&n["/"]===n.bytes||n.asCID===n){const{version:r,code:s,multihash:o,bytes:i}=n;return new oe(r,s,o,i??Ya(r,s,o.bytes))}else if(n[yp]===!0){const{version:r,multihash:s,code:o}=n,i=nd(s);return oe.create(r,o,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!==Wn)throw new Error(`Version 0 CID must use dag-pb (code: ${Wn}) block encoding`);return new oe(e,n,r,r.bytes)}case 1:{const s=Ya(e,n,r.bytes);return new oe(e,n,r,s)}default:throw new Error("Invalid version")}}static createV0(e){return oe.create(0,Wn,e)}static createV1(e,n){return oe.create(1,e,n)}static decode(e){const[n,r]=oe.decodeFirst(e);if(r.length!==0)throw new Error("Incorrect length");return n}static decodeFirst(e){const n=oe.inspectBytes(e),r=n.size-n.multihashSize,s=Us(e.subarray(r,r+n.multihashSize));if(s.byteLength!==n.multihashSize)throw new Error("Incorrect length");const o=s.subarray(n.multihashSize-n.digestSize),i=new zi(n.multihashCode,n.digestSize,o,s);return[n.version===0?oe.createV0(i):oe.createV1(n.codec,i),e.subarray(n.size)]}static inspectBytes(e){let n=0;const r=()=>{const[u,f]=ci(e.subarray(n));return n+=f,u};let s=r(),o=Wn;if(s===18?(s=0,n=0):o=r(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);const i=n,a=r(),c=r(),l=n+c,d=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:d,size:l}}static parse(e,n){const[r,s]=pp(e,n),o=oe.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return li(o).set(r,e),o}}function pp(t,e){switch(t[0]){case"Q":{const n=e??Te;return[Te.prefix,n.decode(`${Te.prefix}${t}`)]}case Te.prefix:{const n=e??Te;return[Te.prefix,n.decode(t)]}case fr.prefix:{const n=e??fr;return[fr.prefix,n.decode(t)]}case ns.prefix:{const n=e??ns;return[ns.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 gp(t,e,n){const{prefix:r}=n;if(r!==Te.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);const s=e.get(r);if(s==null){const o=n.encode(t).slice(1);return e.set(r,o),o}else return s}function mp(t,e,n){const{prefix:r}=n,s=e.get(r);if(s==null){const o=n.encode(t);return e.set(r,o),o}else return s}const Wn=112,wp=18;function Ya(t,e,n){const r=us(t),s=r+us(e),o=new Uint8Array(s+n.byteLength);return ds(t,o,0),ds(e,o,r),o.set(n,s),o}const yp=Symbol.for("@ipld/js-cid/CID"),rd=0,bp="identity",sd=Us;function xp(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 Tr(rd,sd(t))}const Cr={code:rd,name:bp,encode:sd,digest:xp};function Ye(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 Re(t=0){return new Uint8Array(t)}function gt(t=0){return new Uint8Array(t)}function di(t,e){e==null&&(e=t.reduce((s,o)=>s+o.length,0));const n=gt(e);let r=0;for(const s of t)n.set(s,r),r+=s.length;return n}const od=Symbol.for("@achingbrain/uint8arraylist");function Za(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let n=0;for(const r of t){const s=n+r.byteLength;if(e<s)return{buf:r,index:e-n};n=s}throw new RangeError("index is out of bounds")}function Or(t){return!!t?.[od]}class ne{bufs;length;[od]=!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(Or(r)){n+=r.byteLength;for(const s of r.bufs)this.bufs.push(s)}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(Or(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=Za(this.bufs,e);return n.buf[n.index]}set(e,n){const r=Za(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(Or(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:s}=this._subList(e,n);return di(r,s)}subarray(e,n){const{bufs:r,length:s}=this._subList(e,n);return r.length===1?r[0]:di(r,s)}sublist(e,n){const{bufs:r,length:s}=this._subList(e,n),o=new ne;return o.length=s,o.bufs=r,o}_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 s=0;for(let o=0;o<this.bufs.length;o++){const i=this.bufs[o],a=s,c=a+i.byteLength;if(s=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(!Or(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 s=r.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");const o=256,i=new Int32Array(o);for(let u=0;u<o;u++)i[u]=-1;for(let u=0;u<s;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 p=this.get(u+f);if(r[f]!==p){d=Math.max(1,f-a[p]);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=gt(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 s=Re(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,n,r),this.write(s,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 s=Re(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,n,r),this.write(s,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 s=Re(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,n,r),this.write(s,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=gt(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 s=Re(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,n,r),this.write(s,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 s=Re(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,n,r),this.write(s,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 s=Re(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,n,r),this.write(s,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 s=Re(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,n,r),this.write(s,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 s=Re(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,n,r),this.write(s,e)}equals(e){if(e==null||!(e instanceof ne)||e.bufs.length!==this.bufs.length)return!1;for(let n=0;n<this.bufs.length;n++)if(!Ye(this.bufs[n],e.bufs[n]))return!1;return!0}static fromUint8Arrays(e,n){const r=new ne;return r.bufs=e,n==null&&(n=e.reduce((s,o)=>s+o.byteLength,0)),r.length=n,r}}const vp=kr({prefix:"9",name:"base10",alphabet:"0123456789"}),Ep=Object.freeze(Object.defineProperty({__proto__:null,base10:vp},Symbol.toStringTag,{value:"Module"})),Sp=xe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ap=xe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),kp=Object.freeze(Object.defineProperty({__proto__:null,base16:Sp,base16upper:Ap},Symbol.toStringTag,{value:"Module"})),Tp=xe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Cp=Object.freeze(Object.defineProperty({__proto__:null,base2:Tp},Symbol.toStringTag,{value:"Module"})),id=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Ip=id.reduce((t,e,n)=>(t[n]=e,t),[]),Rp=id.reduce((t,e,n)=>{const r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return t[r]=n,t},[]);function Pp(t){return t.reduce((e,n)=>(e+=Ip[n],e),"")}function Np(t){const e=[];for(const n of t){const r=n.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${n}`);const s=Rp[r];if(s==null)throw new Error(`Non-base256emoji character: ${n}`);e.push(s)}return new Uint8Array(e)}const Lp=$s({prefix:"🚀",name:"base256emoji",encode:Pp,decode:Np}),Bp=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:Lp},Symbol.toStringTag,{value:"Module"})),_p=xe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Dp=xe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Fp=xe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Op=xe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Mp=Object.freeze(Object.defineProperty({__proto__:null,base64:_p,base64pad:Dp,base64url:Fp,base64urlpad:Op},Symbol.toStringTag,{value:"Module"})),jp=xe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Up=Object.freeze(Object.defineProperty({__proto__:null,base8:jp},Symbol.toStringTag,{value:"Module"})),$p=$s({prefix:"\0",name:"identity",encode:t=>Ch(t),decode:t=>Th(t)}),Hp=Object.freeze(Object.defineProperty({__proto__:null,identity:$p},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const qp=20;function Kp({name:t,code:e,encode:n,minDigestLength:r,maxDigestLength:s}){return new zp(t,e,n,r,s)}class zp{name;code;encode;minDigestLength;maxDigestLength;constructor(e,n,r,s,o){this.name=e,this.code=n,this.encode=r,this.minDigestLength=s??qp,this.maxDigestLength=o}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?Ja(r,this.code,n?.truncate):r.then(s=>Ja(s,this.code,n?.truncate))}else throw Error("Unknown type, must be binary type")}}function Ja(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 Tr(e,t)}function Vp(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}const Vi=Kp({name:"sha2-256",code:18,encode:Vp("SHA-256")}),Qa={...Hp,...Cp,...Up,...Ep,...kp,...Wh,...Yh,...jh,...Mp,...Bp};function ad(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const ec=ad("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),uo=ad("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=gt(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),cd={utf8:ec,"utf-8":ec,hex:Qa.base16,latin1:uo,ascii:uo,binary:uo,...Qa};function fe(t,e="utf8"){const n=cd[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.decoder.decode(`${n.prefix}${t}`)}function J(t,e="utf8"){const n=cd[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.encoder.encode(t).substring(1)}const Gp=parseInt("11111",2),ui=parseInt("10000000",2),Wp=parseInt("01111111",2),tc={0:Xn,1:Xn,2:Xp,3:Jp,4:Qp,5:Zp,6:Yp,16:Xn,22:Xn,48:Xn};function $n(t,e={offset:0}){const n=t[e.offset]&Gp;if(e.offset++,tc[n]!=null)return tc[n](t,e);throw new Error("No decoder for tag "+n)}function Ir(t,e){let n=0;if((t[e.offset]&ui)===ui){const r=t[e.offset]&Wp;let s="0x";e.offset++;for(let o=0;o<r;o++,e.offset++)s+=t[e.offset].toString(16).padStart(2,"0");n=parseInt(s,16)}else n=t[e.offset],e.offset++;return n}function Xn(t,e){Ir(t,e);const n=[];for(;!(e.offset>=t.byteLength);){const r=$n(t,e);if(r===null)break;n.push(r)}return n}function Xp(t,e){const n=Ir(t,e),r=e.offset,s=e.offset+n,o=[];for(let i=r;i<s;i++)i===r&&t[i]===0||o.push(t[i]);return e.offset+=n,Uint8Array.from(o)}function Yp(t,e){const n=Ir(t,e),r=e.offset+n,s=t[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${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 Zp(t,e){return e.offset++,null}function Jp(t,e){const n=Ir(t,e),r=t[e.offset];e.offset++;const s=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 s}function Qp(t,e){const n=Ir(t,e),r=t.subarray(e.offset,e.offset+n);return e.offset+=n,r}function eg(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);const n=new ne;for(let r=0;r<e.length;r+=2)n.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return n}function Hs(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);const e=eg(t.byteLength);return new ne(Uint8Array.from([e.byteLength|ui]),e)}function Be(t){const e=new ne,n=128;return(t.subarray()[0]&n)===n&&e.append(Uint8Array.from([0])),e.append(t),new ne(Uint8Array.from([2]),Hs(e),e)}function Gi(t){const e=Uint8Array.from([0]),n=new ne(e,t);return new ne(Uint8Array.from([3]),Hs(n),n)}function tg(t){return new ne(Uint8Array.from([4]),Hs(t),t)}function pt(t,e=48){const n=new ne;for(const r of t)n.append(r);return new ne(Uint8Array.from([e]),Hs(n),n)}async function ng(t,e,n){const r=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["sign"]);n?.signal?.throwIfAborted();const s=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function rg(t,e,n,r){const s=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();const o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,e,n.subarray());return r?.signal?.throwIfAborted(),o}const sg=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),og=Uint8Array.from([6,5,43,129,4,0,34]),ig=Uint8Array.from([6,5,43,129,4,0,35]),ld={ext:!0,kty:"EC",crv:"P-256"},dd={ext:!0,kty:"EC",crv:"P-384"},ud={ext:!0,kty:"EC",crv:"P-521"},yn=32,bn=48,xn=66;function ag(t){const e=$n(t);return cg(e)}function cg(t){const e=t[1],n=J(e,"base64url"),r=t[2][1][0],s=1;let o,i;if(e.byteLength===yn)return o=J(r.subarray(s,s+yn),"base64url"),i=J(r.subarray(s+yn),"base64url"),new fo({...ld,key_ops:["sign"],d:n,x:o,y:i});if(e.byteLength===bn)return o=J(r.subarray(s,s+bn),"base64url"),i=J(r.subarray(s+bn),"base64url"),new fo({...dd,key_ops:["sign"],d:n,x:o,y:i});if(e.byteLength===xn)return o=J(r.subarray(s,s+xn),"base64url"),i=J(r.subarray(s+xn),"base64url"),new fo({...ud,key_ops:["sign"],d:n,x:o,y:i});throw new Xe(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function fd(t){const e=$n(t);return lg(e)}function lg(t){const e=t[1][1][0],n=1;let r,s;if(e.byteLength===yn*2+1)return r=J(e.subarray(n,n+yn),"base64url"),s=J(e.subarray(n+yn),"base64url"),new rs({...ld,key_ops:["verify"],x:r,y:s});if(e.byteLength===bn*2+1)return r=J(e.subarray(n,n+bn),"base64url"),s=J(e.subarray(n+bn),"base64url"),new rs({...dd,key_ops:["verify"],x:r,y:s});if(e.byteLength===xn*2+1)return r=J(e.subarray(n,n+xn),"base64url"),s=J(e.subarray(n+xn),"base64url"),new rs({...ud,key_ops:["verify"],x:r,y:s});throw new Xe(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function dg(t){return pt([Be(Uint8Array.from([1])),tg(fe(t.d??"","base64url")),pt([hd(t.crv)],160),pt([Gi(new ne(Uint8Array.from([4]),fe(t.x??"","base64url"),fe(t.y??"","base64url")))],161)]).subarray()}function ug(t){return pt([Be(Uint8Array.from([1])),pt([hd(t.crv)],160),pt([Gi(new ne(Uint8Array.from([4]),fe(t.x??"","base64url"),fe(t.y??"","base64url")))],161)]).subarray()}function hd(t){if(t==="P-256")return sg;if(t==="P-384")return og;if(t==="P-521")return ig;throw new Xe(`Invalid curve ${t}`)}class rs{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=ug(this.jwk)),this._raw}toMultihash(){return Cr.digest(Ws(this))}toCID(){return oe.createV1(114,this.toMultihash())}toString(){return Te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ye(this.raw,e.raw)}async verify(e,n,r){return rg(this.jwk,n,e,r)}}class fo{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new rs({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=dg(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ye(this.raw,e.raw)}async sign(e,n){return ng(this.jwk,e,n)}}const dn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Rr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function fi(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Qt(t,...e){if(!Rr(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 pd(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");fi(t.outputLen),fi(t.blockLen)}function fs(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 fg(t,e){Qt(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Nn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function ho(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Ze(t,e){return t<<32-e|t>>>e}const gd=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",hg=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ht(t){if(Qt(t),gd)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=hg[t[n]];return e}const ot={_0:48,_9:57,A:65,F:70,a:97,f:102};function nc(t){if(t>=ot._0&&t<=ot._9)return t-ot._0;if(t>=ot.A&&t<=ot.F)return t-(ot.A-10);if(t>=ot.a&&t<=ot.f)return t-(ot.a-10)}function hs(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(gd)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 s=0,o=0;s<n;s++,o+=2){const i=nc(t.charCodeAt(o)),a=nc(t.charCodeAt(o+1));if(i===void 0||a===void 0){const c=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}r[s]=i*16+a}return r}function pg(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Wi(t){return typeof t=="string"&&(t=pg(t)),Qt(t),t}function et(...t){let e=0;for(let r=0;r<t.length;r++){const s=t[r];Qt(s),e+=s.length}const n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){const o=t[r];n.set(o,s),s+=o.length}return n}class md{}function wd(t){const e=r=>t().update(Wi(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Xi(t=32){if(dn&&typeof dn.getRandomValues=="function")return dn.getRandomValues(new Uint8Array(t));if(dn&&typeof dn.randomBytes=="function")return Uint8Array.from(dn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function gg(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const s=BigInt(32),o=BigInt(4294967295),i=Number(n>>s&o),a=Number(n&o),c=r?4:0,l=r?0:4;t.setUint32(e+c,i,r),t.setUint32(e+l,a,r)}function mg(t,e,n){return t&e^~t&n}function wg(t,e,n){return t&e^t&n^e&n}let yd=class extends md{constructor(e,n,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=ho(this.buffer)}update(e){fs(this),e=Wi(e),Qt(e);const{view:n,buffer:r,blockLen:s}=this,o=e.length;for(let i=0;i<o;){const a=Math.min(s-this.pos,o-i);if(a===s){const c=ho(e);for(;s<=o-i;i+=s)this.process(c,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){fs(this),fg(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:s,isLE:o}=this;let{pos:i}=this;n[i++]=128,Nn(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(r,0),i=0);for(let u=i;u<s;u++)n[u]=0;gg(r,s-8,BigInt(this.length*8),o),this.process(r,0);const a=ho(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],o)}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:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};const xt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ve=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Mr=BigInt(2**32-1),rc=BigInt(32);function yg(t,e=!1){return e?{h:Number(t&Mr),l:Number(t>>rc&Mr)}:{h:Number(t>>rc&Mr)|0,l:Number(t&Mr)|0}}function bg(t,e=!1){const n=t.length;let r=new Uint32Array(n),s=new Uint32Array(n);for(let o=0;o<n;o++){const{h:i,l:a}=yg(t[o],e);[r[o],s[o]]=[i,a]}return[r,s]}const sc=(t,e,n)=>t>>>n,oc=(t,e,n)=>t<<32-n|e>>>n,un=(t,e,n)=>t>>>n|e<<32-n,fn=(t,e,n)=>t<<32-n|e>>>n,jr=(t,e,n)=>t<<64-n|e>>>n-32,Ur=(t,e,n)=>t>>>n-32|e<<64-n;function it(t,e,n,r){const s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}const xg=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),vg=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Eg=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Sg=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,Ag=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),kg=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0,Tg=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]),vt=new Uint32Array(64);class Cg extends yd{constructor(e=32){super(64,e,8,!1),this.A=xt[0]|0,this.B=xt[1]|0,this.C=xt[2]|0,this.D=xt[3]|0,this.E=xt[4]|0,this.F=xt[5]|0,this.G=xt[6]|0,this.H=xt[7]|0}get(){const{A:e,B:n,C:r,D:s,E:o,F:i,G:a,H:c}=this;return[e,n,r,s,o,i,a,c]}set(e,n,r,s,o,i,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=o|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)vt[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const f=vt[u-15],p=vt[u-2],g=Ze(f,7)^Ze(f,18)^f>>>3,m=Ze(p,17)^Ze(p,19)^p>>>10;vt[u]=m+vt[u-7]+g+vt[u-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=Ze(a,6)^Ze(a,11)^Ze(a,25),p=d+f+mg(a,c,l)+Tg[u]+vt[u]|0,m=(Ze(r,2)^Ze(r,13)^Ze(r,22))+wg(r,s,o)|0;d=l,l=c,c=a,a=i+p|0,i=o,o=s,s=r,r=p+m|0}r=r+this.A|0,s=s+this.B|0,o=o+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,s,o,i,a,c,l,d)}roundClean(){Nn(vt)}destroy(){this.set(0,0,0,0,0,0,0,0),Nn(this.buffer)}}const bd=bg(["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))),Ig=bd[0],Rg=bd[1],Et=new Uint32Array(80),St=new Uint32Array(80);class Pg extends yd{constructor(e=64){super(128,e,16,!1),this.Ah=ve[0]|0,this.Al=ve[1]|0,this.Bh=ve[2]|0,this.Bl=ve[3]|0,this.Ch=ve[4]|0,this.Cl=ve[5]|0,this.Dh=ve[6]|0,this.Dl=ve[7]|0,this.Eh=ve[8]|0,this.El=ve[9]|0,this.Fh=ve[10]|0,this.Fl=ve[11]|0,this.Gh=ve[12]|0,this.Gl=ve[13]|0,this.Hh=ve[14]|0,this.Hl=ve[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:f,Gh:p,Gl:g,Hh:m,Hl:x}=this;return[e,n,r,s,o,i,a,c,l,d,u,f,p,g,m,x]}set(e,n,r,s,o,i,a,c,l,d,u,f,p,g,m,x){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=s|0,this.Ch=o|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=p|0,this.Gl=g|0,this.Hh=m|0,this.Hl=x|0}process(e,n){for(let v=0;v<16;v++,n+=4)Et[v]=e.getUint32(n),St[v]=e.getUint32(n+=4);for(let v=16;v<80;v++){const A=Et[v-15]|0,_=St[v-15]|0,C=un(A,_,1)^un(A,_,8)^sc(A,_,7),L=fn(A,_,1)^fn(A,_,8)^oc(A,_,7),R=Et[v-2]|0,E=St[v-2]|0,S=un(R,E,19)^jr(R,E,61)^sc(R,E,6),P=fn(R,E,19)^Ur(R,E,61)^oc(R,E,6),N=Eg(L,P,St[v-7],St[v-16]),w=Sg(N,C,S,Et[v-7],Et[v-16]);Et[v]=w|0,St[v]=N|0}let{Ah:r,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:f,Fh:p,Fl:g,Gh:m,Gl:x,Hh:y,Hl:T}=this;for(let v=0;v<80;v++){const A=un(u,f,14)^un(u,f,18)^jr(u,f,41),_=fn(u,f,14)^fn(u,f,18)^Ur(u,f,41),C=u&p^~u&m,L=f&g^~f&x,R=Ag(T,_,L,Rg[v],St[v]),E=kg(R,y,A,C,Ig[v],Et[v]),S=R|0,P=un(r,s,28)^jr(r,s,34)^jr(r,s,39),N=fn(r,s,28)^Ur(r,s,34)^Ur(r,s,39),w=r&o^r&a^o&a,b=s&i^s&c^i&c;y=m|0,T=x|0,m=p|0,x=g|0,p=u|0,g=f|0,{h:u,l:f}=it(l|0,d|0,E|0,S|0),l=a|0,d=c|0,a=o|0,c=i|0,o=r|0,i=s|0;const k=xg(S,N,b);r=vg(k,E,P,w),s=k|0}({h:r,l:s}=it(this.Ah|0,this.Al|0,r|0,s|0)),{h:o,l:i}=it(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=it(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=it(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:f}=it(this.Eh|0,this.El|0,u|0,f|0),{h:p,l:g}=it(this.Fh|0,this.Fl|0,p|0,g|0),{h:m,l:x}=it(this.Gh|0,this.Gl|0,m|0,x|0),{h:y,l:T}=it(this.Hh|0,this.Hl|0,y|0,T|0),this.set(r,s,o,i,a,c,l,d,u,f,p,g,m,x,y,T)}roundClean(){Nn(Et,St)}destroy(){Nn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const xd=wd(()=>new Cg),Ng=wd(()=>new Pg);const Yi=BigInt(0),hi=BigInt(1);function Gt(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function ze(t,e,n=""){const r=Rr(t),s=t?.length,o=e!==void 0;if(!r||o&&s!==e){const i=n&&`"${n}" `,a=o?` of length ${e}`:"",c=r?`length=${s}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function $r(t){const e=t.toString(16);return e.length&1?"0"+e:e}function vd(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Yi:BigInt("0x"+t)}function qs(t){return vd(Ht(t))}function yr(t){return Qt(t),vd(Ht(Uint8Array.from(t).reverse()))}function Zi(t,e){return hs(t.toString(16).padStart(e*2,"0"))}function Ed(t,e){return Zi(t,e).reverse()}function le(t,e,n){let r;if(typeof e=="string")try{r=hs(e)}catch(o){throw new Error(t+" must be hex string or Uint8Array, cause: "+o)}else if(Rr(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=r.length;if(typeof n=="number"&&s!==n)throw new Error(t+" of length "+n+" expected, got "+s);return r}function ic(t){return Uint8Array.from(t)}const po=t=>typeof t=="bigint"&&Yi<=t;function Lg(t,e,n){return po(t)&&po(e)&&po(n)&&e<=t&&t<n}function pi(t,e,n,r){if(!Lg(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Sd(t){let e;for(e=0;t>Yi;t>>=hi,e+=1);return e}const Pr=t=>(hi<<BigInt(t))-hi;function Bg(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=p=>new Uint8Array(p),s=p=>Uint8Array.of(p);let o=r(t),i=r(t),a=0;const c=()=>{o.fill(1),i.fill(0),a=0},l=(...p)=>n(i,o,...p),d=(p=r(0))=>{i=l(s(0),p),o=l(),p.length!==0&&(i=l(s(1),p),o=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0;const g=[];for(;p<e;){o=l();const m=o.slice();g.push(m),p+=o.length}return et(...g)};return(p,g)=>{c(),d(p);let m;for(;!(m=g(u()));)d();return c(),m}}function Nr(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(s,o,i){const a=t[s];if(i&&a===void 0)return;const c=typeof a;if(c!==o||a===null)throw new Error(`param "${s}" is invalid: expected ${o}, got ${c}`)}Object.entries(e).forEach(([s,o])=>r(s,o,!1)),Object.entries(n).forEach(([s,o])=>r(s,o,!0))}function ps(t){const e=new WeakMap;return(n,...r)=>{const s=e.get(n);if(s!==void 0)return s;const o=t(n,...r);return e.set(n,o),o}}const Pe=BigInt(0),be=BigInt(1),Ot=BigInt(2),Ad=BigInt(3),kd=BigInt(4),Td=BigInt(5),_g=BigInt(7),Cd=BigInt(8),Dg=BigInt(9),Id=BigInt(16);function he(t,e){const n=t%e;return n>=Pe?n:e+n}function ce(t,e,n){let r=t;for(;e-- >Pe;)r*=r,r%=n;return r}function ac(t,e){if(t===Pe)throw new Error("invert: expected non-zero number");if(e<=Pe)throw new Error("invert: expected positive modulus, got "+e);let n=he(t,e),r=e,s=Pe,o=be;for(;n!==Pe;){const a=r/n,c=r%n,l=s-o*a;r=n,n=c,s=o,o=l}if(r!==be)throw new Error("invert: does not exist");return he(s,e)}function Ji(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Rd(t,e){const n=(t.ORDER+be)/kd,r=t.pow(e,n);return Ji(t,r,e),r}function Fg(t,e){const n=(t.ORDER-Td)/Cd,r=t.mul(e,Ot),s=t.pow(r,n),o=t.mul(e,s),i=t.mul(t.mul(o,Ot),s),a=t.mul(o,t.sub(i,t.ONE));return Ji(t,a,e),a}function Og(t){const e=en(t),n=Pd(t),r=n(e,e.neg(e.ONE)),s=n(e,r),o=n(e,e.neg(r)),i=(t+_g)/Id;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,r);const u=a.mul(l,s),f=a.mul(l,o),p=a.eql(a.sqr(d),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,d,p),d=a.cmov(f,u,g);const m=a.eql(a.sqr(d),c),x=a.cmov(l,d,m);return Ji(a,x,c),x}}function Pd(t){if(t<Ad)throw new Error("sqrt is not defined for small field");let e=t-be,n=0;for(;e%Ot===Pe;)e/=Ot,n++;let r=Ot;const s=en(t);for(;cc(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Rd;let o=s.pow(r,e);const i=(e+be)/Ot;return function(c,l){if(c.is0(l))return l;if(cc(c,l)!==1)throw new Error("Cannot find square root");let d=n,u=c.mul(c.ONE,o),f=c.pow(l,e),p=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 x=be<<BigInt(d-g-1),y=c.pow(u,x);d=g,u=c.sqr(y),f=c.mul(f,u),p=c.mul(p,y)}return p}}function Mg(t){return t%kd===Ad?Rd:t%Cd===Td?Fg:t%Id===Dg?Og(t):Pd(t)}const jg=(t,e)=>(he(t,e)&be)===be,Ug=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function $g(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=Ug.reduce((r,s)=>(r[s]="function",r),e);return Nr(t,n),t}function Hg(t,e,n){if(n<Pe)throw new Error("invalid exponent, negatives unsupported");if(n===Pe)return t.ONE;if(n===be)return e;let r=t.ONE,s=e;for(;n>Pe;)n&be&&(r=t.mul(r,s)),s=t.sqr(s),n>>=be;return r}function Nd(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),s=e.reduce((i,a,c)=>t.is0(a)?i:(r[c]=i,t.mul(i,a)),t.ONE),o=t.inv(s);return e.reduceRight((i,a,c)=>t.is0(a)?i:(r[c]=t.mul(i,r[c]),t.mul(i,a)),o),r}function cc(t,e){const n=(t.ORDER-be)/Ot,r=t.pow(e,n),s=t.eql(r,t.ONE),o=t.eql(r,t.ZERO),i=t.eql(r,t.neg(t.ONE));if(!s&&!o&&!i)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function Ld(t,e){e!==void 0&&fi(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function en(t,e,n=!1,r={}){if(t<=Pe)throw new Error("invalid field: expected ORDER > 0, got "+t);let s,o,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&&(s=f.BITS),f.sqrt&&(o=f.sqrt),typeof f.isLE=="boolean"&&(n=f.isLE),typeof f.modFromBytes=="boolean"&&(i=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(s=e),r.sqrt&&(o=r.sqrt);const{nBitLength:c,nByteLength:l}=Ld(t,s);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:Pr(c),ZERO:Pe,ONE:be,allowedLengths:a,create:f=>he(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return Pe<=f&&f<t},is0:f=>f===Pe,isValidNot0:f=>!u.is0(f)&&u.isValid(f),isOdd:f=>(f&be)===be,neg:f=>he(-f,t),eql:(f,p)=>f===p,sqr:f=>he(f*f,t),add:(f,p)=>he(f+p,t),sub:(f,p)=>he(f-p,t),mul:(f,p)=>he(f*p,t),pow:(f,p)=>Hg(u,f,p),div:(f,p)=>he(f*ac(p,t),t),sqrN:f=>f*f,addN:(f,p)=>f+p,subN:(f,p)=>f-p,mulN:(f,p)=>f*p,inv:f=>ac(f,t),sqrt:o||(f=>(d||(d=Mg(t)),d(u,f))),toBytes:f=>n?Ed(f,l):Zi(f,l),fromBytes:(f,p=!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?yr(f):qs(f);if(i&&(g=he(g,t)),!p&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:f=>Nd(u,f),cmov:(f,p,g)=>g?p:f});return Object.freeze(u)}function Bd(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 _d(t){const e=Bd(t);return e+Math.ceil(e/2)}function qg(t,e,n=!1){const r=t.length,s=Bd(e),o=_d(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);const i=n?yr(t):qs(t),a=he(i,e-be)+be;return n?Ed(a,s):Zi(a,s)}const Ln=BigInt(0),Mt=BigInt(1);function gs(t,e){const n=e.negate();return t?n:e}function jt(t,e){const n=Nd(t.Fp,e.map(r=>r.Z));return e.map((r,s)=>t.fromAffine(r.toAffine(n[s])))}function Dd(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function go(t,e){Dd(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),s=2**t,o=Pr(t),i=BigInt(t);return{windows:n,windowSize:r,mask:o,maxNumber:s,shiftBy:i}}function lc(t,e,n){const{windowSize:r,mask:s,maxNumber:o,shiftBy:i}=n;let a=Number(t&s),c=t>>i;a>r&&(a-=o,c+=Mt);const l=e*r,d=l+Math.abs(a)-1,u=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:f,isNegF:p,offsetF:l}}function Kg(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 zg(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 mo=new WeakMap,Fd=new WeakMap;function wo(t){return Fd.get(t)||1}function dc(t){if(t!==Ln)throw new Error("invalid wNAF")}class Od{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 s=e;for(;n>Ln;)n&Mt&&(r=r.add(s)),s=s.double(),n>>=Mt;return r}precomputeWindow(e,n){const{windows:r,windowSize:s}=go(n,this.bits),o=[];let i=e,a=i;for(let c=0;c<r;c++){a=i,o.push(a);for(let l=1;l<s;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE;const i=go(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:f,offsetF:p}=lc(r,a,i);r=c,d?o=o.add(gs(f,n[p])):s=s.add(gs(u,n[l]))}return dc(r),{p:s,f:o}}wNAFUnsafe(e,n,r,s=this.ZERO){const o=go(e,this.bits);for(let i=0;i<o.windows&&r!==Ln;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=lc(r,i,o);if(r=a,!l){const u=n[c];s=s.add(d?u.negate():u)}}return dc(r),s}getPrecomputes(e,n,r){let s=mo.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(s=r(s)),mo.set(n,s))),s}cached(e,n,r){const s=wo(e);return this.wNAF(s,this.getPrecomputes(s,e,r),n)}unsafe(e,n,r,s){const o=wo(e);return o===1?this._unsafeLadder(e,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),n,s)}createCache(e,n){Dd(n,this.bits),Fd.set(e,n),mo.delete(e)}hasCache(e){return wo(e)!==1}}function Vg(t,e,n,r){let s=e,o=t.ZERO,i=t.ZERO;for(;n>Ln||r>Ln;)n&Mt&&(o=o.add(s)),r&Mt&&(i=i.add(s)),s=s.double(),n>>=Mt,r>>=Mt;return{p1:o,p2:i}}function Md(t,e,n,r){Kg(n,t),zg(r,e);const s=n.length,o=r.length;if(s!==o)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,a=Sd(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Pr(c),d=new Array(Number(l)+1).fill(i),u=Math.floor((e.BITS-1)/c)*c;let f=i;for(let p=u;p>=0;p-=c){d.fill(i);for(let m=0;m<o;m++){const x=r[m],y=Number(x>>BigInt(p)&l);d[y]=d[y].add(n[m])}let g=i;for(let m=d.length-1,x=i;m>0;m--)x=x.add(d[m]),g=g.add(x);if(f=f.add(g),p!==0)for(let m=0;m<c;m++)f=f.double()}return f}function uc(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return $g(e),e}else return en(t,{isLE:n})}function jd(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>Ln))throw new Error(`CURVE.${c} must be positive bigint`)}const s=uc(e.p,n.Fp,r),o=uc(e.n,n.Fn,r),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const c of a)if(!s.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:s,Fn:o}}const At=BigInt(0),pe=BigInt(1),yo=BigInt(2),Gg=BigInt(8);function Wg(t,e,n,r){const s=t.sqr(n),o=t.sqr(r),i=t.add(t.mul(e.a,s),o),a=t.add(t.ONE,t.mul(e.d,t.mul(s,o)));return t.eql(i,a)}function Xg(t,e={}){const n=jd("edwards",t,e,e.FpFnLE),{Fp:r,Fn:s}=n;let o=n.CURVE;const{h:i}=o;Nr(e,{},{uvRatio:"function"});const a=yo<<BigInt(s.BYTES*8)-pe,c=x=>r.create(x),l=e.uvRatio||((x,y)=>{try{return{isValid:!0,value:r.sqrt(r.div(x,y))}}catch{return{isValid:!1,value:At}}});if(!Wg(r,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function d(x,y,T=!1){const v=T?pe:At;return pi("coordinate "+x,y,v,a),y}function u(x){if(!(x instanceof g))throw new Error("ExtendedPoint expected")}const f=ps((x,y)=>{const{X:T,Y:v,Z:A}=x,_=x.is0();y==null&&(y=_?Gg:r.inv(A));const C=c(T*y),L=c(v*y),R=r.mul(A,y);if(_)return{x:At,y:pe};if(R!==pe)throw new Error("invZ was invalid");return{x:C,y:L}}),p=ps(x=>{const{a:y,d:T}=o;if(x.is0())throw new Error("bad point: ZERO");const{X:v,Y:A,Z:_,T:C}=x,L=c(v*v),R=c(A*A),E=c(_*_),S=c(E*E),P=c(L*y),N=c(E*c(P+R)),w=c(S+c(T*c(L*R)));if(N!==w)throw new Error("bad point: equation left != right (1)");const b=c(v*A),k=c(_*C);if(b!==k)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(y,T,v,A){this.X=d("x",y),this.Y=d("y",T),this.Z=d("z",v,!0),this.T=d("t",A),Object.freeze(this)}static CURVE(){return o}static fromAffine(y){if(y instanceof g)throw new Error("extended point not allowed");const{x:T,y:v}=y||{};return d("x",T),d("y",v),new g(T,v,pe,c(T*v))}static fromBytes(y,T=!1){const v=r.BYTES,{a:A,d:_}=o;y=ic(ze(y,v,"point")),Gt(T,"zip215");const C=ic(y),L=y[v-1];C[v-1]=L&-129;const R=yr(C),E=T?a:r.ORDER;pi("point.y",R,At,E);const S=c(R*R),P=c(S-pe),N=c(_*S-A);let{isValid:w,value:b}=l(P,N);if(!w)throw new Error("bad point: invalid y coordinate");const k=(b&pe)===pe,B=(L&128)!==0;if(!T&&b===At&&B)throw new Error("bad point: x=0 and x_0=1");return B!==k&&(b=c(-b)),g.fromAffine({x:b,y:R})}static fromHex(y,T=!1){return g.fromBytes(le("point",y),T)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,T=!0){return m.createCache(this,y),T||this.multiply(yo),this}assertValidity(){p(this)}equals(y){u(y);const{X:T,Y:v,Z:A}=this,{X:_,Y:C,Z:L}=y,R=c(T*L),E=c(_*A),S=c(v*L),P=c(C*A);return R===E&&S===P}is0(){return this.equals(g.ZERO)}negate(){return new g(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:y}=o,{X:T,Y:v,Z:A}=this,_=c(T*T),C=c(v*v),L=c(yo*c(A*A)),R=c(y*_),E=T+v,S=c(c(E*E)-_-C),P=R+C,N=P-L,w=R-C,b=c(S*N),k=c(P*w),B=c(S*w),M=c(N*P);return new g(b,k,M,B)}add(y){u(y);const{a:T,d:v}=o,{X:A,Y:_,Z:C,T:L}=this,{X:R,Y:E,Z:S,T:P}=y,N=c(A*R),w=c(_*E),b=c(L*v*P),k=c(C*S),B=c((A+_)*(R+E)-N-w),M=k-b,U=k+b,D=c(w-T*N),I=c(B*M),F=c(U*D),O=c(B*D),K=c(M*U);return new g(I,F,K,O)}subtract(y){return this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:T,f:v}=m.cached(this,y,A=>jt(g,A));return jt(g,[T,v])[0]}multiplyUnsafe(y,T=g.ZERO){if(!s.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===At?g.ZERO:this.is0()||y===pe?this:m.unsafe(this,y,v=>jt(g,v),T)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,o.n).is0()}toAffine(y){return f(this,y)}clearCofactor(){return i===pe?this:this.multiplyUnsafe(i)}toBytes(){const{x:y,y:T}=this.toAffine(),v=r.toBytes(T);return v[v.length-1]|=y&pe?128:0,v}toHex(){return Ht(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(y){return jt(g,y)}static msm(y,T){return Md(g,s,y,T)}_setWindowSize(y){this.precompute(y)}toRawBytes(){return this.toBytes()}}g.BASE=new g(o.Gx,o.Gy,pe,c(o.Gx*o.Gy)),g.ZERO=new g(At,pe,pe,At),g.Fp=r,g.Fn=s;const m=new Od(g,s.BITS);return g.BASE.precompute(8),g}function Yg(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is required');Nr(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:s,Fp:o,Fn:i}=t,a=n.randomBytes||Xi,c=n.adjustScalarBytes||(E=>E),l=n.domain||((E,S,P)=>{if(Gt(P,"phflag"),S.length||P)throw new Error("Contexts/pre-hash are not supported");return E});function d(E){return i.create(yr(E))}function u(E){const S=v.secretKey;E=le("private key",E,S);const P=le("hashed private key",e(E),2*S),N=c(P.slice(0,S)),w=P.slice(S,2*S),b=d(N);return{head:N,prefix:w,scalar:b}}function f(E){const{head:S,prefix:P,scalar:N}=u(E),w=s.multiply(N),b=w.toBytes();return{head:S,prefix:P,scalar:N,point:w,pointBytes:b}}function p(E){return f(E).pointBytes}function g(E=Uint8Array.of(),...S){const P=et(...S);return d(e(l(P,le("context",E),!!r)))}function m(E,S,P={}){E=le("message",E),r&&(E=r(E));const{prefix:N,scalar:w,pointBytes:b}=f(S),k=g(P.context,N,E),B=s.multiply(k).toBytes(),M=g(P.context,B,b,E),U=i.create(k+M*w);if(!i.isValid(U))throw new Error("sign failed: invalid s");const D=et(B,i.toBytes(U));return ze(D,v.signature,"result")}const x={zip215:!0};function y(E,S,P,N=x){const{context:w,zip215:b}=N,k=v.signature;E=le("signature",E,k),S=le("message",S),P=le("publicKey",P,v.publicKey),b!==void 0&&Gt(b,"zip215"),r&&(S=r(S));const B=k/2,M=E.subarray(0,B),U=yr(E.subarray(B,k));let D,I,F;try{D=t.fromBytes(P,b),I=t.fromBytes(M,b),F=s.multiplyUnsafe(U)}catch{return!1}if(!b&&D.isSmallOrder())return!1;const O=g(w,I.toBytes(),D.toBytes(),S);return I.add(D.multiplyUnsafe(O)).subtract(F).clearCofactor().is0()}const T=o.BYTES,v={secretKey:T,publicKey:T,signature:2*T,seed:T};function A(E=a(v.seed)){return ze(E,v.seed,"seed")}function _(E){const S=R.randomSecretKey(E);return{secretKey:S,publicKey:p(S)}}function C(E){return Rr(E)&&E.length===i.BYTES}function L(E,S){try{return!!t.fromBytes(E,S)}catch{return!1}}const R={getExtendedPublicKey:f,randomSecretKey:A,isValidSecretKey:C,isValidPublicKey:L,toMontgomery(E){const{y:S}=t.fromBytes(E),P=v.publicKey,N=P===32;if(!N&&P!==57)throw new Error("only defined for 25519 and 448");const w=N?o.div(pe+S,pe-S):o.div(S-pe,S+pe);return o.toBytes(w)},toMontgomerySecret(E){const S=v.secretKey;ze(E,S);const P=e(E.subarray(0,S));return c(P).subarray(0,S)},randomPrivateKey:A,precompute(E=8,S=t.BASE){return S.precompute(E,!1)}};return Object.freeze({keygen:_,getPublicKey:p,sign:m,verify:y,utils:R,Point:t,lengths:v})}function Zg(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=en(e.n,t.nBitLength,!0),s={Fp:n,Fn:r,uvRatio:t.uvRatio},o={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:s,hash:t.hash,eddsaOpts:o}}function Jg(t,e){const n=e.Point;return Object.assign({},e,{ExtendedPoint:n,CURVE:t,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function Qg(t){const{CURVE:e,curveOpts:n,hash:r,eddsaOpts:s}=Zg(t),o=Xg(e,n),i=Yg(o,r,s);return Jg(t,i)}const em=BigInt(1),fc=BigInt(2);BigInt(3);const tm=BigInt(5),nm=BigInt(8),Qi=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ud={p:Qi,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:nm,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function rm(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),o=Qi,a=t*t%o*t%o,c=ce(a,fc,o)*a%o,l=ce(c,em,o)*t%o,d=ce(l,tm,o)*l%o,u=ce(d,e,o)*d%o,f=ce(u,n,o)*u%o,p=ce(f,r,o)*f%o,g=ce(p,s,o)*p%o,m=ce(g,s,o)*p%o,x=ce(m,e,o)*d%o;return{pow_p_5_8:ce(x,fc,o)*t%o,b2:a}}function sm(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const hc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function om(t,e){const n=Qi,r=he(e*e*e,n),s=he(r*r*e,n),o=rm(t*s).pow_p_5_8;let i=he(t*r*o,n);const a=he(e*i*i,n),c=i,l=he(i*hc,n),d=a===t,u=a===he(-t,n),f=a===he(-t*hc,n);return d&&(i=c),(u||f)&&(i=l),jg(i,n)&&(i=he(-i,n)),{isValid:d||u,value:i}}const im=en(Ud.p,{isLE:!0}),am={...Ud,Fp:im,hash:Ng,adjustScalarBytes:sm,uvRatio:om},ms=Qg(am);class pc extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}}class gc extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class cm extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}const mt={get(t=globalThis){const e=t.crypto;if(e?.subtle==null)throw new cm("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}},ws=32,ct=64,gi=32;let vn;const $d=(async()=>{try{return await mt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function lm(){const t=ms.utils.randomPrivateKey(),e=ms.getPublicKey(t);return{privateKey:mm(t,e),publicKey:e}}async function dm(t,e){let n;t.length===ct?n=t.subarray(0,32):n=t;const r={crv:"Ed25519",kty:"OKP",x:J(t.subarray(32),"base64url"),d:J(n,"base64url"),ext:!0,key_ops:["sign"]},s=await mt.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),o=await mt.get().subtle.sign({name:"Ed25519"},s,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(o,0,o.byteLength)}function um(t,e){const n=t.subarray(0,gi);return ms.sign(e instanceof Uint8Array?e:e.subarray(),n)}async function fm(t,e){return vn==null&&(vn=await $d),vn?dm(t,e):um(t,e)}async function hm(t,e,n){if(t.buffer instanceof ArrayBuffer){const r=await mt.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await mt.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 pm(t,e,n){return ms.verify(e,n instanceof Uint8Array?n:n.subarray(),t)}async function gm(t,e,n){return vn==null&&(vn=await $d),vn?hm(t,e,n):pm(t,e,n)}function mm(t,e){const n=new Uint8Array(ct);for(let r=0;r<gi;r++)n[r]=t[r],n[gi+r]=e[r];return n}function Ks(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}class Hd{type="Ed25519";raw;constructor(e){this.raw=br(e,ws)}toMultihash(){return Cr.digest(Ws(this))}toCID(){return oe.createV1(114,this.toMultihash())}toString(){return Te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ye(this.raw,e.raw)}verify(e,n,r){r?.signal?.throwIfAborted();const s=gm(this.raw,n,e);return Ks(s)?s.then(o=>(r?.signal?.throwIfAborted(),o)):s}}class mi{type="Ed25519";raw;publicKey;constructor(e,n){this.raw=br(e,ct),this.publicKey=new Hd(n)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ye(this.raw,e.raw)}sign(e,n){n?.signal?.throwIfAborted();const r=fm(this.raw,e);return Ks(r)?r.then(s=>(n?.signal?.throwIfAborted(),s)):(n?.signal?.throwIfAborted(),r)}}function wm(t){if(t.length>ct){t=br(t,ct+ws);const r=t.subarray(0,ct),s=t.subarray(ct,t.length);return new mi(r,s)}t=br(t,ct);const e=t.subarray(0,ct),n=t.subarray(ws);return new mi(e,n)}function qd(t){return t=br(t,ws),new Hd(t)}async function ym(){const{privateKey:t,publicKey:e}=lm();return new mi(t,e)}function br(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new Xe(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}const bm=Math.pow(2,7),xm=Math.pow(2,14),vm=Math.pow(2,21),ea=Math.pow(2,28),ta=Math.pow(2,35),na=Math.pow(2,42),ra=Math.pow(2,49),te=128,Ee=127;function tn(t){if(t<bm)return 1;if(t<xm)return 2;if(t<vm)return 3;if(t<ea)return 4;if(t<ta)return 5;if(t<na)return 6;if(t<ra)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Kd(t,e,n=0){switch(tn(t)){case 8:e[n++]=t&255|te,t/=128;case 7:e[n++]=t&255|te,t/=128;case 6:e[n++]=t&255|te,t/=128;case 5:e[n++]=t&255|te,t/=128;case 4:e[n++]=t&255|te,t>>>=7;case 3:e[n++]=t&255|te,t>>>=7;case 2:e[n++]=t&255|te,t>>>=7;case 1:{e[n++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Em(t,e,n=0){switch(tn(t)){case 8:e.set(n++,t&255|te),t/=128;case 7:e.set(n++,t&255|te),t/=128;case 6:e.set(n++,t&255|te),t/=128;case 5:e.set(n++,t&255|te),t/=128;case 4:e.set(n++,t&255|te),t>>>=7;case 3:e.set(n++,t&255|te),t>>>=7;case 2:e.set(n++,t&255|te),t>>>=7;case 1:{e.set(n++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function zd(t,e){let n=t[e],r=0;if(r+=n&Ee,n<te||(n=t[e+1],r+=(n&Ee)<<7,n<te)||(n=t[e+2],r+=(n&Ee)<<14,n<te)||(n=t[e+3],r+=(n&Ee)<<21,n<te)||(n=t[e+4],r+=(n&Ee)*ea,n<te)||(n=t[e+5],r+=(n&Ee)*ta,n<te)||(n=t[e+6],r+=(n&Ee)*na,n<te)||(n=t[e+7],r+=(n&Ee)*ra,n<te))return r;throw new RangeError("Could not decode varint")}function Sm(t,e){let n=t.get(e),r=0;if(r+=n&Ee,n<te||(n=t.get(e+1),r+=(n&Ee)<<7,n<te)||(n=t.get(e+2),r+=(n&Ee)<<14,n<te)||(n=t.get(e+3),r+=(n&Ee)<<21,n<te)||(n=t.get(e+4),r+=(n&Ee)*ea,n<te)||(n=t.get(e+5),r+=(n&Ee)*ta,n<te)||(n=t.get(e+6),r+=(n&Ee)*na,n<te)||(n=t.get(e+7),r+=(n&Ee)*ra,n<te))return r;throw new RangeError("Could not decode varint")}function Am(t,e,n=0){return e==null&&(e=gt(tn(t))),e instanceof Uint8Array?Kd(t,e,n):Em(t,e,n)}function Vd(t,e=0){return t instanceof Uint8Array?zd(t,e):Sm(t,e)}const sa=new Float32Array([-0]),Nt=new Uint8Array(sa.buffer);function km(t,e,n){sa[0]=t,e[n]=Nt[0],e[n+1]=Nt[1],e[n+2]=Nt[2],e[n+3]=Nt[3]}function Tm(t,e){return Nt[0]=t[e],Nt[1]=t[e+1],Nt[2]=t[e+2],Nt[3]=t[e+3],sa[0]}const oa=new Float64Array([-0]),Se=new Uint8Array(oa.buffer);function Cm(t,e,n){oa[0]=t,e[n]=Se[0],e[n+1]=Se[1],e[n+2]=Se[2],e[n+3]=Se[3],e[n+4]=Se[4],e[n+5]=Se[5],e[n+6]=Se[6],e[n+7]=Se[7]}function Im(t,e){return Se[0]=t[e],Se[1]=t[e+1],Se[2]=t[e+2],Se[3]=t[e+3],Se[4]=t[e+4],Se[5]=t[e+5],Se[6]=t[e+6],Se[7]=t[e+7],oa[0]}const Rm=BigInt(Number.MAX_SAFE_INTEGER),Pm=BigInt(Number.MIN_SAFE_INTEGER);class Ae{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 qt;if(e<Rm&&e>Pm)return this.fromNumber(Number(e));const n=e<0n;n&&(e=-e);let r=e>>32n,s=e-(r<<32n);return n&&(r=~r|0n,s=~s|0n,++s>mc&&(s=0n,++r>mc&&(r=0n))),new Ae(Number(s),Number(r))}static fromNumber(e){if(e===0)return qt;const n=e<0;n&&(e=-e);let r=e>>>0,s=(e-r)/4294967296>>>0;return n&&(s=~s>>>0,r=~r>>>0,++r>4294967295&&(r=0,++s>4294967295&&(s=0))),new Ae(r,s)}static from(e){return typeof e=="number"?Ae.fromNumber(e):typeof e=="bigint"?Ae.fromBigInt(e):typeof e=="string"?Ae.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new Ae(e.low>>>0,e.high>>>0):qt}}const qt=new Ae(0,0);qt.toBigInt=function(){return 0n};qt.zzEncode=qt.zzDecode=function(){return this};qt.length=function(){return 1};const mc=4294967296n;function Nm(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 Lm(t,e,n){if(n-e<1)return"";let s;const o=[];let i=0,a;for(;e<n;)a=t[e++],a<128?o[i++]=a:a>191&&a<224?o[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,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Gd(t,e,n){const r=n;let s,o;for(let i=0;i<t.length;++i)s=t.charCodeAt(i),s<128?e[n++]=s:s<2048?(e[n++]=s>>6|192,e[n++]=s&63|128):(s&64512)===55296&&((o=t.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[n++]=s>>18|240,e[n++]=s>>12&63|128,e[n++]=s>>6&63|128,e[n++]=s&63|128):(e[n++]=s>>12|224,e[n++]=s>>6&63|128,e[n++]=s&63|128);return n-r}function qe(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function Hr(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}class Bm{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,qe(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 qe(this,4);return Hr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw qe(this,4);return Hr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw qe(this,4);const e=Tm(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw qe(this,4);const e=Im(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 qe(this,e);return this.pos+=e,n===r?new Uint8Array(0):this.buf.subarray(n,r)}string(){const e=this.bytes();return Lm(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw qe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw qe(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 Ae(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 qe(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 qe(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 qe(this,8);const e=Hr(this.buf,this.pos+=4),n=Hr(this.buf,this.pos+=4);return new Ae(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=zd(this.buf,this.pos);return this.pos+=tn(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 _m(t){return new Bm(t instanceof Uint8Array?t:t.subarray())}function zs(t,e,n){const r=_m(t);return e.decode(r,void 0,n)}function Dm(t){let r,s=8192;return function(i){if(i<1||i>4096)return gt(i);s+i>8192&&(r=gt(8192),s=0);const a=r.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}class ar{fn;len;next;val;constructor(e,n,r){this.fn=e,this.len=n,this.next=void 0,this.val=r}}function bo(){}class Fm{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const Om=Dm();function Mm(t){return globalThis.Buffer!=null?gt(t):Om(t)}class wi{len;head;tail;states;constructor(){this.len=0,this.head=new ar(bo,0,0),this.tail=this.head,this.states=null}_push(e,n,r){return this.tail=this.tail.next=new ar(e,n,r),this.len+=n,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Um((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(qr,10,Ae.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const n=Ae.fromBigInt(e);return this._push(qr,n.length(),n)}uint64Number(e){return this._push(Kd,tn(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=Ae.fromBigInt(e).zzEncode();return this._push(qr,n.length(),n)}sint64Number(e){const n=Ae.fromNumber(e).zzEncode();return this._push(qr,n.length(),n)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(xo,1,e?1:0)}fixed32(e){return this._push(Yn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const n=Ae.fromBigInt(e);return this._push(Yn,4,n.lo)._push(Yn,4,n.hi)}fixed64Number(e){const n=Ae.fromNumber(e);return this._push(Yn,4,n.lo)._push(Yn,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(km,4,e)}double(e){return this._push(Cm,8,e)}bytes(e){const n=e.length>>>0;return n===0?this._push(xo,1,0):this.uint32(n)._push($m,n,e)}string(e){const n=Nm(e);return n!==0?this.uint32(n)._push(Gd,n,e):this._push(xo,1,0)}fork(){return this.states=new Fm(this),this.head=this.tail=new ar(bo,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 ar(bo,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=Mm(this.len);let r=0;for(;e!=null;)e.fn(e.val,n,r),r+=e.len,e=e.next;return n}}function xo(t,e,n){e[n]=t&255}function jm(t,e,n){for(;t>127;)e[n++]=t&127|128,t>>>=7;e[n]=t}class Um extends ar{next;constructor(e,n){super(jm,e,n),this.next=void 0}}function qr(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 Yn(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 $m(t,e,n){e.set(t,n)}globalThis.Buffer!=null&&(wi.prototype.bytes=function(t){const e=t.length>>>0;return this.uint32(e),e>0&&this._push(Hm,e,t),this},wi.prototype.string=function(t){const e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(qm,e,t),this});function Hm(t,e,n){e.set(t,n)}function qm(t,e,n){t.length<40?Gd(t,e,n):e.utf8Write!=null?e.utf8Write(t,n):e.set(fe(t),n)}function Km(){return new wi}function Vs(t,e){const n=Km();return e.encode(t,n,{lengthDelimited:!1}),n.finish()}var ys;(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"})(ys||(ys={}));function Wd(t,e,n,r){return{name:t,type:e,encode:n,decode:r}}function zm(t){function e(s){if(t[s.toString()]==null)throw new Error("Invalid enum value");return t[s]}const n=function(o,i){const a=e(o);i.int32(a)},r=function(o){const i=o.int32();return e(i)};return Wd("enum",ys.VARINT,n,r)}function Gs(t,e){return Wd("message",ys.LENGTH_DELIMITED,t,e)}class wc extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var ie;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(ie||(ie={}));var yi;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(yi||(yi={}));(function(t){t.codec=()=>zm(yi)})(ie||(ie={}));var Wt;(function(t){let e;t.codec=()=>(e==null&&(e=Gs((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),ie.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const o={},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{o.Type=ie.codec().decode(n);break}case 2:{o.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return o})),e),t.encode=n=>Vs(n,t.codec()),t.decode=(n,r)=>zs(n,t.codec(),r)})(Wt||(Wt={}));var bs;(function(t){let e;t.codec=()=>(e==null&&(e=Gs((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),ie.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const o={},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{o.Type=ie.codec().decode(n);break}case 2:{o.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return o})),e),t.encode=n=>Vs(n,t.codec()),t.decode=(n,r)=>zs(n,t.codec(),r)})(bs||(bs={}));const Xd=xd;class Yd{type="RSA";jwk;_raw;_multihash;constructor(e,n){this.jwk=e,this._multihash=n}get raw(){return this._raw==null&&(this._raw=Jd(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return oe.createV1(114,this._multihash)}toString(){return Te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ye(this.raw,e.raw)}verify(e,n,r){return iw(this.jwk,n,e,r)}}class Vm{type="RSA";jwk;_raw;publicKey;constructor(e,n){this.jwk=e,this.publicKey=n}get raw(){return this._raw==null&&(this._raw=Zm(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ye(this.raw,e.raw)}sign(e,n){return ow(this.jwk,e,n)}}const Gm=8192,Zd=18,Wm=1062,Xm=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Ym(t){return{n:J(t[1],"base64url"),e:J(t[2],"base64url"),d:J(t[3],"base64url"),p:J(t[4],"base64url"),q:J(t[5],"base64url"),dp:J(t[6],"base64url"),dq:J(t[7],"base64url"),qi:J(t[8],"base64url"),kty:"RSA"}}function Zm(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 Xe("JWK was missing components");return pt([Be(Uint8Array.from([0])),Be(fe(t.n,"base64url")),Be(fe(t.e,"base64url")),Be(fe(t.d,"base64url")),Be(fe(t.p,"base64url")),Be(fe(t.q,"base64url")),Be(fe(t.dp,"base64url")),Be(fe(t.dq,"base64url")),Be(fe(t.qi,"base64url"))]).subarray()}function Jm(t){const e=$n(t[1],{offset:0});return{kty:"RSA",n:J(e[0],"base64url"),e:J(e[1],"base64url")}}function Jd(t){if(t.n==null||t.e==null)throw new Xe("JWK was missing components");return pt([Xm,Gi(pt([Be(fe(t.n,"base64url")),Be(fe(t.e,"base64url"))]))]).subarray()}function Qm(t){const e=$n(t);return ew(e)}function ew(t){const e=Ym(t);return rw(e)}function tw(t,e){if(t.byteLength>=Wm)throw new Zl("Key size is too large");const n=$n(t,{offset:0});return nw(n,t,e)}function nw(t,e,n){const r=Jm(t);if(n==null){const s=Xd(Wt.encode({Type:ie.RSA,Data:e}));n=Tr(Zd,s)}return new Yd(r,n)}function rw(t){if(aw(t)>Gm)throw new Xe("Key size is too large");const e=sw(t),n=Xd(Wt.encode({Type:ie.RSA,Data:Jd(e.publicKey)})),r=Tr(Zd,n);return new Vm(e.privateKey,new Yd(e.publicKey,r))}function sw(t){if(t==null)throw new Xe("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function ow(t,e,n){const r=await mt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);n?.signal?.throwIfAborted();const s=await mt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function iw(t,e,n,r){const s=await mt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const o=await mt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,e,n instanceof Uint8Array?n:n.subarray());return r?.signal?.throwIfAborted(),o}function aw(t){if(t.kty!=="RSA")throw new Xe("invalid key type");if(t.n==null)throw new Xe("invalid key modulus");return fe(t.n,"base64url").length*8}class Qd extends md{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,pd(e);const r=Wi(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 s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?e.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Nn(o)}update(e){return fs(this),this.iHash.update(e),this}digestInto(e){fs(this),Qt(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:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,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 eu=(t,e,n)=>new Qd(t,e).update(n).digest();eu.create=(t,e)=>new Qd(t,e);const yc=(t,e)=>(t+(t>=0?e:-e)/tu)/e;function cw(t,e,n){const[[r,s],[o,i]]=e,a=yc(i*t,n),c=yc(-s*t,n);let l=t-a*r-c*o,d=-a*s-c*i;const u=l<dt,f=d<dt;u&&(l=-l),f&&(d=-d);const p=Pr(Math.ceil(Sd(n)/2))+En;if(l<dt||l>=p||d<dt||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:f,k2:d}}function bi(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function vo(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return Gt(n.lowS,"lowS"),Gt(n.prehash,"prehash"),n.format!==void 0&&bi(n.format),n}class lw extends Error{constructor(e=""){super(e)}}const lt={Err:lw,_tlv:{encode:(t,e)=>{const{Err:n}=lt;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,s=$r(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const o=r>127?$r(s.length/2|128):"";return $r(t)+o+s+e},decode(t,e){const{Err:n}=lt;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 s=e[r++],o=!!(s&128);let i=0;if(!o)i=s;else{const c=s&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}=lt;if(t<dt)throw new e("integer: negative integers are not allowed");let n=$r(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}=lt;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 qs(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=lt,s=le("signature",t),{v:o,l:i}=r.decode(48,s);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,o),{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}=lt,r=e.encode(2,n.encode(t.r)),s=e.encode(2,n.encode(t.s)),o=r+s;return e.encode(48,o)}},dt=BigInt(0),En=BigInt(1),tu=BigInt(2),Kr=BigInt(3),dw=BigInt(4);function mn(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let s=le("private key",e);try{r=t.fromBytes(s)}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 uw(t,e={}){const n=jd("weierstrass",t,e),{Fp:r,Fn:s}=n;let o=n.CURVE;const{h:i,n:a}=o;Nr(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=ru(r,s);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(N,w,b){const{x:k,y:B}=w.toAffine(),M=r.toBytes(k);if(Gt(b,"isCompressed"),b){d();const U=!r.isOdd(B);return et(nu(U),M)}else return et(Uint8Array.of(4),M,r.toBytes(B))}function f(N){ze(N,void 0,"Point");const{publicKey:w,publicKeyUncompressed:b}=l,k=N.length,B=N[0],M=N.subarray(1);if(k===w&&(B===2||B===3)){const U=r.fromBytes(M);if(!r.isValid(U))throw new Error("bad point: is not on curve, wrong x");const D=m(U);let I;try{I=r.sqrt(D)}catch(K){const q=K instanceof Error?": "+K.message:"";throw new Error("bad point: is not on curve, sqrt error"+q)}d();const F=r.isOdd(I);return(B&1)===1!==F&&(I=r.neg(I)),{x:U,y:I}}else if(k===b&&B===4){const U=r.BYTES,D=r.fromBytes(M.subarray(0,U)),I=r.fromBytes(M.subarray(U,U*2));if(!x(D,I))throw new Error("bad point: is not on curve");return{x:D,y:I}}else throw new Error(`bad point: got length ${k}, expected compressed=${w} or uncompressed=${b}`)}const p=e.toBytes||u,g=e.fromBytes||f;function m(N){const w=r.sqr(N),b=r.mul(w,N);return r.add(r.add(b,r.mul(N,o.a)),o.b)}function x(N,w){const b=r.sqr(w),k=m(N);return r.eql(b,k)}if(!x(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const y=r.mul(r.pow(o.a,Kr),dw),T=r.mul(r.sqr(o.b),BigInt(27));if(r.is0(r.add(y,T)))throw new Error("bad curve params: a or b");function v(N,w,b=!1){if(!r.isValid(w)||b&&r.is0(w))throw new Error(`bad point coordinate ${N}`);return w}function A(N){if(!(N instanceof E))throw new Error("ProjectivePoint expected")}function _(N){if(!c||!c.basises)throw new Error("no endo");return cw(N,c.basises,s.ORDER)}const C=ps((N,w)=>{const{X:b,Y:k,Z:B}=N;if(r.eql(B,r.ONE))return{x:b,y:k};const M=N.is0();w==null&&(w=M?r.ONE:r.inv(B));const U=r.mul(b,w),D=r.mul(k,w),I=r.mul(B,w);if(M)return{x:r.ZERO,y:r.ZERO};if(!r.eql(I,r.ONE))throw new Error("invZ was invalid");return{x:U,y:D}}),L=ps(N=>{if(N.is0()){if(e.allowInfinityPoint&&!r.is0(N.Y))return;throw new Error("bad point: ZERO")}const{x:w,y:b}=N.toAffine();if(!r.isValid(w)||!r.isValid(b))throw new Error("bad point: x or y not field elements");if(!x(w,b))throw new Error("bad point: equation left != right");if(!N.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function R(N,w,b,k,B){return b=new E(r.mul(b.X,N),b.Y,b.Z),w=gs(k,w),b=gs(B,b),w.add(b)}class E{constructor(w,b,k){this.X=v("x",w),this.Y=v("y",b,!0),this.Z=v("z",k),Object.freeze(this)}static CURVE(){return o}static fromAffine(w){const{x:b,y:k}=w||{};if(!w||!r.isValid(b)||!r.isValid(k))throw new Error("invalid affine point");if(w instanceof E)throw new Error("projective point not allowed");return r.is0(b)&&r.is0(k)?E.ZERO:new E(b,k,r.ONE)}static fromBytes(w){const b=E.fromAffine(g(ze(w,void 0,"point")));return b.assertValidity(),b}static fromHex(w){return E.fromBytes(le("pointHex",w))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,b=!0){return P.createCache(this,w),b||this.multiply(Kr),this}assertValidity(){L(this)}hasEvenY(){const{y:w}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(w)}equals(w){A(w);const{X:b,Y:k,Z:B}=this,{X:M,Y:U,Z:D}=w,I=r.eql(r.mul(b,D),r.mul(M,B)),F=r.eql(r.mul(k,D),r.mul(U,B));return I&&F}negate(){return new E(this.X,r.neg(this.Y),this.Z)}double(){const{a:w,b}=o,k=r.mul(b,Kr),{X:B,Y:M,Z:U}=this;let D=r.ZERO,I=r.ZERO,F=r.ZERO,O=r.mul(B,B),K=r.mul(M,M),q=r.mul(U,U),H=r.mul(B,M);return H=r.add(H,H),F=r.mul(B,U),F=r.add(F,F),D=r.mul(w,F),I=r.mul(k,q),I=r.add(D,I),D=r.sub(K,I),I=r.add(K,I),I=r.mul(D,I),D=r.mul(H,D),F=r.mul(k,F),q=r.mul(w,q),H=r.sub(O,q),H=r.mul(w,H),H=r.add(H,F),F=r.add(O,O),O=r.add(F,O),O=r.add(O,q),O=r.mul(O,H),I=r.add(I,O),q=r.mul(M,U),q=r.add(q,q),O=r.mul(q,H),D=r.sub(D,O),F=r.mul(q,K),F=r.add(F,F),F=r.add(F,F),new E(D,I,F)}add(w){A(w);const{X:b,Y:k,Z:B}=this,{X:M,Y:U,Z:D}=w;let I=r.ZERO,F=r.ZERO,O=r.ZERO;const K=o.a,q=r.mul(o.b,Kr);let H=r.mul(b,M),G=r.mul(k,U),W=r.mul(B,D),X=r.add(b,k),V=r.add(M,U);X=r.mul(X,V),V=r.add(H,G),X=r.sub(X,V),V=r.add(b,B);let Z=r.add(M,D);return V=r.mul(V,Z),Z=r.add(H,W),V=r.sub(V,Z),Z=r.add(k,B),I=r.add(U,D),Z=r.mul(Z,I),I=r.add(G,W),Z=r.sub(Z,I),O=r.mul(K,V),I=r.mul(q,W),O=r.add(I,O),I=r.sub(G,O),O=r.add(G,O),F=r.mul(I,O),G=r.add(H,H),G=r.add(G,H),W=r.mul(K,W),V=r.mul(q,V),G=r.add(G,W),W=r.sub(H,W),W=r.mul(K,W),V=r.add(V,W),H=r.mul(G,V),F=r.add(F,H),H=r.mul(Z,V),I=r.mul(X,I),I=r.sub(I,H),H=r.mul(X,G),O=r.mul(Z,O),O=r.add(O,H),new E(I,F,O)}subtract(w){return this.add(w.negate())}is0(){return this.equals(E.ZERO)}multiply(w){const{endo:b}=e;if(!s.isValidNot0(w))throw new Error("invalid scalar: out of range");let k,B;const M=U=>P.cached(this,U,D=>jt(E,D));if(b){const{k1neg:U,k1:D,k2neg:I,k2:F}=_(w),{p:O,f:K}=M(D),{p:q,f:H}=M(F);B=K.add(H),k=R(b.beta,O,q,U,I)}else{const{p:U,f:D}=M(w);k=U,B=D}return jt(E,[k,B])[0]}multiplyUnsafe(w){const{endo:b}=e,k=this;if(!s.isValid(w))throw new Error("invalid scalar: out of range");if(w===dt||k.is0())return E.ZERO;if(w===En)return k;if(P.hasCache(this))return this.multiply(w);if(b){const{k1neg:B,k1:M,k2neg:U,k2:D}=_(w),{p1:I,p2:F}=Vg(E,k,M,D);return R(b.beta,I,F,B,U)}else return P.unsafe(k,w)}multiplyAndAddUnsafe(w,b,k){const B=this.multiplyUnsafe(b).add(w.multiplyUnsafe(k));return B.is0()?void 0:B}toAffine(w){return C(this,w)}isTorsionFree(){const{isTorsionFree:w}=e;return i===En?!0:w?w(E,this):P.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:w}=e;return i===En?this:w?w(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(w=!0){return Gt(w,"isCompressed"),this.assertValidity(),p(E,this,w)}toHex(w=!0){return Ht(this.toBytes(w))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(w=!0){return this.toBytes(w)}_setWindowSize(w){this.precompute(w)}static normalizeZ(w){return jt(E,w)}static msm(w,b){return Md(E,s,w,b)}static fromPrivateKey(w){return E.BASE.multiply(mn(s,w))}}E.BASE=new E(o.Gx,o.Gy,r.ONE),E.ZERO=new E(r.ZERO,r.ONE,r.ZERO),E.Fp=r,E.Fn=s;const S=s.BITS,P=new Od(E,e.endo?Math.ceil(S/2):S);return E.BASE.precompute(8),E}function nu(t){return Uint8Array.of(t?2:3)}function ru(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function fw(t,e={}){const{Fn:n}=t,r=e.randomBytes||Xi,s=Object.assign(ru(t.Fp,n),{seed:_d(n.ORDER)});function o(p){try{return!!mn(n,p)}catch{return!1}}function i(p,g){const{publicKey:m,publicKeyUncompressed:x}=s;try{const y=p.length;return g===!0&&y!==m||g===!1&&y!==x?!1:!!t.fromBytes(p)}catch{return!1}}function a(p=r(s.seed)){return qg(ze(p,s.seed,"seed"),n.ORDER)}function c(p,g=!0){return t.BASE.multiply(mn(n,p)).toBytes(g)}function l(p){const g=a(p);return{secretKey:g,publicKey:c(g)}}function d(p){if(typeof p=="bigint")return!1;if(p instanceof t)return!0;const{secretKey:g,publicKey:m,publicKeyUncompressed:x}=s;if(n.allowedLengths||g===m)return;const y=le("key",p).length;return y===m||y===x}function u(p,g,m=!0){if(d(p)===!0)throw new Error("first arg must be private key");if(d(g)===!1)throw new Error("second arg must be public key");const x=mn(n,p);return t.fromHex(g).multiply(x).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:t,utils:{isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:p=>mn(n,p),precompute(p=8,g=t.BASE){return g.precompute(p,!1)}},lengths:s})}function hw(t,e,n={}){pd(e),Nr(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Xi,s=n.hmac||((b,...k)=>eu(e,b,et(...k))),{Fp:o,Fn:i}=t,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:p}=fw(t,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function x(b){const k=a>>En;return b>k}function y(b,k){if(!i.isValidNot0(k))throw new Error(`invalid signature ${b}: out of range 1..Point.Fn.ORDER`);return k}function T(b,k){bi(k);const B=p.signature,M=k==="compact"?B:k==="recovered"?B+1:void 0;return ze(b,M,`${k} signature`)}class v{constructor(k,B,M){this.r=y("r",k),this.s=y("s",B),M!=null&&(this.recovery=M),Object.freeze(this)}static fromBytes(k,B=m){T(k,B);let M;if(B==="der"){const{r:F,s:O}=lt.toSig(ze(k));return new v(F,O)}B==="recovered"&&(M=k[0],B="compact",k=k.subarray(1));const U=i.BYTES,D=k.subarray(0,U),I=k.subarray(U,U*2);return new v(i.fromBytes(D),i.fromBytes(I),M)}static fromHex(k,B){return this.fromBytes(hs(k),B)}addRecoveryBit(k){return new v(this.r,this.s,k)}recoverPublicKey(k){const B=o.ORDER,{r:M,s:U,recovery:D}=this;if(D==null||![0,1,2,3].includes(D))throw new Error("recovery id invalid");if(a*tu<B&&D>1)throw new Error("recovery id is ambiguous for h>1 curve");const F=D===2||D===3?M+a:M;if(!o.isValid(F))throw new Error("recovery id 2 or 3 invalid");const O=o.toBytes(F),K=t.fromBytes(et(nu((D&1)===0),O)),q=i.inv(F),H=_(le("msgHash",k)),G=i.create(-H*q),W=i.create(U*q),X=t.BASE.multiplyUnsafe(G).add(K.multiplyUnsafe(W));if(X.is0())throw new Error("point at infinify");return X.assertValidity(),X}hasHighS(){return x(this.s)}toBytes(k=m){if(bi(k),k==="der")return hs(lt.hexFromSig(this));const B=i.toBytes(this.r),M=i.toBytes(this.s);if(k==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return et(Uint8Array.of(this.recovery),B,M)}return et(B,M)}toHex(k){return Ht(this.toBytes(k))}assertValidity(){}static fromCompact(k){return v.fromBytes(le("sig",k),"compact")}static fromDER(k){return v.fromBytes(le("sig",k),"der")}normalizeS(){return this.hasHighS()?new v(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Ht(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ht(this.toBytes("compact"))}}const A=n.bits2int||function(k){if(k.length>8192)throw new Error("input is too large");const B=qs(k),M=k.length*8-c;return M>0?B>>BigInt(M):B},_=n.bits2int_modN||function(k){return i.create(A(k))},C=Pr(c);function L(b){return pi("num < 2^"+c,b,dt,C),i.toBytes(b)}function R(b,k){return ze(b,void 0,"message"),k?ze(e(b),void 0,"prehashed message"):b}function E(b,k,B){if(["recovered","canonical"].some(G=>G in B))throw new Error("sign() legacy options not supported");const{lowS:M,prehash:U,extraEntropy:D}=vo(B,g);b=R(b,U);const I=_(b),F=mn(i,k),O=[L(F),L(I)];if(D!=null&&D!==!1){const G=D===!0?r(p.secretKey):D;O.push(le("extraEntropy",G))}const K=et(...O),q=I;function H(G){const W=A(G);if(!i.isValidNot0(W))return;const X=i.inv(W),V=t.BASE.multiply(W).toAffine(),Z=i.create(V.x);if(Z===dt)return;const ke=i.create(X*i.create(q+Z*F));if(ke===dt)return;let Fe=(V.x===Z?0:2)|Number(V.y&En),rt=ke;return M&&x(ke)&&(rt=i.neg(ke),Fe^=1),new v(Z,rt,Fe)}return{seed:K,k2sig:H}}function S(b,k,B={}){b=le("message",b);const{seed:M,k2sig:U}=E(b,k,B);return Bg(e.outputLen,i.BYTES,s)(M,U)}function P(b){let k;const B=typeof b=="string"||Rr(b),M=!B&&b!==null&&typeof b=="object"&&typeof b.r=="bigint"&&typeof b.s=="bigint";if(!B&&!M)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(M)k=new v(b.r,b.s);else if(B){try{k=v.fromBytes(le("sig",b),"der")}catch(U){if(!(U instanceof lt.Err))throw U}if(!k)try{k=v.fromBytes(le("sig",b),"compact")}catch{return!1}}return k||!1}function N(b,k,B,M={}){const{lowS:U,prehash:D,format:I}=vo(M,g);if(B=le("publicKey",B),k=R(le("message",k),D),"strict"in M)throw new Error("options.strict was renamed to lowS");const F=I===void 0?P(b):v.fromBytes(le("sig",b),I);if(F===!1)return!1;try{const O=t.fromBytes(B);if(U&&F.hasHighS())return!1;const{r:K,s:q}=F,H=_(k),G=i.inv(q),W=i.create(H*G),X=i.create(K*G),V=t.BASE.multiplyUnsafe(W).add(O.multiplyUnsafe(X));return V.is0()?!1:i.create(V.x)===K}catch{return!1}}function w(b,k,B={}){const{prehash:M}=vo(B,g);return k=R(k,M),v.fromBytes(b,"recovered").recoverPublicKey(k).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:p,Point:t,sign:S,verify:N,recoverPublicKey:w,Signature:v,hash:e})}function pw(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 s=en(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),o={Fp:n,Fn:s,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:o}}function gw(t){const{CURVE:e,curveOpts:n}=pw(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 mw(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,Ld(n.Fn.ORDER,n.Fn.BITS))})}function ww(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:s}=gw(t),o=uw(e,n),i=hw(o,r,s);return mw(t,i)}function yw(t,e){const n=r=>ww({...t,hash:r});return{...n(e),create:n}}const ia={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},bw={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},bc=BigInt(2);function xw(t){const e=ia.p,n=BigInt(3),r=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,u=ce(d,n,e)*d%e,f=ce(u,n,e)*d%e,p=ce(f,bc,e)*l%e,g=ce(p,s,e)*p%e,m=ce(g,o,e)*g%e,x=ce(m,a,e)*m%e,y=ce(x,c,e)*x%e,T=ce(y,a,e)*m%e,v=ce(T,n,e)*d%e,A=ce(v,i,e)*g%e,_=ce(A,r,e)*l%e,C=ce(_,bc,e);if(!xi.eql(xi.sqr(C),t))throw new Error("Cannot find square root");return C}const xi=en(ia.p,{sqrt:xw}),Bt=yw({...ia,Fp:xi,lowS:!0,endo:bw},xd);function vw(t,e,n){const r=Vi.digest(e instanceof Uint8Array?e:e.subarray());if(Ks(r))return r.then(({digest:s})=>(n?.signal?.throwIfAborted(),Bt.sign(s,t).toDERRawBytes())).catch(s=>{throw s.name==="AbortError"?s:new pc(String(s))});try{return Bt.sign(r.digest,t).toDERRawBytes()}catch(s){throw new pc(String(s))}}function Ew(t,e,n,r){const s=Vi.digest(n instanceof Uint8Array?n:n.subarray());if(Ks(s))return s.then(({digest:o})=>(r?.signal?.throwIfAborted(),Bt.verify(e,o,t))).catch(o=>{throw o.name==="AbortError"?o:new gc(String(o))});try{return r?.signal?.throwIfAborted(),Bt.verify(e,s.digest,t)}catch(o){throw new gc(String(o))}}class su{type="secp256k1";raw;_key;constructor(e){this._key=Cw(e),this.raw=kw(this._key)}toMultihash(){return Cr.digest(Ws(this))}toCID(){return oe.createV1(114,this.toMultihash())}toString(){return Te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ye(this.raw,e.raw)}verify(e,n,r){return Ew(this._key,n,e,r)}}class Sw{type="secp256k1";raw;publicKey;constructor(e,n){this.raw=Tw(e),this.publicKey=new su(n??Iw(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ye(this.raw,e.raw)}sign(e,n){return vw(this.raw,e,n)}}function Aw(t){return new Sw(t)}function ou(t){return new su(t)}function kw(t){return Bt.ProjectivePoint.fromHex(t).toRawBytes(!0)}function Tw(t){try{return Bt.getPublicKey(t,!0),t}catch(e){throw new Jl(String(e))}}function Cw(t){try{return Bt.ProjectivePoint.fromHex(t),t}catch(e){throw new Zl(String(e))}}function Iw(t){try{return Bt.getPublicKey(t,!0)}catch(e){throw new Jl(String(e))}}async function Rw(t,e){return ym()}function vi(t,e){const{Type:n,Data:r}=Wt.decode(t),s=r??new Uint8Array;switch(n){case ie.RSA:return tw(s,e);case ie.Ed25519:return qd(s);case ie.secp256k1:return ou(s);case ie.ECDSA:return fd(s);default:throw new js}}function Pw(t){const{Type:e,Data:n}=Wt.decode(t.digest),r=n??new Uint8Array;switch(e){case ie.Ed25519:return qd(r);case ie.secp256k1:return ou(r);case ie.ECDSA:return fd(r);default:throw new js}}function Ws(t){return Wt.encode({Type:ie[t.type],Data:t.raw})}function Nw(t){const e=bs.decode(t),n=e.Data??new Uint8Array;switch(e.Type){case ie.RSA:return Qm(n);case ie.Ed25519:return wm(n);case ie.secp256k1:return Aw(n);case ie.ECDSA:return ag(n);default:throw new js}}function Lw(t){return bs.encode({Type:ie[t.type],Data:t.raw})}const iu=Symbol.for("nodejs.util.inspect.custom"),Bw=114;class aa{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()})`}[Ql]=!0;toString(){return this.string==null&&(this.string=Te.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return oe.createV1(Bw,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Ye(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Ye(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[iu](){return`PeerId(${this.toString()})`}}class au extends aa{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class cu extends aa{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class lu extends aa{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}const _w=2336;class du{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Cr.digest(fe(this.url))}[iu](){return`PeerId(${this.url})`}[Ql]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return oe.createV1(_w,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=J(e)),e.toString()===this.toString())}}const Dw=114,xc=2336;function Fw(t,e){let n;if(t.charAt(0)==="1"||t.charAt(0)==="Q")n=nd(Te.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return Ow(oe.parse(t));throw new Xe('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return uu(n)}function Bn(t){if(t.type==="Ed25519")return new cu({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new lu({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new au({multihash:t.toCID().multihash,publicKey:t});throw new js}function uu(t){if(jw(t))return new au({multihash:t});if(Mw(t))try{const e=Pw(t);if(e.type==="Ed25519")return new cu({multihash:t,publicKey:e});if(e.type==="secp256k1")return new lu({multihash:t,publicKey:e})}catch{const n=J(t.digest);return new du(new URL(n))}throw new bh("Supplied PeerID Multihash is invalid")}function Ow(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==Dw&&t.code!==xc)throw new yh("Supplied PeerID CID is invalid");if(t.code===xc){const e=J(t.multihash.digest);return new du(new URL(e))}return uu(t.multihash)}function Mw(t){return t.code===Cr.code}function jw(t){return t.code===Vi.code}class fu extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class Uw extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class Zn extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class vc extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}}class $w extends Event{data;constructor(e,n){super("message",n),this.data=e}}class ca extends Event{error;local;constructor(e,n,r){super("close",r),this.error=n,this.local=e}}class Hw extends ca{constructor(e,n){super(!0,e,n)}}class qw extends ca{constructor(e,n){super(!1,e,n)}}const Kw=t=>t/2**32|0,zw=t=>t>>>0;function Vw(t,e,n,r){const s=Kw(n),o=zw(n);t.setUint32(e,r?o:s,r),t.setUint32(e+4,r?s:o,r)}function Ei(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const Si=t=>t?`"${t}" `:"";function wt(t,e=""){if(typeof t!="number")throw new TypeError(Si(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(Si(e)+"expected integer >= 0, got "+t);return t}function yt(t,e,n=""){if(Ei(t)&&(e===void 0||t.length===e))return t;e!==void 0&&wt(e,"length");const r=Ei(t),s=e!==void 0?` of length ${e}`:"",o=r?`length=${t.length}`:`type=${typeof t}`,i=Si(n)+"expected Uint8Array"+s+", got "+o;throw r?new RangeError(i):new TypeError(i)}function la(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(wt(t.outputLen),wt(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}const Gw=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)},Ec=(t,e)=>{Gw(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 xs(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function hu(t,e){yt(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function fS(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Kt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Eo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Je(t,e){return t<<32-e|t>>>e}function hS(t,e){return t<<e|t>>>32-e>>>0}const Ww=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Xw(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Yw(t){for(let e=0;e<t.length;e++)t[e]=Xw(t[e]);return t}const pS=Ww?t=>t:Yw,pu=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Zw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function da(t){if(yt(t),pu)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Zw[t[n]];return e}function Sc(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function gu(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(pu)try{return Uint8Array.fromHex(t)}catch(s){throw s instanceof SyntaxError?new RangeError(s.message):s}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 s=0,o=0;s<n;s++,o+=2){const i=Sc(t.charCodeAt(o)),a=Sc(t.charCodeAt(o+1));if(i===void 0||a===void 0){const c=t[o]+t[o+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+o)}r[s]=i*16+a}return r}function Jw(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 gS(t,e,n,r){if(wt(t,"iters"),wt(e,"tick"),typeof n!="function")throw new TypeError("callback must be a function");let s=Date.now();for(let o=0;o<t;o++){n(o);const i=Date.now()-s;i>=0&&i<e||(await Jw(r),s=Date.now())}}function Qw(t){if(typeof t!="string")throw new TypeError("string expected");const e=new TextEncoder().encode(t);try{return new Uint8Array(e)}finally{Kt(e)}}function mS(t,e=""){return typeof t=="string"?Qw(t):yt(t,void 0,e)}function ey(t,e,n="opts"){return Ec(t,"defaults"),e!==void 0&&Ec(e,n),Object.assign(Object.create(null),t,e)}function ty(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=ey({},e,"info");const n=(s,o)=>t(o).update(s).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=s=>t(s),Object.assign(n,e),Object.freeze(n)}function ny(t=32){wt(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 ry=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function sy(t,e,n){return t&e^~t&n}function oy(t,e,n){return t&e^t&n^e&n}class iy{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,n,r,s){this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Eo(this.buffer)}update(e){xs(this),yt(e);const{view:n,buffer:r,blockLen:s}=this,o=e.length;let i=!1;for(let a=0;a<o;){const c=Math.min(s-this.pos,o-a);if(c===s){const l=Eo(e);for(;s<=o-a;a+=s)this.process(l,a);i=!0;continue}r.set(a===0&&c===o?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===s&&(this.process(n,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){xs(this),hu(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:s,isLE:o}=this;let{pos:i}=this;n[i++]=128,n.fill(0,i),this.padOffset>s-i&&(this.process(r,0),n.fill(0)),Vw(r,s-8,this.length*8,o),this.process(r,0),this.roundClean();const a=e===n?r:Eo(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],o)}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:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=r,e.pos=i,i&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const ay=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),cy=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]),kt=new Uint32Array(64);class ly extends iy{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:s,E:o,F:i,G:a,H:c}=this;return[e,n,r,s,o,i,a,c]}set(e,n,r,s,o,i,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=o|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)kt[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const f=kt[u-15],p=kt[u-2],g=Je(f,7)^Je(f,18)^f>>>3,m=Je(p,17)^Je(p,19)^p>>>10;kt[u]=m+kt[u-7]+g+kt[u-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=Je(a,6)^Je(a,11)^Je(a,25),p=d+f+sy(a,c,l)+cy[u]+kt[u]|0,m=(Je(r,2)^Je(r,13)^Je(r,22))+oy(r,s,o)|0;d=l,l=c,c=a,a=i+p|0,i=o,o=s,s=r,r=p+m|0}r=r+this.A|0,s=s+this.B|0,o=o+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,s,o,i,a,c,l,d)}roundClean(){Kt(kt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Kt(this.buffer)}}class dy extends ly{constructor(){super(32,ay)}}const So=ty(()=>new dy,ry(1));function mu(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 Sn=(t,e,n)=>yt(t,e,n),wu=wt;function An(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 hr(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}const uy=da,fy=t=>gu(t),yu=Ei,bu=t=>ny(t),vs=BigInt(0),Ac=BigInt(1),hy=t=>t?`"${t}" `:"";function Xs(t,e=""){if(typeof t!="boolean")throw new TypeError(hy(e)+"expected boolean, got type="+typeof t);return t}function py(t){if(typeof t=="bigint"){if(!zt(t))throw new RangeError("positive bigint expected, got "+t)}else wu(t);return t}function Ai(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 xu(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?vs:BigInt("0x"+t)}function vu(t){return xu(da(t))}function Es(t){return xu(da(xr(yt(t)).reverse()))}function Eu(t,e){if(wt(e),e===0)throw new Error("zero output length is invalid");t=py(t);const n=e*2,r=t.toString(16);if(r.length>n)throw new RangeError("number is too large");return gu(r.padStart(n,"0"))}function Su(t,e){return Eu(t,e).reverse()}function xr(t){return Uint8Array.from(Sn(t))}function zt(t){return typeof t=="bigint"&&vs<=t}function Au(t,e,n){return zt(t)&&zt(e)&&zt(n)&&e<=t&&t<n}function pr(t,e,n,r){if(!Au(e,n,r))throw new RangeError("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function gy(t){if(t<vs)throw new Error("expected non-negative bigint, got "+t);return t===vs?0:t.toString(2).length}const my=t=>(Ai(t,"n"),(Ac<<BigInt(t))-Ac);function Ss(t,e={},n={},r="object"){An(t,r),An(e,"fields"),An(n,"optFields");function s(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 o=(i,a)=>Object.entries(i).forEach(([c,l])=>s(c,l,a));o(e,!1),o(n,!0)}const me=BigInt(0),se=BigInt(1),Ut=BigInt(2),ku=BigInt(3),ua=BigInt(4),Tu=BigInt(5),wy=BigInt(7),Cu=BigInt(8),yy=BigInt(9),by=BigInt(15),Iu=BigInt(16),xy=BigInt("0x10000000000000000");function re(t,e){if(e<=me)throw new Error("mod: expected positive modulus, got "+e);const n=t%e;return n>=me?n:e+n}function vy(t,e,n){if(n<=se)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<me)throw new Error("invalid exponent, negatives unsupported");if(e===me)return se;if(e===se)return t;let r=t%n;if(r<me&&(r+=n),e<xy){let a=se;for(;e>me;)e&se&&(a=a*r%n),r=r*r%n,e>>=se;return a}const s=[];for(;e>me;)s.push(Number(e&by)),e>>=ua;const o=new Array(16);o[0]=se,o[1]=r;for(let a=2;a<16;a++)o[a]=o[a-1]*r%n;let i=o[s[s.length-1]];for(let a=s.length-2;a>=0;a--){i=i*i%n,i=i*i%n,i=i*i%n,i=i*i%n;const c=s[a];c!==0&&(i=i*o[c]%n)}return i}function Ke(t,e,n){if(n<=se)throw new Error("pow2: expected modulus > 1, got "+n);if(e<me)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >me;)r*=r,r%=n;return r}function kc(t,e){if(t===me)throw new Error("invert: expected non-zero number");if(e<=se)throw new Error("invert: expected modulus > 1, got "+e);let n=re(t,e),r=e,s=me,o=se;for(;n!==me;){const a=r/n,c=r-n*a,l=s-o*a;r=n,n=c,s=o,o=l}if(r!==se)throw new Error("invert: does not exist");return re(s,e)}function fa(t,e,n){const r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function ha(t,e){if((t&se)===me)throw new Error(e+": expected odd modulus, got "+t)}function Ru(t,e){const n=t,r=(n.ORDER+se)/ua,s=n.pow(e,r);return fa(n,s,e),s}function Ey(t,e){const n=t,r=(n.ORDER-Tu)/Cu,s=n.mul(e,Ut),o=n.pow(s,r),i=n.mul(e,o),a=n.mul(n.mul(i,Ut),o),c=n.mul(i,n.sub(a,n.ONE));return fa(n,c,e),c}function Sy(t){const e=pa(t),n=Pu(t),r=n(e,e.neg(e.ONE)),s=n(e,r),o=n(e,e.neg(r)),i=(t+wy)/Iu;return((a,c)=>{const l=a;let d=l.pow(c,i),u=l.mul(d,r);const f=l.mul(d,s),p=l.mul(d,o),g=l.eql(l.sqr(u),c),m=l.eql(l.sqr(f),c);d=l.cmov(d,u,g),u=l.cmov(p,f,m);const x=l.eql(l.sqr(u),c),y=l.cmov(d,u,x);return fa(l,y,c),y})}function Pu(t){if(t<ku)throw new Error("sqrt is not defined for small field");ha(t,"tonelliShanks");let e=t-se,n=0;for(;e%Ut===me;)e/=Ut,n++;let r=Ut;const s=pa(t);for(;As(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Ru;let o=s.pow(r,e);const i=(e+se)/Ut;return function(c,l){const d=c;if(d.is0(l))return l;if(As(d,l)!==1)throw new Error("Cannot find square root");let u=n,f=d.mul(d.ONE,o),p=d.pow(l,e),g=d.pow(l,i);for(;!d.eql(p,d.ONE);){if(d.is0(p))throw new Error("Cannot find square root: probably non-prime P");let m=1,x=d.sqr(p);for(;!d.eql(x,d.ONE);)if(m++,x=d.sqr(x),m===u)throw new Error("Cannot find square root");const y=se<<BigInt(u-m-1),T=d.pow(f,y);u=m,f=d.sqr(T),p=d.mul(p,f),g=d.mul(g,T)}return g}}function Ay(t){return ha(t,"Fp.sqrt"),t%ua===ku?Ru:t%Cu===Tu?Ey:t%Iu===yy?Sy(t):Pu(t)}const ky=(t,e)=>(re(t,e)&se)===se,Ty=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function vr(t){if(An(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);Ai(t.BYTES,"BYTES"),Ai(t.BITS,"BITS");for(const e of Ty)hr(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=se)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Nu(t,e,n=!1){vr(t),mu(e,"nums"),Xs(n,"passZero");const r=t,s=new Array(e.length).fill(n?r.ZERO:void 0),o=e.reduce((a,c,l)=>r.is0(c)?a:(s[l]=a,r.mul(a,c)),r.ONE),i=r.inv(o);return e.reduceRight((a,c,l)=>r.is0(c)?a:(s[l]=r.mul(a,s[l]),r.mul(a,c)),i),s}function As(t,e){vr(t);const n=t;ha(n.ORDER,"FpLegendre");const r=(n.ORDER-se)/Ut,s=n.pow(e,r),o=n.eql(s,n.ONE),i=n.eql(s,n.ZERO),a=n.eql(s,n.neg(n.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Cy(t,e){if(e!==void 0&&wu(e),t<=me)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=gy(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,s=Math.ceil(r/8);return{nBitLength:r,nByteLength:s}}const Tc=new WeakMap;class Cc{ORDER;BITS;BYTES;isLE;ZERO=me;ONE=se;_lengths;_mod;constructor(e,n={}){if(e<=se)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:s,nByteLength:o}=Cy(e,r);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,Object.freeze(this)}create(e){return re(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return me<=e&&e<this.ORDER}is0(e){return e===me}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&se)===se}neg(e){return re(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return re(e*e,this.ORDER)}add(e,n){return re(e+n,this.ORDER)}sub(e,n){return re(e-n,this.ORDER)}mul(e,n){return re(e*n,this.ORDER)}pow(e,n){return vy(e,n,this.ORDER)}div(e,n){return re(e*kc(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 kc(e,this.ORDER)}sqrt(e){let n=Tc.get(this);return n||Tc.set(this,n=Ay(this.ORDER)),n(this,e)}toBytes(e){return this.isLE?Su(e,this.BYTES):Eu(e,this.BYTES)}fromBytes(e,n=!1){Sn(e);const{_lengths:r,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);const l=new Uint8Array(s);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let c=o?Es(e):vu(e);if(a&&(c=re(c,i)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Nu(this,e,!0)}cmov(e,n,r){return Xs(r,"condition"),r?n:e}}function pa(t,e={}){return Object.freeze(Cc.prototype),new Cc(t,e)}const ga=BigInt(0),Er=BigInt(1),Iy=BigInt(4),Ao=16,Ic=128,Ry=5,Rc=2**31;function ma(t){const e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);hr(e.fromAffine,"Point.fromAffine"),hr(e.fromBytes,"Point.fromBytes"),hr(e.fromHex,"Point.fromHex"),An(e.BASE,"Point.BASE"),An(e.ZERO,"Point.ZERO"),vr(e.Fp),vr(e.Fn)}function Py(t,e){ma(t),Lu(e,t);const n=Nu(t.Fp,e.map(r=>r.Z));return e.map((r,s)=>t.fromAffine(r.toAffine(n[s])))}function Ny(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 Ly(t,e){const n=t*(4*e+128);if(n>Rc)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+Rc/2**20+" MiB")}function By(t,e){if(t!==void 0){hr(t,"randomBytes");try{const n=t(e);if(!yu(n)||n.length!==e)return}catch{return}return t}}function Lu(t,e){mu(t,"points"),t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function _y(t,e,n){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,s)=>{if(!(n===void 0?e.isValid(r):zt(r)&&r<n))throw new Error("invalid scalar at index "+s)})}const Bu=new WeakMap;function ko(t){return Bu.get(t)||1}function Dy(t,e){const n=t.double(),r=[t];for(let s=1;s<e;s++)r.push(r[s-1].add(n));return r}function Fy(t,e){const n=2**e,r=n/2,s=BigInt(n-1),o=[];for(;t>ga;){let i=0;t&Er&&(i=Number(t&s),i>=r&&(i-=n),t-=BigInt(i)),o.push(i),t>>=Er}return o}function Oy(t,e,n){const r=2**e,s=r/2,o=BigInt(r-1),i=BigInt(e),a=[];for(let c=0;c<n;c++){let l=Number(t&o);t>>=i,l>s&&(l-=r,t+=Er),a.push(l)}if(t!==ga)throw new Error("invalid wnaf");return a}function My(t,e,n){let r=0;for(const o of n)r=Math.max(r,o.length);let s=t;for(let o=r-1;o>=0;o--){o!==r-1&&(s=s.double());for(let i=0;i<n.length;i++){const a=n[i][o];if(a){const c=e[i][Math.abs(a)-1>>1];s=s.add(a<0?c.negate():c)}}}return s}class jy{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,n){ma(e),this.randomBytes=By(n,Ao),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,n,r){const s=Math.ceil(r/n)+1,o=2**(n-1),i=[];let a=e;for(let c=0;c<s;c++){let l=a;for(let d=0;d<o;d++)i.push(l),l=l.add(a);a=i[i.length-1].double()}return{W:n,bits:r,windows:s,comp:i}}wnafCachedCT(e,n){const{W:r,windows:s,comp:o}=e,i=2**(r-1),a=Oy(n,r,s);let c=this.ZERO,l=this.BASE;for(let d=0;d<s;d++){const u=a[d],f=d*i,p=Math.abs(u)-1;let g=o[f];for(let x=1;x<i;x++)g=x===p?o[f+x]:g;const m=g.negate();u===0?l=l.add(o[f]):c=c.add(u<0?m:g)}return{p:c,f:l}}getWnafPrecomputes(e,n,r,s){let o=this.wnafPrecomputes.get(n),i=o?.find(a=>a.W===e&&a.bits===r);return i||(i=this.buildWnafTable(n,e,r),typeof s=="function"&&(i={...i,comp:s(i.comp)}),o||(o=[],this.wnafPrecomputes.set(n,o)),o.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),!Au(n,Er,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,n,r,s){const o=ko(e);return o===1?this.fixedWindowCT(e,n,r):this.wnafCachedCT(this.getWnafPrecomputes(o,e,r,s),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 s=this.Point.Fn.BITS+Ic,o=this.randomBytes(Ao);if(!yu(o)||o.length!==Ao)throw new Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;const i=n+vu(o)*this.Point.Fn.ORDER;return this.runCT(e,i,s,r)}fixedWindowCT(e,n,r){const s=Ry,o=1<<s,i=my(s),a=new Array(o);a[0]=this.ZERO;for(let d=1;d<o;d++)a[d]=a[d-1].add(e);const c=Math.ceil(r/s);let l=this.ZERO;for(let d=c-1;d>=0;d--){if(d!==c-1)for(let p=0;p<s;p++)l=l.double();const u=Number(n>>BigInt(d*s)&i);let f=a[0];for(let p=1;p<o;p++)f=p===u?a[p]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(e,n){return this.randomBytes===void 0?!1:n===Er?!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,s){return this.shouldBlind(e,r)?this.mulCTBlinded(e,n,s):this.mulCT(e,n,s)}mulUnsafe(e,n,r){if(this.assertPoint(e),!zt(n))throw new Error("invalid scalar");const s=ko(e);if(s===1||n>=this.Point.Fn.ORDER)return Uy(this.Point,[e],[n],!0);const o=this.getWnafPrecomputes(s,e,this.bits,r);return this.wnafCachedCT(o,n).p}setWindowSize(e,n){this.assertPoint(e),Ny(n,this.bits);const r=Math.ceil((this.bits+Ic)/n)+1;Ly(r*2**(n-1),this.Point.Fp.BYTES),Bu.set(e,n),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return ko(e)!==1}}function Uy(t,e,n,r=!1){if(ma(t),Lu(e,t),Xs(r,"allowOversized"),_y(n,t.Fn,r?t.Fn.ORDER**Iy:void 0),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const s=e.map(i=>Dy(i,4)),o=n.map(i=>Fy(i,4));return My(t.ZERO,s,o)}function Pc(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return vr(e),e}else return pa(t,{isLE:n})}function $y(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(!(zt(l)&&l!==ga))throw new Error(`CURVE.${c} must be positive bigint`)}const s=Pc(e.p,n.Fp,r),o=Pc(e.n,n.Fn,r),a=["Gx","Gy","a","d"];for(const c of a)if(!s.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:s,Fn:o}}function Hy(t,e){return function(r){const s=t(r);return{secretKey:s,publicKey:e(s)}}}const zr=BigInt(0),Vr=BigInt(1),Gr=BigInt(2),qy=BigInt(4),Nc=BigInt(8);function Ky(t,e,n,r){const s=t.sqr(n),o=t.sqr(r),i=t.add(t.mul(e.a,s),o),a=t.add(t.ONE,t.mul(e.d,t.mul(s,o)));return t.eql(i,a)}function zy(t,e={}){Ss(e,{},{},"extraOpts");const n=e,r=$y("edwards",t,n,n.FpFnLE),{Fp:s,Fn:o}=r;let i=r.CURVE;const{h:a}=i;if(As(s,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(As(s,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?bu:n.randomBytes,l=Gr<<BigInt(s.BYTES*8)-Vr;function d(T){if(!s.isOdd)throw new Error("Field does not have .isOdd()");return s.isOdd(T)}const u=n.uvRatio===void 0?(T,v)=>{try{return{isValid:!0,value:s.sqrt(s.div(T,v))}}catch{return{isValid:!1,value:zr}}}:n.uvRatio;if(!Ky(s,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");const f=s.eql(i.a,s.neg(s.ONE))?T=>s.neg(T):s.eql(i.a,s.ONE)?T=>T:T=>s.mul(i.a,T);function p(T,v,A=!1){const _=A?Vr:zr;return pr("coordinate "+T,v,_,l),v}function g(T){if(!(T instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(i.Gx,i.Gy,s.ONE,s.mul(i.Gx,i.Gy));static ZERO=new m(s.ZERO,s.ONE,s.ONE,s.ZERO);static Fp=s;static Fn=o;X;Y;Z;T;constructor(v,A,_,C){this.X=p("x",v),this.Y=p("y",A),this.Z=p("z",_,!0),this.T=p("t",C),Object.freeze(this)}static CURVE(){return i}static fromAffine(v){if(v instanceof m)throw new Error("extended point not allowed");const{x:A,y:_}=v||{};return p("x",A),p("y",_),new m(A,_,s.ONE,s.mul(A,_))}static fromBytes(v,A=!1){const _=s.BYTES,{a:C,d:L}=i;v=xr(Sn(v,_,"point")),Xs(A,"zip215");const R=xr(v),E=v[_-1];R[_-1]=E&-129;const S=Es(R),P=A?l:s.ORDER;pr("point.y",S,zr,P);const N=s.sqr(S),w=s.sub(N,s.ONE),b=s.sub(s.mulN(L,N),C);let{isValid:k,value:B}=u(w,b);if(!k)throw new Error("bad point: invalid y coordinate");const M=d(B),U=(E&128)!==0;if(!A&&s.is0(B)&&U)throw new Error("bad point: x=0 and x_0=1");return U!==M&&(B=s.neg(B)),m.fromAffine({x:B,y:S})}static fromHex(v,A=!1){return m.fromBytes(fy(v),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=6,A=!0){return y.setWindowSize(this,v),A||this.multiply(Gr),this}assertValidity(){const v=this,{a:A,d:_}=i;if(v.is0())throw new Error("bad point: ZERO");const{X:C,Y:L,Z:R,T:E}=v,S=s.sqr(C),P=s.sqr(L),N=s.sqr(R),w=s.sqr(N),b=s.mul(S,A),k=s.mul(s.add(b,P),N),B=s.add(w,s.mul(_,s.mul(S,P)));if(!s.eql(k,B))throw new Error("bad point: equation left != right (1)");const M=s.mul(C,L),U=s.mul(R,E);if(!s.eql(M,U))throw new Error("bad point: equation left != right (2)")}equals(v){g(v);const{X:A,Y:_,Z:C}=this,{X:L,Y:R,Z:E}=v,S=s.mul(A,E),P=s.mul(L,C),N=s.mul(_,E),w=s.mul(R,C);return s.eql(S,P)&&s.eql(N,w)}is0(){return this.equals(m.ZERO)}negate(){return new m(s.neg(this.X),this.Y,this.Z,s.neg(this.T))}double(){const{X:v,Y:A,Z:_}=this,C=s.sqr(v),L=s.sqr(A),R=s.mul(s.sqr(_),Gr),E=f(C),S=s.addN(v,A),P=s.sub(s.subN(s.sqr(S),C),L),N=s.addN(E,L),w=s.subN(N,R),b=s.subN(E,L),k=s.mul(P,w),B=s.mul(N,b),M=s.mul(P,b),U=s.mul(w,N);return new m(k,B,U,M)}add(v){g(v);const{d:A}=i,{X:_,Y:C,Z:L,T:R}=this,{X:E,Y:S,Z:P,T:N}=v,w=s.mul(_,E),b=s.mul(C,S),k=s.mul(s.mulN(R,A),N),B=s.mul(L,P),M=s.sub(s.subN(s.mulN(s.addN(_,C),s.addN(E,S)),w),b),U=s.subN(B,k),D=s.addN(B,k),I=s.sub(b,f(w)),F=s.mul(M,U),O=s.mul(D,I),K=s.mul(M,I),q=s.mul(U,D);return new m(F,O,q,K)}subtract(v){return g(v),this.add(v.negate())}multiply(v){if(!o.isValidNot0(v))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");const{p:A,f:_}=y.mulSecret(this,v,a,x);return x([A,_])[0]}multiplyUnsafe(v){if(!o.isValid(v))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return v===zr?m.ZERO:this.is0()||v===Vr?this:y.mulUnsafe(this,v,x)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return y.mulUnsafe(this,i.n).is0()}toAffine(v){const A=this;let _=v;if(_!=null&&typeof _!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof _);const{X:C,Y:L,Z:R}=A,E=A.is0();_==null&&(_=E?s.create(Nc):s.inv(R));const S=s.mul(C,_),P=s.mul(L,_),N=s.mul(R,_);if(E)return{x:s.ZERO,y:s.ONE};if(!s.eql(N,s.ONE))throw new Error("invZ was invalid");return{x:S,y:P}}clearCofactor(){return a===Vr?this:a===Gr?this.double():a===qy?this.double().double():a===Nc?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){const{x:v,y:A}=this.toAffine(),_=s.toBytes(A);return _[_.length-1]|=d(v)?128:0,_}toHex(){return uy(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const x=T=>Py(m,T),y=new jy(m,c);return y.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}const Ft=BigInt(0),Me=BigInt(1),Wr=BigInt(2);function Lc(t,e){return t+e-(e>>Me<<Me)}function Vy(t){const e=BigInt(6)*t;return(n,r,s)=>{const o=r+s,a=((e+s-r)*n+r)%t;return{x_2:a,x_3:o-a}}}function Gy(t){return Ss(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...t})}function Wy(t){const e=Gy(t),{P:n,type:r,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=e,a=e.scalarMultBase,c=r==="x25519";if(!c&&r!=="x448")throw new Error("invalid type");const l=i===void 0?bu:i,d=c?255:448,u=Vy(n),f=c?32:56,p=BigInt(c?9:5),g=BigInt(c?121665:39081),m=c?Wr**BigInt(254):Wr**BigInt(447),x=c?BigInt(8)*(Wr**BigInt(251)-Me):BigInt(4)*(Wr**BigInt(445)-Me),y=m+x+Me,T=B=>re(B,n),v=A(p);function A(B){return Su(T(B),f)}function _(B){const M=xr(Sn(B,f,"uCoordinate"));return c&&(M[31]&=127),T(Es(M))}function C(B){return Es(s(xr(Sn(B,f,"scalar"))))}const L=new Set(c?[Ft,Me,n-Me,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[Ft,Me,n-Me]);function R(B,M){const U=_(M);if(L.has(U))throw new Error("invalid private or public key received");const D=N(U,C(B));if(D===Ft)throw new Error("invalid private or public key received");return A(D)}function E(B){if(a===void 0)return R(B,v);const M=C(B);pr("scalar",M,m,y);const U=T(a(M));if(U===Ft)throw new Error("invalid private or public key received");return A(U)}const S=E,P=R;function N(B,M){pr("u",B,Ft,n),pr("scalar",M,m,y);const U=M,D=B;let I=Me,F=Ft,O=B,K=Me;const q=U^U>>Me;for(let W=BigInt(d-1);W>=Ft;W--){const X=Lc(n,q>>W);({x_2:I,x_3:O}=u(X,I,O)),{x_2:F,x_3:K}=u(X,F,K);const V=I+F,Z=T(V*V),ke=I-F,Fe=T(ke*ke),rt=Z-Fe,Ie=O+K,Dt=O-K,on=T(Dt*V),bt=T(Ie*ke),He=on+bt,Br=on-bt;O=T(He*He),K=T(D*T(Br*Br)),I=T(Z*Fe),F=T(rt*(Z+T(g*rt)))}const H=Lc(n,U);({x_2:I,x_3:O}=u(H,I,O)),{x_2:F,x_3:K}=u(H,F,K);const G=o(F);return T(I*G)}const w={secretKey:f,publicKey:f,seed:f},b=B=>(B=B===void 0?l(f):B,Sn(B,w.seed,"seed"),B),k={randomSecretKey:b};return Object.freeze(w),Object.freeze(k),Object.freeze({keygen:Hy(b,S),getSharedSecret:P,getPublicKey:S,scalarMult:R,scalarMultBase:E,utils:k,GuBytes:v.slice(),lengths:w})}const Bc=BigInt(0),Xy=BigInt(1),_c=BigInt(2),Yy=BigInt(3),Zy=BigInt(5),Jy=BigInt(8),Ys=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Qy={p:Ys,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Jy,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function _u(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),o=Ys,a=t*t%o*t%o,c=Ke(a,_c,o)*a%o,l=Ke(c,Xy,o)*t%o,d=Ke(l,Zy,o)*l%o,u=Ke(d,e,o)*d%o,f=Ke(u,n,o)*u%o,p=Ke(f,r,o)*f%o,g=Ke(p,s,o)*p%o,m=Ke(g,s,o)*p%o,x=Ke(m,e,o)*d%o;return{pow_p_5_8:Ke(x,_c,o)*t%o,b2:a}}function eb(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Dc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function tb(t,e){const n=Ys,r=re(e*e*e,n),s=re(r*r*e,n),o=_u(t*s).pow_p_5_8;let i=re(t*r*o,n);const a=re(e*i*i,n),c=i,l=re(i*Dc,n),d=a===t,u=a===re(-t,n),f=a===re(-t*Dc,n);return d&&(i=c),(u||f)&&(i=l),ky(i,n)&&(i=re(-i,n)),{isValid:d||u,value:i}}const Fc=zy(Qy,{uvRatio:tb}),Xr=(()=>{const t=Ys,e=n=>{const{pow_p_5_8:r,b2:s}=_u(n);return re(Ke(r,Yy,t)*s,t)};return Wy({P:t,type:"x25519",powPminus2:e,adjustScalarBytes:eb,scalarMultBase:n=>{const r=re(n,Fc.Fn.ORDER);if(r===Bc)return Bc;const s=Fc.BASE.multiply(r);return re((s.Z+s.Y)*e(re(s.Z-s.Y,t)),t)}})})();class Oc{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,n){if(la(e),yt(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,s=new Uint8Array(r);s.set(n.length>r?e.create().update(n).digest():n);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Kt(s)}update(e){return xs(this),this.iHash.update(e),this}digestInto(e){xs(this),hu(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:s,destroyed:o,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=s,e.destroyed=o,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 Du=(()=>{const t=((e,n,r)=>new Oc(e,n).update(r).digest());return t.create=(e,n)=>new Oc(e,n),t})();function Mc(){const t={};return t.promise=new Promise((e,n)=>{t.resolve=e,t.reject=n}),t}class jc{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 To{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new jc(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 jc(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 nb extends Error{type;code;constructor(e,n){super(e??"The operation was aborted"),this.type="aborted",this.code=n??"ABORT_ERR"}}function rb(t={}){return sb(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 sb(t,e){e=e??{};let n=e.onEnd,r=new To,s,o,i,a=Mc();const c=async()=>{try{return r.isEmpty()?i?{done:!0}:await new Promise((x,y)=>{o=T=>{o=null,r.push(T);try{x(t(r))}catch(v){y(v)}return s}}):t(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Mc()})}},l=x=>o!=null?o(x):(r.push(x),s),d=x=>(r=new To,o!=null?o({error:x}):(r.push({error:x}),s)),u=x=>{if(i)return s;if(e?.objectMode!==!0&&x?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:x})},f=x=>i?s:(i=!0,x!=null?d(x):l({done:!0})),p=()=>(r=new To,f(),{done:!0}),g=x=>(f(x),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:p,throw:g,push:u,end:f,get readableLength(){return r.size},onEmpty:async x=>{const y=x?.signal;if(y?.throwIfAborted(),r.isEmpty())return;let T,v;y!=null&&(T=new Promise((A,_)=>{v=()=>{_(new nb)},y.addEventListener("abort",v)}));try{await Promise.race([a.promise,T])}finally{v!=null&&y!=null&&y?.removeEventListener("abort",v)}}},n==null)return s;const m=s;return s={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(x){return m.throw(x),n!=null&&(n(x),n=void 0),{done:!0}},return(){return m.return(),n!=null&&(n(),n=void 0),{done:!0}},push:u,end(x){return m.end(x),n!=null&&(n(x),n=void 0),s},get readableLength(){return m.readableLength},onEmpty:x=>m.onEmpty(x)},s}class wa extends Error{name="TimeoutError";constructor(e,n){super(e,n),Error.captureStackTrace?.(this,wa)}}const Uc=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function ob(t,e){const{milliseconds:n,fallback:r,message:s,customTimers:o={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(Uc(i));return}if(i&&(c=()=>{f(Uc(i))},i.addEventListener("abort",c,{once:!0})),t.then(u,f),n===Number.POSITIVE_INFINITY)return;const p=new wa;a=o.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){f(g)}return}typeof t.cancel=="function"&&t.cancel(),s===!1?u():s instanceof Error?f(s):(p.message=s??`Promise timed out after ${n} milliseconds`,f(p))},n)}).finally(()=>{d.clear(),c&&i&&i.removeEventListener("abort",c)});return d.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},d}const ib=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 ab(t,e,n){let r;const s=new Promise((o,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}=ib(t),u=async(...p)=>{const g=n.multiArgs?p:p[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(),o(c))},f=(...p)=>{r(),i(n.rejectionMultiArgs?p:p[0])};r=()=>{for(const p of a)d(p,u);for(const p of n.rejectionEvents)a.includes(p)||d(p,f)};for(const p of a)l(p,u);for(const p of n.rejectionEvents)a.includes(p)||l(p,f);n.signal&&n.signal.addEventListener("abort",()=>{f(n.signal.reason)},{once:!0}),n.resolveImmediately&&o(c)});if(s.cancel=r,typeof n.timeout=="number"){const o=ob(s,{milliseconds:n.timeout});return o.cancel=()=>{r(),o.clear()},o}return s}function cb(t,e,n){typeof n=="function"&&(n={filter:n}),n={...n,count:1,resolveImmediately:!1};const r=ab(t,e,n),s=r.then(o=>o[0]);return s.cancel=r.cancel,s}class ks extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class lb extends Error{static name="StreamClosedError";name="StreamClosedError"}function db(t){return t.reason}function Fu(t,e,n){if(e==null||t==null)return t;const r=db;if(e.aborted)return t.catch(()=>{}),Promise.reject(r(e));let s;return Promise.race([t,new Promise((o,i)=>{s=()=>{i(r(e))},e.addEventListener("abort",s)})]).finally(()=>{s!=null&&e.removeEventListener("abort",s)})}const ub=Math.pow(2,20)*4;class Ou extends Sh{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??ub,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new ne,this.writeBuffer=new ne,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=s=>{this.onDrainPromise?.reject(s.error??new lb)};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()),Fu(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;const e=rb(),n=o=>{e.push(o.data)};this.addEventListener("message",n);const r=o=>{e.end(o.error)};this.addEventListener("close",r);const s=()=>{e.end()};this.addEventListener("remoteCloseWrite",s);try{yield*e}finally{this.removeEventListener("message",n),this.removeEventListener("close",r),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Zn(`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 Hw(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Zn("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 Zn("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 Zn(`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 Zn(`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 Uw;this.dispatchEvent(new qw(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 ca))}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 s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){e=!1;break}const o=this.writeBuffer.sublist(0,s),i=new ne(o);this.writeBuffer.consume(o.byteLength);const a=this.sendData(o);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 $w(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 vc(`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 vc(`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 fb=4194304;class $c extends Error{static name="UnwrappedError";name="UnwrappedError"}class Mu extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class hb extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class pb extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function gb(t){return typeof t?.closeRead=="function"}function mb(t){return typeof t?.close=="function"}function Co(t){return gb(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:mb(t)?t.status!=="open":!1}function wb(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function yb(t,e){const n=e?.maxBufferSize??fb,r=new ne;let s,o=!1;if(!wb(t))throw new fu("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),s?.reject(new Error(`Read buffer overflow - ${u} > ${n}`))}s?.resolve()};t.addEventListener("message",i);const a=d=>{d.error!=null?s?.reject(d.error):s?.resolve()};t.addEventListener("close",a);const c=()=>{s?.resolve()};t.addEventListener("remoteCloseWrite",c);const l={readBuffer:r,async read(d){if(o===!0)throw new $c("Stream was unwrapped");if(Co(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 ks(`Unexpected EOF - stream closed after reading ${r.byteLength}/${d.bytes} bytes`)}const u=d?.bytes??1;for(s=Promise.withResolvers();;){if(r.byteLength>=u){s.resolve();break}if(await Fu(s.promise,d?.signal),Co(t)){if(r.byteLength===0&&d?.bytes==null)return null;break}s=Promise.withResolvers()}const f=d?.bytes??r.byteLength;if(r.byteLength<f){if(Co(t))throw t.log.error("closed while reading %d/%d bytes",r.byteLength,f),new ks(`Unexpected EOF - stream closed while reading ${r.byteLength}/${f} bytes`);return l.read(d)}const p=r.sublist(0,f);return r.consume(f),p},async write(d,u){if(o===!0)throw new $c("Stream was unwrapped");t.send(d)||await cb(t,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!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 Hc(t,e={}){const n=yb(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=tn(e.maxDataLength));const r=e?.lengthDecoder??Vd,s=e?.lengthEncoder??Am;return{async read(i){let a=-1;const c=new ne;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 Mu("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new pb(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new hb(`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 ks(`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 ks(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await n.write(new ne(s(i.byteLength),i),a)},async writeV(i,a){const c=new ne(...i.flatMap(l=>[s(l.byteLength),l]));await n.write(c,a)},unwrap(){return n.unwrap()}}}const bb=1024*1024*4,xb=1024*1024*4;class vb{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new ne,this.maxBufferSize=e.maxBufferSize??bb,this.maxDataLength=e.maxDataLength??xb,this.lengthDecoder=e.lengthDecoder??Vd,this.encodingLength=e.encodingLength??tn}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new fu(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let n;try{n=this.lengthDecoder(this.buffer)}catch(o){if(o instanceof RangeError)break;throw o}if(n<0||n>this.maxDataLength)throw new Mu("Invalid message length");const r=this.encodingLength(n),s=r+n;if(this.buffer.byteLength>=s){const o=this.buffer.sublist(r,s);this.buffer.consume(s),o.byteLength>0&&(yield o)}else break}}}var Eb={};const Sr=65535,qc=Sr-16,Lr=!!Eb?.DUMP_SESSION_KEYS,Kc=16;function ki(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const Ts=t=>t?`"${t}" `:"";function Ti(t,e=""){if(typeof t!="boolean")throw new TypeError(Ts(e)+"expected boolean, got type="+typeof t);return t}function kn(t,e=""){if(typeof t!="number")throw new TypeError(Ts(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(Ts(e)+"expected integer >= 0, got "+t);return t}function ge(t,e,n=""){if(ki(t)&&(e===void 0||t.length===e))return t;e!==void 0&&kn(e,"length");const r=ki(t),s=e!==void 0?` of length ${e}`:"",o=r?`length=${t.length}`:`type=${typeof t}`,i=Ts(n)+"expected Uint8Array"+s+", got "+o;throw r?new RangeError(i):new TypeError(i)}const zc=(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 Vc(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function Sb(t,e){ge(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function ut(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Lt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Ab(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const Tn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function kb(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Tb(t){for(let e=0;e<t.length;e++)t[e]=kb(t[e]);return t}const $t=Tn?t=>t:Tb;function Cb(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 Ib(t,e){if(Cb(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function Rb(t,e){return zc(t,"defaults"),zc(e,"opts"),Object.assign(t,e)}function Pb(t,e){if(t=ge(t),e=ge(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 Nb(t,e,n){const r=e,s=(()=>[]),o=(a,c)=>r(c,...s(a)).update(a).digest(),i=r(new Uint8Array(t),...s(new Uint8Array(0)));return o.outputLen=i.outputLen,o.blockLen=i.blockLen,o.create=(a,...c)=>r(a,...c),o}const Lb=(t,e)=>{function n(r,...s){if(ge(r,void 0,"key"),t.nonceLength!==void 0){const u=s[0];ge(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}const o=t.tagLength,i=t.nonceLength!==void 0?1:0;if(!t.withAAD){for(let u=i;u<s.length;u++)if(ki(s[u]))throw new Error("AAD not supported")}t.withAAD&&s[i]!==void 0&&ge(s[i],void 0,"AAD");const a=e(r,...s),c=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");ge(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,ge(u,void 0,"data"),c(a.encrypt.length,f),a.encrypt(u,f)},decrypt(u,f){if(ge(u,void 0,"data"),o&&u.length<o)throw new Error('"ciphertext" expected length >= tagLength='+o);return c(a.decrypt.length,f),a.decrypt(u,f)}}}return Object.assign(n,t),n};function Ci(t,e,n=!0){if(e===void 0)return new Uint8Array(t);if(ge(e,t,"output"),n&&!Cs(e))throw new Error("invalid output, must be aligned");return e}function Bb(t,e,n){kn(t),kn(e),Ti(n);const r=new Uint8Array(16),s=Ab(r);return s.setBigUint64(0,BigInt(e),n),s.setBigUint64(8,BigInt(t),n),r}function Cs(t){return t.byteOffset%4===0}function Is(t){return Uint8Array.from(ge(t))}const ju=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),_b=$t(ut(ju("expand 16-byte k"))),Db=$t(ut(ju("expand 32-byte k")));function ee(t,e){return t<<e|t>>>32-e}const Jn=64,Fb=16,Ii=2**32-1,Gc=Uint32Array.of();function Ob(t,e,n,r,s,o,i,a){const c=s.length,l=new Uint8Array(Jn),d=ut(l),u=Tn&&Cs(s)&&Cs(o),f=u?ut(s):Gc,p=u?ut(o):Gc;if(!Tn){for(let g=0;g<c;i++){if(t(e,n,r,d,i,a),$t(d),i>=Ii)throw new Error("arx: counter overflow");const m=Math.min(Jn,c-g);for(let x=0,y;x<m;x++)y=g+x,o[y]=s[y]^l[x];g+=m}return}for(let g=0;g<c;i++){if(t(e,n,r,d,i,a),i>=Ii)throw new Error("arx: counter overflow");const m=Math.min(Jn,c-g);if(u&&m===Jn){const x=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let y=0,T;y<Fb;y++)T=x+y,p[T]=f[T]^d[y];g+=Jn;continue}for(let x=0,y;x<m;x++)y=g+x,o[y]=s[y]^l[x];g+=m}}function Mb(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:s,counterRight:o,rounds:i}=Rb({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return kn(s),kn(i),Ti(o),Ti(n),(a,c,l,d,u=0)=>{ge(a,void 0,"key"),ge(c,void 0,"nonce"),ge(l,void 0,"data");const f=l.length,p=d!==void 0;if(d=Ci(f,d,!1),p&&Ib(l,d),kn(u),u<0||u>=Ii)throw new Error("arx: counter overflow");const g=[];let m=a.length,x,y;if(m===32)g.push(x=Is(a)),y=Db;else if(m===16&&n)x=new Uint8Array(32),x.set(a),x.set(a,16),y=_b,g.push(x);else throw ge(a,32,"arx key"),new Error("invalid key size");(!Tn||!Cs(c))&&g.push(c=Is(c));let T=ut(x);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");const _=c.subarray(0,16);if(Tn)r(y,T,ut(_),T);else{const C=$t(Uint32Array.from(y));r(C,T,ut(_),T),Lt(C),$t(T)}c=c.subarray(16)}else Tn||$t(T);const v=16-s;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){const _=new Uint8Array(12);_.set(c,o?0:12-c.length),c=_,g.push(c)}const A=$t(ut(c));try{return Ob(t,y,T,A,l,d,u,i),d}finally{Lt(...g)}}}function we(t,e){return t[e++]&255|(t[e++]&255)<<8}class jb{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=Is(ge(e,32,"key"));const n=we(e,0),r=we(e,2),s=we(e,4),o=we(e,6),i=we(e,8),a=we(e,10),c=we(e,12),l=we(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|s<<6)&7939,this.r[3]=(s>>>7|o<<9)&8191,this.r[4]=(o>>>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]=we(e,16+2*d)}process(e,n,r=!1){const s=r?0:2048,{h:o,r:i}=this,a=i[0],c=i[1],l=i[2],d=i[3],u=i[4],f=i[5],p=i[6],g=i[7],m=i[8],x=i[9],y=we(e,n+0),T=we(e,n+2),v=we(e,n+4),A=we(e,n+6),_=we(e,n+8),C=we(e,n+10),L=we(e,n+12),R=we(e,n+14);let E=o[0]+(y&8191),S=o[1]+((y>>>13|T<<3)&8191),P=o[2]+((T>>>10|v<<6)&8191),N=o[3]+((v>>>7|A<<9)&8191),w=o[4]+((A>>>4|_<<12)&8191),b=o[5]+(_>>>1&8191),k=o[6]+((_>>>14|C<<2)&8191),B=o[7]+((C>>>11|L<<5)&8191),M=o[8]+((L>>>8|R<<8)&8191),U=o[9]+(R>>>5|s),D=0,I=D+E*a+S*(5*x)+P*(5*m)+N*(5*g)+w*(5*p);D=I>>>13,I&=8191,I+=b*(5*f)+k*(5*u)+B*(5*d)+M*(5*l)+U*(5*c),D+=I>>>13,I&=8191;let F=D+E*c+S*a+P*(5*x)+N*(5*m)+w*(5*g);D=F>>>13,F&=8191,F+=b*(5*p)+k*(5*f)+B*(5*u)+M*(5*d)+U*(5*l),D+=F>>>13,F&=8191;let O=D+E*l+S*c+P*a+N*(5*x)+w*(5*m);D=O>>>13,O&=8191,O+=b*(5*g)+k*(5*p)+B*(5*f)+M*(5*u)+U*(5*d),D+=O>>>13,O&=8191;let K=D+E*d+S*l+P*c+N*a+w*(5*x);D=K>>>13,K&=8191,K+=b*(5*m)+k*(5*g)+B*(5*p)+M*(5*f)+U*(5*u),D+=K>>>13,K&=8191;let q=D+E*u+S*d+P*l+N*c+w*a;D=q>>>13,q&=8191,q+=b*(5*x)+k*(5*m)+B*(5*g)+M*(5*p)+U*(5*f),D+=q>>>13,q&=8191;let H=D+E*f+S*u+P*d+N*l+w*c;D=H>>>13,H&=8191,H+=b*a+k*(5*x)+B*(5*m)+M*(5*g)+U*(5*p),D+=H>>>13,H&=8191;let G=D+E*p+S*f+P*u+N*d+w*l;D=G>>>13,G&=8191,G+=b*c+k*a+B*(5*x)+M*(5*m)+U*(5*g),D+=G>>>13,G&=8191;let W=D+E*g+S*p+P*f+N*u+w*d;D=W>>>13,W&=8191,W+=b*l+k*c+B*a+M*(5*x)+U*(5*m),D+=W>>>13,W&=8191;let X=D+E*m+S*g+P*p+N*f+w*u;D=X>>>13,X&=8191,X+=b*d+k*l+B*c+M*a+U*(5*x),D+=X>>>13,X&=8191;let V=D+E*x+S*m+P*g+N*p+w*f;D=V>>>13,V&=8191,V+=b*u+k*d+B*l+M*c+U*a,D+=V>>>13,V&=8191,D=(D<<2)+D|0,D=D+I|0,I=D&8191,D=D>>>13,F+=D,o[0]=I,o[1]=F,o[2]=O,o[3]=K,o[4]=q,o[5]=H,o[6]=G,o[7]=W,o[8]=X,o[9]=V}finalize(){const{h:e,pad:n}=this,r=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,r[0]=e[0]+5,s=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+s,s=r[a]>>>13,r[a]&=8191;r[9]-=8192;let o=(s^1)-1;for(let a=0;a<10;a++)r[a]&=o;o=~o;for(let a=0;a<10;a++)e[a]=e[a]&o|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;Lt(r)}update(e){Vc(this),ge(e),e=Is(e);const{buffer:n,blockLen:r}=this,s=e.length;for(let o=0;o<s;){const i=Math.min(r-this.pos,s-o);if(i===r){for(;r<=s-o;o+=r)this.process(e,o);continue}n.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,Lt(this.h,this.r,this.buffer,this.pad)}digestInto(e){Vc(this),Sb(e,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:s}=this;if(s){for(n[s++]=1;s<16;s++)n[s]=0;this.process(n,0,!0)}this.finalize();let o=0;for(let i=0;i<8;i++)e[o++]=r[i]>>>0,e[o++]=r[i]>>>8}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}}const Ub=Nb(32,t=>new jb(t));function $b(t,e,n,r,s,o=20){let i=t[0],a=t[1],c=t[2],l=t[3],d=e[0],u=e[1],f=e[2],p=e[3],g=e[4],m=e[5],x=e[6],y=e[7],T=s,v=n[0],A=n[1],_=n[2],C=i,L=a,R=c,E=l,S=d,P=u,N=f,w=p,b=g,k=m,B=x,M=y,U=T,D=v,I=A,F=_;for(let K=0;K<o;K+=2)C=C+S|0,U=ee(U^C,16),b=b+U|0,S=ee(S^b,12),C=C+S|0,U=ee(U^C,8),b=b+U|0,S=ee(S^b,7),L=L+P|0,D=ee(D^L,16),k=k+D|0,P=ee(P^k,12),L=L+P|0,D=ee(D^L,8),k=k+D|0,P=ee(P^k,7),R=R+N|0,I=ee(I^R,16),B=B+I|0,N=ee(N^B,12),R=R+N|0,I=ee(I^R,8),B=B+I|0,N=ee(N^B,7),E=E+w|0,F=ee(F^E,16),M=M+F|0,w=ee(w^M,12),E=E+w|0,F=ee(F^E,8),M=M+F|0,w=ee(w^M,7),C=C+P|0,F=ee(F^C,16),B=B+F|0,P=ee(P^B,12),C=C+P|0,F=ee(F^C,8),B=B+F|0,P=ee(P^B,7),L=L+N|0,U=ee(U^L,16),M=M+U|0,N=ee(N^M,12),L=L+N|0,U=ee(U^L,8),M=M+U|0,N=ee(N^M,7),R=R+w|0,D=ee(D^R,16),b=b+D|0,w=ee(w^b,12),R=R+w|0,D=ee(D^R,8),b=b+D|0,w=ee(w^b,7),E=E+S|0,I=ee(I^E,16),k=k+I|0,S=ee(S^k,12),E=E+S|0,I=ee(I^E,8),k=k+I|0,S=ee(S^k,7);let O=0;r[O++]=i+C|0,r[O++]=a+L|0,r[O++]=c+R|0,r[O++]=l+E|0,r[O++]=d+S|0,r[O++]=u+P|0,r[O++]=f+N|0,r[O++]=p+w|0,r[O++]=g+b|0,r[O++]=m+k|0,r[O++]=x+B|0,r[O++]=y+M|0,r[O++]=T+U|0,r[O++]=v+D|0,r[O++]=A+I|0,r[O++]=_+F|0}const Hb=Mb($b,{counterRight:!1,counterLength:4,allowShortKeys:!1}),qb=new Uint8Array(16),Wc=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(qb.subarray(n))},Kb=new Uint8Array(32);function Xc(t,e,n,r,s){s!==void 0&&ge(s,void 0,"AAD");const o=t(e,n,Kb),i=Bb(r.length,s?s.length:0,!0),a=Ub.create(o);s&&Wc(a,s),Wc(a,r),a.update(i);const c=a.digest();return Lt(o,i),c}const zb=t=>(e,n,r)=>({encrypt(o,i){const a=o.length;i=Ci(a+16,i,!1),i.set(o);const c=i.subarray(0,-16);t(e,n,c,c,1);const l=Xc(t,e,n,c,r);return i.set(l,a),Lt(l),i},decrypt(o,i){i=Ci(o.length-16,i,!1);const a=o.subarray(0,-16),c=o.subarray(-16),l=Xc(t,e,n,a,r);if(!Pb(c,l))throw Lt(l),new Error("invalid tag");return i.set(o.subarray(0,-16)),t(e,n,i,i,1),Lt(l),i}}),Yc=Lb({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},zb(Hb));function Vb(t,e,n){return la(t),n===void 0&&(n=new Uint8Array(t.outputLen)),Du(t,n,e)}const Qn=Uint8Array.of(0),Gb=Uint8Array.of();function Wb(t,e,n,r=32,s){la(t),wt(r,"length"),yt(e,void 0,"prk");const o=t.outputLen;if(e.length<o)throw new Error('"prk" must be at least HashLen octets');if(r>255*o)throw new Error("Length must be <= 255*HashLen");const i=Math.ceil(r/o);if(n===void 0?n=Gb:yt(n,void 0,"info"),!i)return new Uint8Array;const a=new Uint8Array(i*o),{iHash:c,oHash:l}=Du.create(t,e),d=new Uint8Array(o),u=i>1?t.create():void 0;for(let p=0;p<i-1;p++){Qn[0]=p+1;const g=c._cloneInto(u);p&&g.update(d),g.update(n).update(Qn).digestInto(d),l._cloneInto(u).update(d).digestInto(d),a.set(d,o*p)}if(Qn[0]=i,i>1&&c.update(d),c.update(n).update(Qn).digestInto(d),l.update(d).digestInto(d),a.set(d,o*(i-1)),c.destroy(),l.destroy(),u?.destroy(),d!==a&&Kt(d),Kt(Qn),r===a.length)return a;const f=a.slice(0,r);return Kt(a),f}const Uu={hashSHA256(t){return So(t.subarray())},getHKDF(t,e){const n=Vb(So,e,t),s=Wb(So,n,void 0,96),o=s.subarray(0,32),i=s.subarray(32,64),a=s.subarray(64,96);return[o,i,a]},generateX25519KeyPair(){const t=Xr.utils.randomSecretKey();return{publicKey:Xr.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:Xr.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return Xr.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,n,r){return Yc(r,e,n).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,n,r,s){return Yc(r,e,n).decrypt(t.subarray(),s)}},Xb=Uu;function Yb(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 Rs=t=>{const e=gt(2);return e[0]=t>>8,e[1]=t,e};Rs.bytes=2;const Ps=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)};Ps.bytes=2;function Zb(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 $u(t,e){!e.enabled||!Lr||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${J(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${J(t.privateKey,"hex")}`)):e("Missing local static keys."))}function Hu(t,e){!e.enabled||!Lr||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${J(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${J(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Jb(t,e){!e.enabled||!Lr||e(t?`REMOTE_STATIC_PUBLIC_KEY ${J(t.subarray(),"hex")}`:"Missing remote static public key.")}function qu(t,e){!e.enabled||!Lr||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${J(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Ku(t,e,n){!n.enabled||!Lr||(n(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&J(t.k,"hex")}`),n(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&J(e.k,"hex")}`))}class gr extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=gr.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}const Qb=0,e0=4294967295,t0="Cipherstate has reached maximum n, a new handshake must be performed";class n0{n;bytes;view;constructor(e=Qb){this.n=e,this.bytes=Re(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>e0)throw new Error(t0)}}const Cn=Re(0);class Yr{k;n;crypto;constructor(e,n=void 0,r=0){this.crypto=e,this.k=n,this.n=new n0(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 s=this.crypto.decrypt(n,this.n.getBytes(),e,this.k,r);return this.n.increment(),s}}class r0{cs;ck;h;crypto;constructor(e,n){this.crypto=e;const r=fe(n,"utf-8");this.h=o0(e,r),this.ck=this.h,this.cs=new Yr(e)}mixKey(e){const[n,r]=this.crypto.hkdf(this.ck,e);this.ck=n,this.cs=new Yr(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new ne(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,Cn);return[new Yr(this.crypto,e),new Yr(this.crypto,n)]}}class s0{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:n,protocolName:r,prologue:s,initiator:o,s:i,e:a,rs:c,re:l}=e;this.crypto=n,this.ss=new r0(n,r),this.ss.mixHash(s),this.initiator=o,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 s=e.sublist(n,n+r);return this.rs=this.ss.decryptAndHash(s),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class zu extends s0{writeMessageA(e){return new ne(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const n=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new ne(n,r,this.ss.encryptAndHash(e))}writeMessageC(e){const n=this.writeS();return this.writeSE(),new ne(n,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(n){throw new gr(`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 gr(`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 gr(`handshake stage 2 validation fail: ${n.message}`)}}}function o0(t,e){if(e.length<=32){const n=Re(32);return n.set(e),n}else return t.hash(e)}var Ns;(function(t){let e;t.codec=()=>(e==null&&(e=Gs((n,r,s={})=>{if(s.lengthDelimited!==!1&&r.fork(),n.webtransportCerthashes!=null)for(const o of n.webtransportCerthashes)r.uint32(10),r.bytes(o);if(n.streamMuxers!=null)for(const o of n.streamMuxers)r.uint32(18),r.string(o);s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const o={webtransportCerthashes:[],streamMuxers:[]},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{if(s.limits?.webtransportCerthashes!=null&&o.webtransportCerthashes.length===s.limits.webtransportCerthashes)throw new wc('Decode error - map field "webtransportCerthashes" had too many elements');o.webtransportCerthashes.push(n.bytes());break}case 2:{if(s.limits?.streamMuxers!=null&&o.streamMuxers.length===s.limits.streamMuxers)throw new wc('Decode error - map field "streamMuxers" had too many elements');o.streamMuxers.push(n.string());break}default:{n.skipType(a&7);break}}}return o})),e),t.encode=n=>Vs(n,t.codec()),t.decode=(n,r)=>zs(n,t.codec(),r)})(Ns||(Ns={}));var Ls;(function(t){let e;t.codec=()=>(e==null&&(e=Gs((n,r,s={})=>{s.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),Ns.codec().encode(n.extensions,r)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const o={identityKey:Re(0),identitySig:Re(0)},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{o.identityKey=n.bytes();break}case 2:{o.identitySig=n.bytes();break}case 4:{o.extensions=Ns.codec().decode(n,n.uint32(),{limits:s.limits?.extensions});break}default:{n.skipType(a&7);break}}}return o})),e),t.encode=n=>Vs(n,t.codec()),t.decode=(n,r)=>zs(n,t.codec(),r)})(Ls||(Ls={}));async function Vu(t,e,n){const r=await t.sign(Wu(e));return Ls.encode({identityKey:Ws(t.publicKey),identitySig:r,extensions:n})}async function Gu(t,e,n){try{const r=Ls.decode(t),s=vi(r.identityKey);if(n?.equals(s)===!1)throw new Error(`Payload identity key ${s} does not match expected remote identity key ${n}`);if(!e)throw new Error("Remote static does not exist");const o=Wu(e);if(!await s.verify(o,r.identitySig))throw new Error("Invalid payload signature");return r}catch(r){throw new mh(r.message)}}function Wu(t){const e=fe("noise-libp2p-static-key:");return t instanceof Uint8Array?di([e,t],e.length+t.length):(t.prepend(e),t)}class i0 extends Ou{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 vb({lengthDecoder:Ps,maxBufferSize:16*1024*1024,encodingLength:()=>2});const s=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",s);const o=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",o);const i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);const a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){const n=new ne;for(let r=0;r<e.byteLength;r+=qc){let s=r+qc;s>e.byteLength&&(s=e.byteLength);let o;e instanceof Uint8Array?o=this.handshake.encrypt(e.subarray(r,s)):o=this.handshake.encrypt(e.sublist(r,s)),this.metrics?.encryptedPackets.increment(),n.append(Rs(o.byteLength)),n.append(o)}return n}decrypt(e){const n=new ne;for(let r=0;r<e.byteLength;r+=Sr){let s=r+Sr;if(s>e.byteLength&&(s=e.byteLength),s-Kc<r)throw new Error("Invalid chunk");let o;e instanceof Uint8Array?o=e.subarray(r,s):o=e.sublist(r,s);const i=e.subarray(r,s-Kc);try{const a=this.handshake.decrypt(o,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 Zc(t,e,n){return new i0(t,e,n)}async function a0(t,e){const{log:n,connection:r,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Vu(o,a.publicKey,l),u=new zu({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});$u(u.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(u.writeMessageA(Cn),e),n.trace("Stage 0 - Initiator finished sending first message."),Hu(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."),qu(u.re,n),Jb(u.rs,n),n.trace("Initiator going to check remote's signature...");const p=await Gu(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 Ku(g,m,n),{payload:p,encrypt:x=>g.encryptWithAd(Cn,x),decrypt:(x,y)=>m.decryptWithAd(Cn,x,y)}}async function c0(t,e){const{log:n,connection:r,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Vu(o,a.publicKey,l),u=new zu({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});$u(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."),qu(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."),Hu(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 p=await Gu(f,u.rs,c),[g,m]=u.ss.split();return Ku(g,m,n),{payload:p,encrypt:x=>m.encryptWithAd(Cn,x),decrypt:(x,y)=>g.decryptWithAd(Cn,x,y)}}class l0{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,n={}){const{staticNoiseKey:r,extensions:s,crypto:o,prologueBytes:i}=n,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");const c=o??Xb;this.crypto=Yb(c),this.extensions={webtransportCerthashes:[],...s},this.metrics=a?Zb(a):void 0,r?this.staticKey=c.generateX25519KeyPairFromSeed(r):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??Re(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Ah]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,n){const r=e.log?.newScope("noise")??this.log,s=Hc(e,{lengthEncoder:Rs,lengthDecoder:Ps,maxDataLength:Sr}),o=await this.performHandshakeInitiator(s,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=vi(o.payload.identityKey);return{connection:Zc(s.unwrap(),o,this.metrics),remoteExtensions:o.payload.extensions,remotePeer:Bn(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(o.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 s=n.get(r);if(s!=null)return s}if(e.length)throw new wh("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,s=Hc(e,{lengthEncoder:Rs,lengthDecoder:Ps,maxDataLength:Sr}),o=await this.performHandshakeResponder(s,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=vi(o.payload.identityKey);return{connection:Zc(s.unwrap(),o,this.metrics),remoteExtensions:o.payload.extensions,remotePeer:Bn(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,n,r,s,o){let i;const a=o?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await a0({connection:e,privateKey:n,remoteIdentityKey:s,log:r.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,n,r,s,o){let i;const a=o?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await c0({connection:e,privateKey:n,remoteIdentityKey:s,log:r.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}}function d0(t={}){return e=>new l0(e,t)}const u0="termdock-e2ee-v1",Jc=3600*1e3,Qc=512*1024*1024,Ri=4*1024*1024,ss=()=>{},Zs=Object.assign(ss,{enabled:!1,error:ss,trace:ss,newScope:()=>Zs});Object.freeze(Zs);async function Xu(){const t=await Rw();return{privateKey:t,peerId:Bn(t.publicKey).toString()}}function f0(t){return btoa(String.fromCharCode(...Lw(t.privateKey)))}function el(t){if(t.length>512||!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Invalid identity encoding");const e=Nw(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:Bn(e.publicKey).toString()}}class Yu{constructor(e=ss){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>Ri)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 h0 extends Ou{constructor(e,n){super({log:Zs,direction:n?"outbound":"inbound",maxReadBufferLength:Ri,maxWriteBufferLength:Ri}),this.duplex=e,this.finished=e.sink(this.outgoing).catch(r=>{this.abort(_n(r))}),this.readTransport()}duplex;outgoing=new Yu(()=>this.onMuxerDrain());finished;async readTransport(){try{for await(const e of this.duplex.source)this.onData(e.slice());this.onTransportClosed()}catch(e){this.onTransportClosed(_n(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 _n(t){return t instanceof Error?t:new Error("Secure transport failed")}class p0 extends Error{code="E2EE_REHANDSHAKE_REQUIRED";constructor(){super("Encrypted connection lifetime reached; establish a new handshake without replaying pending input")}}function g0(t){const e=t?.maxAgeMs??Jc,n=t?.maxBytesPerDirection??Qc;if(!Number.isSafeInteger(e)||e<=0||e>Jc||!Number.isSafeInteger(n)||n<=0||n>Qc)throw new Error("Encrypted connection limits cannot exceed the production maximum");return{maxAgeMs:e,maxBytesPerDirection:n}}async function m0(t){const{identity:e,duplex:n,initiator:r,targetPinnedPeerId:s,signal:o}=t,i=g0(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&&!s)throw new Error("A pinned target identity is required");const a=s?Fw(s):void 0;if(a&&a.type!=="Ed25519")throw new Error("Only Ed25519 target identities are supported");if(e.peerId!==Bn(e.privateKey.publicKey).toString())throw new Error("Local identity mismatch");if(o?.aborted)throw o.reason??new Error("Connection aborted");const c=new h0(n,r),l=new AbortController,d=setTimeout(()=>{const p=new Error("Encrypted handshake timed out");l.abort(p),c.abort(p)},15e3),u=()=>{l.abort(o?.reason),c.abort(_n(o?.reason))};o?.addEventListener("abort",u,{once:!0}),c.addEventListener("close",()=>o?.removeEventListener("abort",u),{once:!0});const f=d0({crypto:Uu,prologueBytes:new TextEncoder().encode(u0)})({privateKey:e.privateKey,peerId:Bn(e.privateKey.publicKey),logger:{forComponent:()=>Zs},upgrader:{getStreamMuxers:()=>new Map}});try{const p=await(r?f.secureOutbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}):f.secureInbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}));if(p.remotePeer.type!=="Ed25519")throw new Error("Unsupported remote identity");return{authenticatedPeerId:p.remotePeer.toString(),duplex:w0(p.connection,i)}}catch(p){throw c.abort(_n(p)),p}finally{clearTimeout(d),o?.removeEventListener("abort",u)}}function w0(t,e){const n=new Yu,r=performance.now(),s=Date.now();let o=0,i=0,a;const c=()=>(a??=new p0,n.end(a),t.abort(a),a),l=setTimeout(c,e.maxAgeMs);typeof l=="object"&&l.unref?.();const d=(f,p)=>{if(a)throw a;if(Math.max(performance.now()-r,Date.now()-s)>=e.maxAgeMs||f+p>=e.maxBytesPerDirection)throw c()};t.addEventListener("message",f=>{try{d(i,f.data.byteLength),i+=f.data.byteLength,n.push(f.data.subarray())}catch(p){t.abort(_n(p))}}),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 p of f)d(o,p.byteLength),o+=p.byteLength,t.send(p)||await t.onDrain()}catch(p){throw t.abort(_n(p)),p}},close(f){f?t.abort(f):t.close()}}}class ya{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 Io=2*1024*1024,y0=new TextEncoder,b0=new TextDecoder("utf-8",{fatal:!0});class x0{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 ya(256);outgoingBytes=0;done;send(e){const n=y0.encode(JSON.stringify(e));if(n.length>Io)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(s){throw this.outgoingBytes-=r.byteLength,s}}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>Io*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 s=new DataView(e.buffer,e.byteOffset,4).getUint32(0);if(s>Io||s===0)throw new Error("Invalid record size");if(e.length<s+4)break;const o=JSON.parse(b0.decode(e.subarray(4,s+4)));if(!o||typeof o!="object"||typeof o.id!="string"||typeof o.type!="string")throw new Error("Invalid record");yield o,e=e.slice(s+4)}}if(e.length)throw new Error("Truncated record")}}function Zu(t){let e="";for(let n=0;n<t.length;n+=8192)e+=String.fromCharCode(...t.subarray(n,n+8192));return btoa(e)}function Ju(t){const e=atob(t);return Uint8Array.from(e,n=>n.charCodeAt(0))}function v0(t){const e=new ya(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 s of r)for(let o=0;o<s.length;o+=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(s.subarray(o,o+64*1024))}}catch(s){throw n(s instanceof Error?s:new Error("Encrypted transport failed")),s}}}}const Qu=8,ef=128,E0=5*1024*1024,S0=ef+Qu+8,A0=256,Zr=3e4,er=64*1024;function It(t){return t instanceof Error?t:new Error(String(t??"Secure connection closed"))}function tl(t){if(!t.startsWith("/")||t.startsWith("//")||t.includes("#"))throw new Error("A local API path is required");return t}class tf 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(It(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 k0{constructor(e,n,r){this.channel=e,this.identity=n,this.targetPeerId=r,this.read().catch(s=>this.close(It(s))),e.done.catch(s=>this.close(It(s)))}channel;identity;targetPeerId;pending=new Map;waiting=[];stopped=!1;closeReason;get canSwitchTransport(){return![...this.pending.values()].some(e=>e.kind==="http")&&!this.waiting.some(e=>e.kind==="http")}get closed(){return this.stopped}hasCapacity(e){if(this.pending.size>=S0)return!1;const n=[...this.pending.values()].filter(r=>r.kind===e).length;return e==="http"?n<Qu:e==="socket"?n<ef:!0}allocate(e){if(this.stopped)throw this.closeReason??new Error("Secure connection closed");const n=crypto.randomUUID(),r=new ya(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>=A0?Promise.reject(new Error("连接繁忙,请稍后重试。")):new Promise((r,s)=>{const o=l=>{this.waiting=this.waiting.filter(d=>d!==c),c.cleanup(),s(l)},i=()=>o(n?.reason??new Error("Request aborted")),a=setTimeout(()=>o(new Error("连接等待超时,请重试。")),Zr),c={kind:e,resolve:r,reject:s,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:s}=await this.reserve("request"),o=setTimeout(()=>this.close(new Error("Secure connection timed out")),Math.max(1e3,Math.min(Zr,n?.timeoutMs??Zr)));try{if(this.stopped)throw this.closeReason;this.channel.send({...e,id:r});const i=(await s[Symbol.asyncIterator]().next()).value;if(!i)throw new Error("Secure request closed");if(i.type==="error")throw It(i.error);return i}finally{clearTimeout(o),this.release(r)}}openSocket(e){tl(e);let n;const r=new AbortController,s=new tf(e,o=>{n&&this.channel.send({id:n,type:"ws-data",data:o})},()=>{if(r.abort(),n)try{this.channel.send({id:n,type:"ws-close"})}finally{this.release(n)}});return this.reserve("socket",r.signal).then(o=>{if(n=o.id,s.readyState===3){this.release(n);return}const i=this.pending.get(n);if(!i)throw new Error("Secure connection closed");i.socket=s,this.channel.send({id:n,type:"ws-open",path:e})}).catch(o=>{n&&this.release(n),s.fail(It(o))}),s}async fetch(e,n){const r=typeof location>"u"?"https://termdock.invalid":location.origin,s=e instanceof Request?e:null,o=new URL(s?.url??String(e),r);if(o.origin!==r)throw new Error("Only current-service API requests are supported");const i=new Request(o,s?new Request(s,n):n),a=i.method.toUpperCase(),c=tl(o.pathname+o.search),l=o.pathname==="/api/terminal/fs/upload"?110*1024*1024:E0;if(i.signal.aborted)throw i.signal.reason;const d={};i.headers.forEach((A,_)=>{["cookie","authorization","host","connection","content-length"].includes(_)||(d[_]=A)});const{id:u,queue:f}=await this.reserve("http",i.signal),p=f[Symbol.asyncIterator]();let g;const m=()=>{g?.cancel().catch(()=>{})},x=this.pending.get(u);if(!x)throw new Error("Secure connection closed");x.cancelUpload=m;const y=()=>{m();try{this.channel.send({id:u,type:"cancel"})}catch{}f.end(It(i.signal.reason??"Request aborted")),this.release(u)};i.signal.addEventListener("abort",y,{once:!0});const T=()=>{i.signal.removeEventListener("abort",y),this.release(u)},v=async()=>{let A;try{const _=(await Promise.race([p.next(),new Promise((C,L)=>{A=setTimeout(()=>L(new Error("服务响应超时,请重试。")),Zr)})])).value;if(!_)throw new Error("Secure response ended unexpectedly");if(_.type==="error")throw It(_.error);return _}finally{clearTimeout(A)}};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 R=i.body.getReader();g=R;let E=0,S=0;try{for(;;){const{done:P,value:N}=await R.read();if(P)break;if(E+=N.byteLength,E>l)throw new Error("Request body exceeds upload limit");for(let w=0;w<N.byteLength;w+=er){if(this.channel.send({id:u,type:"upload",data:Zu(N.subarray(w,w+er))}),(await v()).type!=="upload-ack")throw new Error("Invalid upload acknowledgement");S+=Math.min(er,N.byteLength-w),n?.onUploadProgress?.(S)}}}catch(P){throw await R.cancel(P).catch(()=>{}),P}finally{g=void 0,R.releaseLock()}}if(i.signal.aborted||this.stopped)throw new Error("Request aborted");this.channel.send({id:u,type:"upload-end"});const A=await v();if(A.type!=="head"||typeof A.status!="number")throw new Error("Invalid response header");const _=new Headers(A.headers);if(a==="HEAD"||[204,205,304].includes(A.status)){if((await v()).type!=="end")throw new Error("Unexpected response body");return T(),new Response(null,{status:A.status,headers:_})}let C=!1;const L=new ReadableStream({pull:async R=>{try{C&&(this.channel.send({id:u,type:"ack"}),C=!1);const E=await v();if(E.type==="end"){R.close(),T();return}if(E.type!=="chunk"||typeof E.data!="string")throw new Error("Invalid response chunk");const S=Ju(E.data);if(S.length>er)throw new Error("Response chunk exceeds budget");R.enqueue(S),C=!0}catch(E){R.error(E),y(),T()}},cancel:()=>{y(),T()}},{highWaterMark:er,size:R=>R.byteLength});return new Response(L,{status:A.status,headers:_})}catch(A){throw y(),T(),A}}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 Xt(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 Xu(),r=(t.socketFactory??(c=>new WebSocket(c)))(e.href),s=v0(r),o=new AbortController,i=setTimeout(()=>o.abort(new Error("Secure handshake timed out")),2e4),a=t.signal?AbortSignal.any([t.signal,o.signal]):o.signal;try{await new Promise((d,u)=>{if(a.aborted){u(a.reason);return}const f=()=>{a.removeEventListener("abort",m),r.removeEventListener("open",p),r.removeEventListener("error",g),r.removeEventListener("close",g)},p=()=>{f(),d()},g=()=>{f(),u(new Error("Secure transport unavailable"))},m=()=>{f(),u(a.reason)};a.addEventListener("abort",m,{once:!0}),r.addEventListener("open",p),r.addEventListener("error",g),r.addEventListener("close",g),r.readyState===1&&p()});const c=await m0({identity:n,duplex:s,initiator:!0,targetPinnedPeerId:t.targetPeerId,signal:a}),l=new k0(new x0(c.duplex),n,c.authenticatedPeerId);if(t.pairingCode)try{await l.request({type:"pair",code:t.pairingCode})}catch(d){throw l.close(It(d)),d}return l}catch(c){throw r.close(),c}finally{clearTimeout(i)}}const nl=256*1024,T0=1024*1024;class C0 extends EventTarget{constructor(e,n,r=s=>new WebSocket(s)){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",s=>{if(this.readyState!==3)try{if(typeof s.data!="string"||new TextEncoder().encode(s.data).length>nl)throw new Error("Invalid relay envelope");const o=JSON.parse(s.data);if(o.type==="ready"&&!this.requested){this.requested=!0,this.transmit({type:"open",streamId:this.streamId,serviceId:n});return}if(o.streamId!==this.streamId)return;if(o.type==="opened"&&this.readyState===0){clearTimeout(this.deadline),this.readyState=1;const l=new Event("open");this.dispatchEvent(l),this.onopen?.(l);return}if(o.type==="close"){this.finish(1001,"Relay route closed"),this.upstream.close();return}if(o.type!=="data"||this.readyState!==1||o.encoding!=="base64"||typeof o.payload!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(o.payload))throw new Error("Invalid ciphertext relay frame");const i=Ju(o.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",s=>this.finish(s.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>T0||n.length>nl)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:Zu(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 nf(t){return e=>new C0(e,t)}function I0(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((s,o)=>{if(o===0||s===""&&o===e.split("/").length-1)return s;const i=decodeURIComponent(s);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 R0(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 s=r.ports[0],{path:o,method:i,headers:a,body:c,expectedTargetPeerId:l,previewPrefix:d}=r.data;let u;try{u=new URL(o,location.origin)}catch{s.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)){s.postMessage({type:"error"}),s.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)||!I0(u.pathname)?.startsWith(d))){s.postMessage({type:"error"}),s.close();return}const f=new AbortController;let p,g,m=!1,x=!1;const y=()=>{x||(x=!0,e.delete(y),f.abort(),p?.cancel().catch(()=>{}),s.close())};e.add(y),s.onmessage=T=>{if(T.data?.type==="cancel"){y();return}T.data?.type!=="pull"||m||x||(m=!0,(async()=>{if(!p){s.postMessage({type:"end"}),y();return}if(!g?.length){const A=await p.read();if(A.done){s.postMessage({type:"end"}),y();return}g=A.value}const v=g.slice(0,64*1024);g=g.subarray(v.length),s.postMessage({type:"chunk",data:v.buffer},[v.buffer])})().catch(()=>{s.postMessage({type:"error"}),y()}).finally(()=>{m=!1}))},s.onmessageerror=y,s.start(),(async()=>{const T=await t();if(x)return;if(l&&l!==T.targetPeerId)throw new Error("Preview target changed");const v=await T.fetch(u.pathname+u.search,{method:i,headers:a,body:["GET","HEAD"].includes(i)?void 0:c,signal:f.signal});if(x){await v.body?.cancel();return}p=v.body?.getReader();const A={};v.headers.forEach((_,C)=>{A[C]=_}),s.postMessage({type:"head",status:v.status,headers:A,bodyless:!p,targetPeerId:T.targetPeerId})})().catch(()=>{x||(s.postMessage({type:"error"}),y())})};return navigator.serviceWorker.addEventListener("message",n),()=>{navigator.serviceWorker.removeEventListener("message",n);for(const r of[...e])r()}}class _e extends Error{constructor(){super("Device authorization expired or revoked")}}async function Dn(t){const e=await t.request({type:"permissions"},{timeoutMs:5e3});if(e.type!=="result"||typeof e.fullService!="boolean"||!Array.isArray(e.grants))throw new Error("Invalid permission response");const n=e.grants,r=e.fullService===!0;if(!r&&n.length===0)throw new _e;return{fullService:r,grants:n,canManage:r&&n.length>0||n.some(s=>s.actions.includes("authorization.manage"))}}let Ro;async function De(){return Ro||(Ro=(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((s,o)=>{const i=t.transaction("keys").objectStore("keys").get("identity");i.onsuccess=()=>s(i.result),i.onerror=()=>o(i.error)});if(e)return el(e);const n=await Xu();let r=n;return await new Promise((s,o)=>{const i=t.transaction("keys","readwrite"),a=i.objectStore("keys"),c=a.get("identity");c.onsuccess=()=>{typeof c.result=="string"?r=el(c.result):a.put(f0(n),"identity")},i.oncomplete=()=>s(),i.onerror=()=>o(i.error)}),r}finally{t.close()}})()),Ro}const Ar="termdock:secure-state";let Q,tr,Ge,Bs="direct",Po=!1;const Fn=globalThis.fetch.bind(globalThis);function ye(){return ch()}function No(){return Q}function Pi(){Q?.close(),Ge?.close(),Q=void 0,Ge=void 0}async function rf(){const t=await Fn("/api/auth/status");if(!t.ok)throw new Error("Failed to query auth status");return t.json()}async function P0(){if(ye()){await ft();return}if((await rf()).enabled)return;const t=await Fn("/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 Ve({url:location.origin,targetPeerId:e,serviceName:location.hostname})}async function N0(t,e){const{startPasswordBootstrap:n,finishPasswordBootstrap:r}=await Un(async()=>{const{startPasswordBootstrap:l,finishPasswordBootstrap:d}=await import("./passwordBootstrap-hj2Lcgoj.js");return{startPasswordBootstrap:l,finishPasswordBootstrap:d}},__vite__mapDeps([0,1,2,3])),s=l=>t===location.origin?l:new URL(l,t).href,o=async(l,d)=>{const u=await Fn(s(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 o("/api/auth/password/parameters"),a=await De(),c=await n(e,i);try{const l=await o("/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 o("/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 ba(t,e){try{return await N0(t,e)}catch(n){if(!(n instanceof TypeError)&&!(n instanceof DOMException))throw n;const r=(await nt()).find(o=>o.targetPeerId&&(o.serviceOrigin||o.url)===t);if(!r?.targetPeerId)throw new Error("暂时连不上这台服务,请检查地址和网络。");const s={...r,targetPeerId:r.targetPeerId,serviceName:r.label};return await sf(s,e),s}}async function sf(t,e){const n=await B0(t),{startPasswordBootstrap:r,finishPasswordBootstrap:s}=await Un(async()=>{const{startPasswordBootstrap:i,finishPasswordBootstrap:a}=await import("./passwordBootstrap-hj2Lcgoj.js");return{startPasswordBootstrap:i,finishPasswordBootstrap:a}},__vite__mapDeps([0,1,2,3]));let o;try{const i=await n.request({type:"password-parameters"},{timeoutMs:5e3});o=await r(e,String(i.saltHex));const a=await n.request({type:"password-start",startLoginRequest:o.startLoginRequest,origin:location.origin}),c=await s(o,a,{clientIdentity:(await De()).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{o&&(o.passwordKey=""),n.close()}}async function L0(t){try{const e=ye(),n=e?.serviceOrigin||location.origin,r=await ba(n,t);return await Ve({...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 rl(t,e){const n=Ce(t),r=(await nt()).find(i=>(i.serviceOrigin||i.url)===n&&i.targetPeerId);if(e===void 0&&r?.targetPeerId)try{return await Ve({...r,targetPeerId:r.targetPeerId,serviceName:r.label}),{}}catch(i){if(!(i instanceof _e))throw i}if(e!==void 0){const i=await ba(n,e);if(r?.targetPeerId&&r.targetPeerId!==i.targetPeerId)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await Ve({...i,routes:r?.routes,serviceName:r?.label||i.serviceName}),{}}const s=await Fn(new URL("/api/auth/open/parameters",n).href,{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(1e4)}).catch(()=>{throw new Error("暂时连不上这台服务,请检查地址和网络后重试。")});if(s.status===403)return{passwordRequired:!0};if(!s.ok)throw new Error("这台服务暂时不可用,请稍后重试。");const{serviceIdentity:o}=await s.json();if(typeof o!="string"||!o)throw new Error("这不是可连接的 Termdock 服务。");if(r?.targetPeerId&&r.targetPeerId!==o)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await Ve({url:n,targetPeerId:o,serviceName:r?.label||new URL(n).host,serviceOrigin:n}),{}}function Yt(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(qi)||"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(s=>s.targetPeerId===n.targetPeerId)===r?[{url:Ce(n.url),targetPeerId:n.targetPeerId}]:[]}catch{return[]}}).slice(0,4)}function Js(t){const e=Yt(t),n=[t.serviceOrigin||t.url,...(t.routes||[]).slice(0,4).filter(s=>s.targetPeerId===t.targetPeerId).map(s=>s.url)],r=new Set;for(const s of n)try{const o=Ce(s);e.some(i=>i.url===o)||r.add(o)}catch{}return[...r]}function Zt(t){const e=new URL("/api/federation/secure",Ce(t));return e.protocol=e.protocol==="https:"?"wss:":"ws:",e.href}async function _t(t){return Xt({url:Zt(t.url),targetPeerId:t.targetPeerId,identity:await De(),signal:AbortSignal.timeout(5e3)})}async function B0(t){const e=Yt(t);for(const n of Js(t))try{return await Xt({url:Zt(n),targetPeerId:t.targetPeerId,identity:await De(),signal:AbortSignal.timeout(3e3)})}catch{}for(const n of e){let r;try{r=await _t(n);const s=await r.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(typeof s.routeToken!="string")continue;const o=new URL(Zt(n.url));return o.pathname="/api/federation/relay",o.searchParams.set("routeToken",s.routeToken),await Xt({url:o.href,targetPeerId:t.targetPeerId,identity:await De(),socketFactory:nf(t.targetPeerId),signal:AbortSignal.timeout(8e3)})}catch{}finally{r?.close()}}throw new Error("当前无法连接。请检查网络,或请入口管理员授权此设备访问该服务。")}async function Ve(t){const e=Q,n=Ge,r=await De(),s=Ce(t.serviceOrigin||t.url),o=(await nt()).find(x=>x.targetPeerId===t.targetPeerId),i={...t,routes:t.routes??o?.routes},a=Yt(i),c=Js(i);let l,d,u=t.pairingCode,f="direct";const p=new Set,g=new Map,m=async x=>{if(n&&!n.closed&&n.targetPeerId===x.targetPeerId)return n;const y=g.get(x.targetPeerId);if(y&&!y.closed)return y;const T=await _t(x);return p.add(T),g.set(x.targetPeerId,T),T};try{if(t.routeCode&&t.entryServiceId){const A=a.find(L=>L.targetPeerId===t.entryServiceId);if(!A)throw new Error("邀请缺少入口信息。");if((await(await m(A)).request({type:"route-pair",code:t.routeCode})).serviceId!==t.targetPeerId)throw new Error("邀请的目标服务不一致。");t.routeOnly&&await Pn({id:t.targetPeerId,url:s,label:t.serviceName||new URL(s).host,targetPeerId:t.targetPeerId,serviceOrigin:s,routes:a})}let x;for(const A of c)try{l=await Xt({url:Zt(A),targetPeerId:t.targetPeerId,pairingCode:u,identity:r,signal:AbortSignal.timeout(a.length||c.length>1?3e3:1e4)}),u=void 0,await Dn(l);break}catch(_){if(l?.close(),l=void 0,_ instanceof _e)throw _;x=_}if(!l)for(const A of a){let _;try{_=await m(A);const C=await _.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(typeof C.routeToken!="string"||!C.routeToken)throw new Error("入口未允许此设备连接该服务。");const L=new URL(Zt(A.url));L.pathname="/api/federation/relay",L.searchParams.set("routeToken",C.routeToken),l=await Xt({url:L.href,targetPeerId:t.targetPeerId,pairingCode:u,identity:r,socketFactory:nf(t.targetPeerId),signal:AbortSignal.timeout(8e3)}),u=void 0,await Dn(l),d=_,f="relay";break}catch(C){if(l?.close(),l=void 0,_&&_!==n&&_.close(),C instanceof _e)throw C;x=C}}if(!l)throw x||new Error("当前网络无法连接这台服务,也没有可用的已授权入口。");if(Q!==e&&Q&&!Q.closed&&Q.targetPeerId===t.targetPeerId){l.close();for(const A of p)A!==Ge&&A.close();return Q}f==="direct"&&new URL(s).host===location.host&&lh(t.targetPeerId);const y=(await nt()).find(A=>A.targetPeerId===t.targetPeerId||!A.targetPeerId&&(A.serviceOrigin||A.url)===s),T=y?.label||t.serviceName||new URL(s).host,v={url:s,targetPeerId:t.targetPeerId,serviceName:T,serviceOrigin:s,routes:i.routes??a};await Pn({id:y?.id||t.targetPeerId,...v,label:T}),Gl(v),Q=l,Bs=f,Ge=d;for(const A of new Set([e,n,...p]))A&&A!==l&&A!==d&&A.close();return Fs!==t.targetPeerId?(location.reload(),new Promise(()=>{})):(window.dispatchEvent(new Event(Ar)),l)}catch(x){l?.close();for(const y of p)y!==n&&y.close();throw x}}async function _0(){const t=Q,e=ye();if(Po||Bs!=="relay"||!t||t.closed||!t.canSwitchTransport||!e?.serviceOrigin)return;Po=!0;let n;try{for(const s of Js(e))try{n=await Xt({url:Zt(s),targetPeerId:e.targetPeerId,identity:await De(),signal:AbortSignal.timeout(3e3)}),await Dn(n);break}catch(o){if(n?.close(),n=void 0,o instanceof _e)throw o}if(!n||Q!==t||!t.canSwitchTransport)return;const r=Ge;Q=n,n=void 0,Ge=void 0,Bs="direct",t.close(),r?.close(),window.dispatchEvent(new Event(Ar))}catch(r){r instanceof _e&&Q===t&&(Pi(),window.dispatchEvent(new Event("auth:unauthorized")))}finally{n?.close(),Po=!1}}async function ft(){if(Q&&!Q.closed)return Q;if(Q=void 0,tr)return tr;const t=ye();if(!t)throw new Error("DEVICE_PAIRING_REQUIRED");return tr=Ve(t).catch(e=>{if(Q&&!Q.closed&&Q.targetPeerId===t.targetPeerId)return Q;throw e}).finally(()=>{tr=void 0}),tr}function D0(t){const e=new URL(t,location.href);if(Q&&!Q.closed)return Q.openSocket(e.pathname+e.search);let n;const r=new tf(t,s=>n?.send(s),()=>n?.close());return ft().then(s=>{r.readyState!==3&&(n=s.openSocket(e.pathname+e.search),n.onopen=()=>r.accept({type:"ws-ready",id:""}),n.onmessage=o=>r.accept({type:"ws-data",id:"",data:o.data}),n.onclose=o=>r.accept({type:"ws-close",id:"",code:o.code,reason:o.reason}),n.onerror=()=>r.fail(new Error("Encrypted connection unavailable")))}).catch(s=>r.fail(s)),r}function F0(){R0(ft),window.fetch=async(t,e)=>{const n=new URL(t instanceof Request?t.url:String(t),location.href);if(!n.pathname.startsWith("/api/"))return Fn(t,e);if(n.origin!==location.origin)throw new Error("Remote business API requires a paired encrypted service");if(n.pathname==="/api/meta")return Fn(t,e);if(n.pathname==="/api/auth/status"){const s=await rf();if(!ye())return Response.json({enabled:s.enabled,authenticated:!1});try{return await Dn(await ft()),Response.json({enabled:s.enabled,authenticated:!0})}catch(o){if(o instanceof _e)return Response.json({enabled:s.enabled,authenticated:!1});throw o}}if(n.pathname==="/api/auth/login"){const o=await new Request(t instanceof Request?t:n.href,e).json();return L0(typeof o.password=="string"?o.password:"")}if(n.pathname==="/api/csrf-token")return Response.json({csrfToken:"encrypted-device-channel"});if(n.pathname==="/api/auth/logout")return Q&&!Q.closed&&await Q.request({type:"logout"}),Q?.close(),Ge?.close(),Q=void 0,Ge=void 0,localStorage.removeItem(Vt),sessionStorage.removeItem(Vt),localStorage.removeItem(qi),location.reload(),Response.json({ok:!0});const r=await ft();return t instanceof Request?r.fetch(t,e):r.fetch(n.pathname+n.search,e)}}async function O0(t){if(!t.targetPeerId)throw new Error("请先连接这台服务,再查看可中转的服务。");for(const e of Js({...t,targetPeerId:t.targetPeerId})){let n;const r={url:e,targetPeerId:t.targetPeerId};try{n=await _t(r)}catch{continue}try{const s=await n.request({type:"route-targets"},{timeoutMs:5e3});if(!Array.isArray(s.items))throw new Error("入口服务需要更新后才能查看中转列表。");return{route:r,canManage:s.canManage===!0,items:s.items}}catch(s){throw s instanceof Error&&/UNKNOWN|UNSUPPORTED/i.test(s.message)?new Error("入口服务需要更新后才能查看中转列表。"):s}finally{n.close()}}throw new Error("暂时连不上中转入口,请检查地址和网络后重试。")}async function M0(t,e){const n=await _t(t);try{const r=await n.request({type:"route-targets"},{timeoutMs:5e3}),s=(Array.isArray(r.items)?r.items:[]).find(c=>c.serviceId===e);if(!s)throw new Error("该服务已不可见,请刷新列表或请入口管理员授权。");if(!s.available)throw new Error("入口暂时无法中转到这台服务,请稍后重试。");const o=(await nt()).find(c=>c.targetPeerId===s.serviceId),i=[t,...(o?.routes||[]).filter(c=>c.targetPeerId!==t.targetPeerId)];if(i.length>4)throw new Error("这台服务已保存 4 个备用连接,请先移除一个后重试。");if(!s.authorized){if(!r.canManage)throw new Error("请先让入口管理员授权此设备。");await n.request({type:"route-grant",serviceId:s.serviceId,subjectId:(await De()).peerId})}const a=o?.serviceOrigin||o?.url||s.url||t.url;return{url:a,serviceOrigin:a,targetPeerId:s.serviceId,serviceName:o?.label||s.label||(s.url?new URL(s.url).host:`中转服务 ${s.serviceId.slice(0,8)}`),routes:i}}finally{n.close()}}async function j0(t,e){const n=await _t(t);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),s=(await De()).peerId;return{canManage:r.canManage===!0,grants:(Array.isArray(r.grants)?r.grants:[]).filter(o=>o.subjectId===s&&o.targetServiceId===e)}}finally{n.close()}}async function U0(t,e,n){if(n!==void 0&&(await ba(Ce(e.url),n)).targetPeerId!==e.targetPeerId)throw new Error("入口服务的身份已改变,请重新连接并确认。");const r=await _t(e);try{await r.request({type:"route-grant",serviceId:t.targetPeerId,subjectId:(await De()).peerId,url:Ce(t.serviceOrigin||t.url)})}finally{r.close()}}async function $0(t,e){const n=await _t(e);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),s=(await De()).peerId,o=(Array.isArray(r.grants)?r.grants:[]).filter(i=>i.subjectId===s&&i.targetServiceId===t&&i.active);for(const i of o)await n.request({type:"route-revoke",grantId:i.id})}finally{n.close()}}async function of(t,e){const n=await _t(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 os(t,e){const n=(await nt()).find(s=>s.id===t.id||t.targetPeerId&&s.targetPeerId===t.targetPeerId)||t;await Pn({...n,url:n.serviceOrigin||n.url,entryServiceId:void 0,routes:e});const r=ye();r&&r.targetPeerId===t.targetPeerId&&Gl({...r,url:r.serviceOrigin||r.url,entryServiceId:void 0,routes:e})}async function H0(t,e){const n=t.targetPeerId;if(!n)throw new Error("请先连接这台服务,再添加备用地址。");let r;try{r=Ce(e)}catch{throw new Error("请输入有效的 HTTPS 地址,例如 https://电脑地址:9834。")}const s=async()=>(await nt()).find(a=>a.targetPeerId===n)||t,o=a=>{const c=a.routes??Yt({...a,targetPeerId:n});if(Ce(a.serviceOrigin||a.url)===r||c.some(l=>Ce(l.url)===r))throw new Error("这个地址已经在连接列表中。");if(c.length>=4)throw new Error("最多保存 4 个备用地址或入口,请先移除不再使用的连接。");return[...c,{url:r,targetPeerId:n}]};o(await s());let i;try{try{i=await Xt({url:Zt(r),targetPeerId:n,identity:await De(),signal:AbortSignal.timeout(5e3)}),await Dn(i)}catch(l){throw l instanceof _e?new Error("这台服务尚未授权当前设备,请先恢复设备授权。"):new Error("无法验证这个地址。请确认能访问该地址、HTTPS 证书受信任,且运行的是同一台 Termdock 服务。")}const a=await s(),c=o(a);if(await os(a,c),ye()?.targetPeerId===n&&Fs===n&&(!Q||Q.closed)){const l=Q,d=Ge;Q=i,i=void 0,Ge=void 0,Bs="direct",l?.close(),d?.close(),window.dispatchEvent(new Event(Ar))}return c}finally{i?.close()}}async function sl(t,e){await sf(t,e),await Ve({...t,pairingCode:void 0,routeCode:void 0})}function q0(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}`}const af=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim();const K0=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const z0=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,r)=>r?r.toUpperCase():n.toLowerCase());const ol=t=>{const e=z0(t);return e.charAt(0).toUpperCase()+e.slice(1)};var Lo={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 V0=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1},G0=$.createContext({}),W0=()=>$.useContext(G0),X0=$.forwardRef(({color:t,size:e,strokeWidth:n,absoluteStrokeWidth:r,className:s="",children:o,iconNode:i,...a},c)=>{const{size:l=24,strokeWidth:d=2,absoluteStrokeWidth:u=!1,color:f="currentColor",className:p=""}=W0()??{},g=r??u?Number(n??d)*24/Number(e??l):n??d;return $.createElement("svg",{ref:c,...Lo,width:e??l??Lo.width,height:e??l??Lo.height,stroke:t??f,strokeWidth:g,className:af("lucide",p,s),...!o&&!V0(a)&&{"aria-hidden":"true"},...a},[...i.map(([m,x])=>$.createElement(m,x)),...Array.isArray(o)?o:[o]])});const Ne=(t,e)=>{const n=$.forwardRef(({className:r,...s},o)=>$.createElement(X0,{ref:o,iconNode:e,className:af(`lucide-${K0(ol(t))}`,`lucide-${t}`,r),...s}));return n.displayName=ol(t),n};const Y0=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],cf=Ne("arrow-left",Y0);const Z0=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],J0=Ne("arrow-right",Z0);const Q0=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],xa=Ne("check",Q0);const ex=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],tx=Ne("chevron-down",ex);const nx=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Jt=Ne("chevron-right",nx);const rx=[["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"}]],lf=Ne("copy",rx);const sx=[["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"}]],ox=Ne("ellipsis",sx);const ix=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],We=Ne("loader-circle",ix);const ax=[["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"}]],cx=Ne("monitor",ax);const lx=[["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"}]],dx=Ne("pencil",lx);const ux=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],df=Ne("plus",ux);const fx=[["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"}]],Qs=Ne("server",fx);const hx=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],uf=Ne("smartphone",hx);const px=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],gx=Ne("x",px);function mx({service:t,onBusyChange:e,onConnect:n,onConnectWithPassword:r}){const[s,o]=$.useState(),[i,a]=$.useState(!0),[c,l]=$.useState(!1),[d,u]=$.useState(""),[f,p]=$.useState(0),[g,m]=$.useState(),[x,y]=$.useState("");$.useEffect(()=>{let A=!1;return a(!0),u(""),o(void 0),O0(t).then(_=>{A||o(_)}).catch(_=>{A||u(_ instanceof Error?_.message:"暂时无法读取中转列表,请重试。")}).finally(()=>{A||a(!1)}),()=>{A=!0}},[t.id,t.url,f]);const T=async A=>{if(!c){l(!0),e(!0),u("");try{await A()}catch(_){u(_ instanceof Error?_.message:"暂时无法连接,请重试。")}finally{l(!1),e(!1)}}},v=async A=>{const _=await M0(s.route,A.serviceId);try{await n(_)}catch(C){if(!(C instanceof _e))throw C;m(_)}};return h.jsxs("div",{className:"service-form",children:[g?h.jsxs("form",{className:"service-form",onSubmit:A=>{A.preventDefault(),T(async()=>{try{await r?.(g,x)}finally{y("")}})},children:[h.jsxs("p",{className:"service-help",children:["已通过“",t.label,"”连接到“",g.serviceName,"”。请登录目标服务,完成此设备的访问授权。"]}),r?h.jsxs(h.Fragment,{children:[h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"目标服务密码"}),h.jsx("input",{type:"password",autoFocus:!0,required:!0,autoComplete:"current-password",value:x,disabled:c,onChange:A=>y(A.target.value)})]}),h.jsx("button",{type:"submit",className:"service-button service-primary",disabled:c||!x,children:c?"正在登录…":"登录并连接"})]}):h.jsx("p",{className:"service-help",children:"请让目标服务管理员邀请此设备后再连接。"}),h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>{m(void 0),y(""),u(""),p(A=>A+1)},children:"返回中转列表"})]}):h.jsxs(h.Fragment,{children:[h.jsxs("p",{className:"service-help",children:["通过“",t.label,"”连接下方服务。",s?.canManage?"选择未授权的服务会授权此设备使用该中转。":"这里只显示已授权给此设备的中转。","目标服务会单独验证访问权限。"]}),i?h.jsxs("p",{className:"service-feedback",role:"status",children:[h.jsx(We,{size:16,className:"service-spinning"}),"正在读取可中转的服务…"]}):s&&h.jsxs("div",{className:"service-list",children:[s.items.map(A=>h.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:c||!A.available,onClick:()=>{T(()=>v(A))},children:[h.jsx("span",{className:"service-icon",children:h.jsx(Qs,{size:19})}),h.jsxs("span",{className:"service-row-copy",children:[h.jsx("span",{className:"service-name",children:A.label||(A.url?new URL(A.url).host:`中转服务 ${A.serviceId.slice(0,8)}`)}),h.jsx("span",{className:"service-description",children:A.available?A.authorized?"已获中转授权 · 连接":"授权此设备并连接":"中转暂不可用"})]}),h.jsx(Jt,{size:16})]},A.serviceId)),s.items.length===0&&h.jsx("p",{className:"service-empty",children:s.canManage?"暂无可中转的服务。可在本机 Mac 客户端连接目标服务,或在目标服务的“备用连接”中启用本入口。":"暂无已授权的中转服务,请让入口管理员分享备用连接邀请。"})]}),c&&h.jsxs("p",{className:"service-feedback",role:"status",children:[h.jsx(We,{size:16,className:"service-spinning"}),"正在授权并连接目标服务…"]}),!i&&h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>p(A=>A+1),children:"刷新列表"})]}),d&&h.jsx("p",{className:"service-error",role:"alert",children:d})]})}const Ni="#termdock-invite=";function ff(t){const e=new URL(t.entryUrl);e.hash="",e.search="",e.pathname="/";const n=new TextEncoder().encode(JSON.stringify(t));return e.hash=Ni.slice(1)+btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.href}function _s(t){const e=new URL(t);if(!["https:","http:"].includes(e.protocol)||!e.hash.startsWith(Ni))throw new Error("这不是有效的 Termdock 邀请链接");const n=e.hash.slice(Ni.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 s=new URL(r.entryUrl);if(s.origin!==e.origin||s.username||s.password||!["https:","http:"].includes(s.protocol))throw new Error("邀请地址与服务不一致");if(s.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(s.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 o=s.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("目标服务地址无效");o=r.entryServiceId&&r.entryServiceId!==r.serviceId?i.origin:s.origin}return{url:s.origin,targetPeerId:r.serviceId,pairingCode:r.code,...r.routeOnly===!0?{routeOnly:!0}:{},serviceOrigin:o,serviceName:typeof r.name=="string"?r.name.slice(0,120):void 0,entryServiceId:r.entryServiceId,routeCode:r.routeCode}}function wx({service:t,onBusyChange:e}){const n={...t,targetPeerId:t.targetPeerId,serviceName:t.label},[r,s]=$.useState(()=>t.routes??Yt(n)),[o,i]=$.useState([]),[a,c]=$.useState(!0),[l,d]=$.useState(!1),[u,f]=$.useState(""),p=I=>{d(I),e(I)},[g,m]=$.useState(),[x,y]=$.useState(""),[T,v]=$.useState(""),[A,_]=$.useState(""),[C,L]=$.useState(!1),[R,E]=$.useState(),[S,P]=$.useState(),[N,w]=$.useState(!1);$.useEffect(()=>{let I=!1;return nt().then(F=>{I||i(F.filter(O=>O.targetPeerId&&O.targetPeerId!==t.targetPeerId))}).catch(()=>{I||f("暂时无法读取可用服务。")}).finally(()=>{I||c(!1)}),()=>{I=!0}},[t.targetPeerId]);const b=I=>o.find(F=>F.targetPeerId===I.targetPeerId)?.label||new URL(I.url).host,k=async I=>{p(!0),f(""),_("");try{await I()}catch(F){const O=F instanceof Error?F.message:"";f(/AUTHORIZATION|DENIED/.test(O)?"当前设备没有入口管理权限。请让管理员分享备用连接邀请,或使用入口密码授权。":"暂时无法完成。请确认入口能连接目标服务,且目标地址、证书和授权有效。")}finally{p(!1)}},B=async(I,F)=>{const O={url:I.serviceOrigin||I.url,targetPeerId:I.targetPeerId};await k(async()=>{const K=await j0(O,n.targetPeerId);if(!K.grants.some(H=>H.active)){if(!K.canManage&&F===void 0){m(I);return}await U0(n,O,F)}const q=[...r.filter(H=>H.targetPeerId!==O.targetPeerId),O];await os(t,q),s(q),m(void 0),y("")})};if(S)return h.jsxs("div",{className:"service-form",children:[h.jsxs("p",{className:"service-help",children:["把链接发给需要使用此备用连接的人。它只允许通过入口连接“",t.label,"”,对方仍需获得目标服务的访问权限。"]}),h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"备用连接邀请"}),h.jsx("input",{readOnly:!0,value:S,onFocus:I=>I.target.select()})]}),h.jsxs("button",{type:"button",className:"service-button service-primary",onClick:()=>{navigator.clipboard.writeText(S).then(()=>w(!0)).catch(()=>f("无法自动复制,请长按链接复制。"))},children:[h.jsx(lf,{size:16}),N?"已复制":"复制邀请链接"]}),h.jsx("button",{type:"button",className:"service-button service-secondary",onClick:()=>{P(void 0),w(!1)},children:"返回备用连接"}),u&&h.jsx("p",{role:"alert",className:"service-error",children:u})]});if(g)return h.jsxs("form",{className:"service-form",onSubmit:I=>{I.preventDefault(),B(g,x).finally(()=>y(""))},children:[h.jsxs("p",{className:"service-help",children:["需要“",g.label,"”的管理员授权。若这是你的服务,可以使用它的密码;否则请管理员分享备用连接邀请。"]}),h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"入口服务密码"}),h.jsx("input",{type:"password",required:!0,value:x,onChange:I=>y(I.target.value),autoComplete:"current-password",disabled:l,autoFocus:!0})]}),h.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||!x,children:l?"正在授权…":"授权并启用"}),h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{m(void 0),y("")},children:"取消"}),u&&h.jsx("p",{role:"alert",className:"service-error",children:u})]});const M=r.filter(I=>I.targetPeerId===n.targetPeerId),U=r.filter(I=>I.targetPeerId!==n.targetPeerId),D=async()=>{if(!l){p(!0),L(!0),f(""),_("");try{s(await H0({...t,routes:r},T)),v(""),_("备用地址已验证并保存。")}catch(I){f(I instanceof Error?I.message:"暂时无法添加地址,请重试。")}finally{p(!1),L(!1)}}};return h.jsxs("div",{className:"service-form",children:[h.jsx("p",{className:"service-help",children:"电脑换了网络?添加它在新网络下的地址,原地址连不上时会自动尝试。只接受同一台服务。"}),h.jsxs("form",{className:"service-form",onSubmit:I=>{I.preventDefault(),D()},children:[h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"备用地址"}),h.jsx("input",{value:T,onChange:I=>{v(I.target.value),f(""),_("")},required:!0,disabled:l||r.length>=4,inputMode:"url",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:192.168.10.20:9834"})]}),h.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||r.length>=4||!T.trim(),children:C?h.jsxs(h.Fragment,{children:[h.jsx(We,{size:16,className:"service-spinning"}),"正在验证…"]}):"验证并添加"})]}),u&&h.jsx("p",{role:"alert",className:"service-error",children:u}),A&&h.jsx("p",{role:"status",className:"service-help",children:A}),r.length>=4&&h.jsx("p",{className:"service-help",children:"已保存 4 个备用连接。移除不再使用的地址或入口后,可以继续添加。"}),h.jsxs("div",{children:[h.jsx("p",{className:"service-help",children:"首选地址"}),h.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url})]}),M.length>0&&h.jsx("div",{className:"service-list",children:M.map(I=>h.jsxs("div",{className:"service-route-item",children:[h.jsxs("div",{className:"service-route-line",children:[h.jsx("span",{className:"service-address service-route-address",children:I.url}),h.jsx("button",{type:"button",className:"service-icon-button","aria-label":`移除地址 ${I.url}`,disabled:l,onClick:()=>E(I),children:"移除"})]}),R?.targetPeerId===I.targetPeerId&&R.url===I.url&&h.jsxs("div",{className:"service-form",children:[h.jsx("p",{className:"service-help",children:"从备用连接中移除此地址?不会停止正在运行的终端。"}),h.jsxs("div",{className:"service-actions service-actions-pair",children:[h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>E(void 0),children:"取消"}),h.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{k(async()=>{const F=r.filter(O=>O.targetPeerId!==I.targetPeerId||O.url!==I.url);await os(t,F),s(F),E(void 0)})},children:"确认移除"})]})]})]},I.url))}),h.jsxs("details",{className:"service-relay-options",children:[h.jsxs("summary",{children:["通过其他服务中转",U.length?`(${U.length})`:""]}),h.jsxs("div",{className:"service-form",children:[h.jsx("p",{className:"service-help",children:"所有直连地址都不可用时,尝试下方已授权入口;直连恢复后自动切回。"}),U.length>0&&h.jsx("div",{className:"service-list",children:U.map(I=>h.jsxs("div",{className:"service-route-item",children:[h.jsxs("div",{className:"service-route-line",children:[h.jsx("span",{className:"service-icon",children:h.jsx(Qs,{size:18})}),h.jsx("span",{className:"service-name",children:b(I)}),h.jsx(xa,{size:16,className:"service-selected"})]}),R?.targetPeerId===I.targetPeerId?h.jsxs("div",{className:"service-form",children:[h.jsxs("p",{className:"service-help",children:["撤销此设备经“",b(I),"”连接目标的权限?如当前无法直连,目标服务将断开。"]}),h.jsxs("div",{className:"service-actions service-actions-pair",children:[h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>E(void 0),children:"取消"}),h.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{k(async()=>{await $0(n.targetPeerId,I);const F=r.filter(O=>O.targetPeerId!==I.targetPeerId);await os(t,F),s(F),E(void 0)})},children:"确认撤销"})]})]}):h.jsxs("div",{className:"service-actions service-actions-pair",children:[h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{k(async()=>{const F=await of(n,I);P(ff({v:1,routeOnly:!0,serviceId:n.targetPeerId,name:t.label,serviceUrl:t.serviceOrigin||t.url,entryUrl:I.url,entryServiceId:I.targetPeerId,routeCode:F.routeCode}))})},children:"分享备用连接"}),h.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>E(I),children:"撤销授权"})]})]},I.targetPeerId))}),a?h.jsxs("p",{role:"status",className:"service-feedback",children:[h.jsx(We,{size:16,className:"service-spinning"}),"正在读取服务…"]}):h.jsxs("div",{children:[h.jsx("p",{className:"service-help",children:"添加中转入口"}),o.filter(I=>!r.some(F=>F.targetPeerId===I.targetPeerId)).map(I=>h.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:l||r.length>=4,onClick:()=>{B(I)},children:[h.jsxs("span",{className:"service-row-copy",children:[h.jsx("span",{className:"service-name",children:I.label}),h.jsx("span",{className:"service-description",children:"验证并授权后启用"})]}),h.jsx(Jt,{size:16})]},I.id)),o.length===0&&h.jsx("p",{className:"service-empty",children:"添加并登录另一台服务后,可以将它设为中转入口。"})]})]})]}),l&&!C&&h.jsxs("p",{role:"status",className:"service-feedback",children:[h.jsx(We,{size:16,className:"service-spinning"}),"正在验证连接与授权…"]})]})}function yx({current:t,renderRoutes:e,renderRelayServices:n,onOpen:r,onAdd:s,onInvite:o,hideHeader:i,onNavigation:a,onBusyChange:c,initiallyAdding:l=!1}){const[d,u]=$.useState([]),[f,p]=$.useState(!0),[g,m]=$.useState(l?{kind:"add"}:{kind:"list"}),[x,y]=$.useState(!1),T=$.useCallback(w=>{y(w),c?.(w)},[c]),[v,A]=$.useState(""),_=$.useCallback(()=>{m(w=>w.kind==="routes"||w.kind==="relay-services"?{kind:"edit",service:w.service}:{kind:"list"}),A("")},[]),C=g.kind==="add"?"添加服务":g.kind==="edit"?"服务设置":g.kind==="routes"?"备用连接":g.kind==="relay-services"?"可中转的服务":void 0;$.useEffect(()=>{a?.({title:C,...C?{back:_}:{}})},[C,_,a]),$.useEffect(()=>{let w=!1,b=0;const k=async()=>{const M=++b;try{const U=await nt();!w&&b===M&&(u(U),A(""))}catch{!w&&b===M&&A("暂时无法读取服务列表,请重试。")}finally{!w&&b===M&&p(!1)}};k();const B=gh(()=>{k()});return()=>{w=!0,B()}},[]);const L=async w=>{if(!x){T(!0),A("");try{await w()}catch(b){A(b instanceof Error?b.message:"暂时无法完成,请重试。")}finally{T(!1)}}},R=g.kind==="edit"||g.kind==="routes"||g.kind==="relay-services"?d.find(w=>Pt(w,g.service))||g.service:void 0,E=t?d.find(w=>Pt(w,t))||t:void 0,S=d.filter(w=>!t||!Pt(w,t)),P=E?[E,...S]:S,N=h.jsxs(h.Fragment,{children:[f?h.jsxs("p",{className:"service-feedback",role:"status",children:[h.jsx(We,{size:16,className:"service-spinning"}),"正在读取服务…"]}):h.jsxs("div",{className:"service-list",children:[P.map(w=>{const b=!!t&&Pt(w,t);return h.jsxs("div",{className:"service-row",children:[h.jsxs("button",{type:"button",className:"service-row-open",disabled:x||b,onClick:()=>{L(async()=>{(await r(w))?.passwordRequired&&m({kind:"add",input:w.serviceOrigin||w.url,passwordRequired:!0})})},"aria-label":b?`当前服务 ${w.label}`:`打开 ${w.label}`,children:[h.jsx("span",{className:"service-icon",children:h.jsx(Qs,{size:20})}),h.jsxs("span",{className:"service-row-copy",children:[h.jsx("span",{className:"service-name",children:w.label}),h.jsx("span",{className:"service-description",children:b?"当前服务":new URL(w.serviceOrigin||w.url).host})]}),b?h.jsx(xa,{size:17,className:"service-selected"}):h.jsx(Jt,{size:16,className:"service-muted"})]}),h.jsx("button",{type:"button",className:"service-icon-button","aria-label":`管理 ${w.label}`,disabled:x,onClick:()=>{m({kind:"edit",service:w}),A("")},children:h.jsx(ox,{size:19})})]},w.id)}),P.length===0&&h.jsx("p",{className:"service-empty",children:"还没有添加服务。连接你的电脑,或粘贴收到的邀请链接。"})]}),h.jsxs("div",{className:`service-actions${o?" service-actions-pair":""}`,children:[h.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:x,onClick:()=>{m({kind:"add"}),A("")},children:[h.jsx(df,{size:16}),"添加服务"]}),o&&h.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:x,onClick:o,children:[h.jsx(uf,{size:16}),"邀请设备"]})]})]});return h.jsxs("div",{className:"service-manager",children:[!i&&h.jsxs("div",{className:"service-heading",children:[C&&h.jsx("button",{type:"button",className:"service-icon-button","aria-label":"返回服务",disabled:x,onClick:_,children:h.jsx(cf,{size:20})}),h.jsx("h2",{children:C||"服务"})]}),g.kind==="relay-services"?n?.(R,T):g.kind==="routes"?e?.(R,T):g.kind==="list"?N:g.kind==="add"?h.jsx(bx,{onSave:w=>L(async()=>{const b=Ce(w);u(await Pn({id:b,url:b,label:new URL(b).host})),_()}),initialInput:g.input,passwordRequired:g.passwordRequired,busy:x,onSubmit:async(w,b)=>{let k;return await L(async()=>{k=await s(w,b),k?.passwordRequired||_()}),k}}):h.jsx(xx,{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:R,busy:x,canRemove:!t||!Pt(g.service,t),onSave:w=>{L(async()=>{u(await Pn({...R,label:w})),_()})},onRemove:()=>{L(async()=>{u(await ph(g.service.id)),_()})}}),v&&h.jsx("p",{className:"service-error",role:"alert",children:v})]})}function bx({busy:t,onSubmit:e,onSave:n,initialInput:r="",passwordRequired:s=!1}){const[o,i]=$.useState(r),[a,c]=$.useState(""),[l,d]=$.useState(s);return h.jsxs("form",{className:"service-form",onSubmit:async u=>{u.preventDefault(),(await e(o.trim(),l?a:void 0))?.passwordRequired&&d(!0),c("")},children:[h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"服务地址或邀请链接"}),h.jsx("input",{value:o,onChange:u=>{i(u.target.value),d(!1),c("")},disabled:t,required:!0,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:电脑地址:9834 或 https://…"})]}),l?h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"服务密码"}),h.jsx("input",{type:"password",value:a,onChange:u=>c(u.target.value),disabled:t,required:!0,autoFocus:!0,autoComplete:"current-password",placeholder:"输入这台服务的密码"})]}):h.jsx("p",{className:"service-help",children:"连接自己的服务,输入地址即可;收到邀请时,粘贴完整链接。"}),h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:t||!o.trim()||o.includes("#termdock-invite="),onClick:()=>{n(o.trim())},children:"仅保存,不连接"}),h.jsx("button",{type:"submit",className:"service-button service-primary",disabled:t||!o.trim()||l&&!a,children:t?h.jsxs(h.Fragment,{children:[h.jsx(We,{size:16,className:"service-spinning"}),"正在连接…"]}):l?"登录并连接":"继续"})]})}function xx({service:t,busy:e,canRemove:n,onSave:r,onRemove:s,onRoutes:o,onRelayServices:i}){const[a,c]=$.useState(t.label),[l,d]=$.useState(!1);return h.jsxs("form",{className:"service-form",onSubmit:u=>{u.preventDefault(),r(a.trim())},children:[h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"服务名称"}),h.jsx("input",{value:a,onChange:u=>c(u.target.value),disabled:e,required:!0,maxLength:120,placeholder:"例如:办公室电脑"})]}),h.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url}),h.jsx("button",{type:"submit",className:"service-button service-primary",disabled:e||!a.trim(),children:"保存名称"}),i&&h.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:i,children:[h.jsxs("span",{className:"service-row-copy",children:[h.jsx("span",{className:"service-name",children:"可中转的服务"}),h.jsx("span",{className:"service-description",children:"通过这台服务连接其他电脑"})]}),h.jsx(Jt,{size:16})]}),o&&h.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:o,children:[h.jsxs("span",{className:"service-row-copy",children:[h.jsx("span",{className:"service-name",children:"备用连接"}),h.jsx("span",{className:"service-description",children:"添加其他网络地址或授权入口"})]}),h.jsx(Jt,{size:16})]}),n&&h.jsx("div",{className:"service-remove",children:l?h.jsxs(h.Fragment,{children:[h.jsxs("p",{className:"service-help",children:["从列表移除“",t.label,"”?不会停止服务或删除终端。"]}),h.jsxs("div",{className:"service-actions service-actions-pair",children:[h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:e,onClick:()=>d(!1),children:"取消"}),h.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:s,children:"确认移除"})]})]}):h.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:()=>d(!0),children:"移除服务"})})]})}var hn={},Bo,il;function vx(){return il||(il=1,Bo=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Bo}var _o={},Tt={},al;function nn(){if(al)return Tt;al=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 Tt.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},Tt.getSymbolTotalCodewords=function(r){return e[r]},Tt.getBCHDigit=function(n){let r=0;for(;n!==0;)r++,n>>>=1;return r},Tt.setToSJISFunction=function(r){if(typeof r!="function")throw new Error('"toSJISFunc" is not a valid function.');t=r},Tt.isKanjiModeEnabled=function(){return typeof t<"u"},Tt.toSJIS=function(r){return t(r)},Tt}var Do={},cl;function va(){return cl||(cl=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,s){if(t.isValid(r))return r;try{return e(r)}catch{return s}}})(Do)),Do}var Fo,ll;function Ex(){if(ll)return Fo;ll=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++}},Fo=t,Fo}var Oo,dl;function Sx(){if(dl)return Oo;dl=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,s){const o=e*this.size+n;this.data[o]=r,s&&(this.reservedBit[o]=!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]},Oo=t,Oo}var Mo={},ul;function Ax(){return ul||(ul=1,(function(t){const e=nn().getSymbolSize;t.getRowColCoords=function(r){if(r===1)return[];const s=Math.floor(r/7)+2,o=e(r),i=o===145?26:Math.ceil((o-13)/(2*s-2))*2,a=[o-7];for(let c=1;c<s-1;c++)a[c]=a[c-1]-i;return a.push(6),a.reverse()},t.getPositions=function(r){const s=[],o=t.getRowColCoords(r),i=o.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||s.push([o[a],o[c]]);return s}})(Mo)),Mo}var jo={},fl;function kx(){if(fl)return jo;fl=1;const t=nn().getSymbolSize,e=7;return jo.getPositions=function(r){const s=t(r);return[[0,0],[s-e,0],[0,s-e]]},jo}var Uo={},hl;function Tx(){return hl||(hl=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(s){return s!=null&&s!==""&&!isNaN(s)&&s>=0&&s<=7},t.from=function(s){return t.isValid(s)?parseInt(s,10):void 0},t.getPenaltyN1=function(s){const o=s.size;let i=0,a=0,c=0,l=null,d=null;for(let u=0;u<o;u++){a=c=0,l=d=null;for(let f=0;f<o;f++){let p=s.get(u,f);p===l?a++:(a>=5&&(i+=e.N1+(a-5)),l=p,a=1),p=s.get(f,u),p===d?c++:(c>=5&&(i+=e.N1+(c-5)),d=p,c=1)}a>=5&&(i+=e.N1+(a-5)),c>=5&&(i+=e.N1+(c-5))}return i},t.getPenaltyN2=function(s){const o=s.size;let i=0;for(let a=0;a<o-1;a++)for(let c=0;c<o-1;c++){const l=s.get(a,c)+s.get(a,c+1)+s.get(a+1,c)+s.get(a+1,c+1);(l===4||l===0)&&i++}return i*e.N2},t.getPenaltyN3=function(s){const o=s.size;let i=0,a=0,c=0;for(let l=0;l<o;l++){a=c=0;for(let d=0;d<o;d++)a=a<<1&2047|s.get(l,d),d>=10&&(a===1488||a===93)&&i++,c=c<<1&2047|s.get(d,l),d>=10&&(c===1488||c===93)&&i++}return i*e.N3},t.getPenaltyN4=function(s){let o=0;const i=s.data.length;for(let c=0;c<i;c++)o+=s.data[c];return Math.abs(Math.ceil(o*100/i/5)-10)*e.N4};function n(r,s,o){switch(r){case t.Patterns.PATTERN000:return(s+o)%2===0;case t.Patterns.PATTERN001:return s%2===0;case t.Patterns.PATTERN010:return o%3===0;case t.Patterns.PATTERN011:return(s+o)%3===0;case t.Patterns.PATTERN100:return(Math.floor(s/2)+Math.floor(o/3))%2===0;case t.Patterns.PATTERN101:return s*o%2+s*o%3===0;case t.Patterns.PATTERN110:return(s*o%2+s*o%3)%2===0;case t.Patterns.PATTERN111:return(s*o%3+(s+o)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}t.applyMask=function(s,o){const i=o.size;for(let a=0;a<i;a++)for(let c=0;c<i;c++)o.isReserved(c,a)||o.xor(c,a,n(s,c,a))},t.getBestMask=function(s,o){const i=Object.keys(t.Patterns).length;let a=0,c=1/0;for(let l=0;l<i;l++){o(l),t.applyMask(l,s);const d=t.getPenaltyN1(s)+t.getPenaltyN2(s)+t.getPenaltyN3(s)+t.getPenaltyN4(s);t.applyMask(l,s),d<c&&(c=d,a=l)}return a}})(Uo)),Uo}var Jr={},pl;function hf(){if(pl)return Jr;pl=1;const t=va(),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 Jr.getBlocksCount=function(s,o){switch(o){case t.L:return e[(s-1)*4+0];case t.M:return e[(s-1)*4+1];case t.Q:return e[(s-1)*4+2];case t.H:return e[(s-1)*4+3];default:return}},Jr.getTotalCodewordsCount=function(s,o){switch(o){case t.L:return n[(s-1)*4+0];case t.M:return n[(s-1)*4+1];case t.Q:return n[(s-1)*4+2];case t.H:return n[(s-1)*4+3];default:return}},Jr}var $o={},nr={},gl;function Cx(){if(gl)return nr;gl=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let r=1;for(let s=0;s<255;s++)t[s]=r,e[r]=s,r<<=1,r&256&&(r^=285);for(let s=255;s<512;s++)t[s]=t[s-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,s){return r===0||s===0?0:t[e[r]+e[s]]},nr}var ml;function Ix(){return ml||(ml=1,(function(t){const e=Cx();t.mul=function(r,s){const o=new Uint8Array(r.length+s.length-1);for(let i=0;i<r.length;i++)for(let a=0;a<s.length;a++)o[i+a]^=e.mul(r[i],s[a]);return o},t.mod=function(r,s){let o=new Uint8Array(r);for(;o.length-s.length>=0;){const i=o[0];for(let c=0;c<s.length;c++)o[c]^=e.mul(s[c],i);let a=0;for(;a<o.length&&o[a]===0;)a++;o=o.slice(a)}return o},t.generateECPolynomial=function(r){let s=new Uint8Array([1]);for(let o=0;o<r;o++)s=t.mul(s,new Uint8Array([1,e.exp(o)]));return s}})($o)),$o}var Ho,wl;function Rx(){if(wl)return Ho;wl=1;const t=Ix();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 s=new Uint8Array(r.length+this.degree);s.set(r);const o=t.mod(s,this.genPoly),i=this.degree-o.length;if(i>0){const a=new Uint8Array(this.degree);return a.set(o,i),a}return o},Ho=e,Ho}var qo={},Ko={},zo={},yl;function pf(){return yl||(yl=1,zo.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),zo}var Qe={},bl;function gf(){if(bl)return Qe;bl=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-CppLqzUc.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/App-B19QjfSB.js","assets/gestureArbiter--GtaPB1X.js","assets/gestureArbiter-C2J0D0kV.css","assets/referenceLongPress-BWY2Jusg.js","assets/triangle-alert-CLJo8ig-.js","assets/DagPlayground-qziF3toU.js","assets/ChangeWalkthroughPanel-DYSWa9RT.js","assets/sparkles-C5UxG6SZ.js","assets/DiffLab-CDUdFYRL.js","assets/DiffViewer-Bg272xI5.js","assets/DiffViewer-T3uj2-aP.css","assets/DiffReviewLab-DUMlD_0N.js","assets/DiffReview-hnUsI_p2.js"])))=>i.map(i=>d[i]);
2
+ import{r as Yf,a as Zf,g as Jf}from"./react-XDCjal2T.js";import{b as $,r as Qf,R as je}from"./dnd-BCFAPC0L.js";import{L as eh,l as th}from"./terminal-C7X98Amf.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();const nh="modulepreload",rh=function(t){return"/"+t},ja={},Un=function(e,n,r){let s=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");s=c(n.map(l=>{if(l=rh(l),l in ja)return;ja[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":nh,d||(f.as="script"),f.crossOrigin="",f.href=l,a&&f.setAttribute("nonce",a),document.head.appendChild(f),d)return new Promise((p,g)=>{f.addEventListener("load",p),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${l}`)))})}))}function o(i){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=i,window.dispatchEvent(a),!a.defaultPrevented)throw i}return s.then(i=>{for(const a of i||[])a.status==="rejected"&&o(a.reason);return e().catch(o)})};var co={exports:{}},Vn={};var Ua;function sh(){if(Ua)return Vn;Ua=1;var t=Yf(),e=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,s=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,o={key:!0,ref:!0,__self:!0,__source:!0};function i(a,c,l){var d,u={},f=null,p=null;l!==void 0&&(f=""+l),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(p=c.ref);for(d in c)r.call(c,d)&&!o.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:p,props:u,_owner:s.current}}return Vn.Fragment=n,Vn.jsx=i,Vn.jsxs=i,Vn}var $a;function oh(){return $a||($a=1,co.exports=sh()),co.exports}var h=oh();const Vt="termdock-secure-target-v1",qi="termdock-secure-entry-v1",ih=new Set([Vt,qi,"termdock-color-theme","termdock:locale","termdock.federation.connections.v1"]),Dr=typeof Storage>"u"?void 0:Storage.prototype.getItem,lo=typeof Storage>"u"?void 0:Storage.prototype.setItem,Ha="termdock-secure-legacy-owner";function ah(){if(typeof window>"u")return null;try{const t=JSON.parse(sessionStorage.getItem(Vt)??localStorage.getItem(Vt)??"null");return t&&typeof t.url=="string"&&typeof t.targetPeerId=="string"?t:null}catch{return null}}let Ki=ah();const Fs=Ki?.targetPeerId??"unpaired";function ch(){return Ki}function Gl(t){Ki=t;const e=JSON.stringify(t);sessionStorage.setItem(Vt,e),localStorage.setItem(Vt,e)}function ur(t,e=Fs){return ih.has(t)||t.startsWith("termdock-secure-")?t:`termdock-service:${e}:${t}`}function lh(t){if(!(!Dr||!lo))try{if(Dr.call(localStorage,Ha))return;lo.call(localStorage,Ha,t);for(const n of[localStorage,sessionStorage]){const r=Array.from({length:n.length},(s,o)=>n.key(o)).filter(s=>!!s);for(const s of r){if(s.startsWith("termdock-service:")||ur(s,t)===s)continue;const o=ur(s,t),i=Dr.call(n,s);i!==null&&Dr.call(n,o)===null&&lo.call(n,o,i)}}}catch{}}let qa=!1;function dh(){if(qa||typeof Storage>"u")return;qa=!0;const t=Storage.prototype.getItem,e=Storage.prototype.setItem,n=Storage.prototype.removeItem;Storage.prototype.getItem=function(r){return t.call(this,ur(String(r)))},Storage.prototype.setItem=function(r,s){e.call(this,ur(String(r)),s)},Storage.prototype.removeItem=function(r){n.call(this,ur(String(r)))}}dh();var Fr={},Ka;function uh(){if(Ka)return Fr;Ka=1;var t=Zf();return Fr.createRoot=t.createRoot,Fr.hydrateRoot=t.hydrateRoot,Fr}var fh=uh();const hh=Jf(fh),Os="termdock.federation.connections.v1",oi="termdock:services-changed";function Ce(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 Wl(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.url=="string")try{const n=Ce(e.url),r=typeof e.targetPeerId=="string"&&e.targetPeerId?e.targetPeerId:void 0,s=(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:s,...r?{targetPeerId:r}:{},...typeof e.serviceOrigin=="string"?{serviceOrigin:Ce(e.serviceOrigin)}:{},...typeof e.entryServiceId=="string"&&e.entryServiceId?{entryServiceId:e.entryServiceId}:{},...Array.isArray(e.routes)?{routes:e.routes.slice(0,4).flatMap(o=>{try{return o&&typeof o.targetPeerId=="string"&&o.targetPeerId?[{url:Ce(o.url),targetPeerId:o.targetPeerId}]:[]}catch{return[]}})}:{}}}catch{return}}function Pt(t,e){return t.targetPeerId&&e.targetPeerId?t.targetPeerId===e.targetPeerId:(t.serviceOrigin||t.url)===(e.serviceOrigin||e.url)}function Xl(t){const e=[];for(const n of t){const r=e.findIndex(s=>Pt(s,n));r<0?e.push(n):e[r]={...e[r],...n,id:e[r].id}}return e}function Ms(){return typeof window>"u"?void 0:window.termdockDesktop}function cs(){try{const t=JSON.parse(localStorage.getItem(Os)||"[]");return Array.isArray(t)?Xl(t.map(Wl).filter(e=>!!e)):[]}catch{return[]}}function Yl(t){localStorage.setItem(Os,JSON.stringify(t.map(e=>({...e,serviceName:e.label})))),window.dispatchEvent(new Event(oi))}let Gn;async function nt(){const t=Ms();if(!t?.serviceConnections||!t.saveServiceConnection)return cs();if(Gn)return Gn;Gn=(async()=>{let e=await t.serviceConnections();const n=cs();for(const r of n)e.some(s=>Pt(s,r))||(e=await(t.importServiceConnection||t.saveServiceConnection)(r));return n.length&&localStorage.removeItem(Os),e})();try{return await Gn}finally{Gn=void 0}}async function Pn(t){const e=Wl(t);if(!e)throw new Error("服务地址无效。");const n=Ms();if(n?.saveServiceConnection)return n.saveServiceConnection(e);const r=cs(),s=r.find(i=>i.id===e.id||Pt(i,e)),o=Xl([...r.filter(i=>i!==s),{...s,...e,id:s?.id||e.id}]);return Yl(o),o}async function ph(t){const e=Ms();if(e?.removeServiceConnection)return e.removeServiceConnection(t);const n=cs().filter(r=>r.id!==t);return Yl(n),n}function gh(t){const e=r=>{(r.key===Os||r.key===null)&&t()};window.addEventListener(oi,t),window.addEventListener("storage",e);const n=Ms()?.onServiceConnections?.(t);return()=>{window.removeEventListener(oi,t),window.removeEventListener("storage",e),n?.()}}class mh extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}let wh=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},Xe=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};class Zl extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class Jl extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}}class yh extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class bh extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class js extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}const Ql=Symbol.for("@libp2p/peer-id");function xh(t){return typeof t?.handleEvent=="function"}function vh(t){return t===!0||t===!1}function Eh(t){return vh(t)?t:t?.capture??!1}function ii(t){const e={capture:Eh(t),once:!!t?.once};return t?.passive!=null&&(e.passive=t?.passive),t?.signal!=null&&(e.signal=t?.signal),e}function za(t,e){return ii(t).capture===ii(e).capture}class Sh 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 s=ii(r);if(s?.signal?.aborted===!0)return;const o=l=>{s.once&&this.removeEventListener(e,n,s),xh(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:za(l.options,s)))return;super.addEventListener(e,o,s);const c=()=>{this.removeEventListener(e,n,s)};s.signal?.addEventListener("abort",c),i.push({callback:n,wrapper:o,options:s,onAbort:c})}removeEventListener(e,n,r){const s=this.#e.get(e);if(s==null){super.removeEventListener(e,n??null,r);return}this.#e.set(e,s.filter(o=>o.callback===n&&za(o.options,r)?(super.removeEventListener(e,o.wrapper,r),o.options?.signal?.removeEventListener("abort",o.onAbort),!1):!0))}safeDispatchEvent(e,n={}){return this.dispatchEvent(new CustomEvent(e,n))}}const Ah=Symbol.for("@libp2p/service-capabilities");function kh(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 Us(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 Th(t){return new TextEncoder().encode(t)}function Ch(t){return new TextDecoder().decode(t)}function Ih(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 s=0;s<t.length;s++){var o=t.charAt(s),i=o.charCodeAt(0);if(n[i]!==255)throw new TypeError(o+" is ambiguous");n[i]=s}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,x=0,y=0,T=g.length;y!==T&&g[y]===0;)y++,m++;for(var v=(T-y)*d+1>>>0,A=new Uint8Array(v);y!==T;){for(var _=g[y],C=0,L=v-1;(_!==0||C<x)&&L!==-1;L--,C++)_+=256*A[L]>>>0,A[L]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");x=C,y++}for(var R=v-x;R!==v&&A[R]===0;)R++;for(var E=c.repeat(m);R<v;++R)E+=t.charAt(A[R]);return E}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 x=0,y=0;g[m]===c;)x++,m++;for(var T=(g.length-m)*l+1>>>0,v=new Uint8Array(T);g[m];){var A=n[g.charCodeAt(m)];if(A===255)return;for(var _=0,C=T-1;(A!==0||_<y)&&C!==-1;C--,_++)A+=a*v[C]>>>0,v[C]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");y=_,m++}if(g[m]!==" "){for(var L=T-y;L!==T&&v[L]===0;)L++;for(var R=new Uint8Array(x+(T-L)),E=x;L!==T;)R[E++]=v[L++];return R}}}function p(g){var m=f(g);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:p}}var Rh=Ih,Ph=Rh;class Nh{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 Lh{name;prefix;baseDecode;prefixCodePoint;constructor(e,n,r){this.name=e,this.prefix=n;const s=n.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,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 ed(this,e)}}class Bh{decoders;constructor(e){this.decoders=e}or(e){return ed(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 ed(t,e){return new Bh({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class _h{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,n,r,s){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=s,this.encoder=new Nh(e,n,r),this.decoder=new Lh(e,n,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function $s({name:t,prefix:e,encode:n,decode:r}){return new _h(t,e,n,r)}function kr({name:t,prefix:e,alphabet:n}){const{encode:r,decode:s}=Ph(n,t);return $s({prefix:e,name:t,encode:r,decode:o=>Us(s(o))})}function Dh(t,e,n,r){let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let i=0,a=0,c=0;for(let l=0;l<s;++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,o[c++]=255&a>>i)}if(i>=n||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function Fh(t,e,n){const r=e[e.length-1]==="=",s=(1<<n)-1;let o="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>n;)i-=n,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<n-i]),r)for(;(o.length*n&7)!==0;)o+="=";return o}function Oh(t){const e={};for(let n=0;n<t.length;++n)e[t[n]]=n;return e}function xe({name:t,prefix:e,bitsPerChar:n,alphabet:r}){const s=Oh(r);return $s({prefix:e,name:t,encode(o){return Fh(o,r,n)},decode(o){return Dh(o,s,n,t)}})}const Te=kr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Mh=kr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),jh=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Te,base58flickr:Mh},Symbol.toStringTag,{value:"Module"})),fr=xe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Uh=xe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),$h=xe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Hh=xe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),qh=xe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Kh=xe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),zh=xe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Vh=xe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Gh=xe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Wh=Object.freeze(Object.defineProperty({__proto__:null,base32:fr,base32hex:qh,base32hexpad:zh,base32hexpadupper:Vh,base32hexupper:Kh,base32pad:$h,base32padupper:Hh,base32upper:Uh,base32z:Gh},Symbol.toStringTag,{value:"Module"})),ns=kr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Xh=kr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Yh=Object.freeze(Object.defineProperty({__proto__:null,base36:ns,base36upper:Xh},Symbol.toStringTag,{value:"Module"}));var Zh=td,Va=128,Jh=-128,Qh=Math.pow(2,31);function td(t,e,n){e=e||[],n=n||0;for(var r=n;t>=Qh;)e[n++]=t&255|Va,t/=128;for(;t&Jh;)e[n++]=t&255|Va,t>>>=7;return e[n]=t|0,td.bytes=n-r+1,e}var ep=ai,tp=128,Ga=127;function ai(t,r){var n=0,r=r||0,s=0,o=r,i,a=t.length;do{if(o>=a)throw ai.bytes=0,new RangeError("Could not decode varint");i=t[o++],n+=s<28?(i&Ga)<<s:(i&Ga)*Math.pow(2,s),s+=7}while(i>=tp);return ai.bytes=o-r,n}var np=Math.pow(2,7),rp=Math.pow(2,14),sp=Math.pow(2,21),op=Math.pow(2,28),ip=Math.pow(2,35),ap=Math.pow(2,42),cp=Math.pow(2,49),lp=Math.pow(2,56),dp=Math.pow(2,63),up=function(t){return t<np?1:t<rp?2:t<sp?3:t<op?4:t<ip?5:t<ap?6:t<cp?7:t<lp?8:t<dp?9:10},fp={encode:Zh,decode:ep,encodingLength:up},ls=fp;function ci(t,e=0){return[ls.decode(t,e),ls.decode.bytes]}function ds(t,e,n=0){return ls.encode(t,e,n),e}function us(t){return ls.encodingLength(t)}function Tr(t,e){const n=e.byteLength,r=us(t),s=r+us(n),o=new Uint8Array(s+n);return ds(t,o,0),ds(n,o,r),o.set(e,s),new zi(t,n,e,o)}function nd(t){const e=Us(t),[n,r]=ci(e),[s,o]=ci(e.subarray(r)),i=e.subarray(r+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new zi(n,s,i,e)}function hp(t,e){if(t===e)return!0;{const n=e;return t.code===n.code&&t.size===n.size&&n.bytes instanceof Uint8Array&&kh(t.bytes,n.bytes)}}class zi{code;size;digest;bytes;constructor(e,n,r,s){this.code=e,this.size=n,this.digest=r,this.bytes=s}}function Wa(t,e){const{bytes:n,version:r}=t;return r===0?gp(n,li(t),e??Te.encoder):mp(n,li(t),e??fr.encoder)}const Xa=new WeakMap;function li(t){const e=Xa.get(t);if(e==null){const n=new Map;return Xa.set(t,n),n}return e}class oe{code;version;multihash;bytes;"/";constructor(e,n,r,s){this.code=n,this.version=e,this.multihash=r,this.bytes=s,this["/"]=s}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!==Wn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==wp)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return oe.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=Tr(e,n);return oe.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 oe.equals(this,e)}static equals(e,n){const r=n;return r!=null&&e.code===r.code&&e.version===r.version&&hp(e.multihash,r.multihash)}toString(e){return Wa(this,e)}toJSON(){return{"/":Wa(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 oe)return n;if(n["/"]!=null&&n["/"]===n.bytes||n.asCID===n){const{version:r,code:s,multihash:o,bytes:i}=n;return new oe(r,s,o,i??Ya(r,s,o.bytes))}else if(n[yp]===!0){const{version:r,multihash:s,code:o}=n,i=nd(s);return oe.create(r,o,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!==Wn)throw new Error(`Version 0 CID must use dag-pb (code: ${Wn}) block encoding`);return new oe(e,n,r,r.bytes)}case 1:{const s=Ya(e,n,r.bytes);return new oe(e,n,r,s)}default:throw new Error("Invalid version")}}static createV0(e){return oe.create(0,Wn,e)}static createV1(e,n){return oe.create(1,e,n)}static decode(e){const[n,r]=oe.decodeFirst(e);if(r.length!==0)throw new Error("Incorrect length");return n}static decodeFirst(e){const n=oe.inspectBytes(e),r=n.size-n.multihashSize,s=Us(e.subarray(r,r+n.multihashSize));if(s.byteLength!==n.multihashSize)throw new Error("Incorrect length");const o=s.subarray(n.multihashSize-n.digestSize),i=new zi(n.multihashCode,n.digestSize,o,s);return[n.version===0?oe.createV0(i):oe.createV1(n.codec,i),e.subarray(n.size)]}static inspectBytes(e){let n=0;const r=()=>{const[u,f]=ci(e.subarray(n));return n+=f,u};let s=r(),o=Wn;if(s===18?(s=0,n=0):o=r(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);const i=n,a=r(),c=r(),l=n+c,d=l-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:d,size:l}}static parse(e,n){const[r,s]=pp(e,n),o=oe.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return li(o).set(r,e),o}}function pp(t,e){switch(t[0]){case"Q":{const n=e??Te;return[Te.prefix,n.decode(`${Te.prefix}${t}`)]}case Te.prefix:{const n=e??Te;return[Te.prefix,n.decode(t)]}case fr.prefix:{const n=e??fr;return[fr.prefix,n.decode(t)]}case ns.prefix:{const n=e??ns;return[ns.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 gp(t,e,n){const{prefix:r}=n;if(r!==Te.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);const s=e.get(r);if(s==null){const o=n.encode(t).slice(1);return e.set(r,o),o}else return s}function mp(t,e,n){const{prefix:r}=n,s=e.get(r);if(s==null){const o=n.encode(t);return e.set(r,o),o}else return s}const Wn=112,wp=18;function Ya(t,e,n){const r=us(t),s=r+us(e),o=new Uint8Array(s+n.byteLength);return ds(t,o,0),ds(e,o,r),o.set(n,s),o}const yp=Symbol.for("@ipld/js-cid/CID"),rd=0,bp="identity",sd=Us;function xp(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 Tr(rd,sd(t))}const Cr={code:rd,name:bp,encode:sd,digest:xp};function Ye(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 Re(t=0){return new Uint8Array(t)}function gt(t=0){return new Uint8Array(t)}function di(t,e){e==null&&(e=t.reduce((s,o)=>s+o.length,0));const n=gt(e);let r=0;for(const s of t)n.set(s,r),r+=s.length;return n}const od=Symbol.for("@achingbrain/uint8arraylist");function Za(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let n=0;for(const r of t){const s=n+r.byteLength;if(e<s)return{buf:r,index:e-n};n=s}throw new RangeError("index is out of bounds")}function Or(t){return!!t?.[od]}class ne{bufs;length;[od]=!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(Or(r)){n+=r.byteLength;for(const s of r.bufs)this.bufs.push(s)}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(Or(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=Za(this.bufs,e);return n.buf[n.index]}set(e,n){const r=Za(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(Or(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:s}=this._subList(e,n);return di(r,s)}subarray(e,n){const{bufs:r,length:s}=this._subList(e,n);return r.length===1?r[0]:di(r,s)}sublist(e,n){const{bufs:r,length:s}=this._subList(e,n),o=new ne;return o.length=s,o.bufs=r,o}_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 s=0;for(let o=0;o<this.bufs.length;o++){const i=this.bufs[o],a=s,c=a+i.byteLength;if(s=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(!Or(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 s=r.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");const o=256,i=new Int32Array(o);for(let u=0;u<o;u++)i[u]=-1;for(let u=0;u<s;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 p=this.get(u+f);if(r[f]!==p){d=Math.max(1,f-a[p]);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=gt(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 s=Re(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,n,r),this.write(s,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 s=Re(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,n,r),this.write(s,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 s=Re(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,n,r),this.write(s,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=gt(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 s=Re(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,n,r),this.write(s,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 s=Re(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,n,r),this.write(s,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 s=Re(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,n,r),this.write(s,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 s=Re(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,n,r),this.write(s,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 s=Re(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,n,r),this.write(s,e)}equals(e){if(e==null||!(e instanceof ne)||e.bufs.length!==this.bufs.length)return!1;for(let n=0;n<this.bufs.length;n++)if(!Ye(this.bufs[n],e.bufs[n]))return!1;return!0}static fromUint8Arrays(e,n){const r=new ne;return r.bufs=e,n==null&&(n=e.reduce((s,o)=>s+o.byteLength,0)),r.length=n,r}}const vp=kr({prefix:"9",name:"base10",alphabet:"0123456789"}),Ep=Object.freeze(Object.defineProperty({__proto__:null,base10:vp},Symbol.toStringTag,{value:"Module"})),Sp=xe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ap=xe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),kp=Object.freeze(Object.defineProperty({__proto__:null,base16:Sp,base16upper:Ap},Symbol.toStringTag,{value:"Module"})),Tp=xe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Cp=Object.freeze(Object.defineProperty({__proto__:null,base2:Tp},Symbol.toStringTag,{value:"Module"})),id=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Ip=id.reduce((t,e,n)=>(t[n]=e,t),[]),Rp=id.reduce((t,e,n)=>{const r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return t[r]=n,t},[]);function Pp(t){return t.reduce((e,n)=>(e+=Ip[n],e),"")}function Np(t){const e=[];for(const n of t){const r=n.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${n}`);const s=Rp[r];if(s==null)throw new Error(`Non-base256emoji character: ${n}`);e.push(s)}return new Uint8Array(e)}const Lp=$s({prefix:"🚀",name:"base256emoji",encode:Pp,decode:Np}),Bp=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:Lp},Symbol.toStringTag,{value:"Module"})),_p=xe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Dp=xe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Fp=xe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Op=xe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Mp=Object.freeze(Object.defineProperty({__proto__:null,base64:_p,base64pad:Dp,base64url:Fp,base64urlpad:Op},Symbol.toStringTag,{value:"Module"})),jp=xe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Up=Object.freeze(Object.defineProperty({__proto__:null,base8:jp},Symbol.toStringTag,{value:"Module"})),$p=$s({prefix:"\0",name:"identity",encode:t=>Ch(t),decode:t=>Th(t)}),Hp=Object.freeze(Object.defineProperty({__proto__:null,identity:$p},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const qp=20;function Kp({name:t,code:e,encode:n,minDigestLength:r,maxDigestLength:s}){return new zp(t,e,n,r,s)}class zp{name;code;encode;minDigestLength;maxDigestLength;constructor(e,n,r,s,o){this.name=e,this.code=n,this.encode=r,this.minDigestLength=s??qp,this.maxDigestLength=o}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?Ja(r,this.code,n?.truncate):r.then(s=>Ja(s,this.code,n?.truncate))}else throw Error("Unknown type, must be binary type")}}function Ja(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 Tr(e,t)}function Vp(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}const Vi=Kp({name:"sha2-256",code:18,encode:Vp("SHA-256")}),Qa={...Hp,...Cp,...Up,...Ep,...kp,...Wh,...Yh,...jh,...Mp,...Bp};function ad(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const ec=ad("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),uo=ad("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=gt(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),cd={utf8:ec,"utf-8":ec,hex:Qa.base16,latin1:uo,ascii:uo,binary:uo,...Qa};function fe(t,e="utf8"){const n=cd[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.decoder.decode(`${n.prefix}${t}`)}function J(t,e="utf8"){const n=cd[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.encoder.encode(t).substring(1)}const Gp=parseInt("11111",2),ui=parseInt("10000000",2),Wp=parseInt("01111111",2),tc={0:Xn,1:Xn,2:Xp,3:Jp,4:Qp,5:Zp,6:Yp,16:Xn,22:Xn,48:Xn};function $n(t,e={offset:0}){const n=t[e.offset]&Gp;if(e.offset++,tc[n]!=null)return tc[n](t,e);throw new Error("No decoder for tag "+n)}function Ir(t,e){let n=0;if((t[e.offset]&ui)===ui){const r=t[e.offset]&Wp;let s="0x";e.offset++;for(let o=0;o<r;o++,e.offset++)s+=t[e.offset].toString(16).padStart(2,"0");n=parseInt(s,16)}else n=t[e.offset],e.offset++;return n}function Xn(t,e){Ir(t,e);const n=[];for(;!(e.offset>=t.byteLength);){const r=$n(t,e);if(r===null)break;n.push(r)}return n}function Xp(t,e){const n=Ir(t,e),r=e.offset,s=e.offset+n,o=[];for(let i=r;i<s;i++)i===r&&t[i]===0||o.push(t[i]);return e.offset+=n,Uint8Array.from(o)}function Yp(t,e){const n=Ir(t,e),r=e.offset+n,s=t[e.offset];e.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let a=`${o}.${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 Zp(t,e){return e.offset++,null}function Jp(t,e){const n=Ir(t,e),r=t[e.offset];e.offset++;const s=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 s}function Qp(t,e){const n=Ir(t,e),r=t.subarray(e.offset,e.offset+n);return e.offset+=n,r}function eg(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);const n=new ne;for(let r=0;r<e.length;r+=2)n.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return n}function Hs(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);const e=eg(t.byteLength);return new ne(Uint8Array.from([e.byteLength|ui]),e)}function Be(t){const e=new ne,n=128;return(t.subarray()[0]&n)===n&&e.append(Uint8Array.from([0])),e.append(t),new ne(Uint8Array.from([2]),Hs(e),e)}function Gi(t){const e=Uint8Array.from([0]),n=new ne(e,t);return new ne(Uint8Array.from([3]),Hs(n),n)}function tg(t){return new ne(Uint8Array.from([4]),Hs(t),t)}function pt(t,e=48){const n=new ne;for(const r of t)n.append(r);return new ne(Uint8Array.from([e]),Hs(n),n)}async function ng(t,e,n){const r=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["sign"]);n?.signal?.throwIfAborted();const s=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function rg(t,e,n,r){const s=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();const o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,e,n.subarray());return r?.signal?.throwIfAborted(),o}const sg=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),og=Uint8Array.from([6,5,43,129,4,0,34]),ig=Uint8Array.from([6,5,43,129,4,0,35]),ld={ext:!0,kty:"EC",crv:"P-256"},dd={ext:!0,kty:"EC",crv:"P-384"},ud={ext:!0,kty:"EC",crv:"P-521"},yn=32,bn=48,xn=66;function ag(t){const e=$n(t);return cg(e)}function cg(t){const e=t[1],n=J(e,"base64url"),r=t[2][1][0],s=1;let o,i;if(e.byteLength===yn)return o=J(r.subarray(s,s+yn),"base64url"),i=J(r.subarray(s+yn),"base64url"),new fo({...ld,key_ops:["sign"],d:n,x:o,y:i});if(e.byteLength===bn)return o=J(r.subarray(s,s+bn),"base64url"),i=J(r.subarray(s+bn),"base64url"),new fo({...dd,key_ops:["sign"],d:n,x:o,y:i});if(e.byteLength===xn)return o=J(r.subarray(s,s+xn),"base64url"),i=J(r.subarray(s+xn),"base64url"),new fo({...ud,key_ops:["sign"],d:n,x:o,y:i});throw new Xe(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function fd(t){const e=$n(t);return lg(e)}function lg(t){const e=t[1][1][0],n=1;let r,s;if(e.byteLength===yn*2+1)return r=J(e.subarray(n,n+yn),"base64url"),s=J(e.subarray(n+yn),"base64url"),new rs({...ld,key_ops:["verify"],x:r,y:s});if(e.byteLength===bn*2+1)return r=J(e.subarray(n,n+bn),"base64url"),s=J(e.subarray(n+bn),"base64url"),new rs({...dd,key_ops:["verify"],x:r,y:s});if(e.byteLength===xn*2+1)return r=J(e.subarray(n,n+xn),"base64url"),s=J(e.subarray(n+xn),"base64url"),new rs({...ud,key_ops:["verify"],x:r,y:s});throw new Xe(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function dg(t){return pt([Be(Uint8Array.from([1])),tg(fe(t.d??"","base64url")),pt([hd(t.crv)],160),pt([Gi(new ne(Uint8Array.from([4]),fe(t.x??"","base64url"),fe(t.y??"","base64url")))],161)]).subarray()}function ug(t){return pt([Be(Uint8Array.from([1])),pt([hd(t.crv)],160),pt([Gi(new ne(Uint8Array.from([4]),fe(t.x??"","base64url"),fe(t.y??"","base64url")))],161)]).subarray()}function hd(t){if(t==="P-256")return sg;if(t==="P-384")return og;if(t==="P-521")return ig;throw new Xe(`Invalid curve ${t}`)}class rs{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=ug(this.jwk)),this._raw}toMultihash(){return Cr.digest(Ws(this))}toCID(){return oe.createV1(114,this.toMultihash())}toString(){return Te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ye(this.raw,e.raw)}async verify(e,n,r){return rg(this.jwk,n,e,r)}}class fo{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new rs({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=dg(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ye(this.raw,e.raw)}async sign(e,n){return ng(this.jwk,e,n)}}const dn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Rr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function fi(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Qt(t,...e){if(!Rr(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 pd(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");fi(t.outputLen),fi(t.blockLen)}function fs(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 fg(t,e){Qt(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Nn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function ho(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Ze(t,e){return t<<32-e|t>>>e}const gd=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",hg=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ht(t){if(Qt(t),gd)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=hg[t[n]];return e}const ot={_0:48,_9:57,A:65,F:70,a:97,f:102};function nc(t){if(t>=ot._0&&t<=ot._9)return t-ot._0;if(t>=ot.A&&t<=ot.F)return t-(ot.A-10);if(t>=ot.a&&t<=ot.f)return t-(ot.a-10)}function hs(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(gd)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 s=0,o=0;s<n;s++,o+=2){const i=nc(t.charCodeAt(o)),a=nc(t.charCodeAt(o+1));if(i===void 0||a===void 0){const c=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}r[s]=i*16+a}return r}function pg(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Wi(t){return typeof t=="string"&&(t=pg(t)),Qt(t),t}function et(...t){let e=0;for(let r=0;r<t.length;r++){const s=t[r];Qt(s),e+=s.length}const n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){const o=t[r];n.set(o,s),s+=o.length}return n}class md{}function wd(t){const e=r=>t().update(Wi(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Xi(t=32){if(dn&&typeof dn.getRandomValues=="function")return dn.getRandomValues(new Uint8Array(t));if(dn&&typeof dn.randomBytes=="function")return Uint8Array.from(dn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function gg(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const s=BigInt(32),o=BigInt(4294967295),i=Number(n>>s&o),a=Number(n&o),c=r?4:0,l=r?0:4;t.setUint32(e+c,i,r),t.setUint32(e+l,a,r)}function mg(t,e,n){return t&e^~t&n}function wg(t,e,n){return t&e^t&n^e&n}let yd=class extends md{constructor(e,n,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=ho(this.buffer)}update(e){fs(this),e=Wi(e),Qt(e);const{view:n,buffer:r,blockLen:s}=this,o=e.length;for(let i=0;i<o;){const a=Math.min(s-this.pos,o-i);if(a===s){const c=ho(e);for(;s<=o-i;i+=s)this.process(c,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){fs(this),fg(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:s,isLE:o}=this;let{pos:i}=this;n[i++]=128,Nn(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(r,0),i=0);for(let u=i;u<s;u++)n[u]=0;gg(r,s-8,BigInt(this.length*8),o),this.process(r,0);const a=ho(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],o)}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:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};const xt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ve=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Mr=BigInt(2**32-1),rc=BigInt(32);function yg(t,e=!1){return e?{h:Number(t&Mr),l:Number(t>>rc&Mr)}:{h:Number(t>>rc&Mr)|0,l:Number(t&Mr)|0}}function bg(t,e=!1){const n=t.length;let r=new Uint32Array(n),s=new Uint32Array(n);for(let o=0;o<n;o++){const{h:i,l:a}=yg(t[o],e);[r[o],s[o]]=[i,a]}return[r,s]}const sc=(t,e,n)=>t>>>n,oc=(t,e,n)=>t<<32-n|e>>>n,un=(t,e,n)=>t>>>n|e<<32-n,fn=(t,e,n)=>t<<32-n|e>>>n,jr=(t,e,n)=>t<<64-n|e>>>n-32,Ur=(t,e,n)=>t>>>n-32|e<<64-n;function it(t,e,n,r){const s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}const xg=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),vg=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Eg=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Sg=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,Ag=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),kg=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0,Tg=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]),vt=new Uint32Array(64);class Cg extends yd{constructor(e=32){super(64,e,8,!1),this.A=xt[0]|0,this.B=xt[1]|0,this.C=xt[2]|0,this.D=xt[3]|0,this.E=xt[4]|0,this.F=xt[5]|0,this.G=xt[6]|0,this.H=xt[7]|0}get(){const{A:e,B:n,C:r,D:s,E:o,F:i,G:a,H:c}=this;return[e,n,r,s,o,i,a,c]}set(e,n,r,s,o,i,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=o|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)vt[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const f=vt[u-15],p=vt[u-2],g=Ze(f,7)^Ze(f,18)^f>>>3,m=Ze(p,17)^Ze(p,19)^p>>>10;vt[u]=m+vt[u-7]+g+vt[u-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=Ze(a,6)^Ze(a,11)^Ze(a,25),p=d+f+mg(a,c,l)+Tg[u]+vt[u]|0,m=(Ze(r,2)^Ze(r,13)^Ze(r,22))+wg(r,s,o)|0;d=l,l=c,c=a,a=i+p|0,i=o,o=s,s=r,r=p+m|0}r=r+this.A|0,s=s+this.B|0,o=o+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,s,o,i,a,c,l,d)}roundClean(){Nn(vt)}destroy(){this.set(0,0,0,0,0,0,0,0),Nn(this.buffer)}}const bd=bg(["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))),Ig=bd[0],Rg=bd[1],Et=new Uint32Array(80),St=new Uint32Array(80);class Pg extends yd{constructor(e=64){super(128,e,16,!1),this.Ah=ve[0]|0,this.Al=ve[1]|0,this.Bh=ve[2]|0,this.Bl=ve[3]|0,this.Ch=ve[4]|0,this.Cl=ve[5]|0,this.Dh=ve[6]|0,this.Dl=ve[7]|0,this.Eh=ve[8]|0,this.El=ve[9]|0,this.Fh=ve[10]|0,this.Fl=ve[11]|0,this.Gh=ve[12]|0,this.Gl=ve[13]|0,this.Hh=ve[14]|0,this.Hl=ve[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:s,Ch:o,Cl:i,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:f,Gh:p,Gl:g,Hh:m,Hl:x}=this;return[e,n,r,s,o,i,a,c,l,d,u,f,p,g,m,x]}set(e,n,r,s,o,i,a,c,l,d,u,f,p,g,m,x){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=s|0,this.Ch=o|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=p|0,this.Gl=g|0,this.Hh=m|0,this.Hl=x|0}process(e,n){for(let v=0;v<16;v++,n+=4)Et[v]=e.getUint32(n),St[v]=e.getUint32(n+=4);for(let v=16;v<80;v++){const A=Et[v-15]|0,_=St[v-15]|0,C=un(A,_,1)^un(A,_,8)^sc(A,_,7),L=fn(A,_,1)^fn(A,_,8)^oc(A,_,7),R=Et[v-2]|0,E=St[v-2]|0,S=un(R,E,19)^jr(R,E,61)^sc(R,E,6),P=fn(R,E,19)^Ur(R,E,61)^oc(R,E,6),N=Eg(L,P,St[v-7],St[v-16]),w=Sg(N,C,S,Et[v-7],Et[v-16]);Et[v]=w|0,St[v]=N|0}let{Ah:r,Al:s,Bh:o,Bl:i,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:f,Fh:p,Fl:g,Gh:m,Gl:x,Hh:y,Hl:T}=this;for(let v=0;v<80;v++){const A=un(u,f,14)^un(u,f,18)^jr(u,f,41),_=fn(u,f,14)^fn(u,f,18)^Ur(u,f,41),C=u&p^~u&m,L=f&g^~f&x,R=Ag(T,_,L,Rg[v],St[v]),E=kg(R,y,A,C,Ig[v],Et[v]),S=R|0,P=un(r,s,28)^jr(r,s,34)^jr(r,s,39),N=fn(r,s,28)^Ur(r,s,34)^Ur(r,s,39),w=r&o^r&a^o&a,b=s&i^s&c^i&c;y=m|0,T=x|0,m=p|0,x=g|0,p=u|0,g=f|0,{h:u,l:f}=it(l|0,d|0,E|0,S|0),l=a|0,d=c|0,a=o|0,c=i|0,o=r|0,i=s|0;const k=xg(S,N,b);r=vg(k,E,P,w),s=k|0}({h:r,l:s}=it(this.Ah|0,this.Al|0,r|0,s|0)),{h:o,l:i}=it(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:c}=it(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=it(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:f}=it(this.Eh|0,this.El|0,u|0,f|0),{h:p,l:g}=it(this.Fh|0,this.Fl|0,p|0,g|0),{h:m,l:x}=it(this.Gh|0,this.Gl|0,m|0,x|0),{h:y,l:T}=it(this.Hh|0,this.Hl|0,y|0,T|0),this.set(r,s,o,i,a,c,l,d,u,f,p,g,m,x,y,T)}roundClean(){Nn(Et,St)}destroy(){Nn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const xd=wd(()=>new Cg),Ng=wd(()=>new Pg);const Yi=BigInt(0),hi=BigInt(1);function Gt(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function ze(t,e,n=""){const r=Rr(t),s=t?.length,o=e!==void 0;if(!r||o&&s!==e){const i=n&&`"${n}" `,a=o?` of length ${e}`:"",c=r?`length=${s}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function $r(t){const e=t.toString(16);return e.length&1?"0"+e:e}function vd(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Yi:BigInt("0x"+t)}function qs(t){return vd(Ht(t))}function yr(t){return Qt(t),vd(Ht(Uint8Array.from(t).reverse()))}function Zi(t,e){return hs(t.toString(16).padStart(e*2,"0"))}function Ed(t,e){return Zi(t,e).reverse()}function le(t,e,n){let r;if(typeof e=="string")try{r=hs(e)}catch(o){throw new Error(t+" must be hex string or Uint8Array, cause: "+o)}else if(Rr(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=r.length;if(typeof n=="number"&&s!==n)throw new Error(t+" of length "+n+" expected, got "+s);return r}function ic(t){return Uint8Array.from(t)}const po=t=>typeof t=="bigint"&&Yi<=t;function Lg(t,e,n){return po(t)&&po(e)&&po(n)&&e<=t&&t<n}function pi(t,e,n,r){if(!Lg(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Sd(t){let e;for(e=0;t>Yi;t>>=hi,e+=1);return e}const Pr=t=>(hi<<BigInt(t))-hi;function Bg(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=p=>new Uint8Array(p),s=p=>Uint8Array.of(p);let o=r(t),i=r(t),a=0;const c=()=>{o.fill(1),i.fill(0),a=0},l=(...p)=>n(i,o,...p),d=(p=r(0))=>{i=l(s(0),p),o=l(),p.length!==0&&(i=l(s(1),p),o=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0;const g=[];for(;p<e;){o=l();const m=o.slice();g.push(m),p+=o.length}return et(...g)};return(p,g)=>{c(),d(p);let m;for(;!(m=g(u()));)d();return c(),m}}function Nr(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(s,o,i){const a=t[s];if(i&&a===void 0)return;const c=typeof a;if(c!==o||a===null)throw new Error(`param "${s}" is invalid: expected ${o}, got ${c}`)}Object.entries(e).forEach(([s,o])=>r(s,o,!1)),Object.entries(n).forEach(([s,o])=>r(s,o,!0))}function ps(t){const e=new WeakMap;return(n,...r)=>{const s=e.get(n);if(s!==void 0)return s;const o=t(n,...r);return e.set(n,o),o}}const Pe=BigInt(0),be=BigInt(1),Ot=BigInt(2),Ad=BigInt(3),kd=BigInt(4),Td=BigInt(5),_g=BigInt(7),Cd=BigInt(8),Dg=BigInt(9),Id=BigInt(16);function he(t,e){const n=t%e;return n>=Pe?n:e+n}function ce(t,e,n){let r=t;for(;e-- >Pe;)r*=r,r%=n;return r}function ac(t,e){if(t===Pe)throw new Error("invert: expected non-zero number");if(e<=Pe)throw new Error("invert: expected positive modulus, got "+e);let n=he(t,e),r=e,s=Pe,o=be;for(;n!==Pe;){const a=r/n,c=r%n,l=s-o*a;r=n,n=c,s=o,o=l}if(r!==be)throw new Error("invert: does not exist");return he(s,e)}function Ji(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Rd(t,e){const n=(t.ORDER+be)/kd,r=t.pow(e,n);return Ji(t,r,e),r}function Fg(t,e){const n=(t.ORDER-Td)/Cd,r=t.mul(e,Ot),s=t.pow(r,n),o=t.mul(e,s),i=t.mul(t.mul(o,Ot),s),a=t.mul(o,t.sub(i,t.ONE));return Ji(t,a,e),a}function Og(t){const e=en(t),n=Pd(t),r=n(e,e.neg(e.ONE)),s=n(e,r),o=n(e,e.neg(r)),i=(t+_g)/Id;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,r);const u=a.mul(l,s),f=a.mul(l,o),p=a.eql(a.sqr(d),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,d,p),d=a.cmov(f,u,g);const m=a.eql(a.sqr(d),c),x=a.cmov(l,d,m);return Ji(a,x,c),x}}function Pd(t){if(t<Ad)throw new Error("sqrt is not defined for small field");let e=t-be,n=0;for(;e%Ot===Pe;)e/=Ot,n++;let r=Ot;const s=en(t);for(;cc(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Rd;let o=s.pow(r,e);const i=(e+be)/Ot;return function(c,l){if(c.is0(l))return l;if(cc(c,l)!==1)throw new Error("Cannot find square root");let d=n,u=c.mul(c.ONE,o),f=c.pow(l,e),p=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 x=be<<BigInt(d-g-1),y=c.pow(u,x);d=g,u=c.sqr(y),f=c.mul(f,u),p=c.mul(p,y)}return p}}function Mg(t){return t%kd===Ad?Rd:t%Cd===Td?Fg:t%Id===Dg?Og(t):Pd(t)}const jg=(t,e)=>(he(t,e)&be)===be,Ug=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function $g(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=Ug.reduce((r,s)=>(r[s]="function",r),e);return Nr(t,n),t}function Hg(t,e,n){if(n<Pe)throw new Error("invalid exponent, negatives unsupported");if(n===Pe)return t.ONE;if(n===be)return e;let r=t.ONE,s=e;for(;n>Pe;)n&be&&(r=t.mul(r,s)),s=t.sqr(s),n>>=be;return r}function Nd(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),s=e.reduce((i,a,c)=>t.is0(a)?i:(r[c]=i,t.mul(i,a)),t.ONE),o=t.inv(s);return e.reduceRight((i,a,c)=>t.is0(a)?i:(r[c]=t.mul(i,r[c]),t.mul(i,a)),o),r}function cc(t,e){const n=(t.ORDER-be)/Ot,r=t.pow(e,n),s=t.eql(r,t.ONE),o=t.eql(r,t.ZERO),i=t.eql(r,t.neg(t.ONE));if(!s&&!o&&!i)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function Ld(t,e){e!==void 0&&fi(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function en(t,e,n=!1,r={}){if(t<=Pe)throw new Error("invalid field: expected ORDER > 0, got "+t);let s,o,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&&(s=f.BITS),f.sqrt&&(o=f.sqrt),typeof f.isLE=="boolean"&&(n=f.isLE),typeof f.modFromBytes=="boolean"&&(i=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(s=e),r.sqrt&&(o=r.sqrt);const{nBitLength:c,nByteLength:l}=Ld(t,s);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:Pr(c),ZERO:Pe,ONE:be,allowedLengths:a,create:f=>he(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return Pe<=f&&f<t},is0:f=>f===Pe,isValidNot0:f=>!u.is0(f)&&u.isValid(f),isOdd:f=>(f&be)===be,neg:f=>he(-f,t),eql:(f,p)=>f===p,sqr:f=>he(f*f,t),add:(f,p)=>he(f+p,t),sub:(f,p)=>he(f-p,t),mul:(f,p)=>he(f*p,t),pow:(f,p)=>Hg(u,f,p),div:(f,p)=>he(f*ac(p,t),t),sqrN:f=>f*f,addN:(f,p)=>f+p,subN:(f,p)=>f-p,mulN:(f,p)=>f*p,inv:f=>ac(f,t),sqrt:o||(f=>(d||(d=Mg(t)),d(u,f))),toBytes:f=>n?Ed(f,l):Zi(f,l),fromBytes:(f,p=!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?yr(f):qs(f);if(i&&(g=he(g,t)),!p&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:f=>Nd(u,f),cmov:(f,p,g)=>g?p:f});return Object.freeze(u)}function Bd(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 _d(t){const e=Bd(t);return e+Math.ceil(e/2)}function qg(t,e,n=!1){const r=t.length,s=Bd(e),o=_d(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);const i=n?yr(t):qs(t),a=he(i,e-be)+be;return n?Ed(a,s):Zi(a,s)}const Ln=BigInt(0),Mt=BigInt(1);function gs(t,e){const n=e.negate();return t?n:e}function jt(t,e){const n=Nd(t.Fp,e.map(r=>r.Z));return e.map((r,s)=>t.fromAffine(r.toAffine(n[s])))}function Dd(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function go(t,e){Dd(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),s=2**t,o=Pr(t),i=BigInt(t);return{windows:n,windowSize:r,mask:o,maxNumber:s,shiftBy:i}}function lc(t,e,n){const{windowSize:r,mask:s,maxNumber:o,shiftBy:i}=n;let a=Number(t&s),c=t>>i;a>r&&(a-=o,c+=Mt);const l=e*r,d=l+Math.abs(a)-1,u=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:f,isNegF:p,offsetF:l}}function Kg(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 zg(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 mo=new WeakMap,Fd=new WeakMap;function wo(t){return Fd.get(t)||1}function dc(t){if(t!==Ln)throw new Error("invalid wNAF")}class Od{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 s=e;for(;n>Ln;)n&Mt&&(r=r.add(s)),s=s.double(),n>>=Mt;return r}precomputeWindow(e,n){const{windows:r,windowSize:s}=go(n,this.bits),o=[];let i=e,a=i;for(let c=0;c<r;c++){a=i,o.push(a);for(let l=1;l<s;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE;const i=go(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:f,offsetF:p}=lc(r,a,i);r=c,d?o=o.add(gs(f,n[p])):s=s.add(gs(u,n[l]))}return dc(r),{p:s,f:o}}wNAFUnsafe(e,n,r,s=this.ZERO){const o=go(e,this.bits);for(let i=0;i<o.windows&&r!==Ln;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=lc(r,i,o);if(r=a,!l){const u=n[c];s=s.add(d?u.negate():u)}}return dc(r),s}getPrecomputes(e,n,r){let s=mo.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(s=r(s)),mo.set(n,s))),s}cached(e,n,r){const s=wo(e);return this.wNAF(s,this.getPrecomputes(s,e,r),n)}unsafe(e,n,r,s){const o=wo(e);return o===1?this._unsafeLadder(e,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),n,s)}createCache(e,n){Dd(n,this.bits),Fd.set(e,n),mo.delete(e)}hasCache(e){return wo(e)!==1}}function Vg(t,e,n,r){let s=e,o=t.ZERO,i=t.ZERO;for(;n>Ln||r>Ln;)n&Mt&&(o=o.add(s)),r&Mt&&(i=i.add(s)),s=s.double(),n>>=Mt,r>>=Mt;return{p1:o,p2:i}}function Md(t,e,n,r){Kg(n,t),zg(r,e);const s=n.length,o=r.length;if(s!==o)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,a=Sd(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Pr(c),d=new Array(Number(l)+1).fill(i),u=Math.floor((e.BITS-1)/c)*c;let f=i;for(let p=u;p>=0;p-=c){d.fill(i);for(let m=0;m<o;m++){const x=r[m],y=Number(x>>BigInt(p)&l);d[y]=d[y].add(n[m])}let g=i;for(let m=d.length-1,x=i;m>0;m--)x=x.add(d[m]),g=g.add(x);if(f=f.add(g),p!==0)for(let m=0;m<c;m++)f=f.double()}return f}function uc(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return $g(e),e}else return en(t,{isLE:n})}function jd(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>Ln))throw new Error(`CURVE.${c} must be positive bigint`)}const s=uc(e.p,n.Fp,r),o=uc(e.n,n.Fn,r),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const c of a)if(!s.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:s,Fn:o}}const At=BigInt(0),pe=BigInt(1),yo=BigInt(2),Gg=BigInt(8);function Wg(t,e,n,r){const s=t.sqr(n),o=t.sqr(r),i=t.add(t.mul(e.a,s),o),a=t.add(t.ONE,t.mul(e.d,t.mul(s,o)));return t.eql(i,a)}function Xg(t,e={}){const n=jd("edwards",t,e,e.FpFnLE),{Fp:r,Fn:s}=n;let o=n.CURVE;const{h:i}=o;Nr(e,{},{uvRatio:"function"});const a=yo<<BigInt(s.BYTES*8)-pe,c=x=>r.create(x),l=e.uvRatio||((x,y)=>{try{return{isValid:!0,value:r.sqrt(r.div(x,y))}}catch{return{isValid:!1,value:At}}});if(!Wg(r,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function d(x,y,T=!1){const v=T?pe:At;return pi("coordinate "+x,y,v,a),y}function u(x){if(!(x instanceof g))throw new Error("ExtendedPoint expected")}const f=ps((x,y)=>{const{X:T,Y:v,Z:A}=x,_=x.is0();y==null&&(y=_?Gg:r.inv(A));const C=c(T*y),L=c(v*y),R=r.mul(A,y);if(_)return{x:At,y:pe};if(R!==pe)throw new Error("invZ was invalid");return{x:C,y:L}}),p=ps(x=>{const{a:y,d:T}=o;if(x.is0())throw new Error("bad point: ZERO");const{X:v,Y:A,Z:_,T:C}=x,L=c(v*v),R=c(A*A),E=c(_*_),S=c(E*E),P=c(L*y),N=c(E*c(P+R)),w=c(S+c(T*c(L*R)));if(N!==w)throw new Error("bad point: equation left != right (1)");const b=c(v*A),k=c(_*C);if(b!==k)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(y,T,v,A){this.X=d("x",y),this.Y=d("y",T),this.Z=d("z",v,!0),this.T=d("t",A),Object.freeze(this)}static CURVE(){return o}static fromAffine(y){if(y instanceof g)throw new Error("extended point not allowed");const{x:T,y:v}=y||{};return d("x",T),d("y",v),new g(T,v,pe,c(T*v))}static fromBytes(y,T=!1){const v=r.BYTES,{a:A,d:_}=o;y=ic(ze(y,v,"point")),Gt(T,"zip215");const C=ic(y),L=y[v-1];C[v-1]=L&-129;const R=yr(C),E=T?a:r.ORDER;pi("point.y",R,At,E);const S=c(R*R),P=c(S-pe),N=c(_*S-A);let{isValid:w,value:b}=l(P,N);if(!w)throw new Error("bad point: invalid y coordinate");const k=(b&pe)===pe,B=(L&128)!==0;if(!T&&b===At&&B)throw new Error("bad point: x=0 and x_0=1");return B!==k&&(b=c(-b)),g.fromAffine({x:b,y:R})}static fromHex(y,T=!1){return g.fromBytes(le("point",y),T)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,T=!0){return m.createCache(this,y),T||this.multiply(yo),this}assertValidity(){p(this)}equals(y){u(y);const{X:T,Y:v,Z:A}=this,{X:_,Y:C,Z:L}=y,R=c(T*L),E=c(_*A),S=c(v*L),P=c(C*A);return R===E&&S===P}is0(){return this.equals(g.ZERO)}negate(){return new g(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:y}=o,{X:T,Y:v,Z:A}=this,_=c(T*T),C=c(v*v),L=c(yo*c(A*A)),R=c(y*_),E=T+v,S=c(c(E*E)-_-C),P=R+C,N=P-L,w=R-C,b=c(S*N),k=c(P*w),B=c(S*w),M=c(N*P);return new g(b,k,M,B)}add(y){u(y);const{a:T,d:v}=o,{X:A,Y:_,Z:C,T:L}=this,{X:R,Y:E,Z:S,T:P}=y,N=c(A*R),w=c(_*E),b=c(L*v*P),k=c(C*S),B=c((A+_)*(R+E)-N-w),M=k-b,U=k+b,D=c(w-T*N),I=c(B*M),F=c(U*D),O=c(B*D),K=c(M*U);return new g(I,F,K,O)}subtract(y){return this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:T,f:v}=m.cached(this,y,A=>jt(g,A));return jt(g,[T,v])[0]}multiplyUnsafe(y,T=g.ZERO){if(!s.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===At?g.ZERO:this.is0()||y===pe?this:m.unsafe(this,y,v=>jt(g,v),T)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,o.n).is0()}toAffine(y){return f(this,y)}clearCofactor(){return i===pe?this:this.multiplyUnsafe(i)}toBytes(){const{x:y,y:T}=this.toAffine(),v=r.toBytes(T);return v[v.length-1]|=y&pe?128:0,v}toHex(){return Ht(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(y){return jt(g,y)}static msm(y,T){return Md(g,s,y,T)}_setWindowSize(y){this.precompute(y)}toRawBytes(){return this.toBytes()}}g.BASE=new g(o.Gx,o.Gy,pe,c(o.Gx*o.Gy)),g.ZERO=new g(At,pe,pe,At),g.Fp=r,g.Fn=s;const m=new Od(g,s.BITS);return g.BASE.precompute(8),g}function Yg(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is required');Nr(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:s,Fp:o,Fn:i}=t,a=n.randomBytes||Xi,c=n.adjustScalarBytes||(E=>E),l=n.domain||((E,S,P)=>{if(Gt(P,"phflag"),S.length||P)throw new Error("Contexts/pre-hash are not supported");return E});function d(E){return i.create(yr(E))}function u(E){const S=v.secretKey;E=le("private key",E,S);const P=le("hashed private key",e(E),2*S),N=c(P.slice(0,S)),w=P.slice(S,2*S),b=d(N);return{head:N,prefix:w,scalar:b}}function f(E){const{head:S,prefix:P,scalar:N}=u(E),w=s.multiply(N),b=w.toBytes();return{head:S,prefix:P,scalar:N,point:w,pointBytes:b}}function p(E){return f(E).pointBytes}function g(E=Uint8Array.of(),...S){const P=et(...S);return d(e(l(P,le("context",E),!!r)))}function m(E,S,P={}){E=le("message",E),r&&(E=r(E));const{prefix:N,scalar:w,pointBytes:b}=f(S),k=g(P.context,N,E),B=s.multiply(k).toBytes(),M=g(P.context,B,b,E),U=i.create(k+M*w);if(!i.isValid(U))throw new Error("sign failed: invalid s");const D=et(B,i.toBytes(U));return ze(D,v.signature,"result")}const x={zip215:!0};function y(E,S,P,N=x){const{context:w,zip215:b}=N,k=v.signature;E=le("signature",E,k),S=le("message",S),P=le("publicKey",P,v.publicKey),b!==void 0&&Gt(b,"zip215"),r&&(S=r(S));const B=k/2,M=E.subarray(0,B),U=yr(E.subarray(B,k));let D,I,F;try{D=t.fromBytes(P,b),I=t.fromBytes(M,b),F=s.multiplyUnsafe(U)}catch{return!1}if(!b&&D.isSmallOrder())return!1;const O=g(w,I.toBytes(),D.toBytes(),S);return I.add(D.multiplyUnsafe(O)).subtract(F).clearCofactor().is0()}const T=o.BYTES,v={secretKey:T,publicKey:T,signature:2*T,seed:T};function A(E=a(v.seed)){return ze(E,v.seed,"seed")}function _(E){const S=R.randomSecretKey(E);return{secretKey:S,publicKey:p(S)}}function C(E){return Rr(E)&&E.length===i.BYTES}function L(E,S){try{return!!t.fromBytes(E,S)}catch{return!1}}const R={getExtendedPublicKey:f,randomSecretKey:A,isValidSecretKey:C,isValidPublicKey:L,toMontgomery(E){const{y:S}=t.fromBytes(E),P=v.publicKey,N=P===32;if(!N&&P!==57)throw new Error("only defined for 25519 and 448");const w=N?o.div(pe+S,pe-S):o.div(S-pe,S+pe);return o.toBytes(w)},toMontgomerySecret(E){const S=v.secretKey;ze(E,S);const P=e(E.subarray(0,S));return c(P).subarray(0,S)},randomPrivateKey:A,precompute(E=8,S=t.BASE){return S.precompute(E,!1)}};return Object.freeze({keygen:_,getPublicKey:p,sign:m,verify:y,utils:R,Point:t,lengths:v})}function Zg(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=en(e.n,t.nBitLength,!0),s={Fp:n,Fn:r,uvRatio:t.uvRatio},o={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:s,hash:t.hash,eddsaOpts:o}}function Jg(t,e){const n=e.Point;return Object.assign({},e,{ExtendedPoint:n,CURVE:t,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function Qg(t){const{CURVE:e,curveOpts:n,hash:r,eddsaOpts:s}=Zg(t),o=Xg(e,n),i=Yg(o,r,s);return Jg(t,i)}const em=BigInt(1),fc=BigInt(2);BigInt(3);const tm=BigInt(5),nm=BigInt(8),Qi=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ud={p:Qi,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:nm,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function rm(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),o=Qi,a=t*t%o*t%o,c=ce(a,fc,o)*a%o,l=ce(c,em,o)*t%o,d=ce(l,tm,o)*l%o,u=ce(d,e,o)*d%o,f=ce(u,n,o)*u%o,p=ce(f,r,o)*f%o,g=ce(p,s,o)*p%o,m=ce(g,s,o)*p%o,x=ce(m,e,o)*d%o;return{pow_p_5_8:ce(x,fc,o)*t%o,b2:a}}function sm(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const hc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function om(t,e){const n=Qi,r=he(e*e*e,n),s=he(r*r*e,n),o=rm(t*s).pow_p_5_8;let i=he(t*r*o,n);const a=he(e*i*i,n),c=i,l=he(i*hc,n),d=a===t,u=a===he(-t,n),f=a===he(-t*hc,n);return d&&(i=c),(u||f)&&(i=l),jg(i,n)&&(i=he(-i,n)),{isValid:d||u,value:i}}const im=en(Ud.p,{isLE:!0}),am={...Ud,Fp:im,hash:Ng,adjustScalarBytes:sm,uvRatio:om},ms=Qg(am);class pc extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}}class gc extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class cm extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}const mt={get(t=globalThis){const e=t.crypto;if(e?.subtle==null)throw new cm("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}},ws=32,ct=64,gi=32;let vn;const $d=(async()=>{try{return await mt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function lm(){const t=ms.utils.randomPrivateKey(),e=ms.getPublicKey(t);return{privateKey:mm(t,e),publicKey:e}}async function dm(t,e){let n;t.length===ct?n=t.subarray(0,32):n=t;const r={crv:"Ed25519",kty:"OKP",x:J(t.subarray(32),"base64url"),d:J(n,"base64url"),ext:!0,key_ops:["sign"]},s=await mt.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),o=await mt.get().subtle.sign({name:"Ed25519"},s,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(o,0,o.byteLength)}function um(t,e){const n=t.subarray(0,gi);return ms.sign(e instanceof Uint8Array?e:e.subarray(),n)}async function fm(t,e){return vn==null&&(vn=await $d),vn?dm(t,e):um(t,e)}async function hm(t,e,n){if(t.buffer instanceof ArrayBuffer){const r=await mt.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await mt.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 pm(t,e,n){return ms.verify(e,n instanceof Uint8Array?n:n.subarray(),t)}async function gm(t,e,n){return vn==null&&(vn=await $d),vn?hm(t,e,n):pm(t,e,n)}function mm(t,e){const n=new Uint8Array(ct);for(let r=0;r<gi;r++)n[r]=t[r],n[gi+r]=e[r];return n}function Ks(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}class Hd{type="Ed25519";raw;constructor(e){this.raw=br(e,ws)}toMultihash(){return Cr.digest(Ws(this))}toCID(){return oe.createV1(114,this.toMultihash())}toString(){return Te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ye(this.raw,e.raw)}verify(e,n,r){r?.signal?.throwIfAborted();const s=gm(this.raw,n,e);return Ks(s)?s.then(o=>(r?.signal?.throwIfAborted(),o)):s}}class mi{type="Ed25519";raw;publicKey;constructor(e,n){this.raw=br(e,ct),this.publicKey=new Hd(n)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ye(this.raw,e.raw)}sign(e,n){n?.signal?.throwIfAborted();const r=fm(this.raw,e);return Ks(r)?r.then(s=>(n?.signal?.throwIfAborted(),s)):(n?.signal?.throwIfAborted(),r)}}function wm(t){if(t.length>ct){t=br(t,ct+ws);const r=t.subarray(0,ct),s=t.subarray(ct,t.length);return new mi(r,s)}t=br(t,ct);const e=t.subarray(0,ct),n=t.subarray(ws);return new mi(e,n)}function qd(t){return t=br(t,ws),new Hd(t)}async function ym(){const{privateKey:t,publicKey:e}=lm();return new mi(t,e)}function br(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new Xe(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}const bm=Math.pow(2,7),xm=Math.pow(2,14),vm=Math.pow(2,21),ea=Math.pow(2,28),ta=Math.pow(2,35),na=Math.pow(2,42),ra=Math.pow(2,49),te=128,Ee=127;function tn(t){if(t<bm)return 1;if(t<xm)return 2;if(t<vm)return 3;if(t<ea)return 4;if(t<ta)return 5;if(t<na)return 6;if(t<ra)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Kd(t,e,n=0){switch(tn(t)){case 8:e[n++]=t&255|te,t/=128;case 7:e[n++]=t&255|te,t/=128;case 6:e[n++]=t&255|te,t/=128;case 5:e[n++]=t&255|te,t/=128;case 4:e[n++]=t&255|te,t>>>=7;case 3:e[n++]=t&255|te,t>>>=7;case 2:e[n++]=t&255|te,t>>>=7;case 1:{e[n++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Em(t,e,n=0){switch(tn(t)){case 8:e.set(n++,t&255|te),t/=128;case 7:e.set(n++,t&255|te),t/=128;case 6:e.set(n++,t&255|te),t/=128;case 5:e.set(n++,t&255|te),t/=128;case 4:e.set(n++,t&255|te),t>>>=7;case 3:e.set(n++,t&255|te),t>>>=7;case 2:e.set(n++,t&255|te),t>>>=7;case 1:{e.set(n++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function zd(t,e){let n=t[e],r=0;if(r+=n&Ee,n<te||(n=t[e+1],r+=(n&Ee)<<7,n<te)||(n=t[e+2],r+=(n&Ee)<<14,n<te)||(n=t[e+3],r+=(n&Ee)<<21,n<te)||(n=t[e+4],r+=(n&Ee)*ea,n<te)||(n=t[e+5],r+=(n&Ee)*ta,n<te)||(n=t[e+6],r+=(n&Ee)*na,n<te)||(n=t[e+7],r+=(n&Ee)*ra,n<te))return r;throw new RangeError("Could not decode varint")}function Sm(t,e){let n=t.get(e),r=0;if(r+=n&Ee,n<te||(n=t.get(e+1),r+=(n&Ee)<<7,n<te)||(n=t.get(e+2),r+=(n&Ee)<<14,n<te)||(n=t.get(e+3),r+=(n&Ee)<<21,n<te)||(n=t.get(e+4),r+=(n&Ee)*ea,n<te)||(n=t.get(e+5),r+=(n&Ee)*ta,n<te)||(n=t.get(e+6),r+=(n&Ee)*na,n<te)||(n=t.get(e+7),r+=(n&Ee)*ra,n<te))return r;throw new RangeError("Could not decode varint")}function Am(t,e,n=0){return e==null&&(e=gt(tn(t))),e instanceof Uint8Array?Kd(t,e,n):Em(t,e,n)}function Vd(t,e=0){return t instanceof Uint8Array?zd(t,e):Sm(t,e)}const sa=new Float32Array([-0]),Nt=new Uint8Array(sa.buffer);function km(t,e,n){sa[0]=t,e[n]=Nt[0],e[n+1]=Nt[1],e[n+2]=Nt[2],e[n+3]=Nt[3]}function Tm(t,e){return Nt[0]=t[e],Nt[1]=t[e+1],Nt[2]=t[e+2],Nt[3]=t[e+3],sa[0]}const oa=new Float64Array([-0]),Se=new Uint8Array(oa.buffer);function Cm(t,e,n){oa[0]=t,e[n]=Se[0],e[n+1]=Se[1],e[n+2]=Se[2],e[n+3]=Se[3],e[n+4]=Se[4],e[n+5]=Se[5],e[n+6]=Se[6],e[n+7]=Se[7]}function Im(t,e){return Se[0]=t[e],Se[1]=t[e+1],Se[2]=t[e+2],Se[3]=t[e+3],Se[4]=t[e+4],Se[5]=t[e+5],Se[6]=t[e+6],Se[7]=t[e+7],oa[0]}const Rm=BigInt(Number.MAX_SAFE_INTEGER),Pm=BigInt(Number.MIN_SAFE_INTEGER);class Ae{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 qt;if(e<Rm&&e>Pm)return this.fromNumber(Number(e));const n=e<0n;n&&(e=-e);let r=e>>32n,s=e-(r<<32n);return n&&(r=~r|0n,s=~s|0n,++s>mc&&(s=0n,++r>mc&&(r=0n))),new Ae(Number(s),Number(r))}static fromNumber(e){if(e===0)return qt;const n=e<0;n&&(e=-e);let r=e>>>0,s=(e-r)/4294967296>>>0;return n&&(s=~s>>>0,r=~r>>>0,++r>4294967295&&(r=0,++s>4294967295&&(s=0))),new Ae(r,s)}static from(e){return typeof e=="number"?Ae.fromNumber(e):typeof e=="bigint"?Ae.fromBigInt(e):typeof e=="string"?Ae.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new Ae(e.low>>>0,e.high>>>0):qt}}const qt=new Ae(0,0);qt.toBigInt=function(){return 0n};qt.zzEncode=qt.zzDecode=function(){return this};qt.length=function(){return 1};const mc=4294967296n;function Nm(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 Lm(t,e,n){if(n-e<1)return"";let s;const o=[];let i=0,a;for(;e<n;)a=t[e++],a<128?o[i++]=a:a>191&&a<224?o[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,o[i++]=55296+(a>>10),o[i++]=56320+(a&1023)):o[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function Gd(t,e,n){const r=n;let s,o;for(let i=0;i<t.length;++i)s=t.charCodeAt(i),s<128?e[n++]=s:s<2048?(e[n++]=s>>6|192,e[n++]=s&63|128):(s&64512)===55296&&((o=t.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,e[n++]=s>>18|240,e[n++]=s>>12&63|128,e[n++]=s>>6&63|128,e[n++]=s&63|128):(e[n++]=s>>12|224,e[n++]=s>>6&63|128,e[n++]=s&63|128);return n-r}function qe(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function Hr(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}class Bm{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,qe(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 qe(this,4);return Hr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw qe(this,4);return Hr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw qe(this,4);const e=Tm(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw qe(this,4);const e=Im(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 qe(this,e);return this.pos+=e,n===r?new Uint8Array(0):this.buf.subarray(n,r)}string(){const e=this.bytes();return Lm(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw qe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw qe(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 Ae(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 qe(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 qe(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 qe(this,8);const e=Hr(this.buf,this.pos+=4),n=Hr(this.buf,this.pos+=4);return new Ae(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=zd(this.buf,this.pos);return this.pos+=tn(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 _m(t){return new Bm(t instanceof Uint8Array?t:t.subarray())}function zs(t,e,n){const r=_m(t);return e.decode(r,void 0,n)}function Dm(t){let r,s=8192;return function(i){if(i<1||i>4096)return gt(i);s+i>8192&&(r=gt(8192),s=0);const a=r.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),a}}class ar{fn;len;next;val;constructor(e,n,r){this.fn=e,this.len=n,this.next=void 0,this.val=r}}function bo(){}class Fm{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const Om=Dm();function Mm(t){return globalThis.Buffer!=null?gt(t):Om(t)}class wi{len;head;tail;states;constructor(){this.len=0,this.head=new ar(bo,0,0),this.tail=this.head,this.states=null}_push(e,n,r){return this.tail=this.tail.next=new ar(e,n,r),this.len+=n,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Um((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(qr,10,Ae.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const n=Ae.fromBigInt(e);return this._push(qr,n.length(),n)}uint64Number(e){return this._push(Kd,tn(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=Ae.fromBigInt(e).zzEncode();return this._push(qr,n.length(),n)}sint64Number(e){const n=Ae.fromNumber(e).zzEncode();return this._push(qr,n.length(),n)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(xo,1,e?1:0)}fixed32(e){return this._push(Yn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const n=Ae.fromBigInt(e);return this._push(Yn,4,n.lo)._push(Yn,4,n.hi)}fixed64Number(e){const n=Ae.fromNumber(e);return this._push(Yn,4,n.lo)._push(Yn,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(km,4,e)}double(e){return this._push(Cm,8,e)}bytes(e){const n=e.length>>>0;return n===0?this._push(xo,1,0):this.uint32(n)._push($m,n,e)}string(e){const n=Nm(e);return n!==0?this.uint32(n)._push(Gd,n,e):this._push(xo,1,0)}fork(){return this.states=new Fm(this),this.head=this.tail=new ar(bo,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 ar(bo,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=Mm(this.len);let r=0;for(;e!=null;)e.fn(e.val,n,r),r+=e.len,e=e.next;return n}}function xo(t,e,n){e[n]=t&255}function jm(t,e,n){for(;t>127;)e[n++]=t&127|128,t>>>=7;e[n]=t}class Um extends ar{next;constructor(e,n){super(jm,e,n),this.next=void 0}}function qr(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 Yn(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 $m(t,e,n){e.set(t,n)}globalThis.Buffer!=null&&(wi.prototype.bytes=function(t){const e=t.length>>>0;return this.uint32(e),e>0&&this._push(Hm,e,t),this},wi.prototype.string=function(t){const e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(qm,e,t),this});function Hm(t,e,n){e.set(t,n)}function qm(t,e,n){t.length<40?Gd(t,e,n):e.utf8Write!=null?e.utf8Write(t,n):e.set(fe(t),n)}function Km(){return new wi}function Vs(t,e){const n=Km();return e.encode(t,n,{lengthDelimited:!1}),n.finish()}var ys;(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"})(ys||(ys={}));function Wd(t,e,n,r){return{name:t,type:e,encode:n,decode:r}}function zm(t){function e(s){if(t[s.toString()]==null)throw new Error("Invalid enum value");return t[s]}const n=function(o,i){const a=e(o);i.int32(a)},r=function(o){const i=o.int32();return e(i)};return Wd("enum",ys.VARINT,n,r)}function Gs(t,e){return Wd("message",ys.LENGTH_DELIMITED,t,e)}class wc extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var ie;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(ie||(ie={}));var yi;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(yi||(yi={}));(function(t){t.codec=()=>zm(yi)})(ie||(ie={}));var Wt;(function(t){let e;t.codec=()=>(e==null&&(e=Gs((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),ie.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const o={},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{o.Type=ie.codec().decode(n);break}case 2:{o.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return o})),e),t.encode=n=>Vs(n,t.codec()),t.decode=(n,r)=>zs(n,t.codec(),r)})(Wt||(Wt={}));var bs;(function(t){let e;t.codec=()=>(e==null&&(e=Gs((n,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),ie.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const o={},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{o.Type=ie.codec().decode(n);break}case 2:{o.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return o})),e),t.encode=n=>Vs(n,t.codec()),t.decode=(n,r)=>zs(n,t.codec(),r)})(bs||(bs={}));const Xd=xd;class Yd{type="RSA";jwk;_raw;_multihash;constructor(e,n){this.jwk=e,this._multihash=n}get raw(){return this._raw==null&&(this._raw=Jd(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return oe.createV1(114,this._multihash)}toString(){return Te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ye(this.raw,e.raw)}verify(e,n,r){return iw(this.jwk,n,e,r)}}class Vm{type="RSA";jwk;_raw;publicKey;constructor(e,n){this.jwk=e,this.publicKey=n}get raw(){return this._raw==null&&(this._raw=Zm(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ye(this.raw,e.raw)}sign(e,n){return ow(this.jwk,e,n)}}const Gm=8192,Zd=18,Wm=1062,Xm=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Ym(t){return{n:J(t[1],"base64url"),e:J(t[2],"base64url"),d:J(t[3],"base64url"),p:J(t[4],"base64url"),q:J(t[5],"base64url"),dp:J(t[6],"base64url"),dq:J(t[7],"base64url"),qi:J(t[8],"base64url"),kty:"RSA"}}function Zm(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 Xe("JWK was missing components");return pt([Be(Uint8Array.from([0])),Be(fe(t.n,"base64url")),Be(fe(t.e,"base64url")),Be(fe(t.d,"base64url")),Be(fe(t.p,"base64url")),Be(fe(t.q,"base64url")),Be(fe(t.dp,"base64url")),Be(fe(t.dq,"base64url")),Be(fe(t.qi,"base64url"))]).subarray()}function Jm(t){const e=$n(t[1],{offset:0});return{kty:"RSA",n:J(e[0],"base64url"),e:J(e[1],"base64url")}}function Jd(t){if(t.n==null||t.e==null)throw new Xe("JWK was missing components");return pt([Xm,Gi(pt([Be(fe(t.n,"base64url")),Be(fe(t.e,"base64url"))]))]).subarray()}function Qm(t){const e=$n(t);return ew(e)}function ew(t){const e=Ym(t);return rw(e)}function tw(t,e){if(t.byteLength>=Wm)throw new Zl("Key size is too large");const n=$n(t,{offset:0});return nw(n,t,e)}function nw(t,e,n){const r=Jm(t);if(n==null){const s=Xd(Wt.encode({Type:ie.RSA,Data:e}));n=Tr(Zd,s)}return new Yd(r,n)}function rw(t){if(aw(t)>Gm)throw new Xe("Key size is too large");const e=sw(t),n=Xd(Wt.encode({Type:ie.RSA,Data:Jd(e.publicKey)})),r=Tr(Zd,n);return new Vm(e.privateKey,new Yd(e.publicKey,r))}function sw(t){if(t==null)throw new Xe("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function ow(t,e,n){const r=await mt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);n?.signal?.throwIfAborted();const s=await mt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}async function iw(t,e,n,r){const s=await mt.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const o=await mt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,e,n instanceof Uint8Array?n:n.subarray());return r?.signal?.throwIfAborted(),o}function aw(t){if(t.kty!=="RSA")throw new Xe("invalid key type");if(t.n==null)throw new Xe("invalid key modulus");return fe(t.n,"base64url").length*8}class Qd extends md{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,pd(e);const r=Wi(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 s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?e.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Nn(o)}update(e){return fs(this),this.iHash.update(e),this}digestInto(e){fs(this),Qt(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:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,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 eu=(t,e,n)=>new Qd(t,e).update(n).digest();eu.create=(t,e)=>new Qd(t,e);const yc=(t,e)=>(t+(t>=0?e:-e)/tu)/e;function cw(t,e,n){const[[r,s],[o,i]]=e,a=yc(i*t,n),c=yc(-s*t,n);let l=t-a*r-c*o,d=-a*s-c*i;const u=l<dt,f=d<dt;u&&(l=-l),f&&(d=-d);const p=Pr(Math.ceil(Sd(n)/2))+En;if(l<dt||l>=p||d<dt||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:f,k2:d}}function bi(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function vo(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return Gt(n.lowS,"lowS"),Gt(n.prehash,"prehash"),n.format!==void 0&&bi(n.format),n}class lw extends Error{constructor(e=""){super(e)}}const lt={Err:lw,_tlv:{encode:(t,e)=>{const{Err:n}=lt;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,s=$r(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const o=r>127?$r(s.length/2|128):"";return $r(t)+o+s+e},decode(t,e){const{Err:n}=lt;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 s=e[r++],o=!!(s&128);let i=0;if(!o)i=s;else{const c=s&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}=lt;if(t<dt)throw new e("integer: negative integers are not allowed");let n=$r(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}=lt;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 qs(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=lt,s=le("signature",t),{v:o,l:i}=r.decode(48,s);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,o),{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}=lt,r=e.encode(2,n.encode(t.r)),s=e.encode(2,n.encode(t.s)),o=r+s;return e.encode(48,o)}},dt=BigInt(0),En=BigInt(1),tu=BigInt(2),Kr=BigInt(3),dw=BigInt(4);function mn(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let s=le("private key",e);try{r=t.fromBytes(s)}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 uw(t,e={}){const n=jd("weierstrass",t,e),{Fp:r,Fn:s}=n;let o=n.CURVE;const{h:i,n:a}=o;Nr(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=ru(r,s);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(N,w,b){const{x:k,y:B}=w.toAffine(),M=r.toBytes(k);if(Gt(b,"isCompressed"),b){d();const U=!r.isOdd(B);return et(nu(U),M)}else return et(Uint8Array.of(4),M,r.toBytes(B))}function f(N){ze(N,void 0,"Point");const{publicKey:w,publicKeyUncompressed:b}=l,k=N.length,B=N[0],M=N.subarray(1);if(k===w&&(B===2||B===3)){const U=r.fromBytes(M);if(!r.isValid(U))throw new Error("bad point: is not on curve, wrong x");const D=m(U);let I;try{I=r.sqrt(D)}catch(K){const q=K instanceof Error?": "+K.message:"";throw new Error("bad point: is not on curve, sqrt error"+q)}d();const F=r.isOdd(I);return(B&1)===1!==F&&(I=r.neg(I)),{x:U,y:I}}else if(k===b&&B===4){const U=r.BYTES,D=r.fromBytes(M.subarray(0,U)),I=r.fromBytes(M.subarray(U,U*2));if(!x(D,I))throw new Error("bad point: is not on curve");return{x:D,y:I}}else throw new Error(`bad point: got length ${k}, expected compressed=${w} or uncompressed=${b}`)}const p=e.toBytes||u,g=e.fromBytes||f;function m(N){const w=r.sqr(N),b=r.mul(w,N);return r.add(r.add(b,r.mul(N,o.a)),o.b)}function x(N,w){const b=r.sqr(w),k=m(N);return r.eql(b,k)}if(!x(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const y=r.mul(r.pow(o.a,Kr),dw),T=r.mul(r.sqr(o.b),BigInt(27));if(r.is0(r.add(y,T)))throw new Error("bad curve params: a or b");function v(N,w,b=!1){if(!r.isValid(w)||b&&r.is0(w))throw new Error(`bad point coordinate ${N}`);return w}function A(N){if(!(N instanceof E))throw new Error("ProjectivePoint expected")}function _(N){if(!c||!c.basises)throw new Error("no endo");return cw(N,c.basises,s.ORDER)}const C=ps((N,w)=>{const{X:b,Y:k,Z:B}=N;if(r.eql(B,r.ONE))return{x:b,y:k};const M=N.is0();w==null&&(w=M?r.ONE:r.inv(B));const U=r.mul(b,w),D=r.mul(k,w),I=r.mul(B,w);if(M)return{x:r.ZERO,y:r.ZERO};if(!r.eql(I,r.ONE))throw new Error("invZ was invalid");return{x:U,y:D}}),L=ps(N=>{if(N.is0()){if(e.allowInfinityPoint&&!r.is0(N.Y))return;throw new Error("bad point: ZERO")}const{x:w,y:b}=N.toAffine();if(!r.isValid(w)||!r.isValid(b))throw new Error("bad point: x or y not field elements");if(!x(w,b))throw new Error("bad point: equation left != right");if(!N.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function R(N,w,b,k,B){return b=new E(r.mul(b.X,N),b.Y,b.Z),w=gs(k,w),b=gs(B,b),w.add(b)}class E{constructor(w,b,k){this.X=v("x",w),this.Y=v("y",b,!0),this.Z=v("z",k),Object.freeze(this)}static CURVE(){return o}static fromAffine(w){const{x:b,y:k}=w||{};if(!w||!r.isValid(b)||!r.isValid(k))throw new Error("invalid affine point");if(w instanceof E)throw new Error("projective point not allowed");return r.is0(b)&&r.is0(k)?E.ZERO:new E(b,k,r.ONE)}static fromBytes(w){const b=E.fromAffine(g(ze(w,void 0,"point")));return b.assertValidity(),b}static fromHex(w){return E.fromBytes(le("pointHex",w))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,b=!0){return P.createCache(this,w),b||this.multiply(Kr),this}assertValidity(){L(this)}hasEvenY(){const{y:w}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(w)}equals(w){A(w);const{X:b,Y:k,Z:B}=this,{X:M,Y:U,Z:D}=w,I=r.eql(r.mul(b,D),r.mul(M,B)),F=r.eql(r.mul(k,D),r.mul(U,B));return I&&F}negate(){return new E(this.X,r.neg(this.Y),this.Z)}double(){const{a:w,b}=o,k=r.mul(b,Kr),{X:B,Y:M,Z:U}=this;let D=r.ZERO,I=r.ZERO,F=r.ZERO,O=r.mul(B,B),K=r.mul(M,M),q=r.mul(U,U),H=r.mul(B,M);return H=r.add(H,H),F=r.mul(B,U),F=r.add(F,F),D=r.mul(w,F),I=r.mul(k,q),I=r.add(D,I),D=r.sub(K,I),I=r.add(K,I),I=r.mul(D,I),D=r.mul(H,D),F=r.mul(k,F),q=r.mul(w,q),H=r.sub(O,q),H=r.mul(w,H),H=r.add(H,F),F=r.add(O,O),O=r.add(F,O),O=r.add(O,q),O=r.mul(O,H),I=r.add(I,O),q=r.mul(M,U),q=r.add(q,q),O=r.mul(q,H),D=r.sub(D,O),F=r.mul(q,K),F=r.add(F,F),F=r.add(F,F),new E(D,I,F)}add(w){A(w);const{X:b,Y:k,Z:B}=this,{X:M,Y:U,Z:D}=w;let I=r.ZERO,F=r.ZERO,O=r.ZERO;const K=o.a,q=r.mul(o.b,Kr);let H=r.mul(b,M),G=r.mul(k,U),W=r.mul(B,D),X=r.add(b,k),V=r.add(M,U);X=r.mul(X,V),V=r.add(H,G),X=r.sub(X,V),V=r.add(b,B);let Z=r.add(M,D);return V=r.mul(V,Z),Z=r.add(H,W),V=r.sub(V,Z),Z=r.add(k,B),I=r.add(U,D),Z=r.mul(Z,I),I=r.add(G,W),Z=r.sub(Z,I),O=r.mul(K,V),I=r.mul(q,W),O=r.add(I,O),I=r.sub(G,O),O=r.add(G,O),F=r.mul(I,O),G=r.add(H,H),G=r.add(G,H),W=r.mul(K,W),V=r.mul(q,V),G=r.add(G,W),W=r.sub(H,W),W=r.mul(K,W),V=r.add(V,W),H=r.mul(G,V),F=r.add(F,H),H=r.mul(Z,V),I=r.mul(X,I),I=r.sub(I,H),H=r.mul(X,G),O=r.mul(Z,O),O=r.add(O,H),new E(I,F,O)}subtract(w){return this.add(w.negate())}is0(){return this.equals(E.ZERO)}multiply(w){const{endo:b}=e;if(!s.isValidNot0(w))throw new Error("invalid scalar: out of range");let k,B;const M=U=>P.cached(this,U,D=>jt(E,D));if(b){const{k1neg:U,k1:D,k2neg:I,k2:F}=_(w),{p:O,f:K}=M(D),{p:q,f:H}=M(F);B=K.add(H),k=R(b.beta,O,q,U,I)}else{const{p:U,f:D}=M(w);k=U,B=D}return jt(E,[k,B])[0]}multiplyUnsafe(w){const{endo:b}=e,k=this;if(!s.isValid(w))throw new Error("invalid scalar: out of range");if(w===dt||k.is0())return E.ZERO;if(w===En)return k;if(P.hasCache(this))return this.multiply(w);if(b){const{k1neg:B,k1:M,k2neg:U,k2:D}=_(w),{p1:I,p2:F}=Vg(E,k,M,D);return R(b.beta,I,F,B,U)}else return P.unsafe(k,w)}multiplyAndAddUnsafe(w,b,k){const B=this.multiplyUnsafe(b).add(w.multiplyUnsafe(k));return B.is0()?void 0:B}toAffine(w){return C(this,w)}isTorsionFree(){const{isTorsionFree:w}=e;return i===En?!0:w?w(E,this):P.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:w}=e;return i===En?this:w?w(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(w=!0){return Gt(w,"isCompressed"),this.assertValidity(),p(E,this,w)}toHex(w=!0){return Ht(this.toBytes(w))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(w=!0){return this.toBytes(w)}_setWindowSize(w){this.precompute(w)}static normalizeZ(w){return jt(E,w)}static msm(w,b){return Md(E,s,w,b)}static fromPrivateKey(w){return E.BASE.multiply(mn(s,w))}}E.BASE=new E(o.Gx,o.Gy,r.ONE),E.ZERO=new E(r.ZERO,r.ONE,r.ZERO),E.Fp=r,E.Fn=s;const S=s.BITS,P=new Od(E,e.endo?Math.ceil(S/2):S);return E.BASE.precompute(8),E}function nu(t){return Uint8Array.of(t?2:3)}function ru(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function fw(t,e={}){const{Fn:n}=t,r=e.randomBytes||Xi,s=Object.assign(ru(t.Fp,n),{seed:_d(n.ORDER)});function o(p){try{return!!mn(n,p)}catch{return!1}}function i(p,g){const{publicKey:m,publicKeyUncompressed:x}=s;try{const y=p.length;return g===!0&&y!==m||g===!1&&y!==x?!1:!!t.fromBytes(p)}catch{return!1}}function a(p=r(s.seed)){return qg(ze(p,s.seed,"seed"),n.ORDER)}function c(p,g=!0){return t.BASE.multiply(mn(n,p)).toBytes(g)}function l(p){const g=a(p);return{secretKey:g,publicKey:c(g)}}function d(p){if(typeof p=="bigint")return!1;if(p instanceof t)return!0;const{secretKey:g,publicKey:m,publicKeyUncompressed:x}=s;if(n.allowedLengths||g===m)return;const y=le("key",p).length;return y===m||y===x}function u(p,g,m=!0){if(d(p)===!0)throw new Error("first arg must be private key");if(d(g)===!1)throw new Error("second arg must be public key");const x=mn(n,p);return t.fromHex(g).multiply(x).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:t,utils:{isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:p=>mn(n,p),precompute(p=8,g=t.BASE){return g.precompute(p,!1)}},lengths:s})}function hw(t,e,n={}){pd(e),Nr(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Xi,s=n.hmac||((b,...k)=>eu(e,b,et(...k))),{Fp:o,Fn:i}=t,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:p}=fw(t,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function x(b){const k=a>>En;return b>k}function y(b,k){if(!i.isValidNot0(k))throw new Error(`invalid signature ${b}: out of range 1..Point.Fn.ORDER`);return k}function T(b,k){bi(k);const B=p.signature,M=k==="compact"?B:k==="recovered"?B+1:void 0;return ze(b,M,`${k} signature`)}class v{constructor(k,B,M){this.r=y("r",k),this.s=y("s",B),M!=null&&(this.recovery=M),Object.freeze(this)}static fromBytes(k,B=m){T(k,B);let M;if(B==="der"){const{r:F,s:O}=lt.toSig(ze(k));return new v(F,O)}B==="recovered"&&(M=k[0],B="compact",k=k.subarray(1));const U=i.BYTES,D=k.subarray(0,U),I=k.subarray(U,U*2);return new v(i.fromBytes(D),i.fromBytes(I),M)}static fromHex(k,B){return this.fromBytes(hs(k),B)}addRecoveryBit(k){return new v(this.r,this.s,k)}recoverPublicKey(k){const B=o.ORDER,{r:M,s:U,recovery:D}=this;if(D==null||![0,1,2,3].includes(D))throw new Error("recovery id invalid");if(a*tu<B&&D>1)throw new Error("recovery id is ambiguous for h>1 curve");const F=D===2||D===3?M+a:M;if(!o.isValid(F))throw new Error("recovery id 2 or 3 invalid");const O=o.toBytes(F),K=t.fromBytes(et(nu((D&1)===0),O)),q=i.inv(F),H=_(le("msgHash",k)),G=i.create(-H*q),W=i.create(U*q),X=t.BASE.multiplyUnsafe(G).add(K.multiplyUnsafe(W));if(X.is0())throw new Error("point at infinify");return X.assertValidity(),X}hasHighS(){return x(this.s)}toBytes(k=m){if(bi(k),k==="der")return hs(lt.hexFromSig(this));const B=i.toBytes(this.r),M=i.toBytes(this.s);if(k==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return et(Uint8Array.of(this.recovery),B,M)}return et(B,M)}toHex(k){return Ht(this.toBytes(k))}assertValidity(){}static fromCompact(k){return v.fromBytes(le("sig",k),"compact")}static fromDER(k){return v.fromBytes(le("sig",k),"der")}normalizeS(){return this.hasHighS()?new v(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Ht(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ht(this.toBytes("compact"))}}const A=n.bits2int||function(k){if(k.length>8192)throw new Error("input is too large");const B=qs(k),M=k.length*8-c;return M>0?B>>BigInt(M):B},_=n.bits2int_modN||function(k){return i.create(A(k))},C=Pr(c);function L(b){return pi("num < 2^"+c,b,dt,C),i.toBytes(b)}function R(b,k){return ze(b,void 0,"message"),k?ze(e(b),void 0,"prehashed message"):b}function E(b,k,B){if(["recovered","canonical"].some(G=>G in B))throw new Error("sign() legacy options not supported");const{lowS:M,prehash:U,extraEntropy:D}=vo(B,g);b=R(b,U);const I=_(b),F=mn(i,k),O=[L(F),L(I)];if(D!=null&&D!==!1){const G=D===!0?r(p.secretKey):D;O.push(le("extraEntropy",G))}const K=et(...O),q=I;function H(G){const W=A(G);if(!i.isValidNot0(W))return;const X=i.inv(W),V=t.BASE.multiply(W).toAffine(),Z=i.create(V.x);if(Z===dt)return;const ke=i.create(X*i.create(q+Z*F));if(ke===dt)return;let Fe=(V.x===Z?0:2)|Number(V.y&En),rt=ke;return M&&x(ke)&&(rt=i.neg(ke),Fe^=1),new v(Z,rt,Fe)}return{seed:K,k2sig:H}}function S(b,k,B={}){b=le("message",b);const{seed:M,k2sig:U}=E(b,k,B);return Bg(e.outputLen,i.BYTES,s)(M,U)}function P(b){let k;const B=typeof b=="string"||Rr(b),M=!B&&b!==null&&typeof b=="object"&&typeof b.r=="bigint"&&typeof b.s=="bigint";if(!B&&!M)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(M)k=new v(b.r,b.s);else if(B){try{k=v.fromBytes(le("sig",b),"der")}catch(U){if(!(U instanceof lt.Err))throw U}if(!k)try{k=v.fromBytes(le("sig",b),"compact")}catch{return!1}}return k||!1}function N(b,k,B,M={}){const{lowS:U,prehash:D,format:I}=vo(M,g);if(B=le("publicKey",B),k=R(le("message",k),D),"strict"in M)throw new Error("options.strict was renamed to lowS");const F=I===void 0?P(b):v.fromBytes(le("sig",b),I);if(F===!1)return!1;try{const O=t.fromBytes(B);if(U&&F.hasHighS())return!1;const{r:K,s:q}=F,H=_(k),G=i.inv(q),W=i.create(H*G),X=i.create(K*G),V=t.BASE.multiplyUnsafe(W).add(O.multiplyUnsafe(X));return V.is0()?!1:i.create(V.x)===K}catch{return!1}}function w(b,k,B={}){const{prehash:M}=vo(B,g);return k=R(k,M),v.fromBytes(b,"recovered").recoverPublicKey(k).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:p,Point:t,sign:S,verify:N,recoverPublicKey:w,Signature:v,hash:e})}function pw(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 s=en(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),o={Fp:n,Fn:s,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:o}}function gw(t){const{CURVE:e,curveOpts:n}=pw(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 mw(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,Ld(n.Fn.ORDER,n.Fn.BITS))})}function ww(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:s}=gw(t),o=uw(e,n),i=hw(o,r,s);return mw(t,i)}function yw(t,e){const n=r=>ww({...t,hash:r});return{...n(e),create:n}}const ia={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},bw={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},bc=BigInt(2);function xw(t){const e=ia.p,n=BigInt(3),r=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,u=ce(d,n,e)*d%e,f=ce(u,n,e)*d%e,p=ce(f,bc,e)*l%e,g=ce(p,s,e)*p%e,m=ce(g,o,e)*g%e,x=ce(m,a,e)*m%e,y=ce(x,c,e)*x%e,T=ce(y,a,e)*m%e,v=ce(T,n,e)*d%e,A=ce(v,i,e)*g%e,_=ce(A,r,e)*l%e,C=ce(_,bc,e);if(!xi.eql(xi.sqr(C),t))throw new Error("Cannot find square root");return C}const xi=en(ia.p,{sqrt:xw}),Bt=yw({...ia,Fp:xi,lowS:!0,endo:bw},xd);function vw(t,e,n){const r=Vi.digest(e instanceof Uint8Array?e:e.subarray());if(Ks(r))return r.then(({digest:s})=>(n?.signal?.throwIfAborted(),Bt.sign(s,t).toDERRawBytes())).catch(s=>{throw s.name==="AbortError"?s:new pc(String(s))});try{return Bt.sign(r.digest,t).toDERRawBytes()}catch(s){throw new pc(String(s))}}function Ew(t,e,n,r){const s=Vi.digest(n instanceof Uint8Array?n:n.subarray());if(Ks(s))return s.then(({digest:o})=>(r?.signal?.throwIfAborted(),Bt.verify(e,o,t))).catch(o=>{throw o.name==="AbortError"?o:new gc(String(o))});try{return r?.signal?.throwIfAborted(),Bt.verify(e,s.digest,t)}catch(o){throw new gc(String(o))}}class su{type="secp256k1";raw;_key;constructor(e){this._key=Cw(e),this.raw=kw(this._key)}toMultihash(){return Cr.digest(Ws(this))}toCID(){return oe.createV1(114,this.toMultihash())}toString(){return Te.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ye(this.raw,e.raw)}verify(e,n,r){return Ew(this._key,n,e,r)}}class Sw{type="secp256k1";raw;publicKey;constructor(e,n){this.raw=Tw(e),this.publicKey=new su(n??Iw(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ye(this.raw,e.raw)}sign(e,n){return vw(this.raw,e,n)}}function Aw(t){return new Sw(t)}function ou(t){return new su(t)}function kw(t){return Bt.ProjectivePoint.fromHex(t).toRawBytes(!0)}function Tw(t){try{return Bt.getPublicKey(t,!0),t}catch(e){throw new Jl(String(e))}}function Cw(t){try{return Bt.ProjectivePoint.fromHex(t),t}catch(e){throw new Zl(String(e))}}function Iw(t){try{return Bt.getPublicKey(t,!0)}catch(e){throw new Jl(String(e))}}async function Rw(t,e){return ym()}function vi(t,e){const{Type:n,Data:r}=Wt.decode(t),s=r??new Uint8Array;switch(n){case ie.RSA:return tw(s,e);case ie.Ed25519:return qd(s);case ie.secp256k1:return ou(s);case ie.ECDSA:return fd(s);default:throw new js}}function Pw(t){const{Type:e,Data:n}=Wt.decode(t.digest),r=n??new Uint8Array;switch(e){case ie.Ed25519:return qd(r);case ie.secp256k1:return ou(r);case ie.ECDSA:return fd(r);default:throw new js}}function Ws(t){return Wt.encode({Type:ie[t.type],Data:t.raw})}function Nw(t){const e=bs.decode(t),n=e.Data??new Uint8Array;switch(e.Type){case ie.RSA:return Qm(n);case ie.Ed25519:return wm(n);case ie.secp256k1:return Aw(n);case ie.ECDSA:return ag(n);default:throw new js}}function Lw(t){return bs.encode({Type:ie[t.type],Data:t.raw})}const iu=Symbol.for("nodejs.util.inspect.custom"),Bw=114;class aa{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()})`}[Ql]=!0;toString(){return this.string==null&&(this.string=Te.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return oe.createV1(Bw,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Ye(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Ye(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[iu](){return`PeerId(${this.toString()})`}}class au extends aa{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class cu extends aa{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class lu extends aa{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}const _w=2336;class du{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Cr.digest(fe(this.url))}[iu](){return`PeerId(${this.url})`}[Ql]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return oe.createV1(_w,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=J(e)),e.toString()===this.toString())}}const Dw=114,xc=2336;function Fw(t,e){let n;if(t.charAt(0)==="1"||t.charAt(0)==="Q")n=nd(Te.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return Ow(oe.parse(t));throw new Xe('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return uu(n)}function Bn(t){if(t.type==="Ed25519")return new cu({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new lu({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new au({multihash:t.toCID().multihash,publicKey:t});throw new js}function uu(t){if(jw(t))return new au({multihash:t});if(Mw(t))try{const e=Pw(t);if(e.type==="Ed25519")return new cu({multihash:t,publicKey:e});if(e.type==="secp256k1")return new lu({multihash:t,publicKey:e})}catch{const n=J(t.digest);return new du(new URL(n))}throw new bh("Supplied PeerID Multihash is invalid")}function Ow(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==Dw&&t.code!==xc)throw new yh("Supplied PeerID CID is invalid");if(t.code===xc){const e=J(t.multihash.digest);return new du(new URL(e))}return uu(t.multihash)}function Mw(t){return t.code===Cr.code}function jw(t){return t.code===Vi.code}class fu extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class Uw extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class Zn extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class vc extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}}class $w extends Event{data;constructor(e,n){super("message",n),this.data=e}}class ca extends Event{error;local;constructor(e,n,r){super("close",r),this.error=n,this.local=e}}class Hw extends ca{constructor(e,n){super(!0,e,n)}}class qw extends ca{constructor(e,n){super(!1,e,n)}}const Kw=t=>t/2**32|0,zw=t=>t>>>0;function Vw(t,e,n,r){const s=Kw(n),o=zw(n);t.setUint32(e,r?o:s,r),t.setUint32(e+4,r?s:o,r)}function Ei(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const Si=t=>t?`"${t}" `:"";function wt(t,e=""){if(typeof t!="number")throw new TypeError(Si(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(Si(e)+"expected integer >= 0, got "+t);return t}function yt(t,e,n=""){if(Ei(t)&&(e===void 0||t.length===e))return t;e!==void 0&&wt(e,"length");const r=Ei(t),s=e!==void 0?` of length ${e}`:"",o=r?`length=${t.length}`:`type=${typeof t}`,i=Si(n)+"expected Uint8Array"+s+", got "+o;throw r?new RangeError(i):new TypeError(i)}function la(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(wt(t.outputLen),wt(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}const Gw=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)},Ec=(t,e)=>{Gw(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 xs(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function hu(t,e){yt(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function fS(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Kt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Eo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Je(t,e){return t<<32-e|t>>>e}function hS(t,e){return t<<e|t>>>32-e>>>0}const Ww=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Xw(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Yw(t){for(let e=0;e<t.length;e++)t[e]=Xw(t[e]);return t}const pS=Ww?t=>t:Yw,pu=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Zw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function da(t){if(yt(t),pu)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Zw[t[n]];return e}function Sc(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function gu(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(pu)try{return Uint8Array.fromHex(t)}catch(s){throw s instanceof SyntaxError?new RangeError(s.message):s}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 s=0,o=0;s<n;s++,o+=2){const i=Sc(t.charCodeAt(o)),a=Sc(t.charCodeAt(o+1));if(i===void 0||a===void 0){const c=t[o]+t[o+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+o)}r[s]=i*16+a}return r}function Jw(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 gS(t,e,n,r){if(wt(t,"iters"),wt(e,"tick"),typeof n!="function")throw new TypeError("callback must be a function");let s=Date.now();for(let o=0;o<t;o++){n(o);const i=Date.now()-s;i>=0&&i<e||(await Jw(r),s=Date.now())}}function Qw(t){if(typeof t!="string")throw new TypeError("string expected");const e=new TextEncoder().encode(t);try{return new Uint8Array(e)}finally{Kt(e)}}function mS(t,e=""){return typeof t=="string"?Qw(t):yt(t,void 0,e)}function ey(t,e,n="opts"){return Ec(t,"defaults"),e!==void 0&&Ec(e,n),Object.assign(Object.create(null),t,e)}function ty(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=ey({},e,"info");const n=(s,o)=>t(o).update(s).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=s=>t(s),Object.assign(n,e),Object.freeze(n)}function ny(t=32){wt(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 ry=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function sy(t,e,n){return t&e^~t&n}function oy(t,e,n){return t&e^t&n^e&n}class iy{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,n,r,s){this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Eo(this.buffer)}update(e){xs(this),yt(e);const{view:n,buffer:r,blockLen:s}=this,o=e.length;let i=!1;for(let a=0;a<o;){const c=Math.min(s-this.pos,o-a);if(c===s){const l=Eo(e);for(;s<=o-a;a+=s)this.process(l,a);i=!0;continue}r.set(a===0&&c===o?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===s&&(this.process(n,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){xs(this),hu(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:s,isLE:o}=this;let{pos:i}=this;n[i++]=128,n.fill(0,i),this.padOffset>s-i&&(this.process(r,0),n.fill(0)),Vw(r,s-8,this.length*8,o),this.process(r,0),this.roundClean();const a=e===n?r:Eo(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],o)}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:s,destroyed:o,pos:i}=this;return e.destroyed=o,e.finished=s,e.length=r,e.pos=i,i&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const ay=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),cy=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]),kt=new Uint32Array(64);class ly extends iy{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:s,E:o,F:i,G:a,H:c}=this;return[e,n,r,s,o,i,a,c]}set(e,n,r,s,o,i,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=o|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)kt[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const f=kt[u-15],p=kt[u-2],g=Je(f,7)^Je(f,18)^f>>>3,m=Je(p,17)^Je(p,19)^p>>>10;kt[u]=m+kt[u-7]+g+kt[u-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=Je(a,6)^Je(a,11)^Je(a,25),p=d+f+sy(a,c,l)+cy[u]+kt[u]|0,m=(Je(r,2)^Je(r,13)^Je(r,22))+oy(r,s,o)|0;d=l,l=c,c=a,a=i+p|0,i=o,o=s,s=r,r=p+m|0}r=r+this.A|0,s=s+this.B|0,o=o+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,s,o,i,a,c,l,d)}roundClean(){Kt(kt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Kt(this.buffer)}}class dy extends ly{constructor(){super(32,ay)}}const So=ty(()=>new dy,ry(1));function mu(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 Sn=(t,e,n)=>yt(t,e,n),wu=wt;function An(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 hr(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}const uy=da,fy=t=>gu(t),yu=Ei,bu=t=>ny(t),vs=BigInt(0),Ac=BigInt(1),hy=t=>t?`"${t}" `:"";function Xs(t,e=""){if(typeof t!="boolean")throw new TypeError(hy(e)+"expected boolean, got type="+typeof t);return t}function py(t){if(typeof t=="bigint"){if(!zt(t))throw new RangeError("positive bigint expected, got "+t)}else wu(t);return t}function Ai(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 xu(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?vs:BigInt("0x"+t)}function vu(t){return xu(da(t))}function Es(t){return xu(da(xr(yt(t)).reverse()))}function Eu(t,e){if(wt(e),e===0)throw new Error("zero output length is invalid");t=py(t);const n=e*2,r=t.toString(16);if(r.length>n)throw new RangeError("number is too large");return gu(r.padStart(n,"0"))}function Su(t,e){return Eu(t,e).reverse()}function xr(t){return Uint8Array.from(Sn(t))}function zt(t){return typeof t=="bigint"&&vs<=t}function Au(t,e,n){return zt(t)&&zt(e)&&zt(n)&&e<=t&&t<n}function pr(t,e,n,r){if(!Au(e,n,r))throw new RangeError("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function gy(t){if(t<vs)throw new Error("expected non-negative bigint, got "+t);return t===vs?0:t.toString(2).length}const my=t=>(Ai(t,"n"),(Ac<<BigInt(t))-Ac);function Ss(t,e={},n={},r="object"){An(t,r),An(e,"fields"),An(n,"optFields");function s(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 o=(i,a)=>Object.entries(i).forEach(([c,l])=>s(c,l,a));o(e,!1),o(n,!0)}const me=BigInt(0),se=BigInt(1),Ut=BigInt(2),ku=BigInt(3),ua=BigInt(4),Tu=BigInt(5),wy=BigInt(7),Cu=BigInt(8),yy=BigInt(9),by=BigInt(15),Iu=BigInt(16),xy=BigInt("0x10000000000000000");function re(t,e){if(e<=me)throw new Error("mod: expected positive modulus, got "+e);const n=t%e;return n>=me?n:e+n}function vy(t,e,n){if(n<=se)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<me)throw new Error("invalid exponent, negatives unsupported");if(e===me)return se;if(e===se)return t;let r=t%n;if(r<me&&(r+=n),e<xy){let a=se;for(;e>me;)e&se&&(a=a*r%n),r=r*r%n,e>>=se;return a}const s=[];for(;e>me;)s.push(Number(e&by)),e>>=ua;const o=new Array(16);o[0]=se,o[1]=r;for(let a=2;a<16;a++)o[a]=o[a-1]*r%n;let i=o[s[s.length-1]];for(let a=s.length-2;a>=0;a--){i=i*i%n,i=i*i%n,i=i*i%n,i=i*i%n;const c=s[a];c!==0&&(i=i*o[c]%n)}return i}function Ke(t,e,n){if(n<=se)throw new Error("pow2: expected modulus > 1, got "+n);if(e<me)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >me;)r*=r,r%=n;return r}function kc(t,e){if(t===me)throw new Error("invert: expected non-zero number");if(e<=se)throw new Error("invert: expected modulus > 1, got "+e);let n=re(t,e),r=e,s=me,o=se;for(;n!==me;){const a=r/n,c=r-n*a,l=s-o*a;r=n,n=c,s=o,o=l}if(r!==se)throw new Error("invert: does not exist");return re(s,e)}function fa(t,e,n){const r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function ha(t,e){if((t&se)===me)throw new Error(e+": expected odd modulus, got "+t)}function Ru(t,e){const n=t,r=(n.ORDER+se)/ua,s=n.pow(e,r);return fa(n,s,e),s}function Ey(t,e){const n=t,r=(n.ORDER-Tu)/Cu,s=n.mul(e,Ut),o=n.pow(s,r),i=n.mul(e,o),a=n.mul(n.mul(i,Ut),o),c=n.mul(i,n.sub(a,n.ONE));return fa(n,c,e),c}function Sy(t){const e=pa(t),n=Pu(t),r=n(e,e.neg(e.ONE)),s=n(e,r),o=n(e,e.neg(r)),i=(t+wy)/Iu;return((a,c)=>{const l=a;let d=l.pow(c,i),u=l.mul(d,r);const f=l.mul(d,s),p=l.mul(d,o),g=l.eql(l.sqr(u),c),m=l.eql(l.sqr(f),c);d=l.cmov(d,u,g),u=l.cmov(p,f,m);const x=l.eql(l.sqr(u),c),y=l.cmov(d,u,x);return fa(l,y,c),y})}function Pu(t){if(t<ku)throw new Error("sqrt is not defined for small field");ha(t,"tonelliShanks");let e=t-se,n=0;for(;e%Ut===me;)e/=Ut,n++;let r=Ut;const s=pa(t);for(;As(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Ru;let o=s.pow(r,e);const i=(e+se)/Ut;return function(c,l){const d=c;if(d.is0(l))return l;if(As(d,l)!==1)throw new Error("Cannot find square root");let u=n,f=d.mul(d.ONE,o),p=d.pow(l,e),g=d.pow(l,i);for(;!d.eql(p,d.ONE);){if(d.is0(p))throw new Error("Cannot find square root: probably non-prime P");let m=1,x=d.sqr(p);for(;!d.eql(x,d.ONE);)if(m++,x=d.sqr(x),m===u)throw new Error("Cannot find square root");const y=se<<BigInt(u-m-1),T=d.pow(f,y);u=m,f=d.sqr(T),p=d.mul(p,f),g=d.mul(g,T)}return g}}function Ay(t){return ha(t,"Fp.sqrt"),t%ua===ku?Ru:t%Cu===Tu?Ey:t%Iu===yy?Sy(t):Pu(t)}const ky=(t,e)=>(re(t,e)&se)===se,Ty=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function vr(t){if(An(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);Ai(t.BYTES,"BYTES"),Ai(t.BITS,"BITS");for(const e of Ty)hr(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=se)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Nu(t,e,n=!1){vr(t),mu(e,"nums"),Xs(n,"passZero");const r=t,s=new Array(e.length).fill(n?r.ZERO:void 0),o=e.reduce((a,c,l)=>r.is0(c)?a:(s[l]=a,r.mul(a,c)),r.ONE),i=r.inv(o);return e.reduceRight((a,c,l)=>r.is0(c)?a:(s[l]=r.mul(a,s[l]),r.mul(a,c)),i),s}function As(t,e){vr(t);const n=t;ha(n.ORDER,"FpLegendre");const r=(n.ORDER-se)/Ut,s=n.pow(e,r),o=n.eql(s,n.ONE),i=n.eql(s,n.ZERO),a=n.eql(s,n.neg(n.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Cy(t,e){if(e!==void 0&&wu(e),t<=me)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=gy(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,s=Math.ceil(r/8);return{nBitLength:r,nByteLength:s}}const Tc=new WeakMap;class Cc{ORDER;BITS;BYTES;isLE;ZERO=me;ONE=se;_lengths;_mod;constructor(e,n={}){if(e<=se)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:s,nByteLength:o}=Cy(e,r);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,Object.freeze(this)}create(e){return re(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return me<=e&&e<this.ORDER}is0(e){return e===me}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&se)===se}neg(e){return re(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return re(e*e,this.ORDER)}add(e,n){return re(e+n,this.ORDER)}sub(e,n){return re(e-n,this.ORDER)}mul(e,n){return re(e*n,this.ORDER)}pow(e,n){return vy(e,n,this.ORDER)}div(e,n){return re(e*kc(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 kc(e,this.ORDER)}sqrt(e){let n=Tc.get(this);return n||Tc.set(this,n=Ay(this.ORDER)),n(this,e)}toBytes(e){return this.isLE?Su(e,this.BYTES):Eu(e,this.BYTES)}fromBytes(e,n=!1){Sn(e);const{_lengths:r,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);const l=new Uint8Array(s);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let c=o?Es(e):vu(e);if(a&&(c=re(c,i)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Nu(this,e,!0)}cmov(e,n,r){return Xs(r,"condition"),r?n:e}}function pa(t,e={}){return Object.freeze(Cc.prototype),new Cc(t,e)}const ga=BigInt(0),Er=BigInt(1),Iy=BigInt(4),Ao=16,Ic=128,Ry=5,Rc=2**31;function ma(t){const e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);hr(e.fromAffine,"Point.fromAffine"),hr(e.fromBytes,"Point.fromBytes"),hr(e.fromHex,"Point.fromHex"),An(e.BASE,"Point.BASE"),An(e.ZERO,"Point.ZERO"),vr(e.Fp),vr(e.Fn)}function Py(t,e){ma(t),Lu(e,t);const n=Nu(t.Fp,e.map(r=>r.Z));return e.map((r,s)=>t.fromAffine(r.toAffine(n[s])))}function Ny(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 Ly(t,e){const n=t*(4*e+128);if(n>Rc)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+Rc/2**20+" MiB")}function By(t,e){if(t!==void 0){hr(t,"randomBytes");try{const n=t(e);if(!yu(n)||n.length!==e)return}catch{return}return t}}function Lu(t,e){mu(t,"points"),t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function _y(t,e,n){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,s)=>{if(!(n===void 0?e.isValid(r):zt(r)&&r<n))throw new Error("invalid scalar at index "+s)})}const Bu=new WeakMap;function ko(t){return Bu.get(t)||1}function Dy(t,e){const n=t.double(),r=[t];for(let s=1;s<e;s++)r.push(r[s-1].add(n));return r}function Fy(t,e){const n=2**e,r=n/2,s=BigInt(n-1),o=[];for(;t>ga;){let i=0;t&Er&&(i=Number(t&s),i>=r&&(i-=n),t-=BigInt(i)),o.push(i),t>>=Er}return o}function Oy(t,e,n){const r=2**e,s=r/2,o=BigInt(r-1),i=BigInt(e),a=[];for(let c=0;c<n;c++){let l=Number(t&o);t>>=i,l>s&&(l-=r,t+=Er),a.push(l)}if(t!==ga)throw new Error("invalid wnaf");return a}function My(t,e,n){let r=0;for(const o of n)r=Math.max(r,o.length);let s=t;for(let o=r-1;o>=0;o--){o!==r-1&&(s=s.double());for(let i=0;i<n.length;i++){const a=n[i][o];if(a){const c=e[i][Math.abs(a)-1>>1];s=s.add(a<0?c.negate():c)}}}return s}class jy{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,n){ma(e),this.randomBytes=By(n,Ao),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,n,r){const s=Math.ceil(r/n)+1,o=2**(n-1),i=[];let a=e;for(let c=0;c<s;c++){let l=a;for(let d=0;d<o;d++)i.push(l),l=l.add(a);a=i[i.length-1].double()}return{W:n,bits:r,windows:s,comp:i}}wnafCachedCT(e,n){const{W:r,windows:s,comp:o}=e,i=2**(r-1),a=Oy(n,r,s);let c=this.ZERO,l=this.BASE;for(let d=0;d<s;d++){const u=a[d],f=d*i,p=Math.abs(u)-1;let g=o[f];for(let x=1;x<i;x++)g=x===p?o[f+x]:g;const m=g.negate();u===0?l=l.add(o[f]):c=c.add(u<0?m:g)}return{p:c,f:l}}getWnafPrecomputes(e,n,r,s){let o=this.wnafPrecomputes.get(n),i=o?.find(a=>a.W===e&&a.bits===r);return i||(i=this.buildWnafTable(n,e,r),typeof s=="function"&&(i={...i,comp:s(i.comp)}),o||(o=[],this.wnafPrecomputes.set(n,o)),o.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),!Au(n,Er,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,n,r,s){const o=ko(e);return o===1?this.fixedWindowCT(e,n,r):this.wnafCachedCT(this.getWnafPrecomputes(o,e,r,s),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 s=this.Point.Fn.BITS+Ic,o=this.randomBytes(Ao);if(!yu(o)||o.length!==Ao)throw new Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;const i=n+vu(o)*this.Point.Fn.ORDER;return this.runCT(e,i,s,r)}fixedWindowCT(e,n,r){const s=Ry,o=1<<s,i=my(s),a=new Array(o);a[0]=this.ZERO;for(let d=1;d<o;d++)a[d]=a[d-1].add(e);const c=Math.ceil(r/s);let l=this.ZERO;for(let d=c-1;d>=0;d--){if(d!==c-1)for(let p=0;p<s;p++)l=l.double();const u=Number(n>>BigInt(d*s)&i);let f=a[0];for(let p=1;p<o;p++)f=p===u?a[p]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(e,n){return this.randomBytes===void 0?!1:n===Er?!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,s){return this.shouldBlind(e,r)?this.mulCTBlinded(e,n,s):this.mulCT(e,n,s)}mulUnsafe(e,n,r){if(this.assertPoint(e),!zt(n))throw new Error("invalid scalar");const s=ko(e);if(s===1||n>=this.Point.Fn.ORDER)return Uy(this.Point,[e],[n],!0);const o=this.getWnafPrecomputes(s,e,this.bits,r);return this.wnafCachedCT(o,n).p}setWindowSize(e,n){this.assertPoint(e),Ny(n,this.bits);const r=Math.ceil((this.bits+Ic)/n)+1;Ly(r*2**(n-1),this.Point.Fp.BYTES),Bu.set(e,n),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return ko(e)!==1}}function Uy(t,e,n,r=!1){if(ma(t),Lu(e,t),Xs(r,"allowOversized"),_y(n,t.Fn,r?t.Fn.ORDER**Iy:void 0),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const s=e.map(i=>Dy(i,4)),o=n.map(i=>Fy(i,4));return My(t.ZERO,s,o)}function Pc(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return vr(e),e}else return pa(t,{isLE:n})}function $y(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(!(zt(l)&&l!==ga))throw new Error(`CURVE.${c} must be positive bigint`)}const s=Pc(e.p,n.Fp,r),o=Pc(e.n,n.Fn,r),a=["Gx","Gy","a","d"];for(const c of a)if(!s.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:s,Fn:o}}function Hy(t,e){return function(r){const s=t(r);return{secretKey:s,publicKey:e(s)}}}const zr=BigInt(0),Vr=BigInt(1),Gr=BigInt(2),qy=BigInt(4),Nc=BigInt(8);function Ky(t,e,n,r){const s=t.sqr(n),o=t.sqr(r),i=t.add(t.mul(e.a,s),o),a=t.add(t.ONE,t.mul(e.d,t.mul(s,o)));return t.eql(i,a)}function zy(t,e={}){Ss(e,{},{},"extraOpts");const n=e,r=$y("edwards",t,n,n.FpFnLE),{Fp:s,Fn:o}=r;let i=r.CURVE;const{h:a}=i;if(As(s,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(As(s,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?bu:n.randomBytes,l=Gr<<BigInt(s.BYTES*8)-Vr;function d(T){if(!s.isOdd)throw new Error("Field does not have .isOdd()");return s.isOdd(T)}const u=n.uvRatio===void 0?(T,v)=>{try{return{isValid:!0,value:s.sqrt(s.div(T,v))}}catch{return{isValid:!1,value:zr}}}:n.uvRatio;if(!Ky(s,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");const f=s.eql(i.a,s.neg(s.ONE))?T=>s.neg(T):s.eql(i.a,s.ONE)?T=>T:T=>s.mul(i.a,T);function p(T,v,A=!1){const _=A?Vr:zr;return pr("coordinate "+T,v,_,l),v}function g(T){if(!(T instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(i.Gx,i.Gy,s.ONE,s.mul(i.Gx,i.Gy));static ZERO=new m(s.ZERO,s.ONE,s.ONE,s.ZERO);static Fp=s;static Fn=o;X;Y;Z;T;constructor(v,A,_,C){this.X=p("x",v),this.Y=p("y",A),this.Z=p("z",_,!0),this.T=p("t",C),Object.freeze(this)}static CURVE(){return i}static fromAffine(v){if(v instanceof m)throw new Error("extended point not allowed");const{x:A,y:_}=v||{};return p("x",A),p("y",_),new m(A,_,s.ONE,s.mul(A,_))}static fromBytes(v,A=!1){const _=s.BYTES,{a:C,d:L}=i;v=xr(Sn(v,_,"point")),Xs(A,"zip215");const R=xr(v),E=v[_-1];R[_-1]=E&-129;const S=Es(R),P=A?l:s.ORDER;pr("point.y",S,zr,P);const N=s.sqr(S),w=s.sub(N,s.ONE),b=s.sub(s.mulN(L,N),C);let{isValid:k,value:B}=u(w,b);if(!k)throw new Error("bad point: invalid y coordinate");const M=d(B),U=(E&128)!==0;if(!A&&s.is0(B)&&U)throw new Error("bad point: x=0 and x_0=1");return U!==M&&(B=s.neg(B)),m.fromAffine({x:B,y:S})}static fromHex(v,A=!1){return m.fromBytes(fy(v),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=6,A=!0){return y.setWindowSize(this,v),A||this.multiply(Gr),this}assertValidity(){const v=this,{a:A,d:_}=i;if(v.is0())throw new Error("bad point: ZERO");const{X:C,Y:L,Z:R,T:E}=v,S=s.sqr(C),P=s.sqr(L),N=s.sqr(R),w=s.sqr(N),b=s.mul(S,A),k=s.mul(s.add(b,P),N),B=s.add(w,s.mul(_,s.mul(S,P)));if(!s.eql(k,B))throw new Error("bad point: equation left != right (1)");const M=s.mul(C,L),U=s.mul(R,E);if(!s.eql(M,U))throw new Error("bad point: equation left != right (2)")}equals(v){g(v);const{X:A,Y:_,Z:C}=this,{X:L,Y:R,Z:E}=v,S=s.mul(A,E),P=s.mul(L,C),N=s.mul(_,E),w=s.mul(R,C);return s.eql(S,P)&&s.eql(N,w)}is0(){return this.equals(m.ZERO)}negate(){return new m(s.neg(this.X),this.Y,this.Z,s.neg(this.T))}double(){const{X:v,Y:A,Z:_}=this,C=s.sqr(v),L=s.sqr(A),R=s.mul(s.sqr(_),Gr),E=f(C),S=s.addN(v,A),P=s.sub(s.subN(s.sqr(S),C),L),N=s.addN(E,L),w=s.subN(N,R),b=s.subN(E,L),k=s.mul(P,w),B=s.mul(N,b),M=s.mul(P,b),U=s.mul(w,N);return new m(k,B,U,M)}add(v){g(v);const{d:A}=i,{X:_,Y:C,Z:L,T:R}=this,{X:E,Y:S,Z:P,T:N}=v,w=s.mul(_,E),b=s.mul(C,S),k=s.mul(s.mulN(R,A),N),B=s.mul(L,P),M=s.sub(s.subN(s.mulN(s.addN(_,C),s.addN(E,S)),w),b),U=s.subN(B,k),D=s.addN(B,k),I=s.sub(b,f(w)),F=s.mul(M,U),O=s.mul(D,I),K=s.mul(M,I),q=s.mul(U,D);return new m(F,O,q,K)}subtract(v){return g(v),this.add(v.negate())}multiply(v){if(!o.isValidNot0(v))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");const{p:A,f:_}=y.mulSecret(this,v,a,x);return x([A,_])[0]}multiplyUnsafe(v){if(!o.isValid(v))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return v===zr?m.ZERO:this.is0()||v===Vr?this:y.mulUnsafe(this,v,x)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return y.mulUnsafe(this,i.n).is0()}toAffine(v){const A=this;let _=v;if(_!=null&&typeof _!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof _);const{X:C,Y:L,Z:R}=A,E=A.is0();_==null&&(_=E?s.create(Nc):s.inv(R));const S=s.mul(C,_),P=s.mul(L,_),N=s.mul(R,_);if(E)return{x:s.ZERO,y:s.ONE};if(!s.eql(N,s.ONE))throw new Error("invZ was invalid");return{x:S,y:P}}clearCofactor(){return a===Vr?this:a===Gr?this.double():a===qy?this.double().double():a===Nc?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){const{x:v,y:A}=this.toAffine(),_=s.toBytes(A);return _[_.length-1]|=d(v)?128:0,_}toHex(){return uy(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const x=T=>Py(m,T),y=new jy(m,c);return y.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}const Ft=BigInt(0),Me=BigInt(1),Wr=BigInt(2);function Lc(t,e){return t+e-(e>>Me<<Me)}function Vy(t){const e=BigInt(6)*t;return(n,r,s)=>{const o=r+s,a=((e+s-r)*n+r)%t;return{x_2:a,x_3:o-a}}}function Gy(t){return Ss(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...t})}function Wy(t){const e=Gy(t),{P:n,type:r,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=e,a=e.scalarMultBase,c=r==="x25519";if(!c&&r!=="x448")throw new Error("invalid type");const l=i===void 0?bu:i,d=c?255:448,u=Vy(n),f=c?32:56,p=BigInt(c?9:5),g=BigInt(c?121665:39081),m=c?Wr**BigInt(254):Wr**BigInt(447),x=c?BigInt(8)*(Wr**BigInt(251)-Me):BigInt(4)*(Wr**BigInt(445)-Me),y=m+x+Me,T=B=>re(B,n),v=A(p);function A(B){return Su(T(B),f)}function _(B){const M=xr(Sn(B,f,"uCoordinate"));return c&&(M[31]&=127),T(Es(M))}function C(B){return Es(s(xr(Sn(B,f,"scalar"))))}const L=new Set(c?[Ft,Me,n-Me,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[Ft,Me,n-Me]);function R(B,M){const U=_(M);if(L.has(U))throw new Error("invalid private or public key received");const D=N(U,C(B));if(D===Ft)throw new Error("invalid private or public key received");return A(D)}function E(B){if(a===void 0)return R(B,v);const M=C(B);pr("scalar",M,m,y);const U=T(a(M));if(U===Ft)throw new Error("invalid private or public key received");return A(U)}const S=E,P=R;function N(B,M){pr("u",B,Ft,n),pr("scalar",M,m,y);const U=M,D=B;let I=Me,F=Ft,O=B,K=Me;const q=U^U>>Me;for(let W=BigInt(d-1);W>=Ft;W--){const X=Lc(n,q>>W);({x_2:I,x_3:O}=u(X,I,O)),{x_2:F,x_3:K}=u(X,F,K);const V=I+F,Z=T(V*V),ke=I-F,Fe=T(ke*ke),rt=Z-Fe,Ie=O+K,Dt=O-K,on=T(Dt*V),bt=T(Ie*ke),He=on+bt,Br=on-bt;O=T(He*He),K=T(D*T(Br*Br)),I=T(Z*Fe),F=T(rt*(Z+T(g*rt)))}const H=Lc(n,U);({x_2:I,x_3:O}=u(H,I,O)),{x_2:F,x_3:K}=u(H,F,K);const G=o(F);return T(I*G)}const w={secretKey:f,publicKey:f,seed:f},b=B=>(B=B===void 0?l(f):B,Sn(B,w.seed,"seed"),B),k={randomSecretKey:b};return Object.freeze(w),Object.freeze(k),Object.freeze({keygen:Hy(b,S),getSharedSecret:P,getPublicKey:S,scalarMult:R,scalarMultBase:E,utils:k,GuBytes:v.slice(),lengths:w})}const Bc=BigInt(0),Xy=BigInt(1),_c=BigInt(2),Yy=BigInt(3),Zy=BigInt(5),Jy=BigInt(8),Ys=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Qy={p:Ys,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Jy,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function _u(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),o=Ys,a=t*t%o*t%o,c=Ke(a,_c,o)*a%o,l=Ke(c,Xy,o)*t%o,d=Ke(l,Zy,o)*l%o,u=Ke(d,e,o)*d%o,f=Ke(u,n,o)*u%o,p=Ke(f,r,o)*f%o,g=Ke(p,s,o)*p%o,m=Ke(g,s,o)*p%o,x=Ke(m,e,o)*d%o;return{pow_p_5_8:Ke(x,_c,o)*t%o,b2:a}}function eb(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Dc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function tb(t,e){const n=Ys,r=re(e*e*e,n),s=re(r*r*e,n),o=_u(t*s).pow_p_5_8;let i=re(t*r*o,n);const a=re(e*i*i,n),c=i,l=re(i*Dc,n),d=a===t,u=a===re(-t,n),f=a===re(-t*Dc,n);return d&&(i=c),(u||f)&&(i=l),ky(i,n)&&(i=re(-i,n)),{isValid:d||u,value:i}}const Fc=zy(Qy,{uvRatio:tb}),Xr=(()=>{const t=Ys,e=n=>{const{pow_p_5_8:r,b2:s}=_u(n);return re(Ke(r,Yy,t)*s,t)};return Wy({P:t,type:"x25519",powPminus2:e,adjustScalarBytes:eb,scalarMultBase:n=>{const r=re(n,Fc.Fn.ORDER);if(r===Bc)return Bc;const s=Fc.BASE.multiply(r);return re((s.Z+s.Y)*e(re(s.Z-s.Y,t)),t)}})})();class Oc{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,n){if(la(e),yt(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,s=new Uint8Array(r);s.set(n.length>r?e.create().update(n).digest():n);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Kt(s)}update(e){return xs(this),this.iHash.update(e),this}digestInto(e){xs(this),hu(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:s,destroyed:o,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=s,e.destroyed=o,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 Du=(()=>{const t=((e,n,r)=>new Oc(e,n).update(r).digest());return t.create=(e,n)=>new Oc(e,n),t})();function Mc(){const t={};return t.promise=new Promise((e,n)=>{t.resolve=e,t.reject=n}),t}class jc{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 To{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new jc(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 jc(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 nb extends Error{type;code;constructor(e,n){super(e??"The operation was aborted"),this.type="aborted",this.code=n??"ABORT_ERR"}}function rb(t={}){return sb(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 sb(t,e){e=e??{};let n=e.onEnd,r=new To,s,o,i,a=Mc();const c=async()=>{try{return r.isEmpty()?i?{done:!0}:await new Promise((x,y)=>{o=T=>{o=null,r.push(T);try{x(t(r))}catch(v){y(v)}return s}}):t(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Mc()})}},l=x=>o!=null?o(x):(r.push(x),s),d=x=>(r=new To,o!=null?o({error:x}):(r.push({error:x}),s)),u=x=>{if(i)return s;if(e?.objectMode!==!0&&x?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:x})},f=x=>i?s:(i=!0,x!=null?d(x):l({done:!0})),p=()=>(r=new To,f(),{done:!0}),g=x=>(f(x),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:p,throw:g,push:u,end:f,get readableLength(){return r.size},onEmpty:async x=>{const y=x?.signal;if(y?.throwIfAborted(),r.isEmpty())return;let T,v;y!=null&&(T=new Promise((A,_)=>{v=()=>{_(new nb)},y.addEventListener("abort",v)}));try{await Promise.race([a.promise,T])}finally{v!=null&&y!=null&&y?.removeEventListener("abort",v)}}},n==null)return s;const m=s;return s={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(x){return m.throw(x),n!=null&&(n(x),n=void 0),{done:!0}},return(){return m.return(),n!=null&&(n(),n=void 0),{done:!0}},push:u,end(x){return m.end(x),n!=null&&(n(x),n=void 0),s},get readableLength(){return m.readableLength},onEmpty:x=>m.onEmpty(x)},s}class wa extends Error{name="TimeoutError";constructor(e,n){super(e,n),Error.captureStackTrace?.(this,wa)}}const Uc=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function ob(t,e){const{milliseconds:n,fallback:r,message:s,customTimers:o={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(Uc(i));return}if(i&&(c=()=>{f(Uc(i))},i.addEventListener("abort",c,{once:!0})),t.then(u,f),n===Number.POSITIVE_INFINITY)return;const p=new wa;a=o.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){f(g)}return}typeof t.cancel=="function"&&t.cancel(),s===!1?u():s instanceof Error?f(s):(p.message=s??`Promise timed out after ${n} milliseconds`,f(p))},n)}).finally(()=>{d.clear(),c&&i&&i.removeEventListener("abort",c)});return d.clear=()=>{o.clearTimeout.call(void 0,a),a=void 0},d}const ib=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 ab(t,e,n){let r;const s=new Promise((o,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}=ib(t),u=async(...p)=>{const g=n.multiArgs?p:p[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(),o(c))},f=(...p)=>{r(),i(n.rejectionMultiArgs?p:p[0])};r=()=>{for(const p of a)d(p,u);for(const p of n.rejectionEvents)a.includes(p)||d(p,f)};for(const p of a)l(p,u);for(const p of n.rejectionEvents)a.includes(p)||l(p,f);n.signal&&n.signal.addEventListener("abort",()=>{f(n.signal.reason)},{once:!0}),n.resolveImmediately&&o(c)});if(s.cancel=r,typeof n.timeout=="number"){const o=ob(s,{milliseconds:n.timeout});return o.cancel=()=>{r(),o.clear()},o}return s}function cb(t,e,n){typeof n=="function"&&(n={filter:n}),n={...n,count:1,resolveImmediately:!1};const r=ab(t,e,n),s=r.then(o=>o[0]);return s.cancel=r.cancel,s}class ks extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class lb extends Error{static name="StreamClosedError";name="StreamClosedError"}function db(t){return t.reason}function Fu(t,e,n){if(e==null||t==null)return t;const r=db;if(e.aborted)return t.catch(()=>{}),Promise.reject(r(e));let s;return Promise.race([t,new Promise((o,i)=>{s=()=>{i(r(e))},e.addEventListener("abort",s)})]).finally(()=>{s!=null&&e.removeEventListener("abort",s)})}const ub=Math.pow(2,20)*4;class Ou extends Sh{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??ub,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new ne,this.writeBuffer=new ne,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=s=>{this.onDrainPromise?.reject(s.error??new lb)};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()),Fu(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;const e=rb(),n=o=>{e.push(o.data)};this.addEventListener("message",n);const r=o=>{e.end(o.error)};this.addEventListener("close",r);const s=()=>{e.end()};this.addEventListener("remoteCloseWrite",s);try{yield*e}finally{this.removeEventListener("message",n),this.removeEventListener("close",r),this.removeEventListener("remoteCloseWrite",s)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Zn(`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 Hw(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Zn("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 Zn("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 Zn(`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 Zn(`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 Uw;this.dispatchEvent(new qw(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 ca))}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 s=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(s===0){e=!1;break}const o=this.writeBuffer.sublist(0,s),i=new ne(o);this.writeBuffer.consume(o.byteLength);const a=this.sendData(o);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 $w(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 vc(`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 vc(`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 fb=4194304;class $c extends Error{static name="UnwrappedError";name="UnwrappedError"}class Mu extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class hb extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class pb extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function gb(t){return typeof t?.closeRead=="function"}function mb(t){return typeof t?.close=="function"}function Co(t){return gb(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:mb(t)?t.status!=="open":!1}function wb(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function yb(t,e){const n=e?.maxBufferSize??fb,r=new ne;let s,o=!1;if(!wb(t))throw new fu("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),s?.reject(new Error(`Read buffer overflow - ${u} > ${n}`))}s?.resolve()};t.addEventListener("message",i);const a=d=>{d.error!=null?s?.reject(d.error):s?.resolve()};t.addEventListener("close",a);const c=()=>{s?.resolve()};t.addEventListener("remoteCloseWrite",c);const l={readBuffer:r,async read(d){if(o===!0)throw new $c("Stream was unwrapped");if(Co(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 ks(`Unexpected EOF - stream closed after reading ${r.byteLength}/${d.bytes} bytes`)}const u=d?.bytes??1;for(s=Promise.withResolvers();;){if(r.byteLength>=u){s.resolve();break}if(await Fu(s.promise,d?.signal),Co(t)){if(r.byteLength===0&&d?.bytes==null)return null;break}s=Promise.withResolvers()}const f=d?.bytes??r.byteLength;if(r.byteLength<f){if(Co(t))throw t.log.error("closed while reading %d/%d bytes",r.byteLength,f),new ks(`Unexpected EOF - stream closed while reading ${r.byteLength}/${f} bytes`);return l.read(d)}const p=r.sublist(0,f);return r.consume(f),p},async write(d,u){if(o===!0)throw new $c("Stream was unwrapped");t.send(d)||await cb(t,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return o||(o=!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 Hc(t,e={}){const n=yb(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=tn(e.maxDataLength));const r=e?.lengthDecoder??Vd,s=e?.lengthEncoder??Am;return{async read(i){let a=-1;const c=new ne;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 Mu("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new pb(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new hb(`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 ks(`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 ks(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await n.write(new ne(s(i.byteLength),i),a)},async writeV(i,a){const c=new ne(...i.flatMap(l=>[s(l.byteLength),l]));await n.write(c,a)},unwrap(){return n.unwrap()}}}const bb=1024*1024*4,xb=1024*1024*4;class vb{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new ne,this.maxBufferSize=e.maxBufferSize??bb,this.maxDataLength=e.maxDataLength??xb,this.lengthDecoder=e.lengthDecoder??Vd,this.encodingLength=e.encodingLength??tn}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new fu(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let n;try{n=this.lengthDecoder(this.buffer)}catch(o){if(o instanceof RangeError)break;throw o}if(n<0||n>this.maxDataLength)throw new Mu("Invalid message length");const r=this.encodingLength(n),s=r+n;if(this.buffer.byteLength>=s){const o=this.buffer.sublist(r,s);this.buffer.consume(s),o.byteLength>0&&(yield o)}else break}}}var Eb={};const Sr=65535,qc=Sr-16,Lr=!!Eb?.DUMP_SESSION_KEYS,Kc=16;function ki(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const Ts=t=>t?`"${t}" `:"";function Ti(t,e=""){if(typeof t!="boolean")throw new TypeError(Ts(e)+"expected boolean, got type="+typeof t);return t}function kn(t,e=""){if(typeof t!="number")throw new TypeError(Ts(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(Ts(e)+"expected integer >= 0, got "+t);return t}function ge(t,e,n=""){if(ki(t)&&(e===void 0||t.length===e))return t;e!==void 0&&kn(e,"length");const r=ki(t),s=e!==void 0?` of length ${e}`:"",o=r?`length=${t.length}`:`type=${typeof t}`,i=Ts(n)+"expected Uint8Array"+s+", got "+o;throw r?new RangeError(i):new TypeError(i)}const zc=(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 Vc(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function Sb(t,e){ge(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function ut(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Lt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Ab(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const Tn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function kb(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Tb(t){for(let e=0;e<t.length;e++)t[e]=kb(t[e]);return t}const $t=Tn?t=>t:Tb;function Cb(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 Ib(t,e){if(Cb(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function Rb(t,e){return zc(t,"defaults"),zc(e,"opts"),Object.assign(t,e)}function Pb(t,e){if(t=ge(t),e=ge(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 Nb(t,e,n){const r=e,s=(()=>[]),o=(a,c)=>r(c,...s(a)).update(a).digest(),i=r(new Uint8Array(t),...s(new Uint8Array(0)));return o.outputLen=i.outputLen,o.blockLen=i.blockLen,o.create=(a,...c)=>r(a,...c),o}const Lb=(t,e)=>{function n(r,...s){if(ge(r,void 0,"key"),t.nonceLength!==void 0){const u=s[0];ge(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}const o=t.tagLength,i=t.nonceLength!==void 0?1:0;if(!t.withAAD){for(let u=i;u<s.length;u++)if(ki(s[u]))throw new Error("AAD not supported")}t.withAAD&&s[i]!==void 0&&ge(s[i],void 0,"AAD");const a=e(r,...s),c=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");ge(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,ge(u,void 0,"data"),c(a.encrypt.length,f),a.encrypt(u,f)},decrypt(u,f){if(ge(u,void 0,"data"),o&&u.length<o)throw new Error('"ciphertext" expected length >= tagLength='+o);return c(a.decrypt.length,f),a.decrypt(u,f)}}}return Object.assign(n,t),n};function Ci(t,e,n=!0){if(e===void 0)return new Uint8Array(t);if(ge(e,t,"output"),n&&!Cs(e))throw new Error("invalid output, must be aligned");return e}function Bb(t,e,n){kn(t),kn(e),Ti(n);const r=new Uint8Array(16),s=Ab(r);return s.setBigUint64(0,BigInt(e),n),s.setBigUint64(8,BigInt(t),n),r}function Cs(t){return t.byteOffset%4===0}function Is(t){return Uint8Array.from(ge(t))}const ju=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),_b=$t(ut(ju("expand 16-byte k"))),Db=$t(ut(ju("expand 32-byte k")));function ee(t,e){return t<<e|t>>>32-e}const Jn=64,Fb=16,Ii=2**32-1,Gc=Uint32Array.of();function Ob(t,e,n,r,s,o,i,a){const c=s.length,l=new Uint8Array(Jn),d=ut(l),u=Tn&&Cs(s)&&Cs(o),f=u?ut(s):Gc,p=u?ut(o):Gc;if(!Tn){for(let g=0;g<c;i++){if(t(e,n,r,d,i,a),$t(d),i>=Ii)throw new Error("arx: counter overflow");const m=Math.min(Jn,c-g);for(let x=0,y;x<m;x++)y=g+x,o[y]=s[y]^l[x];g+=m}return}for(let g=0;g<c;i++){if(t(e,n,r,d,i,a),i>=Ii)throw new Error("arx: counter overflow");const m=Math.min(Jn,c-g);if(u&&m===Jn){const x=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let y=0,T;y<Fb;y++)T=x+y,p[T]=f[T]^d[y];g+=Jn;continue}for(let x=0,y;x<m;x++)y=g+x,o[y]=s[y]^l[x];g+=m}}function Mb(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:s,counterRight:o,rounds:i}=Rb({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return kn(s),kn(i),Ti(o),Ti(n),(a,c,l,d,u=0)=>{ge(a,void 0,"key"),ge(c,void 0,"nonce"),ge(l,void 0,"data");const f=l.length,p=d!==void 0;if(d=Ci(f,d,!1),p&&Ib(l,d),kn(u),u<0||u>=Ii)throw new Error("arx: counter overflow");const g=[];let m=a.length,x,y;if(m===32)g.push(x=Is(a)),y=Db;else if(m===16&&n)x=new Uint8Array(32),x.set(a),x.set(a,16),y=_b,g.push(x);else throw ge(a,32,"arx key"),new Error("invalid key size");(!Tn||!Cs(c))&&g.push(c=Is(c));let T=ut(x);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");const _=c.subarray(0,16);if(Tn)r(y,T,ut(_),T);else{const C=$t(Uint32Array.from(y));r(C,T,ut(_),T),Lt(C),$t(T)}c=c.subarray(16)}else Tn||$t(T);const v=16-s;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){const _=new Uint8Array(12);_.set(c,o?0:12-c.length),c=_,g.push(c)}const A=$t(ut(c));try{return Ob(t,y,T,A,l,d,u,i),d}finally{Lt(...g)}}}function we(t,e){return t[e++]&255|(t[e++]&255)<<8}class jb{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=Is(ge(e,32,"key"));const n=we(e,0),r=we(e,2),s=we(e,4),o=we(e,6),i=we(e,8),a=we(e,10),c=we(e,12),l=we(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|s<<6)&7939,this.r[3]=(s>>>7|o<<9)&8191,this.r[4]=(o>>>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]=we(e,16+2*d)}process(e,n,r=!1){const s=r?0:2048,{h:o,r:i}=this,a=i[0],c=i[1],l=i[2],d=i[3],u=i[4],f=i[5],p=i[6],g=i[7],m=i[8],x=i[9],y=we(e,n+0),T=we(e,n+2),v=we(e,n+4),A=we(e,n+6),_=we(e,n+8),C=we(e,n+10),L=we(e,n+12),R=we(e,n+14);let E=o[0]+(y&8191),S=o[1]+((y>>>13|T<<3)&8191),P=o[2]+((T>>>10|v<<6)&8191),N=o[3]+((v>>>7|A<<9)&8191),w=o[4]+((A>>>4|_<<12)&8191),b=o[5]+(_>>>1&8191),k=o[6]+((_>>>14|C<<2)&8191),B=o[7]+((C>>>11|L<<5)&8191),M=o[8]+((L>>>8|R<<8)&8191),U=o[9]+(R>>>5|s),D=0,I=D+E*a+S*(5*x)+P*(5*m)+N*(5*g)+w*(5*p);D=I>>>13,I&=8191,I+=b*(5*f)+k*(5*u)+B*(5*d)+M*(5*l)+U*(5*c),D+=I>>>13,I&=8191;let F=D+E*c+S*a+P*(5*x)+N*(5*m)+w*(5*g);D=F>>>13,F&=8191,F+=b*(5*p)+k*(5*f)+B*(5*u)+M*(5*d)+U*(5*l),D+=F>>>13,F&=8191;let O=D+E*l+S*c+P*a+N*(5*x)+w*(5*m);D=O>>>13,O&=8191,O+=b*(5*g)+k*(5*p)+B*(5*f)+M*(5*u)+U*(5*d),D+=O>>>13,O&=8191;let K=D+E*d+S*l+P*c+N*a+w*(5*x);D=K>>>13,K&=8191,K+=b*(5*m)+k*(5*g)+B*(5*p)+M*(5*f)+U*(5*u),D+=K>>>13,K&=8191;let q=D+E*u+S*d+P*l+N*c+w*a;D=q>>>13,q&=8191,q+=b*(5*x)+k*(5*m)+B*(5*g)+M*(5*p)+U*(5*f),D+=q>>>13,q&=8191;let H=D+E*f+S*u+P*d+N*l+w*c;D=H>>>13,H&=8191,H+=b*a+k*(5*x)+B*(5*m)+M*(5*g)+U*(5*p),D+=H>>>13,H&=8191;let G=D+E*p+S*f+P*u+N*d+w*l;D=G>>>13,G&=8191,G+=b*c+k*a+B*(5*x)+M*(5*m)+U*(5*g),D+=G>>>13,G&=8191;let W=D+E*g+S*p+P*f+N*u+w*d;D=W>>>13,W&=8191,W+=b*l+k*c+B*a+M*(5*x)+U*(5*m),D+=W>>>13,W&=8191;let X=D+E*m+S*g+P*p+N*f+w*u;D=X>>>13,X&=8191,X+=b*d+k*l+B*c+M*a+U*(5*x),D+=X>>>13,X&=8191;let V=D+E*x+S*m+P*g+N*p+w*f;D=V>>>13,V&=8191,V+=b*u+k*d+B*l+M*c+U*a,D+=V>>>13,V&=8191,D=(D<<2)+D|0,D=D+I|0,I=D&8191,D=D>>>13,F+=D,o[0]=I,o[1]=F,o[2]=O,o[3]=K,o[4]=q,o[5]=H,o[6]=G,o[7]=W,o[8]=X,o[9]=V}finalize(){const{h:e,pad:n}=this,r=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,r[0]=e[0]+5,s=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+s,s=r[a]>>>13,r[a]&=8191;r[9]-=8192;let o=(s^1)-1;for(let a=0;a<10;a++)r[a]&=o;o=~o;for(let a=0;a<10;a++)e[a]=e[a]&o|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;Lt(r)}update(e){Vc(this),ge(e),e=Is(e);const{buffer:n,blockLen:r}=this,s=e.length;for(let o=0;o<s;){const i=Math.min(r-this.pos,s-o);if(i===r){for(;r<=s-o;o+=r)this.process(e,o);continue}n.set(e.subarray(o,o+i),this.pos),this.pos+=i,o+=i,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,Lt(this.h,this.r,this.buffer,this.pad)}digestInto(e){Vc(this),Sb(e,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:s}=this;if(s){for(n[s++]=1;s<16;s++)n[s]=0;this.process(n,0,!0)}this.finalize();let o=0;for(let i=0;i<8;i++)e[o++]=r[i]>>>0,e[o++]=r[i]>>>8}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}}const Ub=Nb(32,t=>new jb(t));function $b(t,e,n,r,s,o=20){let i=t[0],a=t[1],c=t[2],l=t[3],d=e[0],u=e[1],f=e[2],p=e[3],g=e[4],m=e[5],x=e[6],y=e[7],T=s,v=n[0],A=n[1],_=n[2],C=i,L=a,R=c,E=l,S=d,P=u,N=f,w=p,b=g,k=m,B=x,M=y,U=T,D=v,I=A,F=_;for(let K=0;K<o;K+=2)C=C+S|0,U=ee(U^C,16),b=b+U|0,S=ee(S^b,12),C=C+S|0,U=ee(U^C,8),b=b+U|0,S=ee(S^b,7),L=L+P|0,D=ee(D^L,16),k=k+D|0,P=ee(P^k,12),L=L+P|0,D=ee(D^L,8),k=k+D|0,P=ee(P^k,7),R=R+N|0,I=ee(I^R,16),B=B+I|0,N=ee(N^B,12),R=R+N|0,I=ee(I^R,8),B=B+I|0,N=ee(N^B,7),E=E+w|0,F=ee(F^E,16),M=M+F|0,w=ee(w^M,12),E=E+w|0,F=ee(F^E,8),M=M+F|0,w=ee(w^M,7),C=C+P|0,F=ee(F^C,16),B=B+F|0,P=ee(P^B,12),C=C+P|0,F=ee(F^C,8),B=B+F|0,P=ee(P^B,7),L=L+N|0,U=ee(U^L,16),M=M+U|0,N=ee(N^M,12),L=L+N|0,U=ee(U^L,8),M=M+U|0,N=ee(N^M,7),R=R+w|0,D=ee(D^R,16),b=b+D|0,w=ee(w^b,12),R=R+w|0,D=ee(D^R,8),b=b+D|0,w=ee(w^b,7),E=E+S|0,I=ee(I^E,16),k=k+I|0,S=ee(S^k,12),E=E+S|0,I=ee(I^E,8),k=k+I|0,S=ee(S^k,7);let O=0;r[O++]=i+C|0,r[O++]=a+L|0,r[O++]=c+R|0,r[O++]=l+E|0,r[O++]=d+S|0,r[O++]=u+P|0,r[O++]=f+N|0,r[O++]=p+w|0,r[O++]=g+b|0,r[O++]=m+k|0,r[O++]=x+B|0,r[O++]=y+M|0,r[O++]=T+U|0,r[O++]=v+D|0,r[O++]=A+I|0,r[O++]=_+F|0}const Hb=Mb($b,{counterRight:!1,counterLength:4,allowShortKeys:!1}),qb=new Uint8Array(16),Wc=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(qb.subarray(n))},Kb=new Uint8Array(32);function Xc(t,e,n,r,s){s!==void 0&&ge(s,void 0,"AAD");const o=t(e,n,Kb),i=Bb(r.length,s?s.length:0,!0),a=Ub.create(o);s&&Wc(a,s),Wc(a,r),a.update(i);const c=a.digest();return Lt(o,i),c}const zb=t=>(e,n,r)=>({encrypt(o,i){const a=o.length;i=Ci(a+16,i,!1),i.set(o);const c=i.subarray(0,-16);t(e,n,c,c,1);const l=Xc(t,e,n,c,r);return i.set(l,a),Lt(l),i},decrypt(o,i){i=Ci(o.length-16,i,!1);const a=o.subarray(0,-16),c=o.subarray(-16),l=Xc(t,e,n,a,r);if(!Pb(c,l))throw Lt(l),new Error("invalid tag");return i.set(o.subarray(0,-16)),t(e,n,i,i,1),Lt(l),i}}),Yc=Lb({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},zb(Hb));function Vb(t,e,n){return la(t),n===void 0&&(n=new Uint8Array(t.outputLen)),Du(t,n,e)}const Qn=Uint8Array.of(0),Gb=Uint8Array.of();function Wb(t,e,n,r=32,s){la(t),wt(r,"length"),yt(e,void 0,"prk");const o=t.outputLen;if(e.length<o)throw new Error('"prk" must be at least HashLen octets');if(r>255*o)throw new Error("Length must be <= 255*HashLen");const i=Math.ceil(r/o);if(n===void 0?n=Gb:yt(n,void 0,"info"),!i)return new Uint8Array;const a=new Uint8Array(i*o),{iHash:c,oHash:l}=Du.create(t,e),d=new Uint8Array(o),u=i>1?t.create():void 0;for(let p=0;p<i-1;p++){Qn[0]=p+1;const g=c._cloneInto(u);p&&g.update(d),g.update(n).update(Qn).digestInto(d),l._cloneInto(u).update(d).digestInto(d),a.set(d,o*p)}if(Qn[0]=i,i>1&&c.update(d),c.update(n).update(Qn).digestInto(d),l.update(d).digestInto(d),a.set(d,o*(i-1)),c.destroy(),l.destroy(),u?.destroy(),d!==a&&Kt(d),Kt(Qn),r===a.length)return a;const f=a.slice(0,r);return Kt(a),f}const Uu={hashSHA256(t){return So(t.subarray())},getHKDF(t,e){const n=Vb(So,e,t),s=Wb(So,n,void 0,96),o=s.subarray(0,32),i=s.subarray(32,64),a=s.subarray(64,96);return[o,i,a]},generateX25519KeyPair(){const t=Xr.utils.randomSecretKey();return{publicKey:Xr.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:Xr.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return Xr.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,n,r){return Yc(r,e,n).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,n,r,s){return Yc(r,e,n).decrypt(t.subarray(),s)}},Xb=Uu;function Yb(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 Rs=t=>{const e=gt(2);return e[0]=t>>8,e[1]=t,e};Rs.bytes=2;const Ps=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)};Ps.bytes=2;function Zb(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 $u(t,e){!e.enabled||!Lr||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${J(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${J(t.privateKey,"hex")}`)):e("Missing local static keys."))}function Hu(t,e){!e.enabled||!Lr||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${J(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${J(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Jb(t,e){!e.enabled||!Lr||e(t?`REMOTE_STATIC_PUBLIC_KEY ${J(t.subarray(),"hex")}`:"Missing remote static public key.")}function qu(t,e){!e.enabled||!Lr||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${J(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Ku(t,e,n){!n.enabled||!Lr||(n(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&J(t.k,"hex")}`),n(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&J(e.k,"hex")}`))}class gr extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=gr.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}const Qb=0,e0=4294967295,t0="Cipherstate has reached maximum n, a new handshake must be performed";class n0{n;bytes;view;constructor(e=Qb){this.n=e,this.bytes=Re(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>e0)throw new Error(t0)}}const Cn=Re(0);class Yr{k;n;crypto;constructor(e,n=void 0,r=0){this.crypto=e,this.k=n,this.n=new n0(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 s=this.crypto.decrypt(n,this.n.getBytes(),e,this.k,r);return this.n.increment(),s}}class r0{cs;ck;h;crypto;constructor(e,n){this.crypto=e;const r=fe(n,"utf-8");this.h=o0(e,r),this.ck=this.h,this.cs=new Yr(e)}mixKey(e){const[n,r]=this.crypto.hkdf(this.ck,e);this.ck=n,this.cs=new Yr(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new ne(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,Cn);return[new Yr(this.crypto,e),new Yr(this.crypto,n)]}}class s0{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:n,protocolName:r,prologue:s,initiator:o,s:i,e:a,rs:c,re:l}=e;this.crypto=n,this.ss=new r0(n,r),this.ss.mixHash(s),this.initiator=o,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 s=e.sublist(n,n+r);return this.rs=this.ss.decryptAndHash(s),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class zu extends s0{writeMessageA(e){return new ne(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const n=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new ne(n,r,this.ss.encryptAndHash(e))}writeMessageC(e){const n=this.writeS();return this.writeSE(),new ne(n,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(n){throw new gr(`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 gr(`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 gr(`handshake stage 2 validation fail: ${n.message}`)}}}function o0(t,e){if(e.length<=32){const n=Re(32);return n.set(e),n}else return t.hash(e)}var Ns;(function(t){let e;t.codec=()=>(e==null&&(e=Gs((n,r,s={})=>{if(s.lengthDelimited!==!1&&r.fork(),n.webtransportCerthashes!=null)for(const o of n.webtransportCerthashes)r.uint32(10),r.bytes(o);if(n.streamMuxers!=null)for(const o of n.streamMuxers)r.uint32(18),r.string(o);s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const o={webtransportCerthashes:[],streamMuxers:[]},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{if(s.limits?.webtransportCerthashes!=null&&o.webtransportCerthashes.length===s.limits.webtransportCerthashes)throw new wc('Decode error - map field "webtransportCerthashes" had too many elements');o.webtransportCerthashes.push(n.bytes());break}case 2:{if(s.limits?.streamMuxers!=null&&o.streamMuxers.length===s.limits.streamMuxers)throw new wc('Decode error - map field "streamMuxers" had too many elements');o.streamMuxers.push(n.string());break}default:{n.skipType(a&7);break}}}return o})),e),t.encode=n=>Vs(n,t.codec()),t.decode=(n,r)=>zs(n,t.codec(),r)})(Ns||(Ns={}));var Ls;(function(t){let e;t.codec=()=>(e==null&&(e=Gs((n,r,s={})=>{s.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),Ns.codec().encode(n.extensions,r)),s.lengthDelimited!==!1&&r.ldelim()},(n,r,s={})=>{const o={identityKey:Re(0),identitySig:Re(0)},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{o.identityKey=n.bytes();break}case 2:{o.identitySig=n.bytes();break}case 4:{o.extensions=Ns.codec().decode(n,n.uint32(),{limits:s.limits?.extensions});break}default:{n.skipType(a&7);break}}}return o})),e),t.encode=n=>Vs(n,t.codec()),t.decode=(n,r)=>zs(n,t.codec(),r)})(Ls||(Ls={}));async function Vu(t,e,n){const r=await t.sign(Wu(e));return Ls.encode({identityKey:Ws(t.publicKey),identitySig:r,extensions:n})}async function Gu(t,e,n){try{const r=Ls.decode(t),s=vi(r.identityKey);if(n?.equals(s)===!1)throw new Error(`Payload identity key ${s} does not match expected remote identity key ${n}`);if(!e)throw new Error("Remote static does not exist");const o=Wu(e);if(!await s.verify(o,r.identitySig))throw new Error("Invalid payload signature");return r}catch(r){throw new mh(r.message)}}function Wu(t){const e=fe("noise-libp2p-static-key:");return t instanceof Uint8Array?di([e,t],e.length+t.length):(t.prepend(e),t)}class i0 extends Ou{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 vb({lengthDecoder:Ps,maxBufferSize:16*1024*1024,encodingLength:()=>2});const s=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",s);const o=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",o);const i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);const a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){const n=new ne;for(let r=0;r<e.byteLength;r+=qc){let s=r+qc;s>e.byteLength&&(s=e.byteLength);let o;e instanceof Uint8Array?o=this.handshake.encrypt(e.subarray(r,s)):o=this.handshake.encrypt(e.sublist(r,s)),this.metrics?.encryptedPackets.increment(),n.append(Rs(o.byteLength)),n.append(o)}return n}decrypt(e){const n=new ne;for(let r=0;r<e.byteLength;r+=Sr){let s=r+Sr;if(s>e.byteLength&&(s=e.byteLength),s-Kc<r)throw new Error("Invalid chunk");let o;e instanceof Uint8Array?o=e.subarray(r,s):o=e.sublist(r,s);const i=e.subarray(r,s-Kc);try{const a=this.handshake.decrypt(o,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 Zc(t,e,n){return new i0(t,e,n)}async function a0(t,e){const{log:n,connection:r,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Vu(o,a.publicKey,l),u=new zu({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});$u(u.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(u.writeMessageA(Cn),e),n.trace("Stage 0 - Initiator finished sending first message."),Hu(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."),qu(u.re,n),Jb(u.rs,n),n.trace("Initiator going to check remote's signature...");const p=await Gu(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 Ku(g,m,n),{payload:p,encrypt:x=>g.encryptWithAd(Cn,x),decrypt:(x,y)=>m.decryptWithAd(Cn,x,y)}}async function c0(t,e){const{log:n,connection:r,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Vu(o,a.publicKey,l),u=new zu({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});$u(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."),qu(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."),Hu(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 p=await Gu(f,u.rs,c),[g,m]=u.ss.split();return Ku(g,m,n),{payload:p,encrypt:x=>m.encryptWithAd(Cn,x),decrypt:(x,y)=>g.decryptWithAd(Cn,x,y)}}class l0{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,n={}){const{staticNoiseKey:r,extensions:s,crypto:o,prologueBytes:i}=n,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");const c=o??Xb;this.crypto=Yb(c),this.extensions={webtransportCerthashes:[],...s},this.metrics=a?Zb(a):void 0,r?this.staticKey=c.generateX25519KeyPairFromSeed(r):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??Re(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Ah]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,n){const r=e.log?.newScope("noise")??this.log,s=Hc(e,{lengthEncoder:Rs,lengthDecoder:Ps,maxDataLength:Sr}),o=await this.performHandshakeInitiator(s,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=vi(o.payload.identityKey);return{connection:Zc(s.unwrap(),o,this.metrics),remoteExtensions:o.payload.extensions,remotePeer:Bn(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(o.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 s=n.get(r);if(s!=null)return s}if(e.length)throw new wh("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,s=Hc(e,{lengthEncoder:Rs,lengthDecoder:Ps,maxDataLength:Sr}),o=await this.performHandshakeResponder(s,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=vi(o.payload.identityKey);return{connection:Zc(s.unwrap(),o,this.metrics),remoteExtensions:o.payload.extensions,remotePeer:Bn(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,n,r,s,o){let i;const a=o?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await a0({connection:e,privateKey:n,remoteIdentityKey:s,log:r.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,n,r,s,o){let i;const a=o?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await c0({connection:e,privateKey:n,remoteIdentityKey:s,log:r.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}}function d0(t={}){return e=>new l0(e,t)}const u0="termdock-e2ee-v1",Jc=3600*1e3,Qc=512*1024*1024,Ri=4*1024*1024,ss=()=>{},Zs=Object.assign(ss,{enabled:!1,error:ss,trace:ss,newScope:()=>Zs});Object.freeze(Zs);async function Xu(){const t=await Rw();return{privateKey:t,peerId:Bn(t.publicKey).toString()}}function f0(t){return btoa(String.fromCharCode(...Lw(t.privateKey)))}function el(t){if(t.length>512||!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Invalid identity encoding");const e=Nw(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:Bn(e.publicKey).toString()}}class Yu{constructor(e=ss){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>Ri)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 h0 extends Ou{constructor(e,n){super({log:Zs,direction:n?"outbound":"inbound",maxReadBufferLength:Ri,maxWriteBufferLength:Ri}),this.duplex=e,this.finished=e.sink(this.outgoing).catch(r=>{this.abort(_n(r))}),this.readTransport()}duplex;outgoing=new Yu(()=>this.onMuxerDrain());finished;async readTransport(){try{for await(const e of this.duplex.source)this.onData(e.slice());this.onTransportClosed()}catch(e){this.onTransportClosed(_n(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 _n(t){return t instanceof Error?t:new Error("Secure transport failed")}class p0 extends Error{code="E2EE_REHANDSHAKE_REQUIRED";constructor(){super("Encrypted connection lifetime reached; establish a new handshake without replaying pending input")}}function g0(t){const e=t?.maxAgeMs??Jc,n=t?.maxBytesPerDirection??Qc;if(!Number.isSafeInteger(e)||e<=0||e>Jc||!Number.isSafeInteger(n)||n<=0||n>Qc)throw new Error("Encrypted connection limits cannot exceed the production maximum");return{maxAgeMs:e,maxBytesPerDirection:n}}async function m0(t){const{identity:e,duplex:n,initiator:r,targetPinnedPeerId:s,signal:o}=t,i=g0(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&&!s)throw new Error("A pinned target identity is required");const a=s?Fw(s):void 0;if(a&&a.type!=="Ed25519")throw new Error("Only Ed25519 target identities are supported");if(e.peerId!==Bn(e.privateKey.publicKey).toString())throw new Error("Local identity mismatch");if(o?.aborted)throw o.reason??new Error("Connection aborted");const c=new h0(n,r),l=new AbortController,d=setTimeout(()=>{const p=new Error("Encrypted handshake timed out");l.abort(p),c.abort(p)},15e3),u=()=>{l.abort(o?.reason),c.abort(_n(o?.reason))};o?.addEventListener("abort",u,{once:!0}),c.addEventListener("close",()=>o?.removeEventListener("abort",u),{once:!0});const f=d0({crypto:Uu,prologueBytes:new TextEncoder().encode(u0)})({privateKey:e.privateKey,peerId:Bn(e.privateKey.publicKey),logger:{forComponent:()=>Zs},upgrader:{getStreamMuxers:()=>new Map}});try{const p=await(r?f.secureOutbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}):f.secureInbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}));if(p.remotePeer.type!=="Ed25519")throw new Error("Unsupported remote identity");return{authenticatedPeerId:p.remotePeer.toString(),duplex:w0(p.connection,i)}}catch(p){throw c.abort(_n(p)),p}finally{clearTimeout(d),o?.removeEventListener("abort",u)}}function w0(t,e){const n=new Yu,r=performance.now(),s=Date.now();let o=0,i=0,a;const c=()=>(a??=new p0,n.end(a),t.abort(a),a),l=setTimeout(c,e.maxAgeMs);typeof l=="object"&&l.unref?.();const d=(f,p)=>{if(a)throw a;if(Math.max(performance.now()-r,Date.now()-s)>=e.maxAgeMs||f+p>=e.maxBytesPerDirection)throw c()};t.addEventListener("message",f=>{try{d(i,f.data.byteLength),i+=f.data.byteLength,n.push(f.data.subarray())}catch(p){t.abort(_n(p))}}),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 p of f)d(o,p.byteLength),o+=p.byteLength,t.send(p)||await t.onDrain()}catch(p){throw t.abort(_n(p)),p}},close(f){f?t.abort(f):t.close()}}}class ya{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 Io=2*1024*1024,y0=new TextEncoder,b0=new TextDecoder("utf-8",{fatal:!0});class x0{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 ya(256);outgoingBytes=0;done;send(e){const n=y0.encode(JSON.stringify(e));if(n.length>Io)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(s){throw this.outgoingBytes-=r.byteLength,s}}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>Io*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 s=new DataView(e.buffer,e.byteOffset,4).getUint32(0);if(s>Io||s===0)throw new Error("Invalid record size");if(e.length<s+4)break;const o=JSON.parse(b0.decode(e.subarray(4,s+4)));if(!o||typeof o!="object"||typeof o.id!="string"||typeof o.type!="string")throw new Error("Invalid record");yield o,e=e.slice(s+4)}}if(e.length)throw new Error("Truncated record")}}function Zu(t){let e="";for(let n=0;n<t.length;n+=8192)e+=String.fromCharCode(...t.subarray(n,n+8192));return btoa(e)}function Ju(t){const e=atob(t);return Uint8Array.from(e,n=>n.charCodeAt(0))}function v0(t){const e=new ya(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 s of r)for(let o=0;o<s.length;o+=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(s.subarray(o,o+64*1024))}}catch(s){throw n(s instanceof Error?s:new Error("Encrypted transport failed")),s}}}}const Qu=8,ef=128,E0=5*1024*1024,S0=ef+Qu+8,A0=256,Zr=3e4,er=64*1024;function It(t){return t instanceof Error?t:new Error(String(t??"Secure connection closed"))}function tl(t){if(!t.startsWith("/")||t.startsWith("//")||t.includes("#"))throw new Error("A local API path is required");return t}class tf 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(It(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 k0{constructor(e,n,r){this.channel=e,this.identity=n,this.targetPeerId=r,this.read().catch(s=>this.close(It(s))),e.done.catch(s=>this.close(It(s)))}channel;identity;targetPeerId;pending=new Map;waiting=[];stopped=!1;closeReason;get canSwitchTransport(){return![...this.pending.values()].some(e=>e.kind==="http")&&!this.waiting.some(e=>e.kind==="http")}get closed(){return this.stopped}hasCapacity(e){if(this.pending.size>=S0)return!1;const n=[...this.pending.values()].filter(r=>r.kind===e).length;return e==="http"?n<Qu:e==="socket"?n<ef:!0}allocate(e){if(this.stopped)throw this.closeReason??new Error("Secure connection closed");const n=crypto.randomUUID(),r=new ya(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>=A0?Promise.reject(new Error("连接繁忙,请稍后重试。")):new Promise((r,s)=>{const o=l=>{this.waiting=this.waiting.filter(d=>d!==c),c.cleanup(),s(l)},i=()=>o(n?.reason??new Error("Request aborted")),a=setTimeout(()=>o(new Error("连接等待超时,请重试。")),Zr),c={kind:e,resolve:r,reject:s,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:s}=await this.reserve("request"),o=setTimeout(()=>this.close(new Error("Secure connection timed out")),Math.max(1e3,Math.min(Zr,n?.timeoutMs??Zr)));try{if(this.stopped)throw this.closeReason;this.channel.send({...e,id:r});const i=(await s[Symbol.asyncIterator]().next()).value;if(!i)throw new Error("Secure request closed");if(i.type==="error")throw It(i.error);return i}finally{clearTimeout(o),this.release(r)}}openSocket(e){tl(e);let n;const r=new AbortController,s=new tf(e,o=>{n&&this.channel.send({id:n,type:"ws-data",data:o})},()=>{if(r.abort(),n)try{this.channel.send({id:n,type:"ws-close"})}finally{this.release(n)}});return this.reserve("socket",r.signal).then(o=>{if(n=o.id,s.readyState===3){this.release(n);return}const i=this.pending.get(n);if(!i)throw new Error("Secure connection closed");i.socket=s,this.channel.send({id:n,type:"ws-open",path:e})}).catch(o=>{n&&this.release(n),s.fail(It(o))}),s}async fetch(e,n){const r=typeof location>"u"?"https://termdock.invalid":location.origin,s=e instanceof Request?e:null,o=new URL(s?.url??String(e),r);if(o.origin!==r)throw new Error("Only current-service API requests are supported");const i=new Request(o,s?new Request(s,n):n),a=i.method.toUpperCase(),c=tl(o.pathname+o.search),l=o.pathname==="/api/terminal/fs/upload"?110*1024*1024:E0;if(i.signal.aborted)throw i.signal.reason;const d={};i.headers.forEach((A,_)=>{["cookie","authorization","host","connection","content-length"].includes(_)||(d[_]=A)});const{id:u,queue:f}=await this.reserve("http",i.signal),p=f[Symbol.asyncIterator]();let g;const m=()=>{g?.cancel().catch(()=>{})},x=this.pending.get(u);if(!x)throw new Error("Secure connection closed");x.cancelUpload=m;const y=()=>{m();try{this.channel.send({id:u,type:"cancel"})}catch{}f.end(It(i.signal.reason??"Request aborted")),this.release(u)};i.signal.addEventListener("abort",y,{once:!0});const T=()=>{i.signal.removeEventListener("abort",y),this.release(u)},v=async()=>{let A;try{const _=(await Promise.race([p.next(),new Promise((C,L)=>{A=setTimeout(()=>L(new Error("服务响应超时,请重试。")),Zr)})])).value;if(!_)throw new Error("Secure response ended unexpectedly");if(_.type==="error")throw It(_.error);return _}finally{clearTimeout(A)}};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 R=i.body.getReader();g=R;let E=0,S=0;try{for(;;){const{done:P,value:N}=await R.read();if(P)break;if(E+=N.byteLength,E>l)throw new Error("Request body exceeds upload limit");for(let w=0;w<N.byteLength;w+=er){if(this.channel.send({id:u,type:"upload",data:Zu(N.subarray(w,w+er))}),(await v()).type!=="upload-ack")throw new Error("Invalid upload acknowledgement");S+=Math.min(er,N.byteLength-w),n?.onUploadProgress?.(S)}}}catch(P){throw await R.cancel(P).catch(()=>{}),P}finally{g=void 0,R.releaseLock()}}if(i.signal.aborted||this.stopped)throw new Error("Request aborted");this.channel.send({id:u,type:"upload-end"});const A=await v();if(A.type!=="head"||typeof A.status!="number")throw new Error("Invalid response header");const _=new Headers(A.headers);if(a==="HEAD"||[204,205,304].includes(A.status)){if((await v()).type!=="end")throw new Error("Unexpected response body");return T(),new Response(null,{status:A.status,headers:_})}let C=!1;const L=new ReadableStream({pull:async R=>{try{C&&(this.channel.send({id:u,type:"ack"}),C=!1);const E=await v();if(E.type==="end"){R.close(),T();return}if(E.type!=="chunk"||typeof E.data!="string")throw new Error("Invalid response chunk");const S=Ju(E.data);if(S.length>er)throw new Error("Response chunk exceeds budget");R.enqueue(S),C=!0}catch(E){R.error(E),y(),T()}},cancel:()=>{y(),T()}},{highWaterMark:er,size:R=>R.byteLength});return new Response(L,{status:A.status,headers:_})}catch(A){throw y(),T(),A}}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 Xt(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 Xu(),r=(t.socketFactory??(c=>new WebSocket(c)))(e.href),s=v0(r),o=new AbortController,i=setTimeout(()=>o.abort(new Error("Secure handshake timed out")),2e4),a=t.signal?AbortSignal.any([t.signal,o.signal]):o.signal;try{await new Promise((d,u)=>{if(a.aborted){u(a.reason);return}const f=()=>{a.removeEventListener("abort",m),r.removeEventListener("open",p),r.removeEventListener("error",g),r.removeEventListener("close",g)},p=()=>{f(),d()},g=()=>{f(),u(new Error("Secure transport unavailable"))},m=()=>{f(),u(a.reason)};a.addEventListener("abort",m,{once:!0}),r.addEventListener("open",p),r.addEventListener("error",g),r.addEventListener("close",g),r.readyState===1&&p()});const c=await m0({identity:n,duplex:s,initiator:!0,targetPinnedPeerId:t.targetPeerId,signal:a}),l=new k0(new x0(c.duplex),n,c.authenticatedPeerId);if(t.pairingCode)try{await l.request({type:"pair",code:t.pairingCode})}catch(d){throw l.close(It(d)),d}return l}catch(c){throw r.close(),c}finally{clearTimeout(i)}}const nl=256*1024,T0=1024*1024;class C0 extends EventTarget{constructor(e,n,r=s=>new WebSocket(s)){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",s=>{if(this.readyState!==3)try{if(typeof s.data!="string"||new TextEncoder().encode(s.data).length>nl)throw new Error("Invalid relay envelope");const o=JSON.parse(s.data);if(o.type==="ready"&&!this.requested){this.requested=!0,this.transmit({type:"open",streamId:this.streamId,serviceId:n});return}if(o.streamId!==this.streamId)return;if(o.type==="opened"&&this.readyState===0){clearTimeout(this.deadline),this.readyState=1;const l=new Event("open");this.dispatchEvent(l),this.onopen?.(l);return}if(o.type==="close"){this.finish(1001,"Relay route closed"),this.upstream.close();return}if(o.type!=="data"||this.readyState!==1||o.encoding!=="base64"||typeof o.payload!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(o.payload))throw new Error("Invalid ciphertext relay frame");const i=Ju(o.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",s=>this.finish(s.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>T0||n.length>nl)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:Zu(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 nf(t){return e=>new C0(e,t)}function I0(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((s,o)=>{if(o===0||s===""&&o===e.split("/").length-1)return s;const i=decodeURIComponent(s);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 R0(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 s=r.ports[0],{path:o,method:i,headers:a,body:c,expectedTargetPeerId:l,previewPrefix:d}=r.data;let u;try{u=new URL(o,location.origin)}catch{s.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)){s.postMessage({type:"error"}),s.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)||!I0(u.pathname)?.startsWith(d))){s.postMessage({type:"error"}),s.close();return}const f=new AbortController;let p,g,m=!1,x=!1;const y=()=>{x||(x=!0,e.delete(y),f.abort(),p?.cancel().catch(()=>{}),s.close())};e.add(y),s.onmessage=T=>{if(T.data?.type==="cancel"){y();return}T.data?.type!=="pull"||m||x||(m=!0,(async()=>{if(!p){s.postMessage({type:"end"}),y();return}if(!g?.length){const A=await p.read();if(A.done){s.postMessage({type:"end"}),y();return}g=A.value}const v=g.slice(0,64*1024);g=g.subarray(v.length),s.postMessage({type:"chunk",data:v.buffer},[v.buffer])})().catch(()=>{s.postMessage({type:"error"}),y()}).finally(()=>{m=!1}))},s.onmessageerror=y,s.start(),(async()=>{const T=await t();if(x)return;if(l&&l!==T.targetPeerId)throw new Error("Preview target changed");const v=await T.fetch(u.pathname+u.search,{method:i,headers:a,body:["GET","HEAD"].includes(i)?void 0:c,signal:f.signal});if(x){await v.body?.cancel();return}p=v.body?.getReader();const A={};v.headers.forEach((_,C)=>{A[C]=_}),s.postMessage({type:"head",status:v.status,headers:A,bodyless:!p,targetPeerId:T.targetPeerId})})().catch(()=>{x||(s.postMessage({type:"error"}),y())})};return navigator.serviceWorker.addEventListener("message",n),()=>{navigator.serviceWorker.removeEventListener("message",n);for(const r of[...e])r()}}class _e extends Error{constructor(){super("Device authorization expired or revoked")}}async function Dn(t){const e=await t.request({type:"permissions"},{timeoutMs:5e3});if(e.type!=="result"||typeof e.fullService!="boolean"||!Array.isArray(e.grants))throw new Error("Invalid permission response");const n=e.grants,r=e.fullService===!0;if(!r&&n.length===0)throw new _e;return{fullService:r,grants:n,canManage:r&&n.length>0||n.some(s=>s.actions.includes("authorization.manage"))}}let Ro;async function De(){return Ro||(Ro=(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((s,o)=>{const i=t.transaction("keys").objectStore("keys").get("identity");i.onsuccess=()=>s(i.result),i.onerror=()=>o(i.error)});if(e)return el(e);const n=await Xu();let r=n;return await new Promise((s,o)=>{const i=t.transaction("keys","readwrite"),a=i.objectStore("keys"),c=a.get("identity");c.onsuccess=()=>{typeof c.result=="string"?r=el(c.result):a.put(f0(n),"identity")},i.oncomplete=()=>s(),i.onerror=()=>o(i.error)}),r}finally{t.close()}})()),Ro}const Ar="termdock:secure-state";let Q,tr,Ge,Bs="direct",Po=!1;const Fn=globalThis.fetch.bind(globalThis);function ye(){return ch()}function No(){return Q}function Pi(){Q?.close(),Ge?.close(),Q=void 0,Ge=void 0}async function rf(){const t=await Fn("/api/auth/status");if(!t.ok)throw new Error("Failed to query auth status");return t.json()}async function P0(){if(ye()){await ft();return}if((await rf()).enabled)return;const t=await Fn("/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 Ve({url:location.origin,targetPeerId:e,serviceName:location.hostname})}async function N0(t,e){const{startPasswordBootstrap:n,finishPasswordBootstrap:r}=await Un(async()=>{const{startPasswordBootstrap:l,finishPasswordBootstrap:d}=await import("./passwordBootstrap-CppLqzUc.js");return{startPasswordBootstrap:l,finishPasswordBootstrap:d}},__vite__mapDeps([0,1,2,3])),s=l=>t===location.origin?l:new URL(l,t).href,o=async(l,d)=>{const u=await Fn(s(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 o("/api/auth/password/parameters"),a=await De(),c=await n(e,i);try{const l=await o("/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 o("/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 ba(t,e){try{return await N0(t,e)}catch(n){if(!(n instanceof TypeError)&&!(n instanceof DOMException))throw n;const r=(await nt()).find(o=>o.targetPeerId&&(o.serviceOrigin||o.url)===t);if(!r?.targetPeerId)throw new Error("暂时连不上这台服务,请检查地址和网络。");const s={...r,targetPeerId:r.targetPeerId,serviceName:r.label};return await sf(s,e),s}}async function sf(t,e){const n=await B0(t),{startPasswordBootstrap:r,finishPasswordBootstrap:s}=await Un(async()=>{const{startPasswordBootstrap:i,finishPasswordBootstrap:a}=await import("./passwordBootstrap-CppLqzUc.js");return{startPasswordBootstrap:i,finishPasswordBootstrap:a}},__vite__mapDeps([0,1,2,3]));let o;try{const i=await n.request({type:"password-parameters"},{timeoutMs:5e3});o=await r(e,String(i.saltHex));const a=await n.request({type:"password-start",startLoginRequest:o.startLoginRequest,origin:location.origin}),c=await s(o,a,{clientIdentity:(await De()).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{o&&(o.passwordKey=""),n.close()}}async function L0(t){try{const e=ye(),n=e?.serviceOrigin||location.origin,r=await ba(n,t);return await Ve({...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 rl(t,e){const n=Ce(t),r=(await nt()).find(i=>(i.serviceOrigin||i.url)===n&&i.targetPeerId);if(e===void 0&&r?.targetPeerId)try{return await Ve({...r,targetPeerId:r.targetPeerId,serviceName:r.label}),{}}catch(i){if(!(i instanceof _e))throw i}if(e!==void 0){const i=await ba(n,e);if(r?.targetPeerId&&r.targetPeerId!==i.targetPeerId)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await Ve({...i,routes:r?.routes,serviceName:r?.label||i.serviceName}),{}}const s=await Fn(new URL("/api/auth/open/parameters",n).href,{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(1e4)}).catch(()=>{throw new Error("暂时连不上这台服务,请检查地址和网络后重试。")});if(s.status===403)return{passwordRequired:!0};if(!s.ok)throw new Error("这台服务暂时不可用,请稍后重试。");const{serviceIdentity:o}=await s.json();if(typeof o!="string"||!o)throw new Error("这不是可连接的 Termdock 服务。");if(r?.targetPeerId&&r.targetPeerId!==o)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await Ve({url:n,targetPeerId:o,serviceName:r?.label||new URL(n).host,serviceOrigin:n}),{}}function Yt(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(qi)||"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(s=>s.targetPeerId===n.targetPeerId)===r?[{url:Ce(n.url),targetPeerId:n.targetPeerId}]:[]}catch{return[]}}).slice(0,4)}function Js(t){const e=Yt(t),n=[t.serviceOrigin||t.url,...(t.routes||[]).slice(0,4).filter(s=>s.targetPeerId===t.targetPeerId).map(s=>s.url)],r=new Set;for(const s of n)try{const o=Ce(s);e.some(i=>i.url===o)||r.add(o)}catch{}return[...r]}function Zt(t){const e=new URL("/api/federation/secure",Ce(t));return e.protocol=e.protocol==="https:"?"wss:":"ws:",e.href}async function _t(t){return Xt({url:Zt(t.url),targetPeerId:t.targetPeerId,identity:await De(),signal:AbortSignal.timeout(5e3)})}async function B0(t){const e=Yt(t);for(const n of Js(t))try{return await Xt({url:Zt(n),targetPeerId:t.targetPeerId,identity:await De(),signal:AbortSignal.timeout(3e3)})}catch{}for(const n of e){let r;try{r=await _t(n);const s=await r.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(typeof s.routeToken!="string")continue;const o=new URL(Zt(n.url));return o.pathname="/api/federation/relay",o.searchParams.set("routeToken",s.routeToken),await Xt({url:o.href,targetPeerId:t.targetPeerId,identity:await De(),socketFactory:nf(t.targetPeerId),signal:AbortSignal.timeout(8e3)})}catch{}finally{r?.close()}}throw new Error("当前无法连接。请检查网络,或请入口管理员授权此设备访问该服务。")}async function Ve(t){const e=Q,n=Ge,r=await De(),s=Ce(t.serviceOrigin||t.url),o=(await nt()).find(x=>x.targetPeerId===t.targetPeerId),i={...t,routes:t.routes??o?.routes},a=Yt(i),c=Js(i);let l,d,u=t.pairingCode,f="direct";const p=new Set,g=new Map,m=async x=>{if(n&&!n.closed&&n.targetPeerId===x.targetPeerId)return n;const y=g.get(x.targetPeerId);if(y&&!y.closed)return y;const T=await _t(x);return p.add(T),g.set(x.targetPeerId,T),T};try{if(t.routeCode&&t.entryServiceId){const A=a.find(L=>L.targetPeerId===t.entryServiceId);if(!A)throw new Error("邀请缺少入口信息。");if((await(await m(A)).request({type:"route-pair",code:t.routeCode})).serviceId!==t.targetPeerId)throw new Error("邀请的目标服务不一致。");t.routeOnly&&await Pn({id:t.targetPeerId,url:s,label:t.serviceName||new URL(s).host,targetPeerId:t.targetPeerId,serviceOrigin:s,routes:a})}let x;for(const A of c)try{l=await Xt({url:Zt(A),targetPeerId:t.targetPeerId,pairingCode:u,identity:r,signal:AbortSignal.timeout(a.length||c.length>1?3e3:1e4)}),u=void 0,await Dn(l);break}catch(_){if(l?.close(),l=void 0,_ instanceof _e)throw _;x=_}if(!l)for(const A of a){let _;try{_=await m(A);const C=await _.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(typeof C.routeToken!="string"||!C.routeToken)throw new Error("入口未允许此设备连接该服务。");const L=new URL(Zt(A.url));L.pathname="/api/federation/relay",L.searchParams.set("routeToken",C.routeToken),l=await Xt({url:L.href,targetPeerId:t.targetPeerId,pairingCode:u,identity:r,socketFactory:nf(t.targetPeerId),signal:AbortSignal.timeout(8e3)}),u=void 0,await Dn(l),d=_,f="relay";break}catch(C){if(l?.close(),l=void 0,_&&_!==n&&_.close(),C instanceof _e)throw C;x=C}}if(!l)throw x||new Error("当前网络无法连接这台服务,也没有可用的已授权入口。");if(Q!==e&&Q&&!Q.closed&&Q.targetPeerId===t.targetPeerId){l.close();for(const A of p)A!==Ge&&A.close();return Q}f==="direct"&&new URL(s).host===location.host&&lh(t.targetPeerId);const y=(await nt()).find(A=>A.targetPeerId===t.targetPeerId||!A.targetPeerId&&(A.serviceOrigin||A.url)===s),T=y?.label||t.serviceName||new URL(s).host,v={url:s,targetPeerId:t.targetPeerId,serviceName:T,serviceOrigin:s,routes:i.routes??a};await Pn({id:y?.id||t.targetPeerId,...v,label:T}),Gl(v),Q=l,Bs=f,Ge=d;for(const A of new Set([e,n,...p]))A&&A!==l&&A!==d&&A.close();return Fs!==t.targetPeerId?(location.reload(),new Promise(()=>{})):(window.dispatchEvent(new Event(Ar)),l)}catch(x){l?.close();for(const y of p)y!==n&&y.close();throw x}}async function _0(){const t=Q,e=ye();if(Po||Bs!=="relay"||!t||t.closed||!t.canSwitchTransport||!e?.serviceOrigin)return;Po=!0;let n;try{for(const s of Js(e))try{n=await Xt({url:Zt(s),targetPeerId:e.targetPeerId,identity:await De(),signal:AbortSignal.timeout(3e3)}),await Dn(n);break}catch(o){if(n?.close(),n=void 0,o instanceof _e)throw o}if(!n||Q!==t||!t.canSwitchTransport)return;const r=Ge;Q=n,n=void 0,Ge=void 0,Bs="direct",t.close(),r?.close(),window.dispatchEvent(new Event(Ar))}catch(r){r instanceof _e&&Q===t&&(Pi(),window.dispatchEvent(new Event("auth:unauthorized")))}finally{n?.close(),Po=!1}}async function ft(){if(Q&&!Q.closed)return Q;if(Q=void 0,tr)return tr;const t=ye();if(!t)throw new Error("DEVICE_PAIRING_REQUIRED");return tr=Ve(t).catch(e=>{if(Q&&!Q.closed&&Q.targetPeerId===t.targetPeerId)return Q;throw e}).finally(()=>{tr=void 0}),tr}function D0(t){const e=new URL(t,location.href);if(Q&&!Q.closed)return Q.openSocket(e.pathname+e.search);let n;const r=new tf(t,s=>n?.send(s),()=>n?.close());return ft().then(s=>{r.readyState!==3&&(n=s.openSocket(e.pathname+e.search),n.onopen=()=>r.accept({type:"ws-ready",id:""}),n.onmessage=o=>r.accept({type:"ws-data",id:"",data:o.data}),n.onclose=o=>r.accept({type:"ws-close",id:"",code:o.code,reason:o.reason}),n.onerror=()=>r.fail(new Error("Encrypted connection unavailable")))}).catch(s=>r.fail(s)),r}function F0(){R0(ft),window.fetch=async(t,e)=>{const n=new URL(t instanceof Request?t.url:String(t),location.href);if(!n.pathname.startsWith("/api/"))return Fn(t,e);if(n.origin!==location.origin)throw new Error("Remote business API requires a paired encrypted service");if(n.pathname==="/api/meta")return Fn(t,e);if(n.pathname==="/api/auth/status"){const s=await rf();if(!ye())return Response.json({enabled:s.enabled,authenticated:!1});try{return await Dn(await ft()),Response.json({enabled:s.enabled,authenticated:!0})}catch(o){if(o instanceof _e)return Response.json({enabled:s.enabled,authenticated:!1});throw o}}if(n.pathname==="/api/auth/login"){const o=await new Request(t instanceof Request?t:n.href,e).json();return L0(typeof o.password=="string"?o.password:"")}if(n.pathname==="/api/csrf-token")return Response.json({csrfToken:"encrypted-device-channel"});if(n.pathname==="/api/auth/logout")return Q&&!Q.closed&&await Q.request({type:"logout"}),Q?.close(),Ge?.close(),Q=void 0,Ge=void 0,localStorage.removeItem(Vt),sessionStorage.removeItem(Vt),localStorage.removeItem(qi),location.reload(),Response.json({ok:!0});const r=await ft();return t instanceof Request?r.fetch(t,e):r.fetch(n.pathname+n.search,e)}}async function O0(t){if(!t.targetPeerId)throw new Error("请先连接这台服务,再查看可中转的服务。");for(const e of Js({...t,targetPeerId:t.targetPeerId})){let n;const r={url:e,targetPeerId:t.targetPeerId};try{n=await _t(r)}catch{continue}try{const s=await n.request({type:"route-targets"},{timeoutMs:5e3});if(!Array.isArray(s.items))throw new Error("入口服务需要更新后才能查看中转列表。");return{route:r,canManage:s.canManage===!0,items:s.items}}catch(s){throw s instanceof Error&&/UNKNOWN|UNSUPPORTED/i.test(s.message)?new Error("入口服务需要更新后才能查看中转列表。"):s}finally{n.close()}}throw new Error("暂时连不上中转入口,请检查地址和网络后重试。")}async function M0(t,e){const n=await _t(t);try{const r=await n.request({type:"route-targets"},{timeoutMs:5e3}),s=(Array.isArray(r.items)?r.items:[]).find(c=>c.serviceId===e);if(!s)throw new Error("该服务已不可见,请刷新列表或请入口管理员授权。");if(!s.available)throw new Error("入口暂时无法中转到这台服务,请稍后重试。");const o=(await nt()).find(c=>c.targetPeerId===s.serviceId),i=[t,...(o?.routes||[]).filter(c=>c.targetPeerId!==t.targetPeerId)];if(i.length>4)throw new Error("这台服务已保存 4 个备用连接,请先移除一个后重试。");if(!s.authorized){if(!r.canManage)throw new Error("请先让入口管理员授权此设备。");await n.request({type:"route-grant",serviceId:s.serviceId,subjectId:(await De()).peerId})}const a=o?.serviceOrigin||o?.url||s.url||t.url;return{url:a,serviceOrigin:a,targetPeerId:s.serviceId,serviceName:o?.label||s.label||(s.url?new URL(s.url).host:`中转服务 ${s.serviceId.slice(0,8)}`),routes:i}}finally{n.close()}}async function j0(t,e){const n=await _t(t);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),s=(await De()).peerId;return{canManage:r.canManage===!0,grants:(Array.isArray(r.grants)?r.grants:[]).filter(o=>o.subjectId===s&&o.targetServiceId===e)}}finally{n.close()}}async function U0(t,e,n){if(n!==void 0&&(await ba(Ce(e.url),n)).targetPeerId!==e.targetPeerId)throw new Error("入口服务的身份已改变,请重新连接并确认。");const r=await _t(e);try{await r.request({type:"route-grant",serviceId:t.targetPeerId,subjectId:(await De()).peerId,url:Ce(t.serviceOrigin||t.url)})}finally{r.close()}}async function $0(t,e){const n=await _t(e);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),s=(await De()).peerId,o=(Array.isArray(r.grants)?r.grants:[]).filter(i=>i.subjectId===s&&i.targetServiceId===t&&i.active);for(const i of o)await n.request({type:"route-revoke",grantId:i.id})}finally{n.close()}}async function of(t,e){const n=await _t(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 os(t,e){const n=(await nt()).find(s=>s.id===t.id||t.targetPeerId&&s.targetPeerId===t.targetPeerId)||t;await Pn({...n,url:n.serviceOrigin||n.url,entryServiceId:void 0,routes:e});const r=ye();r&&r.targetPeerId===t.targetPeerId&&Gl({...r,url:r.serviceOrigin||r.url,entryServiceId:void 0,routes:e})}async function H0(t,e){const n=t.targetPeerId;if(!n)throw new Error("请先连接这台服务,再添加备用地址。");let r;try{r=Ce(e)}catch{throw new Error("请输入有效的 HTTPS 地址,例如 https://电脑地址:9834。")}const s=async()=>(await nt()).find(a=>a.targetPeerId===n)||t,o=a=>{const c=a.routes??Yt({...a,targetPeerId:n});if(Ce(a.serviceOrigin||a.url)===r||c.some(l=>Ce(l.url)===r))throw new Error("这个地址已经在连接列表中。");if(c.length>=4)throw new Error("最多保存 4 个备用地址或入口,请先移除不再使用的连接。");return[...c,{url:r,targetPeerId:n}]};o(await s());let i;try{try{i=await Xt({url:Zt(r),targetPeerId:n,identity:await De(),signal:AbortSignal.timeout(5e3)}),await Dn(i)}catch(l){throw l instanceof _e?new Error("这台服务尚未授权当前设备,请先恢复设备授权。"):new Error("无法验证这个地址。请确认能访问该地址、HTTPS 证书受信任,且运行的是同一台 Termdock 服务。")}const a=await s(),c=o(a);if(await os(a,c),ye()?.targetPeerId===n&&Fs===n&&(!Q||Q.closed)){const l=Q,d=Ge;Q=i,i=void 0,Ge=void 0,Bs="direct",l?.close(),d?.close(),window.dispatchEvent(new Event(Ar))}return c}finally{i?.close()}}async function sl(t,e){await sf(t,e),await Ve({...t,pairingCode:void 0,routeCode:void 0})}function q0(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}`}const af=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim();const K0=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const z0=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,r)=>r?r.toUpperCase():n.toLowerCase());const ol=t=>{const e=z0(t);return e.charAt(0).toUpperCase()+e.slice(1)};var Lo={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 V0=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1},G0=$.createContext({}),W0=()=>$.useContext(G0),X0=$.forwardRef(({color:t,size:e,strokeWidth:n,absoluteStrokeWidth:r,className:s="",children:o,iconNode:i,...a},c)=>{const{size:l=24,strokeWidth:d=2,absoluteStrokeWidth:u=!1,color:f="currentColor",className:p=""}=W0()??{},g=r??u?Number(n??d)*24/Number(e??l):n??d;return $.createElement("svg",{ref:c,...Lo,width:e??l??Lo.width,height:e??l??Lo.height,stroke:t??f,strokeWidth:g,className:af("lucide",p,s),...!o&&!V0(a)&&{"aria-hidden":"true"},...a},[...i.map(([m,x])=>$.createElement(m,x)),...Array.isArray(o)?o:[o]])});const Ne=(t,e)=>{const n=$.forwardRef(({className:r,...s},o)=>$.createElement(X0,{ref:o,iconNode:e,className:af(`lucide-${K0(ol(t))}`,`lucide-${t}`,r),...s}));return n.displayName=ol(t),n};const Y0=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],cf=Ne("arrow-left",Y0);const Z0=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],J0=Ne("arrow-right",Z0);const Q0=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],xa=Ne("check",Q0);const ex=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],tx=Ne("chevron-down",ex);const nx=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Jt=Ne("chevron-right",nx);const rx=[["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"}]],lf=Ne("copy",rx);const sx=[["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"}]],ox=Ne("ellipsis",sx);const ix=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],We=Ne("loader-circle",ix);const ax=[["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"}]],cx=Ne("monitor",ax);const lx=[["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"}]],dx=Ne("pencil",lx);const ux=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],df=Ne("plus",ux);const fx=[["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"}]],Qs=Ne("server",fx);const hx=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],uf=Ne("smartphone",hx);const px=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],gx=Ne("x",px);function mx({service:t,onBusyChange:e,onConnect:n,onConnectWithPassword:r}){const[s,o]=$.useState(),[i,a]=$.useState(!0),[c,l]=$.useState(!1),[d,u]=$.useState(""),[f,p]=$.useState(0),[g,m]=$.useState(),[x,y]=$.useState("");$.useEffect(()=>{let A=!1;return a(!0),u(""),o(void 0),O0(t).then(_=>{A||o(_)}).catch(_=>{A||u(_ instanceof Error?_.message:"暂时无法读取中转列表,请重试。")}).finally(()=>{A||a(!1)}),()=>{A=!0}},[t.id,t.url,f]);const T=async A=>{if(!c){l(!0),e(!0),u("");try{await A()}catch(_){u(_ instanceof Error?_.message:"暂时无法连接,请重试。")}finally{l(!1),e(!1)}}},v=async A=>{const _=await M0(s.route,A.serviceId);try{await n(_)}catch(C){if(!(C instanceof _e))throw C;m(_)}};return h.jsxs("div",{className:"service-form",children:[g?h.jsxs("form",{className:"service-form",onSubmit:A=>{A.preventDefault(),T(async()=>{try{await r?.(g,x)}finally{y("")}})},children:[h.jsxs("p",{className:"service-help",children:["已通过“",t.label,"”连接到“",g.serviceName,"”。请登录目标服务,完成此设备的访问授权。"]}),r?h.jsxs(h.Fragment,{children:[h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"目标服务密码"}),h.jsx("input",{type:"password",autoFocus:!0,required:!0,autoComplete:"current-password",value:x,disabled:c,onChange:A=>y(A.target.value)})]}),h.jsx("button",{type:"submit",className:"service-button service-primary",disabled:c||!x,children:c?"正在登录…":"登录并连接"})]}):h.jsx("p",{className:"service-help",children:"请让目标服务管理员邀请此设备后再连接。"}),h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>{m(void 0),y(""),u(""),p(A=>A+1)},children:"返回中转列表"})]}):h.jsxs(h.Fragment,{children:[h.jsxs("p",{className:"service-help",children:["通过“",t.label,"”连接下方服务。",s?.canManage?"选择未授权的服务会授权此设备使用该中转。":"这里只显示已授权给此设备的中转。","目标服务会单独验证访问权限。"]}),i?h.jsxs("p",{className:"service-feedback",role:"status",children:[h.jsx(We,{size:16,className:"service-spinning"}),"正在读取可中转的服务…"]}):s&&h.jsxs("div",{className:"service-list",children:[s.items.map(A=>h.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:c||!A.available,onClick:()=>{T(()=>v(A))},children:[h.jsx("span",{className:"service-icon",children:h.jsx(Qs,{size:19})}),h.jsxs("span",{className:"service-row-copy",children:[h.jsx("span",{className:"service-name",children:A.label||(A.url?new URL(A.url).host:`中转服务 ${A.serviceId.slice(0,8)}`)}),h.jsx("span",{className:"service-description",children:A.available?A.authorized?"已获中转授权 · 连接":"授权此设备并连接":"中转暂不可用"})]}),h.jsx(Jt,{size:16})]},A.serviceId)),s.items.length===0&&h.jsx("p",{className:"service-empty",children:s.canManage?"暂无可中转的服务。可在本机 Mac 客户端连接目标服务,或在目标服务的“备用连接”中启用本入口。":"暂无已授权的中转服务,请让入口管理员分享备用连接邀请。"})]}),c&&h.jsxs("p",{className:"service-feedback",role:"status",children:[h.jsx(We,{size:16,className:"service-spinning"}),"正在授权并连接目标服务…"]}),!i&&h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>p(A=>A+1),children:"刷新列表"})]}),d&&h.jsx("p",{className:"service-error",role:"alert",children:d})]})}const Ni="#termdock-invite=";function ff(t){const e=new URL(t.entryUrl);e.hash="",e.search="",e.pathname="/";const n=new TextEncoder().encode(JSON.stringify(t));return e.hash=Ni.slice(1)+btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.href}function _s(t){const e=new URL(t);if(!["https:","http:"].includes(e.protocol)||!e.hash.startsWith(Ni))throw new Error("这不是有效的 Termdock 邀请链接");const n=e.hash.slice(Ni.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 s=new URL(r.entryUrl);if(s.origin!==e.origin||s.username||s.password||!["https:","http:"].includes(s.protocol))throw new Error("邀请地址与服务不一致");if(s.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(s.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 o=s.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("目标服务地址无效");o=r.entryServiceId&&r.entryServiceId!==r.serviceId?i.origin:s.origin}return{url:s.origin,targetPeerId:r.serviceId,pairingCode:r.code,...r.routeOnly===!0?{routeOnly:!0}:{},serviceOrigin:o,serviceName:typeof r.name=="string"?r.name.slice(0,120):void 0,entryServiceId:r.entryServiceId,routeCode:r.routeCode}}function wx({service:t,onBusyChange:e}){const n={...t,targetPeerId:t.targetPeerId,serviceName:t.label},[r,s]=$.useState(()=>t.routes??Yt(n)),[o,i]=$.useState([]),[a,c]=$.useState(!0),[l,d]=$.useState(!1),[u,f]=$.useState(""),p=I=>{d(I),e(I)},[g,m]=$.useState(),[x,y]=$.useState(""),[T,v]=$.useState(""),[A,_]=$.useState(""),[C,L]=$.useState(!1),[R,E]=$.useState(),[S,P]=$.useState(),[N,w]=$.useState(!1);$.useEffect(()=>{let I=!1;return nt().then(F=>{I||i(F.filter(O=>O.targetPeerId&&O.targetPeerId!==t.targetPeerId))}).catch(()=>{I||f("暂时无法读取可用服务。")}).finally(()=>{I||c(!1)}),()=>{I=!0}},[t.targetPeerId]);const b=I=>o.find(F=>F.targetPeerId===I.targetPeerId)?.label||new URL(I.url).host,k=async I=>{p(!0),f(""),_("");try{await I()}catch(F){const O=F instanceof Error?F.message:"";f(/AUTHORIZATION|DENIED/.test(O)?"当前设备没有入口管理权限。请让管理员分享备用连接邀请,或使用入口密码授权。":"暂时无法完成。请确认入口能连接目标服务,且目标地址、证书和授权有效。")}finally{p(!1)}},B=async(I,F)=>{const O={url:I.serviceOrigin||I.url,targetPeerId:I.targetPeerId};await k(async()=>{const K=await j0(O,n.targetPeerId);if(!K.grants.some(H=>H.active)){if(!K.canManage&&F===void 0){m(I);return}await U0(n,O,F)}const q=[...r.filter(H=>H.targetPeerId!==O.targetPeerId),O];await os(t,q),s(q),m(void 0),y("")})};if(S)return h.jsxs("div",{className:"service-form",children:[h.jsxs("p",{className:"service-help",children:["把链接发给需要使用此备用连接的人。它只允许通过入口连接“",t.label,"”,对方仍需获得目标服务的访问权限。"]}),h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"备用连接邀请"}),h.jsx("input",{readOnly:!0,value:S,onFocus:I=>I.target.select()})]}),h.jsxs("button",{type:"button",className:"service-button service-primary",onClick:()=>{navigator.clipboard.writeText(S).then(()=>w(!0)).catch(()=>f("无法自动复制,请长按链接复制。"))},children:[h.jsx(lf,{size:16}),N?"已复制":"复制邀请链接"]}),h.jsx("button",{type:"button",className:"service-button service-secondary",onClick:()=>{P(void 0),w(!1)},children:"返回备用连接"}),u&&h.jsx("p",{role:"alert",className:"service-error",children:u})]});if(g)return h.jsxs("form",{className:"service-form",onSubmit:I=>{I.preventDefault(),B(g,x).finally(()=>y(""))},children:[h.jsxs("p",{className:"service-help",children:["需要“",g.label,"”的管理员授权。若这是你的服务,可以使用它的密码;否则请管理员分享备用连接邀请。"]}),h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"入口服务密码"}),h.jsx("input",{type:"password",required:!0,value:x,onChange:I=>y(I.target.value),autoComplete:"current-password",disabled:l,autoFocus:!0})]}),h.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||!x,children:l?"正在授权…":"授权并启用"}),h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{m(void 0),y("")},children:"取消"}),u&&h.jsx("p",{role:"alert",className:"service-error",children:u})]});const M=r.filter(I=>I.targetPeerId===n.targetPeerId),U=r.filter(I=>I.targetPeerId!==n.targetPeerId),D=async()=>{if(!l){p(!0),L(!0),f(""),_("");try{s(await H0({...t,routes:r},T)),v(""),_("备用地址已验证并保存。")}catch(I){f(I instanceof Error?I.message:"暂时无法添加地址,请重试。")}finally{p(!1),L(!1)}}};return h.jsxs("div",{className:"service-form",children:[h.jsx("p",{className:"service-help",children:"电脑换了网络?添加它在新网络下的地址,原地址连不上时会自动尝试。只接受同一台服务。"}),h.jsxs("form",{className:"service-form",onSubmit:I=>{I.preventDefault(),D()},children:[h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"备用地址"}),h.jsx("input",{value:T,onChange:I=>{v(I.target.value),f(""),_("")},required:!0,disabled:l||r.length>=4,inputMode:"url",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:192.168.10.20:9834"})]}),h.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||r.length>=4||!T.trim(),children:C?h.jsxs(h.Fragment,{children:[h.jsx(We,{size:16,className:"service-spinning"}),"正在验证…"]}):"验证并添加"})]}),u&&h.jsx("p",{role:"alert",className:"service-error",children:u}),A&&h.jsx("p",{role:"status",className:"service-help",children:A}),r.length>=4&&h.jsx("p",{className:"service-help",children:"已保存 4 个备用连接。移除不再使用的地址或入口后,可以继续添加。"}),h.jsxs("div",{children:[h.jsx("p",{className:"service-help",children:"首选地址"}),h.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url})]}),M.length>0&&h.jsx("div",{className:"service-list",children:M.map(I=>h.jsxs("div",{className:"service-route-item",children:[h.jsxs("div",{className:"service-route-line",children:[h.jsx("span",{className:"service-address service-route-address",children:I.url}),h.jsx("button",{type:"button",className:"service-icon-button","aria-label":`移除地址 ${I.url}`,disabled:l,onClick:()=>E(I),children:"移除"})]}),R?.targetPeerId===I.targetPeerId&&R.url===I.url&&h.jsxs("div",{className:"service-form",children:[h.jsx("p",{className:"service-help",children:"从备用连接中移除此地址?不会停止正在运行的终端。"}),h.jsxs("div",{className:"service-actions service-actions-pair",children:[h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>E(void 0),children:"取消"}),h.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{k(async()=>{const F=r.filter(O=>O.targetPeerId!==I.targetPeerId||O.url!==I.url);await os(t,F),s(F),E(void 0)})},children:"确认移除"})]})]})]},I.url))}),h.jsxs("details",{className:"service-relay-options",children:[h.jsxs("summary",{children:["通过其他服务中转",U.length?`(${U.length})`:""]}),h.jsxs("div",{className:"service-form",children:[h.jsx("p",{className:"service-help",children:"所有直连地址都不可用时,尝试下方已授权入口;直连恢复后自动切回。"}),U.length>0&&h.jsx("div",{className:"service-list",children:U.map(I=>h.jsxs("div",{className:"service-route-item",children:[h.jsxs("div",{className:"service-route-line",children:[h.jsx("span",{className:"service-icon",children:h.jsx(Qs,{size:18})}),h.jsx("span",{className:"service-name",children:b(I)}),h.jsx(xa,{size:16,className:"service-selected"})]}),R?.targetPeerId===I.targetPeerId?h.jsxs("div",{className:"service-form",children:[h.jsxs("p",{className:"service-help",children:["撤销此设备经“",b(I),"”连接目标的权限?如当前无法直连,目标服务将断开。"]}),h.jsxs("div",{className:"service-actions service-actions-pair",children:[h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>E(void 0),children:"取消"}),h.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{k(async()=>{await $0(n.targetPeerId,I);const F=r.filter(O=>O.targetPeerId!==I.targetPeerId);await os(t,F),s(F),E(void 0)})},children:"确认撤销"})]})]}):h.jsxs("div",{className:"service-actions service-actions-pair",children:[h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{k(async()=>{const F=await of(n,I);P(ff({v:1,routeOnly:!0,serviceId:n.targetPeerId,name:t.label,serviceUrl:t.serviceOrigin||t.url,entryUrl:I.url,entryServiceId:I.targetPeerId,routeCode:F.routeCode}))})},children:"分享备用连接"}),h.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>E(I),children:"撤销授权"})]})]},I.targetPeerId))}),a?h.jsxs("p",{role:"status",className:"service-feedback",children:[h.jsx(We,{size:16,className:"service-spinning"}),"正在读取服务…"]}):h.jsxs("div",{children:[h.jsx("p",{className:"service-help",children:"添加中转入口"}),o.filter(I=>!r.some(F=>F.targetPeerId===I.targetPeerId)).map(I=>h.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:l||r.length>=4,onClick:()=>{B(I)},children:[h.jsxs("span",{className:"service-row-copy",children:[h.jsx("span",{className:"service-name",children:I.label}),h.jsx("span",{className:"service-description",children:"验证并授权后启用"})]}),h.jsx(Jt,{size:16})]},I.id)),o.length===0&&h.jsx("p",{className:"service-empty",children:"添加并登录另一台服务后,可以将它设为中转入口。"})]})]})]}),l&&!C&&h.jsxs("p",{role:"status",className:"service-feedback",children:[h.jsx(We,{size:16,className:"service-spinning"}),"正在验证连接与授权…"]})]})}function yx({current:t,renderRoutes:e,renderRelayServices:n,onOpen:r,onAdd:s,onInvite:o,hideHeader:i,onNavigation:a,onBusyChange:c,initiallyAdding:l=!1}){const[d,u]=$.useState([]),[f,p]=$.useState(!0),[g,m]=$.useState(l?{kind:"add"}:{kind:"list"}),[x,y]=$.useState(!1),T=$.useCallback(w=>{y(w),c?.(w)},[c]),[v,A]=$.useState(""),_=$.useCallback(()=>{m(w=>w.kind==="routes"||w.kind==="relay-services"?{kind:"edit",service:w.service}:{kind:"list"}),A("")},[]),C=g.kind==="add"?"添加服务":g.kind==="edit"?"服务设置":g.kind==="routes"?"备用连接":g.kind==="relay-services"?"可中转的服务":void 0;$.useEffect(()=>{a?.({title:C,...C?{back:_}:{}})},[C,_,a]),$.useEffect(()=>{let w=!1,b=0;const k=async()=>{const M=++b;try{const U=await nt();!w&&b===M&&(u(U),A(""))}catch{!w&&b===M&&A("暂时无法读取服务列表,请重试。")}finally{!w&&b===M&&p(!1)}};k();const B=gh(()=>{k()});return()=>{w=!0,B()}},[]);const L=async w=>{if(!x){T(!0),A("");try{await w()}catch(b){A(b instanceof Error?b.message:"暂时无法完成,请重试。")}finally{T(!1)}}},R=g.kind==="edit"||g.kind==="routes"||g.kind==="relay-services"?d.find(w=>Pt(w,g.service))||g.service:void 0,E=t?d.find(w=>Pt(w,t))||t:void 0,S=d.filter(w=>!t||!Pt(w,t)),P=E?[E,...S]:S,N=h.jsxs(h.Fragment,{children:[f?h.jsxs("p",{className:"service-feedback",role:"status",children:[h.jsx(We,{size:16,className:"service-spinning"}),"正在读取服务…"]}):h.jsxs("div",{className:"service-list",children:[P.map(w=>{const b=!!t&&Pt(w,t);return h.jsxs("div",{className:"service-row",children:[h.jsxs("button",{type:"button",className:"service-row-open",disabled:x||b,onClick:()=>{L(async()=>{(await r(w))?.passwordRequired&&m({kind:"add",input:w.serviceOrigin||w.url,passwordRequired:!0})})},"aria-label":b?`当前服务 ${w.label}`:`打开 ${w.label}`,children:[h.jsx("span",{className:"service-icon",children:h.jsx(Qs,{size:20})}),h.jsxs("span",{className:"service-row-copy",children:[h.jsx("span",{className:"service-name",children:w.label}),h.jsx("span",{className:"service-description",children:b?"当前服务":new URL(w.serviceOrigin||w.url).host})]}),b?h.jsx(xa,{size:17,className:"service-selected"}):h.jsx(Jt,{size:16,className:"service-muted"})]}),h.jsx("button",{type:"button",className:"service-icon-button","aria-label":`管理 ${w.label}`,disabled:x,onClick:()=>{m({kind:"edit",service:w}),A("")},children:h.jsx(ox,{size:19})})]},w.id)}),P.length===0&&h.jsx("p",{className:"service-empty",children:"还没有添加服务。连接你的电脑,或粘贴收到的邀请链接。"})]}),h.jsxs("div",{className:`service-actions${o?" service-actions-pair":""}`,children:[h.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:x,onClick:()=>{m({kind:"add"}),A("")},children:[h.jsx(df,{size:16}),"添加服务"]}),o&&h.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:x,onClick:o,children:[h.jsx(uf,{size:16}),"邀请设备"]})]})]});return h.jsxs("div",{className:"service-manager",children:[!i&&h.jsxs("div",{className:"service-heading",children:[C&&h.jsx("button",{type:"button",className:"service-icon-button","aria-label":"返回服务",disabled:x,onClick:_,children:h.jsx(cf,{size:20})}),h.jsx("h2",{children:C||"服务"})]}),g.kind==="relay-services"?n?.(R,T):g.kind==="routes"?e?.(R,T):g.kind==="list"?N:g.kind==="add"?h.jsx(bx,{onSave:w=>L(async()=>{const b=Ce(w);u(await Pn({id:b,url:b,label:new URL(b).host})),_()}),initialInput:g.input,passwordRequired:g.passwordRequired,busy:x,onSubmit:async(w,b)=>{let k;return await L(async()=>{k=await s(w,b),k?.passwordRequired||_()}),k}}):h.jsx(xx,{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:R,busy:x,canRemove:!t||!Pt(g.service,t),onSave:w=>{L(async()=>{u(await Pn({...R,label:w})),_()})},onRemove:()=>{L(async()=>{u(await ph(g.service.id)),_()})}}),v&&h.jsx("p",{className:"service-error",role:"alert",children:v})]})}function bx({busy:t,onSubmit:e,onSave:n,initialInput:r="",passwordRequired:s=!1}){const[o,i]=$.useState(r),[a,c]=$.useState(""),[l,d]=$.useState(s);return h.jsxs("form",{className:"service-form",onSubmit:async u=>{u.preventDefault(),(await e(o.trim(),l?a:void 0))?.passwordRequired&&d(!0),c("")},children:[h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"服务地址或邀请链接"}),h.jsx("input",{value:o,onChange:u=>{i(u.target.value),d(!1),c("")},disabled:t,required:!0,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:电脑地址:9834 或 https://…"})]}),l?h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"服务密码"}),h.jsx("input",{type:"password",value:a,onChange:u=>c(u.target.value),disabled:t,required:!0,autoFocus:!0,autoComplete:"current-password",placeholder:"输入这台服务的密码"})]}):h.jsx("p",{className:"service-help",children:"连接自己的服务,输入地址即可;收到邀请时,粘贴完整链接。"}),h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:t||!o.trim()||o.includes("#termdock-invite="),onClick:()=>{n(o.trim())},children:"仅保存,不连接"}),h.jsx("button",{type:"submit",className:"service-button service-primary",disabled:t||!o.trim()||l&&!a,children:t?h.jsxs(h.Fragment,{children:[h.jsx(We,{size:16,className:"service-spinning"}),"正在连接…"]}):l?"登录并连接":"继续"})]})}function xx({service:t,busy:e,canRemove:n,onSave:r,onRemove:s,onRoutes:o,onRelayServices:i}){const[a,c]=$.useState(t.label),[l,d]=$.useState(!1);return h.jsxs("form",{className:"service-form",onSubmit:u=>{u.preventDefault(),r(a.trim())},children:[h.jsxs("label",{className:"service-field",children:[h.jsx("span",{children:"服务名称"}),h.jsx("input",{value:a,onChange:u=>c(u.target.value),disabled:e,required:!0,maxLength:120,placeholder:"例如:办公室电脑"})]}),h.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url}),h.jsx("button",{type:"submit",className:"service-button service-primary",disabled:e||!a.trim(),children:"保存名称"}),i&&h.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:i,children:[h.jsxs("span",{className:"service-row-copy",children:[h.jsx("span",{className:"service-name",children:"可中转的服务"}),h.jsx("span",{className:"service-description",children:"通过这台服务连接其他电脑"})]}),h.jsx(Jt,{size:16})]}),o&&h.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:o,children:[h.jsxs("span",{className:"service-row-copy",children:[h.jsx("span",{className:"service-name",children:"备用连接"}),h.jsx("span",{className:"service-description",children:"添加其他网络地址或授权入口"})]}),h.jsx(Jt,{size:16})]}),n&&h.jsx("div",{className:"service-remove",children:l?h.jsxs(h.Fragment,{children:[h.jsxs("p",{className:"service-help",children:["从列表移除“",t.label,"”?不会停止服务或删除终端。"]}),h.jsxs("div",{className:"service-actions service-actions-pair",children:[h.jsx("button",{type:"button",className:"service-button service-secondary",disabled:e,onClick:()=>d(!1),children:"取消"}),h.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:s,children:"确认移除"})]})]}):h.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:()=>d(!0),children:"移除服务"})})]})}var hn={},Bo,il;function vx(){return il||(il=1,Bo=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Bo}var _o={},Tt={},al;function nn(){if(al)return Tt;al=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 Tt.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},Tt.getSymbolTotalCodewords=function(r){return e[r]},Tt.getBCHDigit=function(n){let r=0;for(;n!==0;)r++,n>>>=1;return r},Tt.setToSJISFunction=function(r){if(typeof r!="function")throw new Error('"toSJISFunc" is not a valid function.');t=r},Tt.isKanjiModeEnabled=function(){return typeof t<"u"},Tt.toSJIS=function(r){return t(r)},Tt}var Do={},cl;function va(){return cl||(cl=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,s){if(t.isValid(r))return r;try{return e(r)}catch{return s}}})(Do)),Do}var Fo,ll;function Ex(){if(ll)return Fo;ll=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++}},Fo=t,Fo}var Oo,dl;function Sx(){if(dl)return Oo;dl=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,s){const o=e*this.size+n;this.data[o]=r,s&&(this.reservedBit[o]=!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]},Oo=t,Oo}var Mo={},ul;function Ax(){return ul||(ul=1,(function(t){const e=nn().getSymbolSize;t.getRowColCoords=function(r){if(r===1)return[];const s=Math.floor(r/7)+2,o=e(r),i=o===145?26:Math.ceil((o-13)/(2*s-2))*2,a=[o-7];for(let c=1;c<s-1;c++)a[c]=a[c-1]-i;return a.push(6),a.reverse()},t.getPositions=function(r){const s=[],o=t.getRowColCoords(r),i=o.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||s.push([o[a],o[c]]);return s}})(Mo)),Mo}var jo={},fl;function kx(){if(fl)return jo;fl=1;const t=nn().getSymbolSize,e=7;return jo.getPositions=function(r){const s=t(r);return[[0,0],[s-e,0],[0,s-e]]},jo}var Uo={},hl;function Tx(){return hl||(hl=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(s){return s!=null&&s!==""&&!isNaN(s)&&s>=0&&s<=7},t.from=function(s){return t.isValid(s)?parseInt(s,10):void 0},t.getPenaltyN1=function(s){const o=s.size;let i=0,a=0,c=0,l=null,d=null;for(let u=0;u<o;u++){a=c=0,l=d=null;for(let f=0;f<o;f++){let p=s.get(u,f);p===l?a++:(a>=5&&(i+=e.N1+(a-5)),l=p,a=1),p=s.get(f,u),p===d?c++:(c>=5&&(i+=e.N1+(c-5)),d=p,c=1)}a>=5&&(i+=e.N1+(a-5)),c>=5&&(i+=e.N1+(c-5))}return i},t.getPenaltyN2=function(s){const o=s.size;let i=0;for(let a=0;a<o-1;a++)for(let c=0;c<o-1;c++){const l=s.get(a,c)+s.get(a,c+1)+s.get(a+1,c)+s.get(a+1,c+1);(l===4||l===0)&&i++}return i*e.N2},t.getPenaltyN3=function(s){const o=s.size;let i=0,a=0,c=0;for(let l=0;l<o;l++){a=c=0;for(let d=0;d<o;d++)a=a<<1&2047|s.get(l,d),d>=10&&(a===1488||a===93)&&i++,c=c<<1&2047|s.get(d,l),d>=10&&(c===1488||c===93)&&i++}return i*e.N3},t.getPenaltyN4=function(s){let o=0;const i=s.data.length;for(let c=0;c<i;c++)o+=s.data[c];return Math.abs(Math.ceil(o*100/i/5)-10)*e.N4};function n(r,s,o){switch(r){case t.Patterns.PATTERN000:return(s+o)%2===0;case t.Patterns.PATTERN001:return s%2===0;case t.Patterns.PATTERN010:return o%3===0;case t.Patterns.PATTERN011:return(s+o)%3===0;case t.Patterns.PATTERN100:return(Math.floor(s/2)+Math.floor(o/3))%2===0;case t.Patterns.PATTERN101:return s*o%2+s*o%3===0;case t.Patterns.PATTERN110:return(s*o%2+s*o%3)%2===0;case t.Patterns.PATTERN111:return(s*o%3+(s+o)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}t.applyMask=function(s,o){const i=o.size;for(let a=0;a<i;a++)for(let c=0;c<i;c++)o.isReserved(c,a)||o.xor(c,a,n(s,c,a))},t.getBestMask=function(s,o){const i=Object.keys(t.Patterns).length;let a=0,c=1/0;for(let l=0;l<i;l++){o(l),t.applyMask(l,s);const d=t.getPenaltyN1(s)+t.getPenaltyN2(s)+t.getPenaltyN3(s)+t.getPenaltyN4(s);t.applyMask(l,s),d<c&&(c=d,a=l)}return a}})(Uo)),Uo}var Jr={},pl;function hf(){if(pl)return Jr;pl=1;const t=va(),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 Jr.getBlocksCount=function(s,o){switch(o){case t.L:return e[(s-1)*4+0];case t.M:return e[(s-1)*4+1];case t.Q:return e[(s-1)*4+2];case t.H:return e[(s-1)*4+3];default:return}},Jr.getTotalCodewordsCount=function(s,o){switch(o){case t.L:return n[(s-1)*4+0];case t.M:return n[(s-1)*4+1];case t.Q:return n[(s-1)*4+2];case t.H:return n[(s-1)*4+3];default:return}},Jr}var $o={},nr={},gl;function Cx(){if(gl)return nr;gl=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let r=1;for(let s=0;s<255;s++)t[s]=r,e[r]=s,r<<=1,r&256&&(r^=285);for(let s=255;s<512;s++)t[s]=t[s-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,s){return r===0||s===0?0:t[e[r]+e[s]]},nr}var ml;function Ix(){return ml||(ml=1,(function(t){const e=Cx();t.mul=function(r,s){const o=new Uint8Array(r.length+s.length-1);for(let i=0;i<r.length;i++)for(let a=0;a<s.length;a++)o[i+a]^=e.mul(r[i],s[a]);return o},t.mod=function(r,s){let o=new Uint8Array(r);for(;o.length-s.length>=0;){const i=o[0];for(let c=0;c<s.length;c++)o[c]^=e.mul(s[c],i);let a=0;for(;a<o.length&&o[a]===0;)a++;o=o.slice(a)}return o},t.generateECPolynomial=function(r){let s=new Uint8Array([1]);for(let o=0;o<r;o++)s=t.mul(s,new Uint8Array([1,e.exp(o)]));return s}})($o)),$o}var Ho,wl;function Rx(){if(wl)return Ho;wl=1;const t=Ix();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 s=new Uint8Array(r.length+this.degree);s.set(r);const o=t.mod(s,this.genPoly),i=this.degree-o.length;if(i>0){const a=new Uint8Array(this.degree);return a.set(o,i),a}return o},Ho=e,Ho}var qo={},Ko={},zo={},yl;function pf(){return yl||(yl=1,zo.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),zo}var Qe={},bl;function gf(){if(bl)return Qe;bl=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
  ]))+`;Qe.KANJI=new RegExp(n,"g"),Qe.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Qe.BYTE=new RegExp(r,"g"),Qe.NUMERIC=new RegExp(t,"g"),Qe.ALPHANUMERIC=new RegExp(e,"g");const s=new RegExp("^"+n+"$"),o=new RegExp("^"+t+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Qe.testKanji=function(c){return s.test(c)},Qe.testNumeric=function(c){return o.test(c)},Qe.testAlphanumeric=function(c){return i.test(c)},Qe}var xl;function rn(){return xl||(xl=1,(function(t){const e=pf(),n=gf();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(o,i){if(!o.ccBits)throw new Error("Invalid mode: "+o);if(!e.isValid(i))throw new Error("Invalid version: "+i);return i>=1&&i<10?o.ccBits[0]:i<27?o.ccBits[1]:o.ccBits[2]},t.getBestModeForData=function(o){return n.testNumeric(o)?t.NUMERIC:n.testAlphanumeric(o)?t.ALPHANUMERIC:n.testKanji(o)?t.KANJI:t.BYTE},t.toString=function(o){if(o&&o.id)return o.id;throw new Error("Invalid mode")},t.isValid=function(o){return o&&o.bit&&o.ccBits};function r(s){if(typeof s!="string")throw new Error("Param is not a string");switch(s.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: "+s)}}t.from=function(o,i){if(t.isValid(o))return o;try{return r(o)}catch{return i}}})(Ko)),Ko}var vl;function Px(){return vl||(vl=1,(function(t){const e=nn(),n=hf(),r=va(),s=rn(),o=pf(),i=7973,a=e.getBCHDigit(i);function c(f,p,g){for(let m=1;m<=40;m++)if(p<=t.getCapacity(m,g,f))return m}function l(f,p){return s.getCharCountIndicator(f,p)+4}function d(f,p){let g=0;return f.forEach(function(m){const x=l(m.mode,p);g+=x+m.getBitsLength()}),g}function u(f,p){for(let g=1;g<=40;g++)if(d(f,g)<=t.getCapacity(g,p,s.MIXED))return g}t.from=function(p,g){return o.isValid(p)?parseInt(p,10):g},t.getCapacity=function(p,g,m){if(!o.isValid(p))throw new Error("Invalid QR Code version");typeof m>"u"&&(m=s.BYTE);const x=e.getSymbolTotalCodewords(p),y=n.getTotalCodewordsCount(p,g),T=(x-y)*8;if(m===s.MIXED)return T;const v=T-l(m,p);switch(m){case s.NUMERIC:return Math.floor(v/10*3);case s.ALPHANUMERIC:return Math.floor(v/11*2);case s.KANJI:return Math.floor(v/13);case s.BYTE:default:return Math.floor(v/8)}},t.getBestVersionForData=function(p,g){let m;const x=r.from(g,r.M);if(Array.isArray(p)){if(p.length>1)return u(p,x);if(p.length===0)return 1;m=p[0]}else m=p;return c(m.mode,m.getLength(),x)},t.getEncodedBits=function(p){if(!o.isValid(p)||p<7)throw new Error("Invalid QR Code version");let g=p<<12;for(;e.getBCHDigit(g)-a>=0;)g^=i<<e.getBCHDigit(g)-a;return p<<12|g}})(qo)),qo}var Vo={},El;function Nx(){if(El)return Vo;El=1;const t=nn(),e=1335,n=21522,r=t.getBCHDigit(e);return Vo.getEncodedBits=function(o,i){const a=o.bit<<3|i;let c=a<<10;for(;t.getBCHDigit(c)-r>=0;)c^=e<<t.getBCHDigit(c)-r;return(a<<10|c)^n},Vo}var Go={},Wo,Sl;function Lx(){if(Sl)return Wo;Sl=1;const t=rn();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 s,o,i;for(s=0;s+3<=this.data.length;s+=3)o=this.data.substr(s,3),i=parseInt(o,10),r.put(i,10);const a=this.data.length-s;a>0&&(o=this.data.substr(s),i=parseInt(o,10),r.put(i,a*3+1))},Wo=e,Wo}var Xo,Al;function Bx(){if(Al)return Xo;Al=1;const t=rn(),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(s){return 11*Math.floor(s/2)+6*(s%2)},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(s){let o;for(o=0;o+2<=this.data.length;o+=2){let i=e.indexOf(this.data[o])*45;i+=e.indexOf(this.data[o+1]),s.put(i,11)}this.data.length%2&&s.put(e.indexOf(this.data[o]),6)},Xo=n,Xo}var Yo,kl;function _x(){if(kl)return Yo;kl=1;const t=rn();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,s=this.data.length;r<s;r++)n.put(this.data[r],8)},Yo=e,Yo}var Zo,Tl;function Dx(){if(Tl)return Zo;Tl=1;const t=rn(),e=nn();function n(r){this.mode=t.KANJI,this.data=r}return n.getBitsLength=function(s){return s*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 s;for(s=0;s<this.data.length;s++){let o=e.toSJIS(this.data[s]);if(o>=33088&&o<=40956)o-=33088;else if(o>=57408&&o<=60351)o-=49472;else throw new Error("Invalid SJIS character: "+this.data[s]+`
4
4
  Make sure your charset is UTF-8`);o=(o>>>8&255)*192+(o&255),r.put(o,13)}},Zo=n,Zo}var Jo={exports:{}},Cl;function Fx(){return Cl||(Cl=1,(function(t){var e={single_source_shortest_paths:function(n,r,s){var o={},i={};i[r]=0;var a=e.PriorityQueue.make();a.push(r,0);for(var c,l,d,u,f,p,g,m,x;!a.empty();){c=a.pop(),l=c.value,u=c.cost,f=n[l]||{};for(d in f)f.hasOwnProperty(d)&&(p=f[d],g=u+p,m=i[d],x=typeof i[d]>"u",(x||m>g)&&(i[d]=g,a.push(d,g),o[d]=l))}if(typeof s<"u"&&typeof i[s]>"u"){var y=["Could not find a path from ",r," to ",s,"."].join("");throw new Error(y)}return o},extract_shortest_path_from_predecessor_list:function(n,r){for(var s=[],o=r;o;)s.push(o),n[o],o=n[o];return s.reverse(),s},find_path:function(n,r,s){var o=e.single_source_shortest_paths(n,r,s);return e.extract_shortest_path_from_predecessor_list(o,s)},PriorityQueue:{make:function(n){var r=e.PriorityQueue,s={},o;n=n||{};for(o in r)r.hasOwnProperty(o)&&(s[o]=r[o]);return s.queue=[],s.sorter=n.sorter||r.default_sorter,s},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var s={value:n,cost:r};this.queue.push(s),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=e})(Jo)),Jo.exports}var Il;function Ox(){return Il||(Il=1,(function(t){const e=rn(),n=Lx(),r=Bx(),s=_x(),o=Dx(),i=gf(),a=nn(),c=Fx();function l(y){return unescape(encodeURIComponent(y)).length}function d(y,T,v){const A=[];let _;for(;(_=y.exec(v))!==null;)A.push({data:_[0],index:_.index,mode:T,length:_[0].length});return A}function u(y){const T=d(i.NUMERIC,e.NUMERIC,y),v=d(i.ALPHANUMERIC,e.ALPHANUMERIC,y);let A,_;return a.isKanjiModeEnabled()?(A=d(i.BYTE,e.BYTE,y),_=d(i.KANJI,e.KANJI,y)):(A=d(i.BYTE_KANJI,e.BYTE,y),_=[]),T.concat(v,A,_).sort(function(L,R){return L.index-R.index}).map(function(L){return{data:L.data,mode:L.mode,length:L.length}})}function f(y,T){switch(T){case e.NUMERIC:return n.getBitsLength(y);case e.ALPHANUMERIC:return r.getBitsLength(y);case e.KANJI:return o.getBitsLength(y);case e.BYTE:return s.getBitsLength(y)}}function p(y){return y.reduce(function(T,v){const A=T.length-1>=0?T[T.length-1]:null;return A&&A.mode===v.mode?(T[T.length-1].data+=v.data,T):(T.push(v),T)},[])}function g(y){const T=[];for(let v=0;v<y.length;v++){const A=y[v];switch(A.mode){case e.NUMERIC:T.push([A,{data:A.data,mode:e.ALPHANUMERIC,length:A.length},{data:A.data,mode:e.BYTE,length:A.length}]);break;case e.ALPHANUMERIC:T.push([A,{data:A.data,mode:e.BYTE,length:A.length}]);break;case e.KANJI:T.push([A,{data:A.data,mode:e.BYTE,length:l(A.data)}]);break;case e.BYTE:T.push([{data:A.data,mode:e.BYTE,length:l(A.data)}])}}return T}function m(y,T){const v={},A={start:{}};let _=["start"];for(let C=0;C<y.length;C++){const L=y[C],R=[];for(let E=0;E<L.length;E++){const S=L[E],P=""+C+E;R.push(P),v[P]={node:S,lastCount:0},A[P]={};for(let N=0;N<_.length;N++){const w=_[N];v[w]&&v[w].node.mode===S.mode?(A[w][P]=f(v[w].lastCount+S.length,S.mode)-f(v[w].lastCount,S.mode),v[w].lastCount+=S.length):(v[w]&&(v[w].lastCount=S.length),A[w][P]=f(S.length,S.mode)+4+e.getCharCountIndicator(S.mode,T))}}_=R}for(let C=0;C<_.length;C++)A[_[C]].end=0;return{map:A,table:v}}function x(y,T){let v;const A=e.getBestModeForData(y);if(v=e.from(T,A),v!==e.BYTE&&v.bit<A.bit)throw new Error('"'+y+'" cannot be encoded with mode '+e.toString(v)+`.
5
5
  Suggested mode is: `+e.toString(A));switch(v===e.KANJI&&!a.isKanjiModeEnabled()&&(v=e.BYTE),v){case e.NUMERIC:return new n(y);case e.ALPHANUMERIC:return new r(y);case e.KANJI:return new o(y);case e.BYTE:return new s(y)}}t.fromArray=function(T){return T.reduce(function(v,A){return typeof A=="string"?v.push(x(A,null)):A.data&&v.push(x(A.data,A.mode)),v},[])},t.fromString=function(T,v){const A=u(T,a.isKanjiModeEnabled()),_=g(A),C=m(_,v),L=c.find_path(C.map,"start","end"),R=[];for(let E=1;E<L.length-1;E++)R.push(C.table[L[E]].node);return t.fromArray(p(R))},t.rawSplit=function(T){return t.fromArray(u(T,a.isKanjiModeEnabled()))}})(Go)),Go}var Rl;function Mx(){if(Rl)return _o;Rl=1;const t=nn(),e=va(),n=Ex(),r=Sx(),s=Ax(),o=kx(),i=Tx(),a=hf(),c=Rx(),l=Px(),d=Nx(),u=rn(),f=Ox();function p(C,L){const R=C.size,E=o.getPositions(L);for(let S=0;S<E.length;S++){const P=E[S][0],N=E[S][1];for(let w=-1;w<=7;w++)if(!(P+w<=-1||R<=P+w))for(let b=-1;b<=7;b++)N+b<=-1||R<=N+b||(w>=0&&w<=6&&(b===0||b===6)||b>=0&&b<=6&&(w===0||w===6)||w>=2&&w<=4&&b>=2&&b<=4?C.set(P+w,N+b,!0,!0):C.set(P+w,N+b,!1,!0))}}function g(C){const L=C.size;for(let R=8;R<L-8;R++){const E=R%2===0;C.set(R,6,E,!0),C.set(6,R,E,!0)}}function m(C,L){const R=s.getPositions(L);for(let E=0;E<R.length;E++){const S=R[E][0],P=R[E][1];for(let N=-2;N<=2;N++)for(let w=-2;w<=2;w++)N===-2||N===2||w===-2||w===2||N===0&&w===0?C.set(S+N,P+w,!0,!0):C.set(S+N,P+w,!1,!0)}}function x(C,L){const R=C.size,E=l.getEncodedBits(L);let S,P,N;for(let w=0;w<18;w++)S=Math.floor(w/3),P=w%3+R-8-3,N=(E>>w&1)===1,C.set(S,P,N,!0),C.set(P,S,N,!0)}function y(C,L,R){const E=C.size,S=d.getEncodedBits(L,R);let P,N;for(P=0;P<15;P++)N=(S>>P&1)===1,P<6?C.set(P,8,N,!0):P<8?C.set(P+1,8,N,!0):C.set(E-15+P,8,N,!0),P<8?C.set(8,E-P-1,N,!0):P<9?C.set(8,15-P-1+1,N,!0):C.set(8,15-P-1,N,!0);C.set(E-8,8,1,!0)}function T(C,L){const R=C.size;let E=-1,S=R-1,P=7,N=0;for(let w=R-1;w>0;w-=2)for(w===6&&w--;;){for(let b=0;b<2;b++)if(!C.isReserved(S,w-b)){let k=!1;N<L.length&&(k=(L[N]>>>P&1)===1),C.set(S,w-b,k),P--,P===-1&&(N++,P=7)}if(S+=E,S<0||R<=S){S-=E,E=-E;break}}}function v(C,L,R){const E=new n;R.forEach(function(b){E.put(b.mode.bit,4),E.put(b.getLength(),u.getCharCountIndicator(b.mode,C)),b.write(E)});const S=t.getSymbolTotalCodewords(C),P=a.getTotalCodewordsCount(C,L),N=(S-P)*8;for(E.getLengthInBits()+4<=N&&E.put(0,4);E.getLengthInBits()%8!==0;)E.putBit(0);const w=(N-E.getLengthInBits())/8;for(let b=0;b<w;b++)E.put(b%2?17:236,8);return A(E,C,L)}function A(C,L,R){const E=t.getSymbolTotalCodewords(L),S=a.getTotalCodewordsCount(L,R),P=E-S,N=a.getBlocksCount(L,R),w=E%N,b=N-w,k=Math.floor(E/N),B=Math.floor(P/N),M=B+1,U=k-B,D=new c(U);let I=0;const F=new Array(N),O=new Array(N);let K=0;const q=new Uint8Array(C.buffer);for(let V=0;V<N;V++){const Z=V<b?B:M;F[V]=q.slice(I,I+Z),O[V]=D.encode(F[V]),I+=Z,K=Math.max(K,Z)}const H=new Uint8Array(E);let G=0,W,X;for(W=0;W<K;W++)for(X=0;X<N;X++)W<F[X].length&&(H[G++]=F[X][W]);for(W=0;W<U;W++)for(X=0;X<N;X++)H[G++]=O[X][W];return H}function _(C,L,R,E){let S;if(Array.isArray(C))S=f.fromArray(C);else if(typeof C=="string"){let k=L;if(!k){const B=f.rawSplit(C);k=l.getBestVersionForData(B,R)}S=f.fromString(C,k||40)}else throw new Error("Invalid data");const P=l.getBestVersionForData(S,R);if(!P)throw new Error("The amount of data is too big to be stored in a QR Code");if(!L)L=P;else if(L<P)throw new Error(`
@@ -31,4 +31,4 @@ Stack:
31
31
  ${t.stack}`:"",e?`
32
32
  React component stack:
33
33
  ${e.trim()}`:""].filter(Boolean).join(`
34
- `)}async function DE(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 FE({error:t,componentStack:e}){const{t:n}=La(),[r,s]=je.useState("idle"),o=async()=>{const i=_E(t,e,{url:window.location.href,userAgent:navigator.userAgent,capturedAt:new Date().toISOString()});s(await DE(i)?"copied":"failed")};return h.jsx("div",{className:"flex h-full items-center justify-center p-4",children:h.jsxs("div",{className:"flex flex-col items-center gap-3 text-center max-w-md",children:[h.jsx("div",{className:"w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center",children:h.jsx("svg",{className:"w-6 h-6 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:h.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"})})}),h.jsxs("div",{className:"space-y-1",children:[h.jsx("h3",{className:"font-medium text-foreground",children:n("errorBoundary.title")}),h.jsx("p",{className:"text-sm text-muted-foreground",children:t?.message||n("errorBoundary.unexpected")})]}),h.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-center gap-2",children:[h.jsx("button",{type:"button",onClick:()=>{o()},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")}),h.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 OE extends je.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:h.jsx(FE,{error:this.state.error,componentStack:this.state.componentStack}):this.props.children}}const ME="debug",jE="termdock:debug";function jl(t){return t?new Set(t.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean)):new Set}function UE(){if(typeof window>"u")return new Set;const t=jl(new URLSearchParams(window.location.search).get(ME));let e=new Set;try{e=jl(window.localStorage.getItem(jE))}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 $E(t){const e=UE();return e.has("*")||e.has(t)}function HE(t){const e=$E(t);return(...n)=>{e&&console.log(`[debug:${t}]`,...n)}}const Ul=80,qE=60,KE="termdock:viewport-keyboard-change",zE="termdock:viewport-layout-change",ht=240,$l=640,Hl=360;function VE({measuredHeight:t,documentVisible:e,editableFocused:n}){return e&&n&&t>0}function ql(){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},Mf=(t,e)=>{const n=t.map(Ds).filter(r=>r>0);return n.find(r=>r>=ht)??n[0]??e},wr=()=>typeof window>"u"?$l:Mf([window.innerHeight,document.documentElement?.clientHeight,document.body?.clientHeight,window.visualViewport?.height,window.screen?.availHeight,window.screen?.height],$l),jf=()=>typeof window>"u"?Hl:Mf([window.innerWidth,document.documentElement?.clientWidth,document.body?.clientWidth,window.visualViewport?.width,window.screen?.availWidth,window.screen?.width],Hl),ts=t=>{const e=Number.parseFloat(t||"0");return Number.isFinite(e)?Math.max(0,Math.round(e)):0},GE=()=>typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,WE=()=>typeof window>"u"?!1:navigator.standalone===!0||window.matchMedia?.("(display-mode: standalone)").matches===!0,Uf=()=>{if(typeof window>"u"||!GE()||!WE())return{top:0,right:0,bottom:0,left:0};if(!(wr()>=jf()))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),s=Math.max(e,n);return r>=700?{top:20,right:0,bottom:20,left:0}:s<780?{top:20,right:0,bottom:0,left:0}:{top:s>=852?59:s>=844?47:44,right:0,bottom:34,left:0}};function XE(t="--app-vh"){if(typeof window>"u"||typeof document>"u")return;const e=Ds(window.visualViewport?.height),n=Math.max(0,Math.round(window.visualViewport?.offsetTop??0)),r=wr(),o=e>=ht?Math.min(r,e+n):r,i=Math.max(r,o),a=document.documentElement.style;a.setProperty(t,`${Math.max(o,ht)}px`),a.setProperty("--app-base-vh",`${Math.max(i,ht)}px`),a.setProperty("--app-visible-vh",`${Math.max(o,ht)}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=Uf();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 xS(t={}){const{cssVarName:e="--app-vh"}=t,n=je.useMemo(()=>HE("viewport"),[]),r=je.useCallback(()=>{if(typeof window>"u")return 0;const d=window.visualViewport,u=wr();if(!d)return u;const f=Ds(d.height);if(f<ht&&u>=ht)return u;const p=d.offsetTop,m=f<u-1&&p>0&&p<=96?f+p:f,x=Math.max(0,Math.min(u,m));return x>0?Math.round(x):u},[]),[s,o]=je.useState(r),i=je.useRef(0),a=je.useRef(0),c=je.useRef(0),l=je.useRef(!1);return je.useEffect(()=>{if(typeof window>"u")return;let d=null,u=null;const f=()=>{if(u?.isConnected)return u;try{return u=document.createElement("div"),u.setAttribute("aria-hidden","true"),u.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(u),u}catch{}return null},p=()=>{let N={top:0,right:0,bottom:0,left:0};try{const k=f();if(k){const B=getComputedStyle(k);N={top:ts(B.paddingTop),right:ts(B.paddingRight),bottom:ts(B.paddingBottom),left:ts(B.paddingLeft)}}}catch{}const w=Uf(),b={top:Math.max(N.top,w.top),right:Math.max(N.right,w.right),bottom:Math.max(N.bottom,w.bottom),left:Math.max(N.left,w.left)};return document.documentElement.style.setProperty("--safe-top-inset",`${b.top}px`),document.documentElement.style.setProperty("--safe-right-inset",`${b.right}px`),document.documentElement.style.setProperty("--safe-bottom-inset",`${b.bottom}px`),document.documentElement.style.setProperty("--safe-left-inset",`${b.left}px`),b},g=(N,w,b,k)=>{const B=Math.max(w,b);if(i.current===0){i.current=B,a.current=N,document.documentElement.style.setProperty("--app-base-vh",`${B}px`);return}const M=Math.abs(N-a.current),U=k<=Ul;(M>qE||U)&&(i.current=B,a.current=N,document.documentElement.style.setProperty("--app-base-vh",`${B}px`))},m=(N="event")=>{d=null;const w=r(),b=Math.round(window.visualViewport?.offsetTop??0),k=Ds(window.visualViewport?.height),B=k>=ht?k:w,M=wr(),U=jf(),D=Math.max(0,B+b),I=p(),F=I.bottom,O=Math.max(0,i.current-D-F);g(U,M,D,O),o(bt=>bt===w?bt:w);const K=Number.parseInt(document.documentElement.style.getPropertyValue(e)||"0",10);document.documentElement.style.setProperty(e,`${w}px`),document.documentElement.style.setProperty("--app-vv-offset-top",`${b}px`);const q=i.current,H=Math.min(w,B),G=Math.max(0,Math.min(q,D)),W=Math.max(0,Math.round(q-G-F)),X=ql(),V=VE({measuredHeight:W,documentVisible:document.visibilityState==="visible",editableFocused:X}),Z=V?W:0,ke=Z>=Ul,Fe=-Z,rt=Z;document.documentElement.style.setProperty("--kb-translate-y",`${Fe}px`),document.documentElement.style.setProperty("--kb-margin-top",`${rt}px`),document.documentElement.style.setProperty("--kb-height",`${Z}px`),document.documentElement.style.setProperty("--app-visible-vh",`${G}px`);const Ie=Math.abs(Z-c.current)>1,Dt=ke!==l.current;(Ie||Dt)&&(c.current=Z,l.current=ke,document.dispatchEvent(new CustomEvent(KE,{detail:{baseHeight:q,visibleHeight:G,visualViewportHeight:B,offsetTop:b,keyboardHeight:Z,isOpen:ke,source:N}}))),(K!==w||b>0||Ie||Dt)&&n("sync",{cssVarName:e,innerHeight:M,baseHeight:q,rawViewportHeight:B,offsetTop:b,visibleHeight:G,rawHeight:w,appliedHeight:w,keyboardViewportHeight:H,measuredKeyboardHeight:W,editableFocused:X,applyKeyboardInset:V,keyboardHeight:Z,isKeyboardOpen:ke,safeAreaInsets:I,source:N}),document.dispatchEvent(new CustomEvent(zE,{detail:{height:w,baseHeight:q,visibleHeight:G,offsetTop:b,source:N}}))},x=(N="event")=>{(N.includes("visibilitychange")||N.includes("pageshow"))&&n("schedule",{source:N}),d===null&&(d=window.requestAnimationFrame(()=>m(N)))};x("mount");const y=()=>x("resize"),T=()=>x("orientationchange"),v=()=>x("visualViewport.resize"),A=()=>x("visualViewport.scroll"),_=()=>x("focusin"),C=()=>x("focusout"),L=N=>{const w=document.activeElement;w instanceof HTMLElement&&ql()&&w.blur(),c.current=0,l.current=!1;const b=Math.max(i.current,wr(),ht),k=document.documentElement.style;k.setProperty(e,`${b}px`),k.setProperty("--app-visible-vh",`${b}px`),k.setProperty("--app-vv-offset-top","0px"),k.setProperty("--kb-translate-y","0px"),k.setProperty("--kb-margin-top","0px"),k.setProperty("--kb-height","0px"),o(B=>B===b?B:b),n("keyboard session reset",{source:N,baseHeight:b})};window.addEventListener("resize",y),window.addEventListener("orientationchange",T),window.visualViewport?.addEventListener("resize",v),window.visualViewport?.addEventListener("scroll",A),document.addEventListener("focusin",_),document.addEventListener("focusout",C);const R=N=>{n("resume",{source:N,innerHeight:Math.round(window.innerHeight),visualViewport:window.visualViewport?{width:Math.round(window.visualViewport.width),height:Math.round(window.visualViewport.height),offsetTop:Math.round(window.visualViewport.offsetTop)}:null,hidden:document.hidden}),x(N)},E=()=>{document.hidden?L("visibilitychange:hidden"):R("visibilitychange")},S=()=>R("pageshow"),P=()=>L("pagehide");return document.addEventListener("visibilitychange",E),window.addEventListener("pageshow",S),window.addEventListener("pagehide",P),()=>{window.removeEventListener("resize",y),window.removeEventListener("orientationchange",T),window.visualViewport?.removeEventListener("resize",v),window.visualViewport?.removeEventListener("scroll",A),document.removeEventListener("focusin",_),document.removeEventListener("focusout",C),document.removeEventListener("visibilitychange",E),window.removeEventListener("pageshow",S),window.removeEventListener("pagehide",P),d!==null&&window.cancelAnimationFrame(d),u?.remove()}},[e,n,r]),s}const Kl=5*6e4;let $i,$f=!1,Hf=!1,zl=!1;const Hi=new Set;function Vl(){$f=!0,Hi.forEach(t=>t())}function YE(){return $.useSyncExternalStore(t=>(Hi.add(t),()=>{Hi.delete(t)}),()=>$f,()=>!1)}function ZE(){window.dispatchEvent(new Event("termdock:before-update")),Hf=!0,$i?.waiting?$i.waiting.postMessage({type:"SKIP_WAITING"}):window.location.reload()}function JE(t,e){let n=t;return()=>{if(!n){n=!0;return}e()}}function QE(){if(zl||typeof window>"u"||!("serviceWorker"in navigator))return;zl=!0,navigator.serviceWorker.addEventListener("controllerchange",JE(!!navigator.serviceWorker.controller,()=>{Hf?window.location.reload():Vl()}));const t=()=>{navigator.serviceWorker.register("/sw.js",{scope:"/",updateViaCache:"none"}).then(e=>{$i=e;const n=()=>{e.waiting&&Vl()},r=()=>{const i=e.installing;i?.addEventListener("statechange",()=>{i.state==="installed"&&navigator.serviceWorker.controller&&n()})};e.addEventListener("updatefound",r),r(),n();let s=0;const o=()=>{document.visibilityState!=="visible"||Date.now()-s<Kl||(s=Date.now(),e.update().then(n).catch(()=>{}))};o(),window.setInterval(o,Kl),document.addEventListener("visibilitychange",o)}).catch(()=>{})};document.readyState==="complete"?t():window.addEventListener("load",t,{once:!0})}function eS(){const t=YE(),[e,n]=$.useState(!1),{locale:r}=La();if(!t||e)return null;const s=r==="zh";return h.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:[h.jsx("span",{children:s?"新版本已就绪":"An update is ready"}),h.jsx("button",{type:"button",className:"whitespace-nowrap text-primary",onClick:ZE,children:s?"重新加载":"Reload"}),h.jsx("button",{type:"button",className:"whitespace-nowrap text-muted-foreground",onClick:()=>n(!0),children:s?"稍后":"Later"})]})}function tS(t){const e=document.querySelector('meta[name="theme-color"]');e&&e.setAttribute("content",t==="light"?"#FFFCF0":"#1C1B1A")}const nS=$.lazy(()=>Un(()=>import("./App-DBds0RoW.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,7,3,8]))),rS=$.lazy(()=>Un(()=>import("./DagPlayground-CYL8vhaU.js"),__vite__mapDeps([9,10,2,1,11,8,3])).then(t=>({default:t.DagPlayground}))),sS=$.lazy(()=>Un(()=>import("./DiffLab-COUjebir.js"),__vite__mapDeps([12,2,1,13,7,14,3])).then(t=>({default:t.DiffLab}))),oS=$.lazy(()=>Un(()=>import("./DiffReviewLab-Aqib8Qr6.js"),__vite__mapDeps([15,2,1,16,5,6,7,11,13,14,3])).then(t=>({default:t.DiffReviewLab})));XE();F0();QE();try{const t=JSON.parse(window.localStorage.getItem("termdock-color-theme")||"null");(t==="dark"||t==="light")&&(document.documentElement.dataset.theme=t,tS(t))}catch{}hh.createRoot(document.getElementById("root")).render(h.jsx(je.StrictMode,{children:h.jsxs(RE,{children:[h.jsx(eS,{}),h.jsx(OE,{children:h.jsx($.Suspense,{fallback:h.jsx("div",{className:"termdock-boot",role:"status",children:"Loading Termdock"}),children:(()=>{const t=new URLSearchParams(window.location.search);return t.get("dag-playground")==="1"?h.jsx(rS,{}):t.get("diff-review-lab")==="1"?h.jsx(oS,{}):t.get("diff-lab")==="1"?h.jsx(sS,{}):h.jsx(BE,{children:h.jsx(nS,{})})})()})})]})}));export{yf as $,Ia as A,Jv as B,xa as C,Ov as D,xf as E,av as F,kv as G,Js as H,Yt as I,d1 as J,HE as K,We as L,bf as M,Ne as N,Av as O,dx as P,Eo as Q,g1 as R,Qs as S,Ue as T,G1 as U,zE as V,zv as W,gx as X,p1 as Y,V1 as Z,Un as _,cf as a,lv as a$,cv as a0,Uv as a1,ft as a2,i1 as a3,o1 as a4,l1 as a5,Sv as a6,sE as a7,tE as a8,eE as a9,Lf as aA,N1 as aB,B1 as aC,T1 as aD,P1 as aE,I1 as aF,h as aG,mS as aH,qv as aI,fE as aJ,w1 as aK,wE as aL,vE as aM,F1 as aN,$v as aO,s1 as aP,Y1 as aQ,Xx as aR,Wv as aS,y1 as aT,Cv as aU,q1 as aV,U1 as aW,H1 as aX,z1 as aY,wS as aZ,Iv as a_,nE as aa,n1 as ab,L1 as ac,J1 as ad,dE as ae,$1 as af,cE as ag,Q1 as ah,X1 as ai,E1 as aj,rE as ak,Gv as al,Rf as am,ov as an,Wx as ao,t1 as ap,Hv as aq,Qv as ar,aE as as,Bf as at,ql as au,gu as av,Du as aw,K1 as ax,a1 as ay,u1 as az,J0 as b,mE as b0,b1,xE as b2,Zv as b3,Yv as b4,S1 as b5,x1 as b6,e1 as b7,A1 as b8,v1 as b9,Rv as bA,pS as bB,tS as bC,fS as bD,c1 as bE,h1 as bF,r1 as bG,Xv as bH,Pf as bI,W1 as bJ,La as bK,xS as bL,M1 as bM,yS as bN,Dv as ba,Mv as bb,Kv as bc,m1 as bd,hS as be,pE as bf,lE as bg,hE as bh,yE as bi,ye as bj,O1 as bk,SE as bl,D0 as bm,ch as bn,Bv as bo,EE as bp,_v as bq,Pv as br,Tv as bs,Lv as bt,Fv as bu,gE as bv,Cf as bw,Ev as bx,So as by,bE as bz,tx as c,Jt as d,lf as e,ox as f,OE as g,df as h,Nv as i,la as j,wt as k,bS as l,uE as m,gS as n,_1 as o,R1 as p,da as q,j1 as r,I0 as s,f1 as t,ey as u,iv as v,jv as w,Kt as x,iE as y,oE as z};
34
+ `)}async function DE(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 FE({error:t,componentStack:e}){const{t:n}=La(),[r,s]=je.useState("idle"),o=async()=>{const i=_E(t,e,{url:window.location.href,userAgent:navigator.userAgent,capturedAt:new Date().toISOString()});s(await DE(i)?"copied":"failed")};return h.jsx("div",{className:"flex h-full items-center justify-center p-4",children:h.jsxs("div",{className:"flex flex-col items-center gap-3 text-center max-w-md",children:[h.jsx("div",{className:"w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center",children:h.jsx("svg",{className:"w-6 h-6 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:h.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"})})}),h.jsxs("div",{className:"space-y-1",children:[h.jsx("h3",{className:"font-medium text-foreground",children:n("errorBoundary.title")}),h.jsx("p",{className:"text-sm text-muted-foreground",children:t?.message||n("errorBoundary.unexpected")})]}),h.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-center gap-2",children:[h.jsx("button",{type:"button",onClick:()=>{o()},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")}),h.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 OE extends je.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:h.jsx(FE,{error:this.state.error,componentStack:this.state.componentStack}):this.props.children}}const ME="debug",jE="termdock:debug";function jl(t){return t?new Set(t.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean)):new Set}function UE(){if(typeof window>"u")return new Set;const t=jl(new URLSearchParams(window.location.search).get(ME));let e=new Set;try{e=jl(window.localStorage.getItem(jE))}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 $E(t){const e=UE();return e.has("*")||e.has(t)}function HE(t){const e=$E(t);return(...n)=>{e&&console.log(`[debug:${t}]`,...n)}}const Ul=80,qE=60,KE="termdock:viewport-keyboard-change",zE="termdock:viewport-layout-change",ht=240,$l=640,Hl=360;function VE({measuredHeight:t,documentVisible:e,editableFocused:n}){return e&&n&&t>0}function ql(){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},Mf=(t,e)=>{const n=t.map(Ds).filter(r=>r>0);return n.find(r=>r>=ht)??n[0]??e},wr=()=>typeof window>"u"?$l:Mf([window.innerHeight,document.documentElement?.clientHeight,document.body?.clientHeight,window.visualViewport?.height,window.screen?.availHeight,window.screen?.height],$l),jf=()=>typeof window>"u"?Hl:Mf([window.innerWidth,document.documentElement?.clientWidth,document.body?.clientWidth,window.visualViewport?.width,window.screen?.availWidth,window.screen?.width],Hl),ts=t=>{const e=Number.parseFloat(t||"0");return Number.isFinite(e)?Math.max(0,Math.round(e)):0},GE=()=>typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,WE=()=>typeof window>"u"?!1:navigator.standalone===!0||window.matchMedia?.("(display-mode: standalone)").matches===!0,Uf=()=>{if(typeof window>"u"||!GE()||!WE())return{top:0,right:0,bottom:0,left:0};if(!(wr()>=jf()))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),s=Math.max(e,n);return r>=700?{top:20,right:0,bottom:20,left:0}:s<780?{top:20,right:0,bottom:0,left:0}:{top:s>=852?59:s>=844?47:44,right:0,bottom:34,left:0}};function XE(t="--app-vh"){if(typeof window>"u"||typeof document>"u")return;const e=Ds(window.visualViewport?.height),n=Math.max(0,Math.round(window.visualViewport?.offsetTop??0)),r=wr(),o=e>=ht?Math.min(r,e+n):r,i=Math.max(r,o),a=document.documentElement.style;a.setProperty(t,`${Math.max(o,ht)}px`),a.setProperty("--app-base-vh",`${Math.max(i,ht)}px`),a.setProperty("--app-visible-vh",`${Math.max(o,ht)}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=Uf();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 xS(t={}){const{cssVarName:e="--app-vh"}=t,n=je.useMemo(()=>HE("viewport"),[]),r=je.useCallback(()=>{if(typeof window>"u")return 0;const d=window.visualViewport,u=wr();if(!d)return u;const f=Ds(d.height);if(f<ht&&u>=ht)return u;const p=d.offsetTop,m=f<u-1&&p>0&&p<=96?f+p:f,x=Math.max(0,Math.min(u,m));return x>0?Math.round(x):u},[]),[s,o]=je.useState(r),i=je.useRef(0),a=je.useRef(0),c=je.useRef(0),l=je.useRef(!1);return je.useEffect(()=>{if(typeof window>"u")return;let d=null,u=null;const f=()=>{if(u?.isConnected)return u;try{return u=document.createElement("div"),u.setAttribute("aria-hidden","true"),u.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(u),u}catch{}return null},p=()=>{let N={top:0,right:0,bottom:0,left:0};try{const k=f();if(k){const B=getComputedStyle(k);N={top:ts(B.paddingTop),right:ts(B.paddingRight),bottom:ts(B.paddingBottom),left:ts(B.paddingLeft)}}}catch{}const w=Uf(),b={top:Math.max(N.top,w.top),right:Math.max(N.right,w.right),bottom:Math.max(N.bottom,w.bottom),left:Math.max(N.left,w.left)};return document.documentElement.style.setProperty("--safe-top-inset",`${b.top}px`),document.documentElement.style.setProperty("--safe-right-inset",`${b.right}px`),document.documentElement.style.setProperty("--safe-bottom-inset",`${b.bottom}px`),document.documentElement.style.setProperty("--safe-left-inset",`${b.left}px`),b},g=(N,w,b,k)=>{const B=Math.max(w,b);if(i.current===0){i.current=B,a.current=N,document.documentElement.style.setProperty("--app-base-vh",`${B}px`);return}const M=Math.abs(N-a.current),U=k<=Ul;(M>qE||U)&&(i.current=B,a.current=N,document.documentElement.style.setProperty("--app-base-vh",`${B}px`))},m=(N="event")=>{d=null;const w=r(),b=Math.round(window.visualViewport?.offsetTop??0),k=Ds(window.visualViewport?.height),B=k>=ht?k:w,M=wr(),U=jf(),D=Math.max(0,B+b),I=p(),F=I.bottom,O=Math.max(0,i.current-D-F);g(U,M,D,O),o(bt=>bt===w?bt:w);const K=Number.parseInt(document.documentElement.style.getPropertyValue(e)||"0",10);document.documentElement.style.setProperty(e,`${w}px`),document.documentElement.style.setProperty("--app-vv-offset-top",`${b}px`);const q=i.current,H=Math.min(w,B),G=Math.max(0,Math.min(q,D)),W=Math.max(0,Math.round(q-G-F)),X=ql(),V=VE({measuredHeight:W,documentVisible:document.visibilityState==="visible",editableFocused:X}),Z=V?W:0,ke=Z>=Ul,Fe=-Z,rt=Z;document.documentElement.style.setProperty("--kb-translate-y",`${Fe}px`),document.documentElement.style.setProperty("--kb-margin-top",`${rt}px`),document.documentElement.style.setProperty("--kb-height",`${Z}px`),document.documentElement.style.setProperty("--app-visible-vh",`${G}px`);const Ie=Math.abs(Z-c.current)>1,Dt=ke!==l.current;(Ie||Dt)&&(c.current=Z,l.current=ke,document.dispatchEvent(new CustomEvent(KE,{detail:{baseHeight:q,visibleHeight:G,visualViewportHeight:B,offsetTop:b,keyboardHeight:Z,isOpen:ke,source:N}}))),(K!==w||b>0||Ie||Dt)&&n("sync",{cssVarName:e,innerHeight:M,baseHeight:q,rawViewportHeight:B,offsetTop:b,visibleHeight:G,rawHeight:w,appliedHeight:w,keyboardViewportHeight:H,measuredKeyboardHeight:W,editableFocused:X,applyKeyboardInset:V,keyboardHeight:Z,isKeyboardOpen:ke,safeAreaInsets:I,source:N}),document.dispatchEvent(new CustomEvent(zE,{detail:{height:w,baseHeight:q,visibleHeight:G,offsetTop:b,source:N}}))},x=(N="event")=>{(N.includes("visibilitychange")||N.includes("pageshow"))&&n("schedule",{source:N}),d===null&&(d=window.requestAnimationFrame(()=>m(N)))};x("mount");const y=()=>x("resize"),T=()=>x("orientationchange"),v=()=>x("visualViewport.resize"),A=()=>x("visualViewport.scroll"),_=()=>x("focusin"),C=()=>x("focusout"),L=N=>{const w=document.activeElement;w instanceof HTMLElement&&ql()&&w.blur(),c.current=0,l.current=!1;const b=Math.max(i.current,wr(),ht),k=document.documentElement.style;k.setProperty(e,`${b}px`),k.setProperty("--app-visible-vh",`${b}px`),k.setProperty("--app-vv-offset-top","0px"),k.setProperty("--kb-translate-y","0px"),k.setProperty("--kb-margin-top","0px"),k.setProperty("--kb-height","0px"),o(B=>B===b?B:b),n("keyboard session reset",{source:N,baseHeight:b})};window.addEventListener("resize",y),window.addEventListener("orientationchange",T),window.visualViewport?.addEventListener("resize",v),window.visualViewport?.addEventListener("scroll",A),document.addEventListener("focusin",_),document.addEventListener("focusout",C);const R=N=>{n("resume",{source:N,innerHeight:Math.round(window.innerHeight),visualViewport:window.visualViewport?{width:Math.round(window.visualViewport.width),height:Math.round(window.visualViewport.height),offsetTop:Math.round(window.visualViewport.offsetTop)}:null,hidden:document.hidden}),x(N)},E=()=>{document.hidden?L("visibilitychange:hidden"):R("visibilitychange")},S=()=>R("pageshow"),P=()=>L("pagehide");return document.addEventListener("visibilitychange",E),window.addEventListener("pageshow",S),window.addEventListener("pagehide",P),()=>{window.removeEventListener("resize",y),window.removeEventListener("orientationchange",T),window.visualViewport?.removeEventListener("resize",v),window.visualViewport?.removeEventListener("scroll",A),document.removeEventListener("focusin",_),document.removeEventListener("focusout",C),document.removeEventListener("visibilitychange",E),window.removeEventListener("pageshow",S),window.removeEventListener("pagehide",P),d!==null&&window.cancelAnimationFrame(d),u?.remove()}},[e,n,r]),s}const Kl=5*6e4;let $i,$f=!1,Hf=!1,zl=!1;const Hi=new Set;function Vl(){$f=!0,Hi.forEach(t=>t())}function YE(){return $.useSyncExternalStore(t=>(Hi.add(t),()=>{Hi.delete(t)}),()=>$f,()=>!1)}function ZE(){window.dispatchEvent(new Event("termdock:before-update")),Hf=!0,$i?.waiting?$i.waiting.postMessage({type:"SKIP_WAITING"}):window.location.reload()}function JE(t,e){let n=t;return()=>{if(!n){n=!0;return}e()}}function QE(){if(zl||typeof window>"u"||!("serviceWorker"in navigator))return;zl=!0,navigator.serviceWorker.addEventListener("controllerchange",JE(!!navigator.serviceWorker.controller,()=>{Hf?window.location.reload():Vl()}));const t=()=>{navigator.serviceWorker.register("/sw.js",{scope:"/",updateViaCache:"none"}).then(e=>{$i=e;const n=()=>{e.waiting&&Vl()},r=()=>{const i=e.installing;i?.addEventListener("statechange",()=>{i.state==="installed"&&navigator.serviceWorker.controller&&n()})};e.addEventListener("updatefound",r),r(),n();let s=0;const o=()=>{document.visibilityState!=="visible"||Date.now()-s<Kl||(s=Date.now(),e.update().then(n).catch(()=>{}))};o(),window.setInterval(o,Kl),document.addEventListener("visibilitychange",o)}).catch(()=>{})};document.readyState==="complete"?t():window.addEventListener("load",t,{once:!0})}function eS(){const t=YE(),[e,n]=$.useState(!1),{locale:r}=La();if(!t||e)return null;const s=r==="zh";return h.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:[h.jsx("span",{children:s?"新版本已就绪":"An update is ready"}),h.jsx("button",{type:"button",className:"whitespace-nowrap text-primary",onClick:ZE,children:s?"重新加载":"Reload"}),h.jsx("button",{type:"button",className:"whitespace-nowrap text-muted-foreground",onClick:()=>n(!0),children:s?"稍后":"Later"})]})}function tS(t){const e=document.querySelector('meta[name="theme-color"]');e&&e.setAttribute("content",t==="light"?"#FFFCF0":"#1C1B1A")}const nS=$.lazy(()=>Un(()=>import("./App-B19QjfSB.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,7,3,8]))),rS=$.lazy(()=>Un(()=>import("./DagPlayground-qziF3toU.js"),__vite__mapDeps([9,10,2,1,11,8,3])).then(t=>({default:t.DagPlayground}))),sS=$.lazy(()=>Un(()=>import("./DiffLab-CDUdFYRL.js"),__vite__mapDeps([12,2,1,13,7,14,3])).then(t=>({default:t.DiffLab}))),oS=$.lazy(()=>Un(()=>import("./DiffReviewLab-DUMlD_0N.js"),__vite__mapDeps([15,2,1,16,5,6,7,11,13,14,3])).then(t=>({default:t.DiffReviewLab})));XE();F0();QE();try{const t=JSON.parse(window.localStorage.getItem("termdock-color-theme")||"null");(t==="dark"||t==="light")&&(document.documentElement.dataset.theme=t,tS(t))}catch{}hh.createRoot(document.getElementById("root")).render(h.jsx(je.StrictMode,{children:h.jsxs(RE,{children:[h.jsx(eS,{}),h.jsx(OE,{children:h.jsx($.Suspense,{fallback:h.jsx("div",{className:"termdock-boot",role:"status",children:"Loading Termdock"}),children:(()=>{const t=new URLSearchParams(window.location.search);return t.get("dag-playground")==="1"?h.jsx(rS,{}):t.get("diff-review-lab")==="1"?h.jsx(oS,{}):t.get("diff-lab")==="1"?h.jsx(sS,{}):h.jsx(BE,{children:h.jsx(nS,{})})})()})})]})}));export{yf as $,Ia as A,Jv as B,xa as C,Ov as D,xf as E,av as F,kv as G,Js as H,Yt as I,d1 as J,HE as K,We as L,bf as M,Ne as N,Av as O,dx as P,Eo as Q,g1 as R,Qs as S,Ue as T,G1 as U,zE as V,zv as W,gx as X,p1 as Y,V1 as Z,Un as _,cf as a,lv as a$,cv as a0,Uv as a1,ft as a2,i1 as a3,o1 as a4,l1 as a5,Sv as a6,sE as a7,tE as a8,eE as a9,Lf as aA,N1 as aB,B1 as aC,T1 as aD,P1 as aE,I1 as aF,h as aG,mS as aH,qv as aI,fE as aJ,w1 as aK,wE as aL,vE as aM,F1 as aN,$v as aO,s1 as aP,Y1 as aQ,Xx as aR,Wv as aS,y1 as aT,Cv as aU,q1 as aV,U1 as aW,H1 as aX,z1 as aY,wS as aZ,Iv as a_,nE as aa,n1 as ab,L1 as ac,J1 as ad,dE as ae,$1 as af,cE as ag,Q1 as ah,X1 as ai,E1 as aj,rE as ak,Gv as al,Rf as am,ov as an,Wx as ao,t1 as ap,Hv as aq,Qv as ar,aE as as,Bf as at,ql as au,gu as av,Du as aw,K1 as ax,a1 as ay,u1 as az,J0 as b,mE as b0,b1,xE as b2,Zv as b3,Yv as b4,S1 as b5,x1 as b6,e1 as b7,A1 as b8,v1 as b9,Rv as bA,pS as bB,tS as bC,fS as bD,c1 as bE,h1 as bF,r1 as bG,Xv as bH,Pf as bI,W1 as bJ,La as bK,xS as bL,M1 as bM,yS as bN,Dv as ba,Mv as bb,Kv as bc,m1 as bd,hS as be,pE as bf,lE as bg,hE as bh,yE as bi,ye as bj,O1 as bk,SE as bl,D0 as bm,ch as bn,Bv as bo,EE as bp,_v as bq,Pv as br,Tv as bs,Lv as bt,Fv as bu,gE as bv,Cf as bw,Ev as bx,So as by,bE as bz,tx as c,Jt as d,lf as e,ox as f,OE as g,df as h,Nv as i,la as j,wt as k,bS as l,uE as m,gS as n,_1 as o,R1 as p,da as q,j1 as r,I0 as s,f1 as t,ey as u,iv as v,jv as w,Kt as x,iE as y,oE as z};