termdock 1.4.291 → 1.4.292

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 (315) hide show
  1. package/.desktop-dist/main.js +2 -2
  2. package/dist/client/assets/{App-ecgsYB-4.js → App-B6IcjDoE.js} +43 -43
  3. package/dist/client/assets/App-B6IcjDoE.js.br +0 -0
  4. package/dist/client/assets/App-B6IcjDoE.js.gz +0 -0
  5. package/dist/client/assets/{ChangeWalkthroughPanel-C1H2M30E.js → ChangeWalkthroughPanel-DrFaKK1O.js} +1 -1
  6. package/dist/client/assets/ChangeWalkthroughPanel-DrFaKK1O.js.br +0 -0
  7. package/dist/client/assets/ChangeWalkthroughPanel-DrFaKK1O.js.gz +0 -0
  8. package/dist/client/assets/{DagPlayground-BCp8dP9Q.js → DagPlayground-B0RDj7Hc.js} +1 -1
  9. package/dist/client/assets/DagPlayground-B0RDj7Hc.js.br +0 -0
  10. package/dist/client/assets/DagPlayground-B0RDj7Hc.js.gz +0 -0
  11. package/dist/client/assets/{DiffLab-CoflQdbG.js → DiffLab-CPYmWsZm.js} +1 -1
  12. package/dist/client/assets/DiffLab-CPYmWsZm.js.br +0 -0
  13. package/dist/client/assets/DiffLab-CPYmWsZm.js.gz +0 -0
  14. package/dist/client/assets/{DiffReview-Bm0V1DMo.js → DiffReview-DTcdS9M-.js} +1 -1
  15. package/dist/client/assets/DiffReview-DTcdS9M-.js.br +0 -0
  16. package/dist/client/assets/DiffReview-DTcdS9M-.js.gz +0 -0
  17. package/dist/client/assets/{DiffReviewLab-cxdwBbrY.js → DiffReviewLab-COARnMyi.js} +1 -1
  18. package/dist/client/assets/DiffReviewLab-COARnMyi.js.br +0 -0
  19. package/dist/client/assets/DiffReviewLab-COARnMyi.js.gz +0 -0
  20. package/dist/client/assets/{DiffViewer-l4NqePTF.js → DiffViewer-Bf310S35.js} +1 -1
  21. package/dist/client/assets/DiffViewer-Bf310S35.js.br +0 -0
  22. package/dist/client/assets/DiffViewer-Bf310S35.js.gz +0 -0
  23. package/dist/client/assets/{ModelPreview-BlheKlpw.js → ModelPreview-OjAF6G25.js} +1 -1
  24. package/dist/client/assets/ModelPreview-OjAF6G25.js.br +0 -0
  25. package/dist/client/assets/ModelPreview-OjAF6G25.js.gz +0 -0
  26. package/dist/client/assets/{RightSidebar-Cem7Mh34.js → RightSidebar-BR7BIPmS.js} +4 -4
  27. package/dist/client/assets/RightSidebar-BR7BIPmS.js.br +0 -0
  28. package/dist/client/assets/RightSidebar-BR7BIPmS.js.gz +0 -0
  29. package/dist/client/assets/{abnfDiagram-VCTEODGH-BkZFHB-5.js → abnfDiagram-VCTEODGH-CqbrEwa0.js} +1 -1
  30. package/dist/client/assets/abnfDiagram-VCTEODGH-CqbrEwa0.js.br +0 -0
  31. package/dist/client/assets/abnfDiagram-VCTEODGH-CqbrEwa0.js.gz +0 -0
  32. package/dist/client/assets/{app-C6yj_rb6.js → app-ZUNhr7lR.js} +3 -3
  33. package/dist/client/assets/app-ZUNhr7lR.js.br +0 -0
  34. package/dist/client/assets/app-ZUNhr7lR.js.gz +0 -0
  35. package/dist/client/assets/{arc-fgnCbTwI.js → arc-hi65jb-e.js} +1 -1
  36. package/dist/client/assets/arc-hi65jb-e.js.br +0 -0
  37. package/dist/client/assets/arc-hi65jb-e.js.gz +0 -0
  38. package/dist/client/assets/{architectureDiagram-5GKGNRK7-D__ADLrK.js → architectureDiagram-5GKGNRK7-C692H3oz.js} +1 -1
  39. package/dist/client/assets/architectureDiagram-5GKGNRK7-C692H3oz.js.br +0 -0
  40. package/dist/client/assets/architectureDiagram-5GKGNRK7-C692H3oz.js.gz +0 -0
  41. package/dist/client/assets/{blockDiagram-I7D4REHJ-DcUNZnOI.js → blockDiagram-I7D4REHJ-QjCCaiPm.js} +1 -1
  42. package/dist/client/assets/blockDiagram-I7D4REHJ-QjCCaiPm.js.br +0 -0
  43. package/dist/client/assets/blockDiagram-I7D4REHJ-QjCCaiPm.js.gz +0 -0
  44. package/dist/client/assets/{c4Diagram-7LVT6UL2-DE-yMuRW.js → c4Diagram-7LVT6UL2-CdGojsWm.js} +1 -1
  45. package/dist/client/assets/c4Diagram-7LVT6UL2-CdGojsWm.js.br +0 -0
  46. package/dist/client/assets/c4Diagram-7LVT6UL2-CdGojsWm.js.gz +0 -0
  47. package/dist/client/assets/channel-BqslBrOF.js +1 -0
  48. package/dist/client/assets/{chunk-2Q5K7J3B-BxOCDT4t.js → chunk-2Q5K7J3B-Da5DGGu4.js} +1 -1
  49. package/dist/client/assets/{chunk-5VM5RSS4-DlfyUckJ.js → chunk-5VM5RSS4-CyOAQVvx.js} +1 -1
  50. package/dist/client/assets/{chunk-F27PBJKO-BPbkNlKe.js → chunk-F27PBJKO-DSYISYC8.js} +1 -1
  51. package/dist/client/assets/chunk-F27PBJKO-DSYISYC8.js.br +0 -0
  52. package/dist/client/assets/chunk-F27PBJKO-DSYISYC8.js.gz +0 -0
  53. package/dist/client/assets/{chunk-IMKFNOWR-BI6yxSN1.js → chunk-IMKFNOWR-CSHvBSkb.js} +1 -1
  54. package/dist/client/assets/chunk-IMKFNOWR-CSHvBSkb.js.br +0 -0
  55. package/dist/client/assets/chunk-IMKFNOWR-CSHvBSkb.js.gz +0 -0
  56. package/dist/client/assets/{chunk-JWPE2WC7-mc4JNqpA.js → chunk-JWPE2WC7-CAKJupsf.js} +1 -1
  57. package/dist/client/assets/{chunk-POPQ4Y6H-CltNKnZi.js → chunk-POPQ4Y6H-CRoAQ_B7.js} +1 -1
  58. package/dist/client/assets/{chunk-SVP7TREG-8mJBZp4f.js → chunk-SVP7TREG-6RKqTE9J.js} +1 -1
  59. package/dist/client/assets/chunk-SVP7TREG-6RKqTE9J.js.br +0 -0
  60. package/dist/client/assets/chunk-SVP7TREG-6RKqTE9J.js.gz +0 -0
  61. package/dist/client/assets/{chunk-TICWLB2K-r0qyCdBf.js → chunk-TICWLB2K-CPmISmQX.js} +1 -1
  62. package/dist/client/assets/chunk-TICWLB2K-CPmISmQX.js.br +0 -0
  63. package/dist/client/assets/chunk-TICWLB2K-CPmISmQX.js.gz +0 -0
  64. package/dist/client/assets/{chunk-XXDRQBXY-Cu2DJttR.js → chunk-XXDRQBXY-C3uP0_5w.js} +1 -1
  65. package/dist/client/assets/classDiagram-ZZMXUADV-ykeSSblN.js +1 -0
  66. package/dist/client/assets/classDiagram-v2-VYDZK3BY-ykeSSblN.js +1 -0
  67. package/dist/client/assets/{cose-bilkent-JH36ORCC-CjyWQlEW.js → cose-bilkent-JH36ORCC-C8Qyo0Vy.js} +1 -1
  68. package/dist/client/assets/cose-bilkent-JH36ORCC-C8Qyo0Vy.js.br +0 -0
  69. package/dist/client/assets/cose-bilkent-JH36ORCC-C8Qyo0Vy.js.gz +0 -0
  70. package/dist/client/assets/{cynefin-OW5HDTMX-DCGkZ4uD.js → cynefin-OW5HDTMX-CMTdnM61.js} +1 -1
  71. package/dist/client/assets/cynefin-OW5HDTMX-CMTdnM61.js.br +0 -0
  72. package/dist/client/assets/cynefin-OW5HDTMX-CMTdnM61.js.gz +0 -0
  73. package/dist/client/assets/{cynefinDiagram-5FMLGOSQ-Cd6CLE7x.js → cynefinDiagram-5FMLGOSQ-Bju2CHl-.js} +1 -1
  74. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-Bju2CHl-.js.br +0 -0
  75. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-Bju2CHl-.js.gz +0 -0
  76. package/dist/client/assets/{dagre-GXQ25YYZ-DLP7f5Qn.js → dagre-GXQ25YYZ-B2_sgdCD.js} +1 -1
  77. package/dist/client/assets/dagre-GXQ25YYZ-B2_sgdCD.js.br +0 -0
  78. package/dist/client/assets/dagre-GXQ25YYZ-B2_sgdCD.js.gz +0 -0
  79. package/dist/client/assets/{diagram-S7CK7UJ4-DW3tN0ae.js → diagram-S7CK7UJ4-Cot_awY-.js} +1 -1
  80. package/dist/client/assets/diagram-S7CK7UJ4-Cot_awY-.js.br +0 -0
  81. package/dist/client/assets/diagram-S7CK7UJ4-Cot_awY-.js.gz +0 -0
  82. package/dist/client/assets/{diagram-UQ7AKVKN-TJf6Kkrk.js → diagram-UQ7AKVKN-kPzGJXnc.js} +1 -1
  83. package/dist/client/assets/diagram-UQ7AKVKN-kPzGJXnc.js.br +0 -0
  84. package/dist/client/assets/diagram-UQ7AKVKN-kPzGJXnc.js.gz +0 -0
  85. package/dist/client/assets/{diagram-VSXAHHWV-BcbH2sKu.js → diagram-VSXAHHWV-07RtoPR0.js} +1 -1
  86. package/dist/client/assets/diagram-VSXAHHWV-07RtoPR0.js.br +0 -0
  87. package/dist/client/assets/diagram-VSXAHHWV-07RtoPR0.js.gz +0 -0
  88. package/dist/client/assets/{diagram-VX7I27RA-BfHjQAOg.js → diagram-VX7I27RA-6DKrmGyG.js} +1 -1
  89. package/dist/client/assets/diagram-VX7I27RA-6DKrmGyG.js.br +0 -0
  90. package/dist/client/assets/diagram-VX7I27RA-6DKrmGyG.js.gz +0 -0
  91. package/dist/client/assets/{diagram-Z3DM3KII-DLyiCc82.js → diagram-Z3DM3KII-CO5c5MEi.js} +1 -1
  92. package/dist/client/assets/diagram-Z3DM3KII-CO5c5MEi.js.br +0 -0
  93. package/dist/client/assets/diagram-Z3DM3KII-CO5c5MEi.js.gz +0 -0
  94. package/dist/client/assets/{ebnfDiagram-PWID7BFC-DBW34qgr.js → ebnfDiagram-PWID7BFC-Bo_w-tIL.js} +1 -1
  95. package/dist/client/assets/ebnfDiagram-PWID7BFC-Bo_w-tIL.js.br +0 -0
  96. package/dist/client/assets/ebnfDiagram-PWID7BFC-Bo_w-tIL.js.gz +0 -0
  97. package/dist/client/assets/{erDiagram-RLTQ6QDP-jbhjVnoy.js → erDiagram-RLTQ6QDP-Djl5aWAc.js} +1 -1
  98. package/dist/client/assets/erDiagram-RLTQ6QDP-Djl5aWAc.js.br +0 -0
  99. package/dist/client/assets/erDiagram-RLTQ6QDP-Djl5aWAc.js.gz +0 -0
  100. package/dist/client/assets/{flowDiagram-HODETNUW-D_E0T1md.js → flowDiagram-HODETNUW-DZMfxfe8.js} +1 -1
  101. package/dist/client/assets/flowDiagram-HODETNUW-DZMfxfe8.js.br +0 -0
  102. package/dist/client/assets/flowDiagram-HODETNUW-DZMfxfe8.js.gz +0 -0
  103. package/dist/client/assets/{ganttDiagram-EL5Y4UJY-BrDlmhf8.js → ganttDiagram-EL5Y4UJY-Cv0rWr4X.js} +1 -1
  104. package/dist/client/assets/ganttDiagram-EL5Y4UJY-Cv0rWr4X.js.br +0 -0
  105. package/dist/client/assets/ganttDiagram-EL5Y4UJY-Cv0rWr4X.js.gz +0 -0
  106. package/dist/client/assets/{gestureArbiter-DQPWM7WT.js → gestureArbiter-rtOG53-b.js} +1 -1
  107. package/dist/client/assets/gestureArbiter-rtOG53-b.js.br +0 -0
  108. package/dist/client/assets/gestureArbiter-rtOG53-b.js.gz +0 -0
  109. package/dist/client/assets/{gitGraphDiagram-WWUBYQGX-DDu259m5.js → gitGraphDiagram-WWUBYQGX-ZwIzv5Oi.js} +1 -1
  110. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-ZwIzv5Oi.js.br +0 -0
  111. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-ZwIzv5Oi.js.gz +0 -0
  112. package/dist/client/assets/{infoDiagram-27XIBGKW-CK4BorRY.js → infoDiagram-27XIBGKW-tRIpwAmI.js} +1 -1
  113. package/dist/client/assets/{ishikawaDiagram-5VMMS53U-BVu1-hfj.js → ishikawaDiagram-5VMMS53U-DOxOV2qF.js} +1 -1
  114. package/dist/client/assets/ishikawaDiagram-5VMMS53U-DOxOV2qF.js.br +0 -0
  115. package/dist/client/assets/ishikawaDiagram-5VMMS53U-DOxOV2qF.js.gz +0 -0
  116. package/dist/client/assets/{journeyDiagram-3NMN7TZE-3bxyOdZZ.js → journeyDiagram-3NMN7TZE-Bcp6ka-X.js} +1 -1
  117. package/dist/client/assets/journeyDiagram-3NMN7TZE-Bcp6ka-X.js.br +0 -0
  118. package/dist/client/assets/journeyDiagram-3NMN7TZE-Bcp6ka-X.js.gz +0 -0
  119. package/dist/client/assets/{kanban-definition-UXKFOSKX-c52cbwBd.js → kanban-definition-UXKFOSKX-BG-NpwQX.js} +1 -1
  120. package/dist/client/assets/kanban-definition-UXKFOSKX-BG-NpwQX.js.br +0 -0
  121. package/dist/client/assets/kanban-definition-UXKFOSKX-BG-NpwQX.js.gz +0 -0
  122. package/dist/client/assets/{layout-CWV5rtq-.js → layout-DpJQa239.js} +1 -1
  123. package/dist/client/assets/layout-DpJQa239.js.br +0 -0
  124. package/dist/client/assets/layout-DpJQa239.js.gz +0 -0
  125. package/dist/client/assets/{linear-0zsykq62.js → linear-Xgd-wMq4.js} +1 -1
  126. package/dist/client/assets/{linear-0zsykq62.js.br → linear-Xgd-wMq4.js.br} +0 -0
  127. package/dist/client/assets/linear-Xgd-wMq4.js.gz +0 -0
  128. package/dist/client/assets/{mermaid.core-8DpvdZOL.js → mermaid.core-Cg87VRsD.js} +5 -5
  129. package/dist/client/assets/mermaid.core-Cg87VRsD.js.br +0 -0
  130. package/dist/client/assets/mermaid.core-Cg87VRsD.js.gz +0 -0
  131. package/dist/client/assets/{mindmap-definition-YA3MSWOX-Q5-MURdO.js → mindmap-definition-YA3MSWOX-NvIZ5GdZ.js} +1 -1
  132. package/dist/client/assets/mindmap-definition-YA3MSWOX-NvIZ5GdZ.js.br +0 -0
  133. package/dist/client/assets/mindmap-definition-YA3MSWOX-NvIZ5GdZ.js.gz +0 -0
  134. package/dist/client/assets/{passwordBootstrap-C6YjAkMT.js → passwordBootstrap-C-wELkSK.js} +1 -1
  135. package/dist/client/assets/passwordBootstrap-C-wELkSK.js.br +0 -0
  136. package/dist/client/assets/passwordBootstrap-C-wELkSK.js.gz +0 -0
  137. package/dist/client/assets/{pegDiagram-XKGWAZYB-91ooSSOL.js → pegDiagram-XKGWAZYB-p_86_WfN.js} +1 -1
  138. package/dist/client/assets/pegDiagram-XKGWAZYB-p_86_WfN.js.br +0 -0
  139. package/dist/client/assets/pegDiagram-XKGWAZYB-p_86_WfN.js.gz +0 -0
  140. package/dist/client/assets/{pieDiagram-E7YTZNPT-7-5UDdMh.js → pieDiagram-E7YTZNPT-AtUgAjwU.js} +1 -1
  141. package/dist/client/assets/pieDiagram-E7YTZNPT-AtUgAjwU.js.br +0 -0
  142. package/dist/client/assets/pieDiagram-E7YTZNPT-AtUgAjwU.js.gz +0 -0
  143. package/dist/client/assets/{quadrantDiagram-AXDQQJYC-BocMXzqc.js → quadrantDiagram-AXDQQJYC-CnpxHhP7.js} +1 -1
  144. package/dist/client/assets/quadrantDiagram-AXDQQJYC-CnpxHhP7.js.br +0 -0
  145. package/dist/client/assets/quadrantDiagram-AXDQQJYC-CnpxHhP7.js.gz +0 -0
  146. package/dist/client/assets/{railroadDiagram-O6MQD6OU-f77_PHdI.js → railroadDiagram-O6MQD6OU-pNXnS4a0.js} +1 -1
  147. package/dist/client/assets/railroadDiagram-O6MQD6OU-pNXnS4a0.js.br +0 -0
  148. package/dist/client/assets/railroadDiagram-O6MQD6OU-pNXnS4a0.js.gz +0 -0
  149. package/dist/client/assets/{referenceLongPress-DF6Hk2O6.js → referenceLongPress-Dwy-aM4B.js} +1 -1
  150. package/dist/client/assets/referenceLongPress-Dwy-aM4B.js.br +0 -0
  151. package/dist/client/assets/referenceLongPress-Dwy-aM4B.js.gz +0 -0
  152. package/dist/client/assets/{requirementDiagram-BXWQKSXE-BapwIILN.js → requirementDiagram-BXWQKSXE-D3lsPYth.js} +1 -1
  153. package/dist/client/assets/requirementDiagram-BXWQKSXE-D3lsPYth.js.br +0 -0
  154. package/dist/client/assets/requirementDiagram-BXWQKSXE-D3lsPYth.js.gz +0 -0
  155. package/dist/client/assets/{sankeyDiagram-P5KCCOFB-DXHaMFDj.js → sankeyDiagram-P5KCCOFB-DhM3_3mY.js} +1 -1
  156. package/dist/client/assets/sankeyDiagram-P5KCCOFB-DhM3_3mY.js.br +0 -0
  157. package/dist/client/assets/sankeyDiagram-P5KCCOFB-DhM3_3mY.js.gz +0 -0
  158. package/dist/client/assets/{sequenceDiagram-WJ2MYXX4-wu29rs8_.js → sequenceDiagram-WJ2MYXX4-C20OjmvF.js} +1 -1
  159. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-C20OjmvF.js.br +0 -0
  160. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-C20OjmvF.js.gz +0 -0
  161. package/dist/client/assets/{sizeCapture-INFHLROL-C1qehanF.js → sizeCapture-INFHLROL-DQ3lhd_i.js} +1 -1
  162. package/dist/client/assets/sizeCapture-INFHLROL-DQ3lhd_i.js.br +0 -0
  163. package/dist/client/assets/sizeCapture-INFHLROL-DQ3lhd_i.js.gz +0 -0
  164. package/dist/client/assets/{sparkles-DU83CizP.js → sparkles-Dleyh-x5.js} +1 -1
  165. package/dist/client/assets/{stateDiagram-D77RDMKH-DocdzEMr.js → stateDiagram-D77RDMKH-BMrEz7IB.js} +1 -1
  166. package/dist/client/assets/stateDiagram-D77RDMKH-BMrEz7IB.js.br +0 -0
  167. package/dist/client/assets/stateDiagram-D77RDMKH-BMrEz7IB.js.gz +0 -0
  168. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-BjAUnd-V.js +1 -0
  169. package/dist/client/assets/{swimlanes-42K2YHIH-BCC8R-LW.js → swimlanes-42K2YHIH-BQFzXsBC.js} +1 -1
  170. package/dist/client/assets/swimlanes-42K2YHIH-BQFzXsBC.js.br +0 -0
  171. package/dist/client/assets/swimlanes-42K2YHIH-BQFzXsBC.js.gz +0 -0
  172. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-nkri6RMv.js +8 -0
  173. package/dist/client/assets/{timeline-definition-24CTP7MA-Awsj6YKn.js → timeline-definition-24CTP7MA-B5E5rgAW.js} +1 -1
  174. package/dist/client/assets/{timeline-definition-24CTP7MA-Awsj6YKn.js.br → timeline-definition-24CTP7MA-B5E5rgAW.js.br} +0 -0
  175. package/dist/client/assets/timeline-definition-24CTP7MA-B5E5rgAW.js.gz +0 -0
  176. package/dist/client/assets/{triangle-alert-CleSfO5g.js → triangle-alert-Qoe61fzS.js} +1 -1
  177. package/dist/client/assets/{vennDiagram-4TSXK5OY-plF3aolQ.js → vennDiagram-4TSXK5OY-331LWKVM.js} +1 -1
  178. package/dist/client/assets/vennDiagram-4TSXK5OY-331LWKVM.js.br +0 -0
  179. package/dist/client/assets/vennDiagram-4TSXK5OY-331LWKVM.js.gz +0 -0
  180. package/dist/client/assets/{videoCompression-0j6TkMXy.js → videoCompression-DtAduptJ.js} +1 -1
  181. package/dist/client/assets/videoCompression-DtAduptJ.js.br +0 -0
  182. package/dist/client/assets/videoCompression-DtAduptJ.js.gz +0 -0
  183. package/dist/client/assets/{wardleyDiagram-VM6X3IG4-P26bUhgZ.js → wardleyDiagram-VM6X3IG4-8cMdga4X.js} +1 -1
  184. package/dist/client/assets/wardleyDiagram-VM6X3IG4-8cMdga4X.js.br +0 -0
  185. package/dist/client/assets/wardleyDiagram-VM6X3IG4-8cMdga4X.js.gz +0 -0
  186. package/dist/client/assets/{xychartDiagram-S5SC5T6Z-BDPOD_Oa.js → xychartDiagram-S5SC5T6Z-CfDQh93n.js} +1 -1
  187. package/dist/client/assets/xychartDiagram-S5SC5T6Z-CfDQh93n.js.br +0 -0
  188. package/dist/client/assets/xychartDiagram-S5SC5T6Z-CfDQh93n.js.gz +0 -0
  189. package/dist/client/index.html +1 -1
  190. package/dist/client/index.html.br +0 -0
  191. package/dist/client/index.html.gz +0 -0
  192. package/dist/client/sw.js +1 -1
  193. package/dist/client/sw.js.br +0 -0
  194. package/dist/client/sw.js.gz +0 -0
  195. package/package.json +1 -1
  196. package/runtime-manifest.json +2 -2
  197. package/dist/client/assets/App-ecgsYB-4.js.br +0 -0
  198. package/dist/client/assets/App-ecgsYB-4.js.gz +0 -0
  199. package/dist/client/assets/ChangeWalkthroughPanel-C1H2M30E.js.br +0 -0
  200. package/dist/client/assets/ChangeWalkthroughPanel-C1H2M30E.js.gz +0 -0
  201. package/dist/client/assets/DagPlayground-BCp8dP9Q.js.br +0 -0
  202. package/dist/client/assets/DagPlayground-BCp8dP9Q.js.gz +0 -0
  203. package/dist/client/assets/DiffLab-CoflQdbG.js.br +0 -0
  204. package/dist/client/assets/DiffLab-CoflQdbG.js.gz +0 -0
  205. package/dist/client/assets/DiffReview-Bm0V1DMo.js.br +0 -0
  206. package/dist/client/assets/DiffReview-Bm0V1DMo.js.gz +0 -0
  207. package/dist/client/assets/DiffReviewLab-cxdwBbrY.js.br +0 -0
  208. package/dist/client/assets/DiffReviewLab-cxdwBbrY.js.gz +0 -0
  209. package/dist/client/assets/DiffViewer-l4NqePTF.js.br +0 -0
  210. package/dist/client/assets/DiffViewer-l4NqePTF.js.gz +0 -0
  211. package/dist/client/assets/ModelPreview-BlheKlpw.js.br +0 -0
  212. package/dist/client/assets/ModelPreview-BlheKlpw.js.gz +0 -0
  213. package/dist/client/assets/RightSidebar-Cem7Mh34.js.br +0 -0
  214. package/dist/client/assets/RightSidebar-Cem7Mh34.js.gz +0 -0
  215. package/dist/client/assets/abnfDiagram-VCTEODGH-BkZFHB-5.js.br +0 -0
  216. package/dist/client/assets/abnfDiagram-VCTEODGH-BkZFHB-5.js.gz +0 -0
  217. package/dist/client/assets/app-C6yj_rb6.js.br +0 -0
  218. package/dist/client/assets/app-C6yj_rb6.js.gz +0 -0
  219. package/dist/client/assets/arc-fgnCbTwI.js.br +0 -0
  220. package/dist/client/assets/arc-fgnCbTwI.js.gz +0 -0
  221. package/dist/client/assets/architectureDiagram-5GKGNRK7-D__ADLrK.js.br +0 -0
  222. package/dist/client/assets/architectureDiagram-5GKGNRK7-D__ADLrK.js.gz +0 -0
  223. package/dist/client/assets/blockDiagram-I7D4REHJ-DcUNZnOI.js.br +0 -0
  224. package/dist/client/assets/blockDiagram-I7D4REHJ-DcUNZnOI.js.gz +0 -0
  225. package/dist/client/assets/c4Diagram-7LVT6UL2-DE-yMuRW.js.br +0 -0
  226. package/dist/client/assets/c4Diagram-7LVT6UL2-DE-yMuRW.js.gz +0 -0
  227. package/dist/client/assets/channel-Cf8T4SKt.js +0 -1
  228. package/dist/client/assets/chunk-F27PBJKO-BPbkNlKe.js.br +0 -0
  229. package/dist/client/assets/chunk-F27PBJKO-BPbkNlKe.js.gz +0 -0
  230. package/dist/client/assets/chunk-IMKFNOWR-BI6yxSN1.js.br +0 -0
  231. package/dist/client/assets/chunk-IMKFNOWR-BI6yxSN1.js.gz +0 -0
  232. package/dist/client/assets/chunk-SVP7TREG-8mJBZp4f.js.br +0 -0
  233. package/dist/client/assets/chunk-SVP7TREG-8mJBZp4f.js.gz +0 -0
  234. package/dist/client/assets/chunk-TICWLB2K-r0qyCdBf.js.br +0 -0
  235. package/dist/client/assets/chunk-TICWLB2K-r0qyCdBf.js.gz +0 -0
  236. package/dist/client/assets/classDiagram-ZZMXUADV-BZUbvj32.js +0 -1
  237. package/dist/client/assets/classDiagram-v2-VYDZK3BY-BZUbvj32.js +0 -1
  238. package/dist/client/assets/cose-bilkent-JH36ORCC-CjyWQlEW.js.br +0 -0
  239. package/dist/client/assets/cose-bilkent-JH36ORCC-CjyWQlEW.js.gz +0 -0
  240. package/dist/client/assets/cynefin-OW5HDTMX-DCGkZ4uD.js.br +0 -0
  241. package/dist/client/assets/cynefin-OW5HDTMX-DCGkZ4uD.js.gz +0 -0
  242. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-Cd6CLE7x.js.br +0 -0
  243. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-Cd6CLE7x.js.gz +0 -0
  244. package/dist/client/assets/dagre-GXQ25YYZ-DLP7f5Qn.js.br +0 -0
  245. package/dist/client/assets/dagre-GXQ25YYZ-DLP7f5Qn.js.gz +0 -0
  246. package/dist/client/assets/diagram-S7CK7UJ4-DW3tN0ae.js.br +0 -0
  247. package/dist/client/assets/diagram-S7CK7UJ4-DW3tN0ae.js.gz +0 -0
  248. package/dist/client/assets/diagram-UQ7AKVKN-TJf6Kkrk.js.br +0 -0
  249. package/dist/client/assets/diagram-UQ7AKVKN-TJf6Kkrk.js.gz +0 -0
  250. package/dist/client/assets/diagram-VSXAHHWV-BcbH2sKu.js.br +0 -0
  251. package/dist/client/assets/diagram-VSXAHHWV-BcbH2sKu.js.gz +0 -0
  252. package/dist/client/assets/diagram-VX7I27RA-BfHjQAOg.js.br +0 -0
  253. package/dist/client/assets/diagram-VX7I27RA-BfHjQAOg.js.gz +0 -0
  254. package/dist/client/assets/diagram-Z3DM3KII-DLyiCc82.js.br +0 -0
  255. package/dist/client/assets/diagram-Z3DM3KII-DLyiCc82.js.gz +0 -0
  256. package/dist/client/assets/ebnfDiagram-PWID7BFC-DBW34qgr.js.br +0 -0
  257. package/dist/client/assets/ebnfDiagram-PWID7BFC-DBW34qgr.js.gz +0 -0
  258. package/dist/client/assets/erDiagram-RLTQ6QDP-jbhjVnoy.js.br +0 -0
  259. package/dist/client/assets/erDiagram-RLTQ6QDP-jbhjVnoy.js.gz +0 -0
  260. package/dist/client/assets/flowDiagram-HODETNUW-D_E0T1md.js.br +0 -0
  261. package/dist/client/assets/flowDiagram-HODETNUW-D_E0T1md.js.gz +0 -0
  262. package/dist/client/assets/ganttDiagram-EL5Y4UJY-BrDlmhf8.js.br +0 -0
  263. package/dist/client/assets/ganttDiagram-EL5Y4UJY-BrDlmhf8.js.gz +0 -0
  264. package/dist/client/assets/gestureArbiter-DQPWM7WT.js.br +0 -0
  265. package/dist/client/assets/gestureArbiter-DQPWM7WT.js.gz +0 -0
  266. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-DDu259m5.js.br +0 -0
  267. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-DDu259m5.js.gz +0 -0
  268. package/dist/client/assets/ishikawaDiagram-5VMMS53U-BVu1-hfj.js.br +0 -0
  269. package/dist/client/assets/ishikawaDiagram-5VMMS53U-BVu1-hfj.js.gz +0 -0
  270. package/dist/client/assets/journeyDiagram-3NMN7TZE-3bxyOdZZ.js.br +0 -0
  271. package/dist/client/assets/journeyDiagram-3NMN7TZE-3bxyOdZZ.js.gz +0 -0
  272. package/dist/client/assets/kanban-definition-UXKFOSKX-c52cbwBd.js.br +0 -0
  273. package/dist/client/assets/kanban-definition-UXKFOSKX-c52cbwBd.js.gz +0 -0
  274. package/dist/client/assets/layout-CWV5rtq-.js.br +0 -0
  275. package/dist/client/assets/layout-CWV5rtq-.js.gz +0 -0
  276. package/dist/client/assets/linear-0zsykq62.js.gz +0 -0
  277. package/dist/client/assets/mermaid.core-8DpvdZOL.js.br +0 -0
  278. package/dist/client/assets/mermaid.core-8DpvdZOL.js.gz +0 -0
  279. package/dist/client/assets/mindmap-definition-YA3MSWOX-Q5-MURdO.js.br +0 -0
  280. package/dist/client/assets/mindmap-definition-YA3MSWOX-Q5-MURdO.js.gz +0 -0
  281. package/dist/client/assets/passwordBootstrap-C6YjAkMT.js.br +0 -0
  282. package/dist/client/assets/passwordBootstrap-C6YjAkMT.js.gz +0 -0
  283. package/dist/client/assets/pegDiagram-XKGWAZYB-91ooSSOL.js.br +0 -0
  284. package/dist/client/assets/pegDiagram-XKGWAZYB-91ooSSOL.js.gz +0 -0
  285. package/dist/client/assets/pieDiagram-E7YTZNPT-7-5UDdMh.js.br +0 -0
  286. package/dist/client/assets/pieDiagram-E7YTZNPT-7-5UDdMh.js.gz +0 -0
  287. package/dist/client/assets/quadrantDiagram-AXDQQJYC-BocMXzqc.js.br +0 -0
  288. package/dist/client/assets/quadrantDiagram-AXDQQJYC-BocMXzqc.js.gz +0 -0
  289. package/dist/client/assets/railroadDiagram-O6MQD6OU-f77_PHdI.js.br +0 -0
  290. package/dist/client/assets/railroadDiagram-O6MQD6OU-f77_PHdI.js.gz +0 -0
  291. package/dist/client/assets/referenceLongPress-DF6Hk2O6.js.br +0 -0
  292. package/dist/client/assets/referenceLongPress-DF6Hk2O6.js.gz +0 -0
  293. package/dist/client/assets/requirementDiagram-BXWQKSXE-BapwIILN.js.br +0 -0
  294. package/dist/client/assets/requirementDiagram-BXWQKSXE-BapwIILN.js.gz +0 -0
  295. package/dist/client/assets/sankeyDiagram-P5KCCOFB-DXHaMFDj.js.br +0 -0
  296. package/dist/client/assets/sankeyDiagram-P5KCCOFB-DXHaMFDj.js.gz +0 -0
  297. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-wu29rs8_.js.br +0 -0
  298. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-wu29rs8_.js.gz +0 -0
  299. package/dist/client/assets/sizeCapture-INFHLROL-C1qehanF.js.br +0 -0
  300. package/dist/client/assets/sizeCapture-INFHLROL-C1qehanF.js.gz +0 -0
  301. package/dist/client/assets/stateDiagram-D77RDMKH-DocdzEMr.js.br +0 -0
  302. package/dist/client/assets/stateDiagram-D77RDMKH-DocdzEMr.js.gz +0 -0
  303. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-DJ2KOlPz.js +0 -1
  304. package/dist/client/assets/swimlanes-42K2YHIH-BCC8R-LW.js.br +0 -0
  305. package/dist/client/assets/swimlanes-42K2YHIH-BCC8R-LW.js.gz +0 -0
  306. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-Byq6GIzA.js +0 -8
  307. package/dist/client/assets/timeline-definition-24CTP7MA-Awsj6YKn.js.gz +0 -0
  308. package/dist/client/assets/vennDiagram-4TSXK5OY-plF3aolQ.js.br +0 -0
  309. package/dist/client/assets/vennDiagram-4TSXK5OY-plF3aolQ.js.gz +0 -0
  310. package/dist/client/assets/videoCompression-0j6TkMXy.js.br +0 -0
  311. package/dist/client/assets/videoCompression-0j6TkMXy.js.gz +0 -0
  312. package/dist/client/assets/wardleyDiagram-VM6X3IG4-P26bUhgZ.js.br +0 -0
  313. package/dist/client/assets/wardleyDiagram-VM6X3IG4-P26bUhgZ.js.gz +0 -0
  314. package/dist/client/assets/xychartDiagram-S5SC5T6Z-BDPOD_Oa.js.br +0 -0
  315. package/dist/client/assets/xychartDiagram-S5SC5T6Z-BDPOD_Oa.js.gz +0 -0
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/passwordBootstrap-C6YjAkMT.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/App-ecgsYB-4.js","assets/gestureArbiter-DQPWM7WT.js","assets/gestureArbiter-C2J0D0kV.css","assets/triangle-alert-CleSfO5g.js","assets/referenceLongPress-DF6Hk2O6.js","assets/DagPlayground-BCp8dP9Q.js","assets/ChangeWalkthroughPanel-C1H2M30E.js","assets/sparkles-DU83CizP.js","assets/DiffLab-CoflQdbG.js","assets/DiffViewer-l4NqePTF.js","assets/DiffViewer-T3uj2-aP.css","assets/DiffReviewLab-cxdwBbrY.js","assets/DiffReview-Bm0V1DMo.js"])))=>i.map(i=>d[i]);
2
- import{r as zc,a as $m,g as jf}from"./react-XDCjal2T.js";import{b as O,R as Ye,r as Gc}from"./dnd-BCFAPC0L.js";import{L as qm,l as Km}from"./terminal-C7X98Amf.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const i of s.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(o){if(o.ep)return;o.ep=!0;const s=n(o);fetch(o.href,s)}})();const zm="modulepreload",Gm=function(t){return"/"+t},rd={},tn=function(e,n,r){let o=Promise.resolve();if(n&&n.length>0){let c=function(l){return Promise.all(l.map(d=>Promise.resolve(d).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),a=i?.nonce||i?.getAttribute("nonce");o=c(n.map(l=>{if(l=Gm(l),l in rd)return;rd[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":zm,d||(f.as="script"),f.crossOrigin="",f.href=l,a&&f.setAttribute("nonce",a),document.head.appendChild(f),d)return new Promise((h,g)=>{f.addEventListener("load",h),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${l}`)))})}))}function s(i){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=i,window.dispatchEvent(a),!a.defaultPrevented)throw i}return o.then(i=>{for(const a of i||[])a.status==="rejected"&&s(a.reason);return e().catch(s)})};var Bi={exports:{}},Ir={};var od;function Wm(){if(od)return Ir;od=1;var t=zc(),e=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function i(a,c,l){var d,u={},f=null,h=null;l!==void 0&&(f=""+l),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(h=c.ref);for(d in c)r.call(c,d)&&!s.hasOwnProperty(d)&&(u[d]=c[d]);if(a&&a.defaultProps)for(d in c=a.defaultProps,c)u[d]===void 0&&(u[d]=c[d]);return{$$typeof:e,type:a,key:f,ref:h,props:u,_owner:o.current}}return Ir.Fragment=n,Ir.jsx=i,Ir.jsxs=i,Ir}var sd;function Vm(){return sd||(sd=1,Bi.exports=Wm()),Bi.exports}var p=Vm();const wn="termdock-secure-target-v1",Wc="termdock-secure-entry-v1",Xm=new Set([wn,Wc,"termdock-color-theme","termdock:locale","termdock.federation.connections.v1"]),Bo=typeof Storage>"u"?void 0:Storage.prototype.getItem,_i=typeof Storage>"u"?void 0:Storage.prototype.setItem,id="termdock-secure-legacy-owner",Js=typeof window<"u"&&window.parent!==window&&location.pathname==="/workspace.html";function Ym(){if(typeof window>"u")return null;try{if(Js){const e=new URLSearchParams(location.search).get("termdock-workspace"),n=JSON.parse(localStorage.getItem("termdock.federation.connections.v1")||"[]"),r=Array.isArray(n)?n.find(o=>o?.targetPeerId===e):void 0;return r&&typeof r.url=="string"&&typeof r.targetPeerId=="string"?{...r,serviceName:r.label||r.serviceName}:null}const t=JSON.parse(sessionStorage.getItem(wn)??localStorage.getItem(wn)??"null");return t&&typeof t.url=="string"&&typeof t.targetPeerId=="string"?t:null}catch{return null}}let Qs=Ym();const Vn=Qs?.targetPeerId??"unpaired";function fo(){return Qs}function Hf(t){if(Qs=t,Js)return;const e=JSON.stringify(t);sessionStorage.setItem(wn,e),localStorage.setItem(wn,e)}function Zm(){Qs=null,!Js&&(localStorage.removeItem(wn),sessionStorage.removeItem(wn),localStorage.removeItem(Wc))}function to(t,e=Vn){return Xm.has(t)||t.startsWith("termdock-secure-")?t:`termdock-service:${e}:${t}`}function Jm(t){if(!(!Bo||!_i))try{if(Bo.call(localStorage,id))return;_i.call(localStorage,id,t);for(const n of[localStorage,sessionStorage]){const r=Array.from({length:n.length},(o,s)=>n.key(s)).filter(o=>!!o);for(const o of r){if(o.startsWith("termdock-service:")||to(o,t)===o)continue;const s=to(o,t),i=Bo.call(n,o);i!==null&&Bo.call(n,s)===null&&_i.call(n,s,i)}}}catch{}}let ad=!1;function Qm(){if(ad||typeof Storage>"u")return;ad=!0;const t=Storage.prototype.getItem,e=Storage.prototype.setItem,n=Storage.prototype.removeItem;Storage.prototype.getItem=function(r){return t.call(this,to(String(r)))},Storage.prototype.setItem=function(r,o){e.call(this,to(String(r)),o)},Storage.prototype.removeItem=function(r){n.call(this,to(String(r)))}}Qm();const ei="termdock.federation.connections.v1",Ua="termdock:services-changed",Vc="termdock-secure-removed-services",bs=t=>[t.id,t.targetPeerId,t.serviceOrigin||t.url].filter(e=>!!e);function Xc(){try{const t=JSON.parse(localStorage.getItem(Vc)||"[]");return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}catch{return[]}}function Me(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 ti(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.url=="string")try{const n=Me(e.url),r=typeof e.targetPeerId=="string"&&e.targetPeerId?e.targetPeerId:void 0,o=(typeof e.label=="string"?e.label:typeof e.serviceName=="string"?e.serviceName:"").trim().slice(0,120)||new URL(n).host;return{id:typeof e.id=="string"&&e.id?e.id:r||n,url:n,label:o,...r?{targetPeerId:r}:{},...typeof e.serviceOrigin=="string"?{serviceOrigin:Me(e.serviceOrigin)}:{},...typeof e.entryServiceId=="string"&&e.entryServiceId?{entryServiceId:e.entryServiceId}:{},...Array.isArray(e.routes)?{routes:e.routes.slice(0,4).flatMap(s=>{try{return s&&typeof s.targetPeerId=="string"&&s.targetPeerId?[{url:Me(s.url),targetPeerId:s.targetPeerId}]:[]}catch{return[]}})}:{}}}catch{return}}function Ct(t,e){return t.targetPeerId&&e.targetPeerId?t.targetPeerId===e.targetPeerId:(t.serviceOrigin||t.url)===(e.serviceOrigin||e.url)}function Uf(t){const e=[];for(const n of t){const r=e.findIndex(o=>Ct(o,n));r<0?e.push(n):e[r]={...e[r],...n,id:e[r].id}}return e}function xo(){return typeof window>"u"?void 0:window.termdockDesktop}function yn(){try{const t=JSON.parse(localStorage.getItem(ei)||"[]");return Array.isArray(t)?Uf(t.map(ti).filter(e=>!!e)):[]}catch{return[]}}function $f(t){localStorage.setItem(ei,JSON.stringify(t.map(e=>({...e,serviceName:e.label})))),window.dispatchEvent(new Event(Ua))}let Rr;async function Ge(){const t=xo();if(!t?.serviceConnections||!t.saveServiceConnection)return yn();if(Rr)return Rr;Rr=(async()=>{let e=await t.serviceConnections();const n=yn();for(const r of n)e.some(o=>Ct(o,r))||(e=await(t.importServiceConnection||t.saveServiceConnection)(r));return n.length&&localStorage.removeItem(ei),e})();try{return await Rr}finally{Rr=void 0}}async function Lt(t){const e=ti(t);if(!e)throw new Error("服务地址无效。");const n=xo();if(n?.saveServiceConnection)return n.saveServiceConnection(e);const r=yn(),o=r.find(a=>a.id===e.id||Ct(a,e)),s=new Set([...bs(e),...o?bs(o):[]]);localStorage.setItem(Vc,JSON.stringify(Xc().filter(a=>!s.has(a))));const i=Uf([...r.filter(a=>a!==o),{...o,...e,id:o?.id||e.id}]);return $f(i),i}async function ew(t){const e=ti(t);if(!e)throw new Error("服务地址无效。");const n=xo();if(n?.importServiceConnection)return n.importServiceConnection(e);if(n?.serviceConnections){const r=await n.serviceConnections();return r.some(o=>Ct(o,e))?Lt(e):r}return bs(e).some(r=>Xc().includes(r))?yn():Lt(e)}async function tw(t){const e=xo();if(e?.removeServiceConnection)return e.removeServiceConnection(t);const n=yn(),r=n.find(s=>s.id===t);r&&localStorage.setItem(Vc,JSON.stringify([...new Set([...Xc(),...bs(r)])].slice(-768)));const o=n.filter(s=>s.id!==t);return $f(o),o}function ni(t){const e=r=>{(r.key===ei||r.key===null)&&t()};window.addEventListener(Ua,t),window.addEventListener("storage",e);const n=xo()?.onServiceConnections?.(t);return()=>{window.removeEventListener(Ua,t),window.removeEventListener("storage",e),n?.()}}class nw extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}let rw=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},lt=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};class qf extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class Kf extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}}class ow extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class sw extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class ri extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}const zf=Symbol.for("@libp2p/peer-id");function iw(t){return typeof t?.handleEvent=="function"}function aw(t){return t===!0||t===!1}function cw(t){return aw(t)?t:t?.capture??!1}function $a(t){const e={capture:cw(t),once:!!t?.once};return t?.passive!=null&&(e.passive=t?.passive),t?.signal!=null&&(e.signal=t?.signal),e}function cd(t,e){return $a(t).capture===$a(e).capture}class lw extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const n=this.#e.get(e);return n==null?0:n.length}addEventListener(e,n,r){const o=$a(r);if(o?.signal?.aborted===!0)return;const s=l=>{o.once&&this.removeEventListener(e,n,o),iw(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:cd(l.options,o)))return;super.addEventListener(e,s,o);const c=()=>{this.removeEventListener(e,n,o)};o.signal?.addEventListener("abort",c),i.push({callback:n,wrapper:s,options:o,onAbort:c})}removeEventListener(e,n,r){const o=this.#e.get(e);if(o==null){super.removeEventListener(e,n??null,r);return}this.#e.set(e,o.filter(s=>s.callback===n&&cd(s.options,r)?(super.removeEventListener(e,s.wrapper,r),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,n={}){return this.dispatchEvent(new CustomEvent(e,n))}}const dw=Symbol.for("@libp2p/service-capabilities");function uw(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 oi(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 fw(t){return new TextEncoder().encode(t)}function hw(t){return new TextDecoder().decode(t)}function pw(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(n[i]!==255)throw new TypeError(s+" is ambiguous");n[i]=o}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var m=0,b=0,w=0,I=g.length;w!==I&&g[w]===0;)w++,m++;for(var y=(I-w)*d+1>>>0,A=new Uint8Array(y);w!==I;){for(var N=g[w],k=0,T=y-1;(N!==0||k<b)&&T!==-1;T--,k++)N+=256*A[T]>>>0,A[T]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");b=k,w++}for(var S=y-b;S!==y&&A[S]===0;)S++;for(var v=c.repeat(m);S<y;++S)v+=t.charAt(A[S]);return v}function f(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var m=0;if(g[m]!==" "){for(var b=0,w=0;g[m]===c;)b++,m++;for(var I=(g.length-m)*l+1>>>0,y=new Uint8Array(I);g[m];){var A=n[g.charCodeAt(m)];if(A===255)return;for(var N=0,k=I-1;(A!==0||N<w)&&k!==-1;k--,N++)A+=a*y[k]>>>0,y[k]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");w=N,m++}if(g[m]!==" "){for(var T=I-w;T!==I&&y[T]===0;)T++;for(var S=new Uint8Array(b+(I-T)),v=b;T!==I;)S[v++]=y[T++];return S}}}function h(g){var m=f(g);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:h}}var gw=pw,mw=gw;class ww{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 yw{name;prefix;baseDecode;prefixCodePoint;constructor(e,n,r){this.name=e,this.prefix=n;const o=n.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Gf(this,e)}}class bw{decoders;constructor(e){this.decoders=e}or(e){return Gf(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 Gf(t,e){return new bw({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class vw{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,n,r,o){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=o,this.encoder=new ww(e,n,r),this.decoder=new yw(e,n,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function si({name:t,prefix:e,encode:n,decode:r}){return new vw(t,e,n,r)}function Eo({name:t,prefix:e,alphabet:n}){const{encode:r,decode:o}=mw(n,t);return si({prefix:e,name:t,encode:r,decode:s=>oi(o(s))})}function Sw(t,e,n,r){let o=t.length;for(;t[o-1]==="=";)--o;const s=new Uint8Array(o*n/8|0);let i=0,a=0,c=0;for(let l=0;l<o;++l){const d=e[t[l]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<n|d,i+=n,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=n||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function xw(t,e,n){const r=e[e.length-1]==="=",o=(1<<n)-1;let s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>n;)i-=n,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<n-i]),r)for(;(s.length*n&7)!==0;)s+="=";return s}function Ew(t){const e={};for(let n=0;n<t.length;++n)e[t[n]]=n;return e}function Ne({name:t,prefix:e,bitsPerChar:n,alphabet:r}){const o=Ew(r);return si({prefix:e,name:t,encode(s){return xw(s,r,n)},decode(s){return Sw(s,o,n,t)}})}const He=Eo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Aw=Eo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),kw=Object.freeze(Object.defineProperty({__proto__:null,base58btc:He,base58flickr:Aw},Symbol.toStringTag,{value:"Module"})),no=Ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Cw=Ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Iw=Ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Rw=Ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Tw=Ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Pw=Ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Nw=Ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Lw=Ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Bw=Ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),_w=Object.freeze(Object.defineProperty({__proto__:null,base32:no,base32hex:Tw,base32hexpad:Nw,base32hexpadupper:Lw,base32hexupper:Pw,base32pad:Iw,base32padupper:Rw,base32upper:Cw,base32z:Bw},Symbol.toStringTag,{value:"Module"})),os=Eo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ow=Eo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Dw=Object.freeze(Object.defineProperty({__proto__:null,base36:os,base36upper:Ow},Symbol.toStringTag,{value:"Module"}));var Fw=Wf,ld=128,Mw=-128,jw=Math.pow(2,31);function Wf(t,e,n){e=e||[],n=n||0;for(var r=n;t>=jw;)e[n++]=t&255|ld,t/=128;for(;t&Mw;)e[n++]=t&255|ld,t>>>=7;return e[n]=t|0,Wf.bytes=n-r+1,e}var Hw=qa,Uw=128,dd=127;function qa(t,r){var n=0,r=r||0,o=0,s=r,i,a=t.length;do{if(s>=a)throw qa.bytes=0,new RangeError("Could not decode varint");i=t[s++],n+=o<28?(i&dd)<<o:(i&dd)*Math.pow(2,o),o+=7}while(i>=Uw);return qa.bytes=s-r,n}var $w=Math.pow(2,7),qw=Math.pow(2,14),Kw=Math.pow(2,21),zw=Math.pow(2,28),Gw=Math.pow(2,35),Ww=Math.pow(2,42),Vw=Math.pow(2,49),Xw=Math.pow(2,56),Yw=Math.pow(2,63),Zw=function(t){return t<$w?1:t<qw?2:t<Kw?3:t<zw?4:t<Gw?5:t<Ww?6:t<Vw?7:t<Xw?8:t<Yw?9:10},Jw={encode:Fw,decode:Hw,encodingLength:Zw},vs=Jw;function Ka(t,e=0){return[vs.decode(t,e),vs.decode.bytes]}function Ss(t,e,n=0){return vs.encode(t,e,n),e}function xs(t){return vs.encodingLength(t)}function Ao(t,e){const n=e.byteLength,r=xs(t),o=r+xs(n),s=new Uint8Array(o+n);return Ss(t,s,0),Ss(n,s,r),s.set(e,o),new Yc(t,n,e,s)}function Vf(t){const e=oi(t),[n,r]=Ka(e),[o,s]=Ka(e.subarray(r)),i=e.subarray(r+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Yc(n,o,i,e)}function Qw(t,e){if(t===e)return!0;{const n=e;return t.code===n.code&&t.size===n.size&&n.bytes instanceof Uint8Array&&uw(t.bytes,n.bytes)}}class Yc{code;size;digest;bytes;constructor(e,n,r,o){this.code=e,this.size=n,this.digest=r,this.bytes=o}}function ud(t,e){const{bytes:n,version:r}=t;return r===0?ty(n,za(t),e??He.encoder):ny(n,za(t),e??no.encoder)}const fd=new WeakMap;function za(t){const e=fd.get(t);if(e==null){const n=new Map;return fd.set(t,n),n}return e}class ue{code;version;multihash;bytes;"/";constructor(e,n,r,o){this.code=n,this.version=e,this.multihash=r,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:e,multihash:n}=this;if(e!==Tr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==ry)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ue.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=Ao(e,n);return ue.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 ue.equals(this,e)}static equals(e,n){const r=n;return r!=null&&e.code===r.code&&e.version===r.version&&Qw(e.multihash,r.multihash)}toString(e){return ud(this,e)}toJSON(){return{"/":ud(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 ue)return n;if(n["/"]!=null&&n["/"]===n.bytes||n.asCID===n){const{version:r,code:o,multihash:s,bytes:i}=n;return new ue(r,o,s,i??hd(r,o,s.bytes))}else if(n[oy]===!0){const{version:r,multihash:o,code:s}=n,i=Vf(o);return ue.create(r,s,i)}else return null}static create(e,n,r){if(typeof n!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(n!==Tr)throw new Error(`Version 0 CID must use dag-pb (code: ${Tr}) block encoding`);return new ue(e,n,r,r.bytes)}case 1:{const o=hd(e,n,r.bytes);return new ue(e,n,r,o)}default:throw new Error("Invalid version")}}static createV0(e){return ue.create(0,Tr,e)}static createV1(e,n){return ue.create(1,e,n)}static decode(e){const[n,r]=ue.decodeFirst(e);if(r.length!==0)throw new Error("Incorrect length");return n}static decodeFirst(e){const n=ue.inspectBytes(e),r=n.size-n.multihashSize,o=oi(e.subarray(r,r+n.multihashSize));if(o.byteLength!==n.multihashSize)throw new Error("Incorrect length");const s=o.subarray(n.multihashSize-n.digestSize),i=new Yc(n.multihashCode,n.digestSize,s,o);return[n.version===0?ue.createV0(i):ue.createV1(n.codec,i),e.subarray(n.size)]}static inspectBytes(e){let n=0;const r=()=>{const[u,f]=Ka(e.subarray(n));return n+=f,u};let o=r(),s=Tr;if(o===18?(o=0,n=0):s=r(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);const i=n,a=r(),c=r(),l=n+c,d=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:l}}static parse(e,n){const[r,o]=ey(e,n),s=ue.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return za(s).set(r,e),s}}function ey(t,e){switch(t[0]){case"Q":{const n=e??He;return[He.prefix,n.decode(`${He.prefix}${t}`)]}case He.prefix:{const n=e??He;return[He.prefix,n.decode(t)]}case no.prefix:{const n=e??no;return[no.prefix,n.decode(t)]}case os.prefix:{const n=e??os;return[os.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 ty(t,e,n){const{prefix:r}=n;if(r!==He.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);const o=e.get(r);if(o==null){const s=n.encode(t).slice(1);return e.set(r,s),s}else return o}function ny(t,e,n){const{prefix:r}=n,o=e.get(r);if(o==null){const s=n.encode(t);return e.set(r,s),s}else return o}const Tr=112,ry=18;function hd(t,e,n){const r=xs(t),o=r+xs(e),s=new Uint8Array(o+n.byteLength);return Ss(t,s,0),Ss(e,s,r),s.set(n,o),s}const oy=Symbol.for("@ipld/js-cid/CID"),Xf=0,sy="identity",Yf=oi;function iy(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 Ao(Xf,Yf(t))}const ko={code:Xf,name:sy,encode:Yf,digest:iy};function dt(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 qe(t=0){return new Uint8Array(t)}function Bt(t=0){return new Uint8Array(t)}function Ga(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));const n=Bt(e);let r=0;for(const o of t)n.set(o,r),r+=o.length;return n}const Zf=Symbol.for("@achingbrain/uint8arraylist");function pd(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let n=0;for(const r of t){const o=n+r.byteLength;if(e<o)return{buf:r,index:e-n};n=o}throw new RangeError("index is out of bounds")}function _o(t){return!!t?.[Zf]}class ce{bufs;length;[Zf]=!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(_o(r)){n+=r.byteLength;for(const o of r.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=n}prepend(...e){this.prependAll(e)}prependAll(e){let n=0;for(const r of e.reverse())if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.unshift(r);else if(_o(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=pd(this.bufs,e);return n.buf[n.index]}set(e,n){const r=pd(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(_o(e))for(let r=0;r<e.length;r++)this.set(n+r,e.get(r));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,n){const{bufs:r,length:o}=this._subList(e,n);return Ga(r,o)}subarray(e,n){const{bufs:r,length:o}=this._subList(e,n);return r.length===1?r[0]:Ga(r,o)}sublist(e,n){const{bufs:r,length:o}=this._subList(e,n),s=new ce;return s.length=o,s.bufs=r,s}_subList(e,n){if(e=e??0,n=n??this.length,e<0&&(e=this.length+e),n<0&&(n=this.length+n),e<0||n>this.length)throw new RangeError("index is out of bounds");if(e===n)return{bufs:[],length:0};if(e===0&&n===this.length)return{bufs:[...this.bufs],length:this.length};const r=[];let o=0;for(let s=0;s<this.bufs.length;s++){const i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;const l=e>=a&&e<c,d=n>a&&n<=c;if(l&&d){if(e===a&&n===c){r.push(i);break}const u=e-a;r.push(i.subarray(u,u+(n-e)));break}if(l){if(e===0){r.push(i);continue}r.push(i.subarray(e-a));continue}if(d){if(n===c){r.push(i);break}r.push(i.subarray(0,n-a));break}r.push(i)}return{bufs:r,length:n-e}}indexOf(e,n=0){if(!_o(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(n=Number(n??0),isNaN(n)&&(n=0),n<0&&(n=this.length+n),n<0&&(n=0),e.length===0)return n>this.length?this.length:n;const o=r.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");const s=256,i=new Int32Array(s);for(let u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[r[u]]=u;const a=i,c=this.byteLength-r.byteLength,l=r.byteLength-1;let d;for(let u=n;u<=c;u+=d){d=0;for(let f=l;f>=0;f--){const h=this.get(u+f);if(r[f]!==h){d=Math.max(1,f-a[h]);break}}if(d===0)return u}return-1}getInt8(e){const n=this.subarray(e,e+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt8(0)}setInt8(e,n){const r=Bt(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,n),this.write(r,e)}getInt16(e,n){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,n)}setInt16(e,n,r){const o=qe(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,n,r),this.write(o,e)}getInt32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,n)}setInt32(e,n,r){const o=qe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,n,r),this.write(o,e)}getBigInt64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,n)}setBigInt64(e,n,r){const o=qe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,n,r),this.write(o,e)}getUint8(e){const n=this.subarray(e,e+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint8(0)}setUint8(e,n){const r=Bt(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,n),this.write(r,e)}getUint16(e,n){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,n)}setUint16(e,n,r){const o=qe(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,n,r),this.write(o,e)}getUint32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,n)}setUint32(e,n,r){const o=qe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,n,r),this.write(o,e)}getBigUint64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,n)}setBigUint64(e,n,r){const o=qe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,n,r),this.write(o,e)}getFloat32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,n)}setFloat32(e,n,r){const o=qe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,n,r),this.write(o,e)}getFloat64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,n)}setFloat64(e,n,r){const o=qe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,n,r),this.write(o,e)}equals(e){if(e==null||!(e instanceof ce)||e.bufs.length!==this.bufs.length)return!1;for(let n=0;n<this.bufs.length;n++)if(!dt(this.bufs[n],e.bufs[n]))return!1;return!0}static fromUint8Arrays(e,n){const r=new ce;return r.bufs=e,n==null&&(n=e.reduce((o,s)=>o+s.byteLength,0)),r.length=n,r}}const ay=Eo({prefix:"9",name:"base10",alphabet:"0123456789"}),cy=Object.freeze(Object.defineProperty({__proto__:null,base10:ay},Symbol.toStringTag,{value:"Module"})),ly=Ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),dy=Ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),uy=Object.freeze(Object.defineProperty({__proto__:null,base16:ly,base16upper:dy},Symbol.toStringTag,{value:"Module"})),fy=Ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),hy=Object.freeze(Object.defineProperty({__proto__:null,base2:fy},Symbol.toStringTag,{value:"Module"})),Jf=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),py=Jf.reduce((t,e,n)=>(t[n]=e,t),[]),gy=Jf.reduce((t,e,n)=>{const r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return t[r]=n,t},[]);function my(t){return t.reduce((e,n)=>(e+=py[n],e),"")}function wy(t){const e=[];for(const n of t){const r=n.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${n}`);const o=gy[r];if(o==null)throw new Error(`Non-base256emoji character: ${n}`);e.push(o)}return new Uint8Array(e)}const yy=si({prefix:"🚀",name:"base256emoji",encode:my,decode:wy}),by=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:yy},Symbol.toStringTag,{value:"Module"})),vy=Ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Sy=Ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),xy=Ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ey=Ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Ay=Object.freeze(Object.defineProperty({__proto__:null,base64:vy,base64pad:Sy,base64url:xy,base64urlpad:Ey},Symbol.toStringTag,{value:"Module"})),ky=Ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Cy=Object.freeze(Object.defineProperty({__proto__:null,base8:ky},Symbol.toStringTag,{value:"Module"})),Iy=si({prefix:"\0",name:"identity",encode:t=>hw(t),decode:t=>fw(t)}),Ry=Object.freeze(Object.defineProperty({__proto__:null,identity:Iy},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const Ty=20;function Py({name:t,code:e,encode:n,minDigestLength:r,maxDigestLength:o}){return new Ny(t,e,n,r,o)}class Ny{name;code;encode;minDigestLength;maxDigestLength;constructor(e,n,r,o,s){this.name=e,this.code=n,this.encode=r,this.minDigestLength=o??Ty,this.maxDigestLength=s}digest(e,n){if(n?.truncate!=null){if(n.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&n.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?gd(r,this.code,n?.truncate):r.then(o=>gd(o,this.code,n?.truncate))}else throw Error("Unknown type, must be binary type")}}function gd(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 Ao(e,t)}function Ly(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}const Zc=Py({name:"sha2-256",code:18,encode:Ly("SHA-256")}),md={...Ry,...hy,...Cy,...cy,...uy,..._w,...Dw,...kw,...Ay,...by};function Qf(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const wd=Qf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Oi=Qf("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=Bt(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),eh={utf8:wd,"utf-8":wd,hex:md.base16,latin1:Oi,ascii:Oi,binary:Oi,...md};function Se(t,e="utf8"){const n=eh[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.decoder.decode(`${n.prefix}${t}`)}function te(t,e="utf8"){const n=eh[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.encoder.encode(t).substring(1)}const By=parseInt("11111",2),Wa=parseInt("10000000",2),_y=parseInt("01111111",2),yd={0:Pr,1:Pr,2:Oy,3:My,4:jy,5:Fy,6:Dy,16:Pr,22:Pr,48:Pr};function br(t,e={offset:0}){const n=t[e.offset]&By;if(e.offset++,yd[n]!=null)return yd[n](t,e);throw new Error("No decoder for tag "+n)}function Co(t,e){let n=0;if((t[e.offset]&Wa)===Wa){const r=t[e.offset]&_y;let o="0x";e.offset++;for(let s=0;s<r;s++,e.offset++)o+=t[e.offset].toString(16).padStart(2,"0");n=parseInt(o,16)}else n=t[e.offset],e.offset++;return n}function Pr(t,e){Co(t,e);const n=[];for(;!(e.offset>=t.byteLength);){const r=br(t,e);if(r===null)break;n.push(r)}return n}function Oy(t,e){const n=Co(t,e),r=e.offset,o=e.offset+n,s=[];for(let i=r;i<o;i++)i===r&&t[i]===0||s.push(t[i]);return e.offset+=n,Uint8Array.from(s)}function Dy(t,e){const n=Co(t,e),r=e.offset+n,o=t[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<r;){const l=t[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let d=0;for(let u=0;u<c.length;u++)d+=c[u]<<u*7;a+=`.${d}`,c=[]}}return a}function Fy(t,e){return e.offset++,null}function My(t,e){const n=Co(t,e),r=t[e.offset];e.offset++;const o=t.subarray(e.offset,e.offset+n-1);if(e.offset+=n,r!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function jy(t,e){const n=Co(t,e),r=t.subarray(e.offset,e.offset+n);return e.offset+=n,r}function Hy(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);const n=new ce;for(let r=0;r<e.length;r+=2)n.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return n}function ii(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);const e=Hy(t.byteLength);return new ce(Uint8Array.from([e.byteLength|Wa]),e)}function Xe(t){const e=new ce,n=128;return(t.subarray()[0]&n)===n&&e.append(Uint8Array.from([0])),e.append(t),new ce(Uint8Array.from([2]),ii(e),e)}function Jc(t){const e=Uint8Array.from([0]),n=new ce(e,t);return new ce(Uint8Array.from([3]),ii(n),n)}function Uy(t){return new ce(Uint8Array.from([4]),ii(t),t)}function Pt(t,e=48){const n=new ce;for(const r of t)n.append(r);return new ce(Uint8Array.from([e]),ii(n),n)}async function $y(t,e,n){const r=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["sign"]);n?.signal?.throwIfAborted();const o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function qy(t,e,n,r){const o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();const s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,n.subarray());return r?.signal?.throwIfAborted(),s}const Ky=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),zy=Uint8Array.from([6,5,43,129,4,0,34]),Gy=Uint8Array.from([6,5,43,129,4,0,35]),th={ext:!0,kty:"EC",crv:"P-256"},nh={ext:!0,kty:"EC",crv:"P-384"},rh={ext:!0,kty:"EC",crv:"P-521"},Xn=32,Yn=48,Zn=66;function Wy(t){const e=br(t);return Vy(e)}function Vy(t){const e=t[1],n=te(e,"base64url"),r=t[2][1][0],o=1;let s,i;if(e.byteLength===Xn)return s=te(r.subarray(o,o+Xn),"base64url"),i=te(r.subarray(o+Xn),"base64url"),new Di({...th,key_ops:["sign"],d:n,x:s,y:i});if(e.byteLength===Yn)return s=te(r.subarray(o,o+Yn),"base64url"),i=te(r.subarray(o+Yn),"base64url"),new Di({...nh,key_ops:["sign"],d:n,x:s,y:i});if(e.byteLength===Zn)return s=te(r.subarray(o,o+Zn),"base64url"),i=te(r.subarray(o+Zn),"base64url"),new Di({...rh,key_ops:["sign"],d:n,x:s,y:i});throw new lt(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function oh(t){const e=br(t);return Xy(e)}function Xy(t){const e=t[1][1][0],n=1;let r,o;if(e.byteLength===Xn*2+1)return r=te(e.subarray(n,n+Xn),"base64url"),o=te(e.subarray(n+Xn),"base64url"),new ss({...th,key_ops:["verify"],x:r,y:o});if(e.byteLength===Yn*2+1)return r=te(e.subarray(n,n+Yn),"base64url"),o=te(e.subarray(n+Yn),"base64url"),new ss({...nh,key_ops:["verify"],x:r,y:o});if(e.byteLength===Zn*2+1)return r=te(e.subarray(n,n+Zn),"base64url"),o=te(e.subarray(n+Zn),"base64url"),new ss({...rh,key_ops:["verify"],x:r,y:o});throw new lt(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Yy(t){return Pt([Xe(Uint8Array.from([1])),Uy(Se(t.d??"","base64url")),Pt([sh(t.crv)],160),Pt([Jc(new ce(Uint8Array.from([4]),Se(t.x??"","base64url"),Se(t.y??"","base64url")))],161)]).subarray()}function Zy(t){return Pt([Xe(Uint8Array.from([1])),Pt([sh(t.crv)],160),Pt([Jc(new ce(Uint8Array.from([4]),Se(t.x??"","base64url"),Se(t.y??"","base64url")))],161)]).subarray()}function sh(t){if(t==="P-256")return Ky;if(t==="P-384")return zy;if(t==="P-521")return Gy;throw new lt(`Invalid curve ${t}`)}class ss{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Zy(this.jwk)),this._raw}toMultihash(){return ko.digest(fi(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return He.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:dt(this.raw,e.raw)}async verify(e,n,r){return qy(this.jwk,n,e,r)}}class Di{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new ss({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=Yy(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:dt(this.raw,e.raw)}async sign(e,n){return $y(this.jwk,e,n)}}const On=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Io(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Va(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function An(t,...e){if(!Io(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 ih(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Va(t.outputLen),Va(t.blockLen)}function Es(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 Jy(t,e){An(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function dr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Fi(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function ft(t,e){return t<<32-e|t>>>e}const ah=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qy=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function hn(t){if(An(t),ah)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Qy[t[n]];return e}const vt={_0:48,_9:57,A:65,F:70,a:97,f:102};function bd(t){if(t>=vt._0&&t<=vt._9)return t-vt._0;if(t>=vt.A&&t<=vt.F)return t-(vt.A-10);if(t>=vt.a&&t<=vt.f)return t-(vt.a-10)}function As(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(ah)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){const i=bd(t.charCodeAt(s)),a=bd(t.charCodeAt(s+1));if(i===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a}return r}function eb(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Qc(t){return typeof t=="string"&&(t=eb(t)),An(t),t}function mt(...t){let e=0;for(let r=0;r<t.length;r++){const o=t[r];An(o),e+=o.length}const n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){const s=t[r];n.set(s,o),o+=s.length}return n}class ch{}function lh(t){const e=r=>t().update(Qc(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function el(t=32){if(On&&typeof On.getRandomValues=="function")return On.getRandomValues(new Uint8Array(t));if(On&&typeof On.randomBytes=="function")return Uint8Array.from(On.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function tb(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const o=BigInt(32),s=BigInt(4294967295),i=Number(n>>o&s),a=Number(n&s),c=r?4:0,l=r?0:4;t.setUint32(e+c,i,r),t.setUint32(e+l,a,r)}function nb(t,e,n){return t&e^~t&n}function rb(t,e,n){return t&e^t&n^e&n}let dh=class extends ch{constructor(e,n,r,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Fi(this.buffer)}update(e){Es(this),e=Qc(e),An(e);const{view:n,buffer:r,blockLen:o}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(o-this.pos,s-i);if(a===o){const c=Fi(e);for(;o<=s-i;i+=o)this.process(c,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Es(this),Jy(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:o,isLE:s}=this;let{pos:i}=this;n[i++]=128,dr(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(r,0),i=0);for(let u=i;u<o;u++)n[u]=0;tb(r,o-8,BigInt(this.length*8),s),this.process(r,0);const a=Fi(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};const Mt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),_e=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Oo=BigInt(2**32-1),vd=BigInt(32);function ob(t,e=!1){return e?{h:Number(t&Oo),l:Number(t>>vd&Oo)}:{h:Number(t>>vd&Oo)|0,l:Number(t&Oo)|0}}function sb(t,e=!1){const n=t.length;let r=new Uint32Array(n),o=new Uint32Array(n);for(let s=0;s<n;s++){const{h:i,l:a}=ob(t[s],e);[r[s],o[s]]=[i,a]}return[r,o]}const Sd=(t,e,n)=>t>>>n,xd=(t,e,n)=>t<<32-n|e>>>n,Dn=(t,e,n)=>t>>>n|e<<32-n,Fn=(t,e,n)=>t<<32-n|e>>>n,Do=(t,e,n)=>t<<64-n|e>>>n-32,Fo=(t,e,n)=>t>>>n-32|e<<64-n;function St(t,e,n,r){const o=(e>>>0)+(r>>>0);return{h:t+n+(o/2**32|0)|0,l:o|0}}const ib=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),ab=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,cb=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),lb=(t,e,n,r,o)=>e+n+r+o+(t/2**32|0)|0,db=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),ub=(t,e,n,r,o,s)=>e+n+r+o+s+(t/2**32|0)|0,fb=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]),jt=new Uint32Array(64);class hb extends dh{constructor(e=32){super(64,e,8,!1),this.A=Mt[0]|0,this.B=Mt[1]|0,this.C=Mt[2]|0,this.D=Mt[3]|0,this.E=Mt[4]|0,this.F=Mt[5]|0,this.G=Mt[6]|0,this.H=Mt[7]|0}get(){const{A:e,B:n,C:r,D:o,E:s,F:i,G:a,H:c}=this;return[e,n,r,o,s,i,a,c]}set(e,n,r,o,s,i,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,n){for(let u=0;u<16;u++,n+=4)jt[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const f=jt[u-15],h=jt[u-2],g=ft(f,7)^ft(f,18)^f>>>3,m=ft(h,17)^ft(h,19)^h>>>10;jt[u]=m+jt[u-7]+g+jt[u-16]|0}let{A:r,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=ft(a,6)^ft(a,11)^ft(a,25),h=d+f+nb(a,c,l)+fb[u]+jt[u]|0,m=(ft(r,2)^ft(r,13)^ft(r,22))+rb(r,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=r,r=h+m|0}r=r+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,s,i,a,c,l,d)}roundClean(){dr(jt)}destroy(){this.set(0,0,0,0,0,0,0,0),dr(this.buffer)}}const uh=sb(["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))),pb=uh[0],gb=uh[1],Ht=new Uint32Array(80),Ut=new Uint32Array(80);class mb extends dh{constructor(e=64){super(128,e,16,!1),this.Ah=_e[0]|0,this.Al=_e[1]|0,this.Bh=_e[2]|0,this.Bl=_e[3]|0,this.Ch=_e[4]|0,this.Cl=_e[5]|0,this.Dh=_e[6]|0,this.Dl=_e[7]|0,this.Eh=_e[8]|0,this.El=_e[9]|0,this.Fh=_e[10]|0,this.Fl=_e[11]|0,this.Gh=_e[12]|0,this.Gl=_e[13]|0,this.Hh=_e[14]|0,this.Hl=_e[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:f,Gh:h,Gl:g,Hh:m,Hl:b}=this;return[e,n,r,o,s,i,a,c,l,d,u,f,h,g,m,b]}set(e,n,r,o,s,i,a,c,l,d,u,f,h,g,m,b){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=d|0,this.Fh=u|0,this.Fl=f|0,this.Gh=h|0,this.Gl=g|0,this.Hh=m|0,this.Hl=b|0}process(e,n){for(let y=0;y<16;y++,n+=4)Ht[y]=e.getUint32(n),Ut[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){const A=Ht[y-15]|0,N=Ut[y-15]|0,k=Dn(A,N,1)^Dn(A,N,8)^Sd(A,N,7),T=Fn(A,N,1)^Fn(A,N,8)^xd(A,N,7),S=Ht[y-2]|0,v=Ut[y-2]|0,E=Dn(S,v,19)^Do(S,v,61)^Sd(S,v,6),_=Fn(S,v,19)^Fo(S,v,61)^xd(S,v,6),L=cb(T,_,Ut[y-7],Ut[y-16]),C=lb(L,k,E,Ht[y-7],Ht[y-16]);Ht[y]=C|0,Ut[y]=L|0}let{Ah:r,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:f,Fh:h,Fl:g,Gh:m,Gl:b,Hh:w,Hl:I}=this;for(let y=0;y<80;y++){const A=Dn(u,f,14)^Dn(u,f,18)^Do(u,f,41),N=Fn(u,f,14)^Fn(u,f,18)^Fo(u,f,41),k=u&h^~u&m,T=f&g^~f&b,S=db(I,N,T,gb[y],Ut[y]),v=ub(S,w,A,k,pb[y],Ht[y]),E=S|0,_=Dn(r,o,28)^Do(r,o,34)^Do(r,o,39),L=Fn(r,o,28)^Fo(r,o,34)^Fo(r,o,39),C=r&s^r&a^s&a,x=o&i^o&c^i&c;w=m|0,I=b|0,m=h|0,b=g|0,h=u|0,g=f|0,{h:u,l:f}=St(l|0,d|0,v|0,E|0),l=a|0,d=c|0,a=s|0,c=i|0,s=r|0,i=o|0;const P=ib(E,L,x);r=ab(P,v,_,C),o=P|0}({h:r,l:o}=St(this.Ah|0,this.Al|0,r|0,o|0)),{h:s,l:i}=St(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=St(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=St(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:f}=St(this.Eh|0,this.El|0,u|0,f|0),{h,l:g}=St(this.Fh|0,this.Fl|0,h|0,g|0),{h:m,l:b}=St(this.Gh|0,this.Gl|0,m|0,b|0),{h:w,l:I}=St(this.Hh|0,this.Hl|0,w|0,I|0),this.set(r,o,s,i,a,c,l,d,u,f,h,g,m,b,w,I)}roundClean(){dr(Ht,Ut)}destroy(){dr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const fh=lh(()=>new hb),wb=lh(()=>new mb);const tl=BigInt(0),Xa=BigInt(1);function bn(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function at(t,e,n=""){const r=Io(t),o=t?.length,s=e!==void 0;if(!r||s&&o!==e){const i=n&&`"${n}" `,a=s?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function Mo(t){const e=t.toString(16);return e.length&1?"0"+e:e}function hh(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?tl:BigInt("0x"+t)}function ai(t){return hh(hn(t))}function ho(t){return An(t),hh(hn(Uint8Array.from(t).reverse()))}function nl(t,e){return As(t.toString(16).padStart(e*2,"0"))}function ph(t,e){return nl(t,e).reverse()}function ge(t,e,n){let r;if(typeof e=="string")try{r=As(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Io(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const o=r.length;if(typeof n=="number"&&o!==n)throw new Error(t+" of length "+n+" expected, got "+o);return r}function Ed(t){return Uint8Array.from(t)}const Mi=t=>typeof t=="bigint"&&tl<=t;function yb(t,e,n){return Mi(t)&&Mi(e)&&Mi(n)&&e<=t&&t<n}function Ya(t,e,n,r){if(!yb(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function gh(t){let e;for(e=0;t>tl;t>>=Xa,e+=1);return e}const Ro=t=>(Xa<<BigInt(t))-Xa;function bb(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=h=>new Uint8Array(h),o=h=>Uint8Array.of(h);let s=r(t),i=r(t),a=0;const c=()=>{s.fill(1),i.fill(0),a=0},l=(...h)=>n(i,s,...h),d=(h=r(0))=>{i=l(o(0),h),s=l(),h.length!==0&&(i=l(o(1),h),s=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const g=[];for(;h<e;){s=l();const m=s.slice();g.push(m),h+=s.length}return mt(...g)};return(h,g)=>{c(),d(h);let m;for(;!(m=g(u()));)d();return c(),m}}function To(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(o,s,i){const a=t[o];if(i&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([o,s])=>r(o,s,!1)),Object.entries(n).forEach(([o,s])=>r(o,s,!0))}function ks(t){const e=new WeakMap;return(n,...r)=>{const o=e.get(n);if(o!==void 0)return o;const s=t(n,...r);return e.set(n,s),s}}const Ke=BigInt(0),Pe=BigInt(1),an=BigInt(2),mh=BigInt(3),wh=BigInt(4),yh=BigInt(5),vb=BigInt(7),bh=BigInt(8),Sb=BigInt(9),vh=BigInt(16);function xe(t,e){const n=t%e;return n>=Ke?n:e+n}function pe(t,e,n){let r=t;for(;e-- >Ke;)r*=r,r%=n;return r}function Ad(t,e){if(t===Ke)throw new Error("invert: expected non-zero number");if(e<=Ke)throw new Error("invert: expected positive modulus, got "+e);let n=xe(t,e),r=e,o=Ke,s=Pe;for(;n!==Ke;){const a=r/n,c=r%n,l=o-s*a;r=n,n=c,o=s,s=l}if(r!==Pe)throw new Error("invert: does not exist");return xe(o,e)}function rl(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Sh(t,e){const n=(t.ORDER+Pe)/wh,r=t.pow(e,n);return rl(t,r,e),r}function xb(t,e){const n=(t.ORDER-yh)/bh,r=t.mul(e,an),o=t.pow(r,n),s=t.mul(e,o),i=t.mul(t.mul(s,an),o),a=t.mul(s,t.sub(i,t.ONE));return rl(t,a,e),a}function Eb(t){const e=kn(t),n=xh(t),r=n(e,e.neg(e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+vb)/vh;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,r);const u=a.mul(l,o),f=a.mul(l,s),h=a.eql(a.sqr(d),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,d,h),d=a.cmov(f,u,g);const m=a.eql(a.sqr(d),c),b=a.cmov(l,d,m);return rl(a,b,c),b}}function xh(t){if(t<mh)throw new Error("sqrt is not defined for small field");let e=t-Pe,n=0;for(;e%an===Ke;)e/=an,n++;let r=an;const o=kn(t);for(;kd(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Sh;let s=o.pow(r,e);const i=(e+Pe)/an;return function(c,l){if(c.is0(l))return l;if(kd(c,l)!==1)throw new Error("Cannot find square root");let d=n,u=c.mul(c.ONE,s),f=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let g=1,m=c.sqr(f);for(;!c.eql(m,c.ONE);)if(g++,m=c.sqr(m),g===d)throw new Error("Cannot find square root");const b=Pe<<BigInt(d-g-1),w=c.pow(u,b);d=g,u=c.sqr(w),f=c.mul(f,u),h=c.mul(h,w)}return h}}function Ab(t){return t%wh===mh?Sh:t%bh===yh?xb:t%vh===Sb?Eb(t):xh(t)}const kb=(t,e)=>(xe(t,e)&Pe)===Pe,Cb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ib(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=Cb.reduce((r,o)=>(r[o]="function",r),e);return To(t,n),t}function Rb(t,e,n){if(n<Ke)throw new Error("invalid exponent, negatives unsupported");if(n===Ke)return t.ONE;if(n===Pe)return e;let r=t.ONE,o=e;for(;n>Ke;)n&Pe&&(r=t.mul(r,o)),o=t.sqr(o),n>>=Pe;return r}function Eh(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),o=e.reduce((i,a,c)=>t.is0(a)?i:(r[c]=i,t.mul(i,a)),t.ONE),s=t.inv(o);return e.reduceRight((i,a,c)=>t.is0(a)?i:(r[c]=t.mul(i,r[c]),t.mul(i,a)),s),r}function kd(t,e){const n=(t.ORDER-Pe)/an,r=t.pow(e,n),o=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),i=t.eql(r,t.neg(t.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function Ah(t,e){e!==void 0&&Va(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function kn(t,e,n=!1,r={}){if(t<=Ke)throw new Error("invalid field: expected ORDER > 0, got "+t);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const f=e;f.BITS&&(o=f.BITS),f.sqrt&&(s=f.sqrt),typeof f.isLE=="boolean"&&(n=f.isLE),typeof f.modFromBytes=="boolean"&&(i=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(o=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:l}=Ah(t,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:l,MASK:Ro(c),ZERO:Ke,ONE:Pe,allowedLengths:a,create:f=>xe(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return Ke<=f&&f<t},is0:f=>f===Ke,isValidNot0:f=>!u.is0(f)&&u.isValid(f),isOdd:f=>(f&Pe)===Pe,neg:f=>xe(-f,t),eql:(f,h)=>f===h,sqr:f=>xe(f*f,t),add:(f,h)=>xe(f+h,t),sub:(f,h)=>xe(f-h,t),mul:(f,h)=>xe(f*h,t),pow:(f,h)=>Rb(u,f,h),div:(f,h)=>xe(f*Ad(h,t),t),sqrN:f=>f*f,addN:(f,h)=>f+h,subN:(f,h)=>f-h,mulN:(f,h)=>f*h,inv:f=>Ad(f,t),sqrt:s||(f=>(d||(d=Ab(t)),d(u,f))),toBytes:f=>n?ph(f,l):nl(f,l),fromBytes:(f,h=!0)=>{if(a){if(!a.includes(f.length)||f.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);const m=new Uint8Array(l);m.set(f,n?0:m.length-f.length),f=m}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let g=n?ho(f):ai(f);if(i&&(g=xe(g,t)),!h&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:f=>Eh(u,f),cmov:(f,h,g)=>g?h:f});return Object.freeze(u)}function kh(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 Ch(t){const e=kh(t);return e+Math.ceil(e/2)}function Tb(t,e,n=!1){const r=t.length,o=kh(e),s=Ch(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const i=n?ho(t):ai(t),a=xe(i,e-Pe)+Pe;return n?ph(a,o):nl(a,o)}const ur=BigInt(0),cn=BigInt(1);function Cs(t,e){const n=e.negate();return t?n:e}function ln(t,e){const n=Eh(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function Ih(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ji(t,e){Ih(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,s=Ro(t),i=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function Cd(t,e,n){const{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n;let a=Number(t&o),c=t>>i;a>r&&(a-=s,c+=cn);const l=e*r,d=l+Math.abs(a)-1,u=a===0,f=a<0,h=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:f,isNegF:h,offsetF:l}}function Pb(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 Nb(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 Hi=new WeakMap,Rh=new WeakMap;function Ui(t){return Rh.get(t)||1}function Id(t){if(t!==ur)throw new Error("invalid wNAF")}class Th{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>ur;)n&cn&&(r=r.add(o)),o=o.double(),n>>=cn;return r}precomputeWindow(e,n){const{windows:r,windowSize:o}=ji(n,this.bits),s=[];let i=e,a=i;for(let c=0;c<r;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE;const i=ji(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:f,offsetF:h}=Cd(r,a,i);r=c,d?s=s.add(Cs(f,n[h])):o=o.add(Cs(u,n[l]))}return Id(r),{p:o,f:s}}wNAFUnsafe(e,n,r,o=this.ZERO){const s=ji(e,this.bits);for(let i=0;i<s.windows&&r!==ur;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=Cd(r,i,s);if(r=a,!l){const u=n[c];o=o.add(d?u.negate():u)}}return Id(r),o}getPrecomputes(e,n,r){let o=Hi.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Hi.set(n,o))),o}cached(e,n,r){const o=Ui(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){const s=Ui(e);return s===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,o)}createCache(e,n){Ih(n,this.bits),Rh.set(e,n),Hi.delete(e)}hasCache(e){return Ui(e)!==1}}function Lb(t,e,n,r){let o=e,s=t.ZERO,i=t.ZERO;for(;n>ur||r>ur;)n&cn&&(s=s.add(o)),r&cn&&(i=i.add(o)),o=o.double(),n>>=cn,r>>=cn;return{p1:s,p2:i}}function Ph(t,e,n,r){Pb(n,t),Nb(r,e);const o=n.length,s=r.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,a=gh(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Ro(c),d=new Array(Number(l)+1).fill(i),u=Math.floor((e.BITS-1)/c)*c;let f=i;for(let h=u;h>=0;h-=c){d.fill(i);for(let m=0;m<s;m++){const b=r[m],w=Number(b>>BigInt(h)&l);d[w]=d[w].add(n[m])}let g=i;for(let m=d.length-1,b=i;m>0;m--)b=b.add(d[m]),g=g.add(b);if(f=f.add(g),h!==0)for(let m=0;m<c;m++)f=f.double()}return f}function Rd(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ib(e),e}else return kn(t,{isLE:n})}function Nh(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>ur))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Rd(e.p,n.Fp,r),s=Rd(e.n,n.Fn,r),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}const $t=BigInt(0),Ce=BigInt(1),$i=BigInt(2),Bb=BigInt(8);function _b(t,e,n,r){const o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function Ob(t,e={}){const n=Nh("edwards",t,e,e.FpFnLE),{Fp:r,Fn:o}=n;let s=n.CURVE;const{h:i}=s;To(e,{},{uvRatio:"function"});const a=$i<<BigInt(o.BYTES*8)-Ce,c=b=>r.create(b),l=e.uvRatio||((b,w)=>{try{return{isValid:!0,value:r.sqrt(r.div(b,w))}}catch{return{isValid:!1,value:$t}}});if(!_b(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(b,w,I=!1){const y=I?Ce:$t;return Ya("coordinate "+b,w,y,a),w}function u(b){if(!(b instanceof g))throw new Error("ExtendedPoint expected")}const f=ks((b,w)=>{const{X:I,Y:y,Z:A}=b,N=b.is0();w==null&&(w=N?Bb:r.inv(A));const k=c(I*w),T=c(y*w),S=r.mul(A,w);if(N)return{x:$t,y:Ce};if(S!==Ce)throw new Error("invZ was invalid");return{x:k,y:T}}),h=ks(b=>{const{a:w,d:I}=s;if(b.is0())throw new Error("bad point: ZERO");const{X:y,Y:A,Z:N,T:k}=b,T=c(y*y),S=c(A*A),v=c(N*N),E=c(v*v),_=c(T*w),L=c(v*c(_+S)),C=c(E+c(I*c(T*S)));if(L!==C)throw new Error("bad point: equation left != right (1)");const x=c(y*A),P=c(N*k);if(x!==P)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(w,I,y,A){this.X=d("x",w),this.Y=d("y",I),this.Z=d("z",y,!0),this.T=d("t",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(w){if(w instanceof g)throw new Error("extended point not allowed");const{x:I,y}=w||{};return d("x",I),d("y",y),new g(I,y,Ce,c(I*y))}static fromBytes(w,I=!1){const y=r.BYTES,{a:A,d:N}=s;w=Ed(at(w,y,"point")),bn(I,"zip215");const k=Ed(w),T=w[y-1];k[y-1]=T&-129;const S=ho(k),v=I?a:r.ORDER;Ya("point.y",S,$t,v);const E=c(S*S),_=c(E-Ce),L=c(N*E-A);let{isValid:C,value:x}=l(_,L);if(!C)throw new Error("bad point: invalid y coordinate");const P=(x&Ce)===Ce,R=(T&128)!==0;if(!I&&x===$t&&R)throw new Error("bad point: x=0 and x_0=1");return R!==P&&(x=c(-x)),g.fromAffine({x,y:S})}static fromHex(w,I=!1){return g.fromBytes(ge("point",w),I)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,I=!0){return m.createCache(this,w),I||this.multiply($i),this}assertValidity(){h(this)}equals(w){u(w);const{X:I,Y:y,Z:A}=this,{X:N,Y:k,Z:T}=w,S=c(I*T),v=c(N*A),E=c(y*T),_=c(k*A);return S===v&&E===_}is0(){return this.equals(g.ZERO)}negate(){return new g(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:w}=s,{X:I,Y:y,Z:A}=this,N=c(I*I),k=c(y*y),T=c($i*c(A*A)),S=c(w*N),v=I+y,E=c(c(v*v)-N-k),_=S+k,L=_-T,C=S-k,x=c(E*L),P=c(_*C),R=c(E*C),D=c(L*_);return new g(x,P,D,R)}add(w){u(w);const{a:I,d:y}=s,{X:A,Y:N,Z:k,T}=this,{X:S,Y:v,Z:E,T:_}=w,L=c(A*S),C=c(N*v),x=c(T*y*_),P=c(k*E),R=c((A+N)*(S+v)-L-C),D=P-x,M=P+x,F=c(C-I*L),B=c(R*D),H=c(M*F),$=c(R*F),X=c(D*M);return new g(B,H,X,$)}subtract(w){return this.add(w.negate())}multiply(w){if(!o.isValidNot0(w))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:I,f:y}=m.cached(this,w,A=>ln(g,A));return ln(g,[I,y])[0]}multiplyUnsafe(w,I=g.ZERO){if(!o.isValid(w))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return w===$t?g.ZERO:this.is0()||w===Ce?this:m.unsafe(this,w,y=>ln(g,y),I)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(w){return f(this,w)}clearCofactor(){return i===Ce?this:this.multiplyUnsafe(i)}toBytes(){const{x:w,y:I}=this.toAffine(),y=r.toBytes(I);return y[y.length-1]|=w&Ce?128:0,y}toHex(){return hn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(w){return ln(g,w)}static msm(w,I){return Ph(g,o,w,I)}_setWindowSize(w){this.precompute(w)}toRawBytes(){return this.toBytes()}}g.BASE=new g(s.Gx,s.Gy,Ce,c(s.Gx*s.Gy)),g.ZERO=new g($t,Ce,Ce,$t),g.Fp=r,g.Fn=o;const m=new Th(g,o.BITS);return g.BASE.precompute(8),g}function Db(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is required');To(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:o,Fp:s,Fn:i}=t,a=n.randomBytes||el,c=n.adjustScalarBytes||(v=>v),l=n.domain||((v,E,_)=>{if(bn(_,"phflag"),E.length||_)throw new Error("Contexts/pre-hash are not supported");return v});function d(v){return i.create(ho(v))}function u(v){const E=y.secretKey;v=ge("private key",v,E);const _=ge("hashed private key",e(v),2*E),L=c(_.slice(0,E)),C=_.slice(E,2*E),x=d(L);return{head:L,prefix:C,scalar:x}}function f(v){const{head:E,prefix:_,scalar:L}=u(v),C=o.multiply(L),x=C.toBytes();return{head:E,prefix:_,scalar:L,point:C,pointBytes:x}}function h(v){return f(v).pointBytes}function g(v=Uint8Array.of(),...E){const _=mt(...E);return d(e(l(_,ge("context",v),!!r)))}function m(v,E,_={}){v=ge("message",v),r&&(v=r(v));const{prefix:L,scalar:C,pointBytes:x}=f(E),P=g(_.context,L,v),R=o.multiply(P).toBytes(),D=g(_.context,R,x,v),M=i.create(P+D*C);if(!i.isValid(M))throw new Error("sign failed: invalid s");const F=mt(R,i.toBytes(M));return at(F,y.signature,"result")}const b={zip215:!0};function w(v,E,_,L=b){const{context:C,zip215:x}=L,P=y.signature;v=ge("signature",v,P),E=ge("message",E),_=ge("publicKey",_,y.publicKey),x!==void 0&&bn(x,"zip215"),r&&(E=r(E));const R=P/2,D=v.subarray(0,R),M=ho(v.subarray(R,P));let F,B,H;try{F=t.fromBytes(_,x),B=t.fromBytes(D,x),H=o.multiplyUnsafe(M)}catch{return!1}if(!x&&F.isSmallOrder())return!1;const $=g(C,B.toBytes(),F.toBytes(),E);return B.add(F.multiplyUnsafe($)).subtract(H).clearCofactor().is0()}const I=s.BYTES,y={secretKey:I,publicKey:I,signature:2*I,seed:I};function A(v=a(y.seed)){return at(v,y.seed,"seed")}function N(v){const E=S.randomSecretKey(v);return{secretKey:E,publicKey:h(E)}}function k(v){return Io(v)&&v.length===i.BYTES}function T(v,E){try{return!!t.fromBytes(v,E)}catch{return!1}}const S={getExtendedPublicKey:f,randomSecretKey:A,isValidSecretKey:k,isValidPublicKey:T,toMontgomery(v){const{y:E}=t.fromBytes(v),_=y.publicKey,L=_===32;if(!L&&_!==57)throw new Error("only defined for 25519 and 448");const C=L?s.div(Ce+E,Ce-E):s.div(E-Ce,E+Ce);return s.toBytes(C)},toMontgomerySecret(v){const E=y.secretKey;at(v,E);const _=e(v.subarray(0,E));return c(_).subarray(0,E)},randomPrivateKey:A,precompute(v=8,E=t.BASE){return E.precompute(v,!1)}};return Object.freeze({keygen:N,getPublicKey:h,sign:m,verify:w,utils:S,Point:t,lengths:y})}function Fb(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=kn(e.n,t.nBitLength,!0),o={Fp:n,Fn:r,uvRatio:t.uvRatio},s={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:o,hash:t.hash,eddsaOpts:s}}function Mb(t,e){const n=e.Point;return Object.assign({},e,{ExtendedPoint:n,CURVE:t,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function jb(t){const{CURVE:e,curveOpts:n,hash:r,eddsaOpts:o}=Fb(t),s=Ob(e,n),i=Db(s,r,o);return Mb(t,i)}const Hb=BigInt(1),Td=BigInt(2);BigInt(3);const Ub=BigInt(5),$b=BigInt(8),ol=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Lh={p:ol,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:$b,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function qb(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=ol,a=t*t%s*t%s,c=pe(a,Td,s)*a%s,l=pe(c,Hb,s)*t%s,d=pe(l,Ub,s)*l%s,u=pe(d,e,s)*d%s,f=pe(u,n,s)*u%s,h=pe(f,r,s)*f%s,g=pe(h,o,s)*h%s,m=pe(g,o,s)*h%s,b=pe(m,e,s)*d%s;return{pow_p_5_8:pe(b,Td,s)*t%s,b2:a}}function Kb(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Pd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function zb(t,e){const n=ol,r=xe(e*e*e,n),o=xe(r*r*e,n),s=qb(t*o).pow_p_5_8;let i=xe(t*r*s,n);const a=xe(e*i*i,n),c=i,l=xe(i*Pd,n),d=a===t,u=a===xe(-t,n),f=a===xe(-t*Pd,n);return d&&(i=c),(u||f)&&(i=l),kb(i,n)&&(i=xe(-i,n)),{isValid:d||u,value:i}}const Gb=kn(Lh.p,{isLE:!0}),Wb={...Lh,Fp:Gb,hash:wb,adjustScalarBytes:Kb,uvRatio:zb},Is=jb(Wb);class Nd extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}}class Ld extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class Vb extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}const _t={get(t=globalThis){const e=t.crypto;if(e?.subtle==null)throw new Vb("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}},Rs=32,At=64,Za=32;let Jn;const Bh=(async()=>{try{return await _t.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Xb(){const t=Is.utils.randomPrivateKey(),e=Is.getPublicKey(t);return{privateKey:n0(t,e),publicKey:e}}async function Yb(t,e){let n;t.length===At?n=t.subarray(0,32):n=t;const r={crv:"Ed25519",kty:"OKP",x:te(t.subarray(32),"base64url"),d:te(n,"base64url"),ext:!0,key_ops:["sign"]},o=await _t.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),s=await _t.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function Zb(t,e){const n=t.subarray(0,Za);return Is.sign(e instanceof Uint8Array?e:e.subarray(),n)}async function Jb(t,e){return Jn==null&&(Jn=await Bh),Jn?Yb(t,e):Zb(t,e)}async function Qb(t,e,n){if(t.buffer instanceof ArrayBuffer){const r=await _t.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await _t.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 e0(t,e,n){return Is.verify(e,n instanceof Uint8Array?n:n.subarray(),t)}async function t0(t,e,n){return Jn==null&&(Jn=await Bh),Jn?Qb(t,e,n):e0(t,e,n)}function n0(t,e){const n=new Uint8Array(At);for(let r=0;r<Za;r++)n[r]=t[r],n[Za+r]=e[r];return n}function ci(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}class _h{type="Ed25519";raw;constructor(e){this.raw=po(e,Rs)}toMultihash(){return ko.digest(fi(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return He.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:dt(this.raw,e.raw)}verify(e,n,r){r?.signal?.throwIfAborted();const o=t0(this.raw,n,e);return ci(o)?o.then(s=>(r?.signal?.throwIfAborted(),s)):o}}class Ja{type="Ed25519";raw;publicKey;constructor(e,n){this.raw=po(e,At),this.publicKey=new _h(n)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:dt(this.raw,e.raw)}sign(e,n){n?.signal?.throwIfAborted();const r=Jb(this.raw,e);return ci(r)?r.then(o=>(n?.signal?.throwIfAborted(),o)):(n?.signal?.throwIfAborted(),r)}}function r0(t){if(t.length>At){t=po(t,At+Rs);const r=t.subarray(0,At),o=t.subarray(At,t.length);return new Ja(r,o)}t=po(t,At);const e=t.subarray(0,At),n=t.subarray(Rs);return new Ja(e,n)}function Oh(t){return t=po(t,Rs),new _h(t)}async function o0(){const{privateKey:t,publicKey:e}=Xb();return new Ja(t,e)}function po(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new lt(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}const s0=Math.pow(2,7),i0=Math.pow(2,14),a0=Math.pow(2,21),sl=Math.pow(2,28),il=Math.pow(2,35),al=Math.pow(2,42),cl=Math.pow(2,49),ie=128,Oe=127;function Cn(t){if(t<s0)return 1;if(t<i0)return 2;if(t<a0)return 3;if(t<sl)return 4;if(t<il)return 5;if(t<al)return 6;if(t<cl)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Dh(t,e,n=0){switch(Cn(t)){case 8:e[n++]=t&255|ie,t/=128;case 7:e[n++]=t&255|ie,t/=128;case 6:e[n++]=t&255|ie,t/=128;case 5:e[n++]=t&255|ie,t/=128;case 4:e[n++]=t&255|ie,t>>>=7;case 3:e[n++]=t&255|ie,t>>>=7;case 2:e[n++]=t&255|ie,t>>>=7;case 1:{e[n++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function c0(t,e,n=0){switch(Cn(t)){case 8:e.set(n++,t&255|ie),t/=128;case 7:e.set(n++,t&255|ie),t/=128;case 6:e.set(n++,t&255|ie),t/=128;case 5:e.set(n++,t&255|ie),t/=128;case 4:e.set(n++,t&255|ie),t>>>=7;case 3:e.set(n++,t&255|ie),t>>>=7;case 2:e.set(n++,t&255|ie),t>>>=7;case 1:{e.set(n++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function Fh(t,e){let n=t[e],r=0;if(r+=n&Oe,n<ie||(n=t[e+1],r+=(n&Oe)<<7,n<ie)||(n=t[e+2],r+=(n&Oe)<<14,n<ie)||(n=t[e+3],r+=(n&Oe)<<21,n<ie)||(n=t[e+4],r+=(n&Oe)*sl,n<ie)||(n=t[e+5],r+=(n&Oe)*il,n<ie)||(n=t[e+6],r+=(n&Oe)*al,n<ie)||(n=t[e+7],r+=(n&Oe)*cl,n<ie))return r;throw new RangeError("Could not decode varint")}function l0(t,e){let n=t.get(e),r=0;if(r+=n&Oe,n<ie||(n=t.get(e+1),r+=(n&Oe)<<7,n<ie)||(n=t.get(e+2),r+=(n&Oe)<<14,n<ie)||(n=t.get(e+3),r+=(n&Oe)<<21,n<ie)||(n=t.get(e+4),r+=(n&Oe)*sl,n<ie)||(n=t.get(e+5),r+=(n&Oe)*il,n<ie)||(n=t.get(e+6),r+=(n&Oe)*al,n<ie)||(n=t.get(e+7),r+=(n&Oe)*cl,n<ie))return r;throw new RangeError("Could not decode varint")}function d0(t,e,n=0){return e==null&&(e=Bt(Cn(t))),e instanceof Uint8Array?Dh(t,e,n):c0(t,e,n)}function Mh(t,e=0){return t instanceof Uint8Array?Fh(t,e):l0(t,e)}const ll=new Float32Array([-0]),Zt=new Uint8Array(ll.buffer);function u0(t,e,n){ll[0]=t,e[n]=Zt[0],e[n+1]=Zt[1],e[n+2]=Zt[2],e[n+3]=Zt[3]}function f0(t,e){return Zt[0]=t[e],Zt[1]=t[e+1],Zt[2]=t[e+2],Zt[3]=t[e+3],ll[0]}const dl=new Float64Array([-0]),De=new Uint8Array(dl.buffer);function h0(t,e,n){dl[0]=t,e[n]=De[0],e[n+1]=De[1],e[n+2]=De[2],e[n+3]=De[3],e[n+4]=De[4],e[n+5]=De[5],e[n+6]=De[6],e[n+7]=De[7]}function p0(t,e){return De[0]=t[e],De[1]=t[e+1],De[2]=t[e+2],De[3]=t[e+3],De[4]=t[e+4],De[5]=t[e+5],De[6]=t[e+6],De[7]=t[e+7],dl[0]}const g0=BigInt(Number.MAX_SAFE_INTEGER),m0=BigInt(Number.MIN_SAFE_INTEGER);class Fe{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 pn;if(e<g0&&e>m0)return this.fromNumber(Number(e));const n=e<0n;n&&(e=-e);let r=e>>32n,o=e-(r<<32n);return n&&(r=~r|0n,o=~o|0n,++o>Bd&&(o=0n,++r>Bd&&(r=0n))),new Fe(Number(o),Number(r))}static fromNumber(e){if(e===0)return pn;const n=e<0;n&&(e=-e);let r=e>>>0,o=(e-r)/4294967296>>>0;return n&&(o=~o>>>0,r=~r>>>0,++r>4294967295&&(r=0,++o>4294967295&&(o=0))),new Fe(r,o)}static from(e){return typeof e=="number"?Fe.fromNumber(e):typeof e=="bigint"?Fe.fromBigInt(e):typeof e=="string"?Fe.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new Fe(e.low>>>0,e.high>>>0):pn}}const pn=new Fe(0,0);pn.toBigInt=function(){return 0n};pn.zzEncode=pn.zzDecode=function(){return this};pn.length=function(){return 1};const Bd=4294967296n;function w0(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 y0(t,e,n){if(n-e<1)return"";let o;const s=[];let i=0,a;for(;e<n;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function jh(t,e,n){const r=n;let o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[n++]=o:o<2048?(e[n++]=o>>6|192,e[n++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[n++]=o>>18|240,e[n++]=o>>12&63|128,e[n++]=o>>6&63|128,e[n++]=o&63|128):(e[n++]=o>>12|224,e[n++]=o>>6&63|128,e[n++]=o&63|128);return n-r}function ot(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function jo(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}class b0{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,ot(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 ot(this,4);return jo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ot(this,4);return jo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ot(this,4);const e=f0(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ot(this,4);const e=p0(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 ot(this,e);return this.pos+=e,n===r?new Uint8Array(0):this.buf.subarray(n,r)}string(){const e=this.bytes();return y0(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ot(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ot(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 Fe(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 ot(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 ot(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 ot(this,8);const e=jo(this.buf,this.pos+=4),n=jo(this.buf,this.pos+=4);return new Fe(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=Fh(this.buf,this.pos);return this.pos+=Cn(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 v0(t){return new b0(t instanceof Uint8Array?t:t.subarray())}function li(t,e,n){const r=v0(t);return e.decode(r,void 0,n)}function S0(t){let r,o=8192;return function(i){if(i<1||i>4096)return Bt(i);o+i>8192&&(r=Bt(8192),o=0);const a=r.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}class Yr{fn;len;next;val;constructor(e,n,r){this.fn=e,this.len=n,this.next=void 0,this.val=r}}function qi(){}class x0{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const E0=S0();function A0(t){return globalThis.Buffer!=null?Bt(t):E0(t)}class Qa{len;head;tail;states;constructor(){this.len=0,this.head=new Yr(qi,0,0),this.tail=this.head,this.states=null}_push(e,n,r){return this.tail=this.tail.next=new Yr(e,n,r),this.len+=n,this}uint32(e){return this.len+=(this.tail=this.tail.next=new C0((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(Ho,10,Fe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const n=Fe.fromBigInt(e);return this._push(Ho,n.length(),n)}uint64Number(e){return this._push(Dh,Cn(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=Fe.fromBigInt(e).zzEncode();return this._push(Ho,n.length(),n)}sint64Number(e){const n=Fe.fromNumber(e).zzEncode();return this._push(Ho,n.length(),n)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ki,1,e?1:0)}fixed32(e){return this._push(Nr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const n=Fe.fromBigInt(e);return this._push(Nr,4,n.lo)._push(Nr,4,n.hi)}fixed64Number(e){const n=Fe.fromNumber(e);return this._push(Nr,4,n.lo)._push(Nr,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(u0,4,e)}double(e){return this._push(h0,8,e)}bytes(e){const n=e.length>>>0;return n===0?this._push(Ki,1,0):this.uint32(n)._push(I0,n,e)}string(e){const n=w0(e);return n!==0?this.uint32(n)._push(jh,n,e):this._push(Ki,1,0)}fork(){return this.states=new x0(this),this.head=this.tail=new Yr(qi,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 Yr(qi,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=A0(this.len);let r=0;for(;e!=null;)e.fn(e.val,n,r),r+=e.len,e=e.next;return n}}function Ki(t,e,n){e[n]=t&255}function k0(t,e,n){for(;t>127;)e[n++]=t&127|128,t>>>=7;e[n]=t}class C0 extends Yr{next;constructor(e,n){super(k0,e,n),this.next=void 0}}function Ho(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 Nr(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 I0(t,e,n){e.set(t,n)}globalThis.Buffer!=null&&(Qa.prototype.bytes=function(t){const e=t.length>>>0;return this.uint32(e),e>0&&this._push(R0,e,t),this},Qa.prototype.string=function(t){const e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(T0,e,t),this});function R0(t,e,n){e.set(t,n)}function T0(t,e,n){t.length<40?jh(t,e,n):e.utf8Write!=null?e.utf8Write(t,n):e.set(Se(t),n)}function P0(){return new Qa}function di(t,e){const n=P0();return e.encode(t,n,{lengthDelimited:!1}),n.finish()}var Ts;(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"})(Ts||(Ts={}));function Hh(t,e,n,r){return{name:t,type:e,encode:n,decode:r}}function N0(t){function e(o){if(t[o.toString()]==null)throw new Error("Invalid enum value");return t[o]}const n=function(s,i){const a=e(s);i.int32(a)},r=function(s){const i=s.int32();return e(i)};return Hh("enum",Ts.VARINT,n,r)}function ui(t,e){return Hh("message",Ts.LENGTH_DELIMITED,t,e)}class _d extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var fe;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(fe||(fe={}));var ec;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(ec||(ec={}));(function(t){t.codec=()=>N0(ec)})(fe||(fe={}));var vn;(function(t){let e;t.codec=()=>(e==null&&(e=ui((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),fe.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(n);break}case 2:{s.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>di(n,t.codec()),t.decode=(n,r)=>li(n,t.codec(),r)})(vn||(vn={}));var Ps;(function(t){let e;t.codec=()=>(e==null&&(e=ui((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),fe.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(n);break}case 2:{s.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>di(n,t.codec()),t.decode=(n,r)=>li(n,t.codec(),r)})(Ps||(Ps={}));const Uh=fh;class $h{type="RSA";jwk;_raw;_multihash;constructor(e,n){this.jwk=e,this._multihash=n}get raw(){return this._raw==null&&(this._raw=Kh(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ue.createV1(114,this._multihash)}toString(){return He.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:dt(this.raw,e.raw)}verify(e,n,r){return G0(this.jwk,n,e,r)}}class L0{type="RSA";jwk;_raw;publicKey;constructor(e,n){this.jwk=e,this.publicKey=n}get raw(){return this._raw==null&&(this._raw=F0(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:dt(this.raw,e.raw)}sign(e,n){return z0(this.jwk,e,n)}}const B0=8192,qh=18,_0=1062,O0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function D0(t){return{n:te(t[1],"base64url"),e:te(t[2],"base64url"),d:te(t[3],"base64url"),p:te(t[4],"base64url"),q:te(t[5],"base64url"),dp:te(t[6],"base64url"),dq:te(t[7],"base64url"),qi:te(t[8],"base64url"),kty:"RSA"}}function F0(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 lt("JWK was missing components");return Pt([Xe(Uint8Array.from([0])),Xe(Se(t.n,"base64url")),Xe(Se(t.e,"base64url")),Xe(Se(t.d,"base64url")),Xe(Se(t.p,"base64url")),Xe(Se(t.q,"base64url")),Xe(Se(t.dp,"base64url")),Xe(Se(t.dq,"base64url")),Xe(Se(t.qi,"base64url"))]).subarray()}function M0(t){const e=br(t[1],{offset:0});return{kty:"RSA",n:te(e[0],"base64url"),e:te(e[1],"base64url")}}function Kh(t){if(t.n==null||t.e==null)throw new lt("JWK was missing components");return Pt([O0,Jc(Pt([Xe(Se(t.n,"base64url")),Xe(Se(t.e,"base64url"))]))]).subarray()}function j0(t){const e=br(t);return H0(e)}function H0(t){const e=D0(t);return q0(e)}function U0(t,e){if(t.byteLength>=_0)throw new qf("Key size is too large");const n=br(t,{offset:0});return $0(n,t,e)}function $0(t,e,n){const r=M0(t);if(n==null){const o=Uh(vn.encode({Type:fe.RSA,Data:e}));n=Ao(qh,o)}return new $h(r,n)}function q0(t){if(W0(t)>B0)throw new lt("Key size is too large");const e=K0(t),n=Uh(vn.encode({Type:fe.RSA,Data:Kh(e.publicKey)})),r=Ao(qh,n);return new L0(e.privateKey,new $h(e.publicKey,r))}function K0(t){if(t==null)throw new lt("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function z0(t,e,n){const r=await _t.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);n?.signal?.throwIfAborted();const o=await _t.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function G0(t,e,n,r){const o=await _t.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const s=await _t.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,n instanceof Uint8Array?n:n.subarray());return r?.signal?.throwIfAborted(),s}function W0(t){if(t.kty!=="RSA")throw new lt("invalid key type");if(t.n==null)throw new lt("invalid key modulus");return Se(t.n,"base64url").length*8}class zh extends ch{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,ih(e);const r=Qc(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const o=this.blockLen,s=new Uint8Array(o);s.set(r.length>o?e.create().update(r).digest():r);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),dr(s)}update(e){return Es(this),this.iHash.update(e),this}digestInto(e){Es(this),An(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Gh=(t,e,n)=>new zh(t,e).update(n).digest();Gh.create=(t,e)=>new zh(t,e);const Od=(t,e)=>(t+(t>=0?e:-e)/Wh)/e;function V0(t,e,n){const[[r,o],[s,i]]=e,a=Od(i*t,n),c=Od(-o*t,n);let l=t-a*r-c*s,d=-a*o-c*i;const u=l<It,f=d<It;u&&(l=-l),f&&(d=-d);const h=Ro(Math.ceil(gh(n)/2))+Qn;if(l<It||l>=h||d<It||d>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:f,k2:d}}function tc(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function zi(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return bn(n.lowS,"lowS"),bn(n.prehash,"prehash"),n.format!==void 0&&tc(n.format),n}class X0 extends Error{constructor(e=""){super(e)}}const kt={Err:X0,_tlv:{encode:(t,e)=>{const{Err:n}=kt;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,o=Mo(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Mo(o.length/2|128):"";return Mo(t)+s+o+e},decode(t,e){const{Err:n}=kt;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const o=e[r++],s=!!(o&128);let i=0;if(!s)i=o;else{const c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(r+=c,i<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+i);if(a.length!==i)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+i)}}},_int:{encode(t){const{Err:e}=kt;if(t<It)throw new e("integer: negative integers are not allowed");let n=Mo(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}=kt;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 ai(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=kt,o=ge("signature",t),{v:s,l:i}=r.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:l,l:d}=r.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){const{_tlv:e,_int:n}=kt,r=e.encode(2,n.encode(t.r)),o=e.encode(2,n.encode(t.s)),s=r+o;return e.encode(48,s)}},It=BigInt(0),Qn=BigInt(1),Wh=BigInt(2),Uo=BigInt(3),Y0=BigInt(4);function zn(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let o=ge("private key",e);try{r=t.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function Z0(t,e={}){const n=Nh("weierstrass",t,e),{Fp:r,Fn:o}=n;let s=n.CURVE;const{h:i,n:a}=s;To(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Xh(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(L,C,x){const{x:P,y:R}=C.toAffine(),D=r.toBytes(P);if(bn(x,"isCompressed"),x){d();const M=!r.isOdd(R);return mt(Vh(M),D)}else return mt(Uint8Array.of(4),D,r.toBytes(R))}function f(L){at(L,void 0,"Point");const{publicKey:C,publicKeyUncompressed:x}=l,P=L.length,R=L[0],D=L.subarray(1);if(P===C&&(R===2||R===3)){const M=r.fromBytes(D);if(!r.isValid(M))throw new Error("bad point: is not on curve, wrong x");const F=m(M);let B;try{B=r.sqrt(F)}catch(X){const Y=X instanceof Error?": "+X.message:"";throw new Error("bad point: is not on curve, sqrt error"+Y)}d();const H=r.isOdd(B);return(R&1)===1!==H&&(B=r.neg(B)),{x:M,y:B}}else if(P===x&&R===4){const M=r.BYTES,F=r.fromBytes(D.subarray(0,M)),B=r.fromBytes(D.subarray(M,M*2));if(!b(F,B))throw new Error("bad point: is not on curve");return{x:F,y:B}}else throw new Error(`bad point: got length ${P}, expected compressed=${C} or uncompressed=${x}`)}const h=e.toBytes||u,g=e.fromBytes||f;function m(L){const C=r.sqr(L),x=r.mul(C,L);return r.add(r.add(x,r.mul(L,s.a)),s.b)}function b(L,C){const x=r.sqr(C),P=m(L);return r.eql(x,P)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const w=r.mul(r.pow(s.a,Uo),Y0),I=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(w,I)))throw new Error("bad curve params: a or b");function y(L,C,x=!1){if(!r.isValid(C)||x&&r.is0(C))throw new Error(`bad point coordinate ${L}`);return C}function A(L){if(!(L instanceof v))throw new Error("ProjectivePoint expected")}function N(L){if(!c||!c.basises)throw new Error("no endo");return V0(L,c.basises,o.ORDER)}const k=ks((L,C)=>{const{X:x,Y:P,Z:R}=L;if(r.eql(R,r.ONE))return{x,y:P};const D=L.is0();C==null&&(C=D?r.ONE:r.inv(R));const M=r.mul(x,C),F=r.mul(P,C),B=r.mul(R,C);if(D)return{x:r.ZERO,y:r.ZERO};if(!r.eql(B,r.ONE))throw new Error("invZ was invalid");return{x:M,y:F}}),T=ks(L=>{if(L.is0()){if(e.allowInfinityPoint&&!r.is0(L.Y))return;throw new Error("bad point: ZERO")}const{x:C,y:x}=L.toAffine();if(!r.isValid(C)||!r.isValid(x))throw new Error("bad point: x or y not field elements");if(!b(C,x))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(L,C,x,P,R){return x=new v(r.mul(x.X,L),x.Y,x.Z),C=Cs(P,C),x=Cs(R,x),C.add(x)}class v{constructor(C,x,P){this.X=y("x",C),this.Y=y("y",x,!0),this.Z=y("z",P),Object.freeze(this)}static CURVE(){return s}static fromAffine(C){const{x,y:P}=C||{};if(!C||!r.isValid(x)||!r.isValid(P))throw new Error("invalid affine point");if(C instanceof v)throw new Error("projective point not allowed");return r.is0(x)&&r.is0(P)?v.ZERO:new v(x,P,r.ONE)}static fromBytes(C){const x=v.fromAffine(g(at(C,void 0,"point")));return x.assertValidity(),x}static fromHex(C){return v.fromBytes(ge("pointHex",C))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(C=8,x=!0){return _.createCache(this,C),x||this.multiply(Uo),this}assertValidity(){T(this)}hasEvenY(){const{y:C}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(C)}equals(C){A(C);const{X:x,Y:P,Z:R}=this,{X:D,Y:M,Z:F}=C,B=r.eql(r.mul(x,F),r.mul(D,R)),H=r.eql(r.mul(P,F),r.mul(M,R));return B&&H}negate(){return new v(this.X,r.neg(this.Y),this.Z)}double(){const{a:C,b:x}=s,P=r.mul(x,Uo),{X:R,Y:D,Z:M}=this;let F=r.ZERO,B=r.ZERO,H=r.ZERO,$=r.mul(R,R),X=r.mul(D,D),Y=r.mul(M,M),U=r.mul(R,D);return U=r.add(U,U),H=r.mul(R,M),H=r.add(H,H),F=r.mul(C,H),B=r.mul(P,Y),B=r.add(F,B),F=r.sub(X,B),B=r.add(X,B),B=r.mul(F,B),F=r.mul(U,F),H=r.mul(P,H),Y=r.mul(C,Y),U=r.sub($,Y),U=r.mul(C,U),U=r.add(U,H),H=r.add($,$),$=r.add(H,$),$=r.add($,Y),$=r.mul($,U),B=r.add(B,$),Y=r.mul(D,M),Y=r.add(Y,Y),$=r.mul(Y,U),F=r.sub(F,$),H=r.mul(Y,X),H=r.add(H,H),H=r.add(H,H),new v(F,B,H)}add(C){A(C);const{X:x,Y:P,Z:R}=this,{X:D,Y:M,Z:F}=C;let B=r.ZERO,H=r.ZERO,$=r.ZERO;const X=s.a,Y=r.mul(s.b,Uo);let U=r.mul(x,D),K=r.mul(P,M),q=r.mul(R,F),G=r.add(x,P),z=r.add(D,M);G=r.mul(G,z),z=r.add(U,K),G=r.sub(G,z),z=r.add(x,R);let V=r.add(D,F);return z=r.mul(z,V),V=r.add(U,q),z=r.sub(z,V),V=r.add(P,R),B=r.add(M,F),V=r.mul(V,B),B=r.add(K,q),V=r.sub(V,B),$=r.mul(X,z),B=r.mul(Y,q),$=r.add(B,$),B=r.sub(K,$),$=r.add(K,$),H=r.mul(B,$),K=r.add(U,U),K=r.add(K,U),q=r.mul(X,q),z=r.mul(Y,z),K=r.add(K,q),q=r.sub(U,q),q=r.mul(X,q),z=r.add(z,q),U=r.mul(K,z),H=r.add(H,U),U=r.mul(V,z),B=r.mul(G,B),B=r.sub(B,U),U=r.mul(G,K),$=r.mul(V,$),$=r.add($,U),new v(B,H,$)}subtract(C){return this.add(C.negate())}is0(){return this.equals(v.ZERO)}multiply(C){const{endo:x}=e;if(!o.isValidNot0(C))throw new Error("invalid scalar: out of range");let P,R;const D=M=>_.cached(this,M,F=>ln(v,F));if(x){const{k1neg:M,k1:F,k2neg:B,k2:H}=N(C),{p:$,f:X}=D(F),{p:Y,f:U}=D(H);R=X.add(U),P=S(x.beta,$,Y,M,B)}else{const{p:M,f:F}=D(C);P=M,R=F}return ln(v,[P,R])[0]}multiplyUnsafe(C){const{endo:x}=e,P=this;if(!o.isValid(C))throw new Error("invalid scalar: out of range");if(C===It||P.is0())return v.ZERO;if(C===Qn)return P;if(_.hasCache(this))return this.multiply(C);if(x){const{k1neg:R,k1:D,k2neg:M,k2:F}=N(C),{p1:B,p2:H}=Lb(v,P,D,F);return S(x.beta,B,H,R,M)}else return _.unsafe(P,C)}multiplyAndAddUnsafe(C,x,P){const R=this.multiplyUnsafe(x).add(C.multiplyUnsafe(P));return R.is0()?void 0:R}toAffine(C){return k(this,C)}isTorsionFree(){const{isTorsionFree:C}=e;return i===Qn?!0:C?C(v,this):_.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:C}=e;return i===Qn?this:C?C(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(C=!0){return bn(C,"isCompressed"),this.assertValidity(),h(v,this,C)}toHex(C=!0){return hn(this.toBytes(C))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(C=!0){return this.toBytes(C)}_setWindowSize(C){this.precompute(C)}static normalizeZ(C){return ln(v,C)}static msm(C,x){return Ph(v,o,C,x)}static fromPrivateKey(C){return v.BASE.multiply(zn(o,C))}}v.BASE=new v(s.Gx,s.Gy,r.ONE),v.ZERO=new v(r.ZERO,r.ONE,r.ZERO),v.Fp=r,v.Fn=o;const E=o.BITS,_=new Th(v,e.endo?Math.ceil(E/2):E);return v.BASE.precompute(8),v}function Vh(t){return Uint8Array.of(t?2:3)}function Xh(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function J0(t,e={}){const{Fn:n}=t,r=e.randomBytes||el,o=Object.assign(Xh(t.Fp,n),{seed:Ch(n.ORDER)});function s(h){try{return!!zn(n,h)}catch{return!1}}function i(h,g){const{publicKey:m,publicKeyUncompressed:b}=o;try{const w=h.length;return g===!0&&w!==m||g===!1&&w!==b?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=r(o.seed)){return Tb(at(h,o.seed,"seed"),n.ORDER)}function c(h,g=!0){return t.BASE.multiply(zn(n,h)).toBytes(g)}function l(h){const g=a(h);return{secretKey:g,publicKey:c(g)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:g,publicKey:m,publicKeyUncompressed:b}=o;if(n.allowedLengths||g===m)return;const w=ge("key",h).length;return w===m||w===b}function u(h,g,m=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(g)===!1)throw new Error("second arg must be public key");const b=zn(n,h);return t.fromHex(g).multiply(b).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>zn(n,h),precompute(h=8,g=t.BASE){return g.precompute(h,!1)}},lengths:o})}function Q0(t,e,n={}){ih(e),To(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||el,o=n.hmac||((x,...P)=>Gh(e,x,mt(...P))),{Fp:s,Fn:i}=t,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h}=J0(t,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function b(x){const P=a>>Qn;return x>P}function w(x,P){if(!i.isValidNot0(P))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return P}function I(x,P){tc(P);const R=h.signature,D=P==="compact"?R:P==="recovered"?R+1:void 0;return at(x,D,`${P} signature`)}class y{constructor(P,R,D){this.r=w("r",P),this.s=w("s",R),D!=null&&(this.recovery=D),Object.freeze(this)}static fromBytes(P,R=m){I(P,R);let D;if(R==="der"){const{r:H,s:$}=kt.toSig(at(P));return new y(H,$)}R==="recovered"&&(D=P[0],R="compact",P=P.subarray(1));const M=i.BYTES,F=P.subarray(0,M),B=P.subarray(M,M*2);return new y(i.fromBytes(F),i.fromBytes(B),D)}static fromHex(P,R){return this.fromBytes(As(P),R)}addRecoveryBit(P){return new y(this.r,this.s,P)}recoverPublicKey(P){const R=s.ORDER,{r:D,s:M,recovery:F}=this;if(F==null||![0,1,2,3].includes(F))throw new Error("recovery id invalid");if(a*Wh<R&&F>1)throw new Error("recovery id is ambiguous for h>1 curve");const H=F===2||F===3?D+a:D;if(!s.isValid(H))throw new Error("recovery id 2 or 3 invalid");const $=s.toBytes(H),X=t.fromBytes(mt(Vh((F&1)===0),$)),Y=i.inv(H),U=N(ge("msgHash",P)),K=i.create(-U*Y),q=i.create(M*Y),G=t.BASE.multiplyUnsafe(K).add(X.multiplyUnsafe(q));if(G.is0())throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return b(this.s)}toBytes(P=m){if(tc(P),P==="der")return As(kt.hexFromSig(this));const R=i.toBytes(this.r),D=i.toBytes(this.s);if(P==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return mt(Uint8Array.of(this.recovery),R,D)}return mt(R,D)}toHex(P){return hn(this.toBytes(P))}assertValidity(){}static fromCompact(P){return y.fromBytes(ge("sig",P),"compact")}static fromDER(P){return y.fromBytes(ge("sig",P),"der")}normalizeS(){return this.hasHighS()?new y(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return hn(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return hn(this.toBytes("compact"))}}const A=n.bits2int||function(P){if(P.length>8192)throw new Error("input is too large");const R=ai(P),D=P.length*8-c;return D>0?R>>BigInt(D):R},N=n.bits2int_modN||function(P){return i.create(A(P))},k=Ro(c);function T(x){return Ya("num < 2^"+c,x,It,k),i.toBytes(x)}function S(x,P){return at(x,void 0,"message"),P?at(e(x),void 0,"prehashed message"):x}function v(x,P,R){if(["recovered","canonical"].some(K=>K in R))throw new Error("sign() legacy options not supported");const{lowS:D,prehash:M,extraEntropy:F}=zi(R,g);x=S(x,M);const B=N(x),H=zn(i,P),$=[T(H),T(B)];if(F!=null&&F!==!1){const K=F===!0?r(h.secretKey):F;$.push(ge("extraEntropy",K))}const X=mt(...$),Y=B;function U(K){const q=A(K);if(!i.isValidNot0(q))return;const G=i.inv(q),z=t.BASE.multiply(q).toAffine(),V=i.create(z.x);if(V===It)return;const J=i.create(G*i.create(Y+V*H));if(J===It)return;let oe=(z.x===V?0:2)|Number(z.y&Qn),ne=J;return D&&b(J)&&(ne=i.neg(J),oe^=1),new y(V,ne,oe)}return{seed:X,k2sig:U}}function E(x,P,R={}){x=ge("message",x);const{seed:D,k2sig:M}=v(x,P,R);return bb(e.outputLen,i.BYTES,o)(D,M)}function _(x){let P;const R=typeof x=="string"||Io(x),D=!R&&x!==null&&typeof x=="object"&&typeof x.r=="bigint"&&typeof x.s=="bigint";if(!R&&!D)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(D)P=new y(x.r,x.s);else if(R){try{P=y.fromBytes(ge("sig",x),"der")}catch(M){if(!(M instanceof kt.Err))throw M}if(!P)try{P=y.fromBytes(ge("sig",x),"compact")}catch{return!1}}return P||!1}function L(x,P,R,D={}){const{lowS:M,prehash:F,format:B}=zi(D,g);if(R=ge("publicKey",R),P=S(ge("message",P),F),"strict"in D)throw new Error("options.strict was renamed to lowS");const H=B===void 0?_(x):y.fromBytes(ge("sig",x),B);if(H===!1)return!1;try{const $=t.fromBytes(R);if(M&&H.hasHighS())return!1;const{r:X,s:Y}=H,U=N(P),K=i.inv(Y),q=i.create(U*K),G=i.create(X*K),z=t.BASE.multiplyUnsafe(q).add($.multiplyUnsafe(G));return z.is0()?!1:i.create(z.x)===X}catch{return!1}}function C(x,P,R={}){const{prehash:D}=zi(R,g);return P=S(P,D),y.fromBytes(x,"recovered").recoverPublicKey(P).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h,Point:t,sign:E,verify:L,recoverPublicKey:C,Signature:y,hash:e})}function ev(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp;let r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0;const o=kn(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),s={Fp:n,Fn:o,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function tv(t){const{CURVE:e,curveOpts:n}=ev(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 nv(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,Ah(n.Fn.ORDER,n.Fn.BITS))})}function rv(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:o}=tv(t),s=Z0(e,n),i=Q0(s,r,o);return nv(t,i)}function ov(t,e){const n=r=>rv({...t,hash:r});return{...n(e),create:n}}const ul={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},sv={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Dd=BigInt(2);function iv(t){const e=ul.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,u=pe(d,n,e)*d%e,f=pe(u,n,e)*d%e,h=pe(f,Dd,e)*l%e,g=pe(h,o,e)*h%e,m=pe(g,s,e)*g%e,b=pe(m,a,e)*m%e,w=pe(b,c,e)*b%e,I=pe(w,a,e)*m%e,y=pe(I,n,e)*d%e,A=pe(y,i,e)*g%e,N=pe(A,r,e)*l%e,k=pe(N,Dd,e);if(!nc.eql(nc.sqr(k),t))throw new Error("Cannot find square root");return k}const nc=kn(ul.p,{sqrt:iv}),Qt=ov({...ul,Fp:nc,lowS:!0,endo:sv},fh);function av(t,e,n){const r=Zc.digest(e instanceof Uint8Array?e:e.subarray());if(ci(r))return r.then(({digest:o})=>(n?.signal?.throwIfAborted(),Qt.sign(o,t).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new Nd(String(o))});try{return Qt.sign(r.digest,t).toDERRawBytes()}catch(o){throw new Nd(String(o))}}function cv(t,e,n,r){const o=Zc.digest(n instanceof Uint8Array?n:n.subarray());if(ci(o))return o.then(({digest:s})=>(r?.signal?.throwIfAborted(),Qt.verify(e,s,t))).catch(s=>{throw s.name==="AbortError"?s:new Ld(String(s))});try{return r?.signal?.throwIfAborted(),Qt.verify(e,o.digest,t)}catch(s){throw new Ld(String(s))}}class Yh{type="secp256k1";raw;_key;constructor(e){this._key=hv(e),this.raw=uv(this._key)}toMultihash(){return ko.digest(fi(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return He.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:dt(this.raw,e.raw)}verify(e,n,r){return cv(this._key,n,e,r)}}class lv{type="secp256k1";raw;publicKey;constructor(e,n){this.raw=fv(e),this.publicKey=new Yh(n??pv(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:dt(this.raw,e.raw)}sign(e,n){return av(this.raw,e,n)}}function dv(t){return new lv(t)}function Zh(t){return new Yh(t)}function uv(t){return Qt.ProjectivePoint.fromHex(t).toRawBytes(!0)}function fv(t){try{return Qt.getPublicKey(t,!0),t}catch(e){throw new Kf(String(e))}}function hv(t){try{return Qt.ProjectivePoint.fromHex(t),t}catch(e){throw new qf(String(e))}}function pv(t){try{return Qt.getPublicKey(t,!0)}catch(e){throw new Kf(String(e))}}async function gv(t,e){return o0()}function rc(t,e){const{Type:n,Data:r}=vn.decode(t),o=r??new Uint8Array;switch(n){case fe.RSA:return U0(o,e);case fe.Ed25519:return Oh(o);case fe.secp256k1:return Zh(o);case fe.ECDSA:return oh(o);default:throw new ri}}function mv(t){const{Type:e,Data:n}=vn.decode(t.digest),r=n??new Uint8Array;switch(e){case fe.Ed25519:return Oh(r);case fe.secp256k1:return Zh(r);case fe.ECDSA:return oh(r);default:throw new ri}}function fi(t){return vn.encode({Type:fe[t.type],Data:t.raw})}function wv(t){const e=Ps.decode(t),n=e.Data??new Uint8Array;switch(e.Type){case fe.RSA:return j0(n);case fe.Ed25519:return r0(n);case fe.secp256k1:return dv(n);case fe.ECDSA:return Wy(n);default:throw new ri}}function yv(t){return Ps.encode({Type:fe[t.type],Data:t.raw})}const Jh=Symbol.for("nodejs.util.inspect.custom"),bv=114;class fl{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()})`}[zf]=!0;toString(){return this.string==null&&(this.string=He.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ue.createV1(bv,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return dt(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return dt(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Jh](){return`PeerId(${this.toString()})`}}class Qh extends fl{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class ep extends fl{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class tp extends fl{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}const vv=2336;class np{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ko.digest(Se(this.url))}[Jh](){return`PeerId(${this.url})`}[zf]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ue.createV1(vv,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=te(e)),e.toString()===this.toString())}}const Sv=114,Fd=2336;function xv(t,e){let n;if(t.charAt(0)==="1"||t.charAt(0)==="Q")n=Vf(He.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return Ev(ue.parse(t));throw new lt('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return rp(n)}function fr(t){if(t.type==="Ed25519")return new ep({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new tp({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new Qh({multihash:t.toCID().multihash,publicKey:t});throw new ri}function rp(t){if(kv(t))return new Qh({multihash:t});if(Av(t))try{const e=mv(t);if(e.type==="Ed25519")return new ep({multihash:t,publicKey:e});if(e.type==="secp256k1")return new tp({multihash:t,publicKey:e})}catch{const n=te(t.digest);return new np(new URL(n))}throw new sw("Supplied PeerID Multihash is invalid")}function Ev(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==Sv&&t.code!==Fd)throw new ow("Supplied PeerID CID is invalid");if(t.code===Fd){const e=te(t.multihash.digest);return new np(new URL(e))}return rp(t.multihash)}function Av(t){return t.code===ko.code}function kv(t){return t.code===Zc.code}class op extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class Cv extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class Lr extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class Md extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}}class Iv extends Event{data;constructor(e,n){super("message",n),this.data=e}}class hl extends Event{error;local;constructor(e,n,r){super("close",r),this.error=n,this.local=e}}class Rv extends hl{constructor(e,n){super(!0,e,n)}}class Tv extends hl{constructor(e,n){super(!1,e,n)}}const Pv=t=>t/2**32|0,Nv=t=>t>>>0;function Lv(t,e,n,r){const o=Pv(n),s=Nv(n);t.setUint32(e,r?s:o,r),t.setUint32(e+4,r?o:s,r)}function oc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const sc=t=>t?`"${t}" `:"";function Ot(t,e=""){if(typeof t!="number")throw new TypeError(sc(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(sc(e)+"expected integer >= 0, got "+t);return t}function Dt(t,e,n=""){if(oc(t)&&(e===void 0||t.length===e))return t;e!==void 0&&Ot(e,"length");const r=oc(t),o=e!==void 0?` of length ${e}`:"",s=r?`length=${t.length}`:`type=${typeof t}`,i=sc(n)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}function pl(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Ot(t.outputLen),Ot(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}const Bv=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)},jd=(t,e)=>{Bv(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 Ns(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function sp(t,e){Dt(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function LR(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function gn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Gi(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function ht(t,e){return t<<32-e|t>>>e}function BR(t,e){return t<<e|t>>>32-e>>>0}const _v=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Ov(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Dv(t){for(let e=0;e<t.length;e++)t[e]=Ov(t[e]);return t}const _R=_v?t=>t:Dv,ip=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Fv=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function gl(t){if(Dt(t),ip)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Fv[t[n]];return e}function Hd(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function ap(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(ip)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}const e=t.length,n=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){const i=Hd(t.charCodeAt(s)),a=Hd(t.charCodeAt(s+1));if(i===void 0||a===void 0){const c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a}return r}function Mv(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 OR(t,e,n,r){if(Ot(t,"iters"),Ot(e,"tick"),typeof n!="function")throw new TypeError("callback must be a function");let o=Date.now();for(let s=0;s<t;s++){n(s);const i=Date.now()-o;i>=0&&i<e||(await Mv(r),o=Date.now())}}function jv(t){if(typeof t!="string")throw new TypeError("string expected");const e=new TextEncoder().encode(t);try{return new Uint8Array(e)}finally{gn(e)}}function DR(t,e=""){return typeof t=="string"?jv(t):Dt(t,void 0,e)}function Hv(t,e,n="opts"){return jd(t,"defaults"),e!==void 0&&jd(e,n),Object.assign(Object.create(null),t,e)}function Uv(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=Hv({},e,"info");const n=(o,s)=>t(s).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function $v(t=32){Ot(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 qv=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Kv(t,e,n){return t&e^~t&n}function zv(t,e,n){return t&e^t&n^e&n}class Gv{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,n,r,o){this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Gi(this.buffer)}update(e){Ns(this),Dt(e);const{view:n,buffer:r,blockLen:o}=this,s=e.length;let i=!1;for(let a=0;a<s;){const c=Math.min(o-this.pos,s-a);if(c===o){const l=Gi(e);for(;o<=s-a;a+=o)this.process(l,a);i=!0;continue}r.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(n,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){Ns(this),sp(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:o,isLE:s}=this;let{pos:i}=this;n[i++]=128,n.fill(0,i),this.padOffset>o-i&&(this.process(r,0),n.fill(0)),Lv(r,o-8,this.length*8,s),this.process(r,0),this.roundClean();const a=e===n?r:Gi(e),c=this.outputLen,l=c/4,d=this.get();if(c%4||l>d.length)throw new Error("invalid outputLen");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneIntoMeta(e){const{buffer:n,length:r,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=r,e.pos=i,i&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Wv=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Vv=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]),qt=new Uint32Array(64);class Xv extends Gv{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,n){super(64,e,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){const{A:e,B:n,C:r,D:o,E:s,F:i,G:a,H:c}=this;return[e,n,r,o,s,i,a,c]}set(e,n,r,o,s,i,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,n){for(let u=0;u<16;u++,n+=4)qt[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const f=qt[u-15],h=qt[u-2],g=ht(f,7)^ht(f,18)^f>>>3,m=ht(h,17)^ht(h,19)^h>>>10;qt[u]=m+qt[u-7]+g+qt[u-16]|0}let{A:r,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=ht(a,6)^ht(a,11)^ht(a,25),h=d+f+Kv(a,c,l)+Vv[u]+qt[u]|0,m=(ht(r,2)^ht(r,13)^ht(r,22))+zv(r,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=r,r=h+m|0}r=r+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,s,i,a,c,l,d)}roundClean(){gn(qt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),gn(this.buffer)}}class Yv extends Xv{constructor(){super(32,Wv)}}const Wi=Uv(()=>new Yv,qv(1));function cp(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 er=(t,e,n)=>Dt(t,e,n),lp=Ot;function tr(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 ro(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}const Zv=gl,Jv=t=>ap(t),dp=oc,up=t=>$v(t),Ls=BigInt(0),Ud=BigInt(1),Qv=t=>t?`"${t}" `:"";function hi(t,e=""){if(typeof t!="boolean")throw new TypeError(Qv(e)+"expected boolean, got type="+typeof t);return t}function eS(t){if(typeof t=="bigint"){if(!mn(t))throw new RangeError("positive bigint expected, got "+t)}else lp(t);return t}function ic(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 fp(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Ls:BigInt("0x"+t)}function hp(t){return fp(gl(t))}function Bs(t){return fp(gl(go(Dt(t)).reverse()))}function pp(t,e){if(Ot(e),e===0)throw new Error("zero output length is invalid");t=eS(t);const n=e*2,r=t.toString(16);if(r.length>n)throw new RangeError("number is too large");return ap(r.padStart(n,"0"))}function gp(t,e){return pp(t,e).reverse()}function go(t){return Uint8Array.from(er(t))}function mn(t){return typeof t=="bigint"&&Ls<=t}function mp(t,e,n){return mn(t)&&mn(e)&&mn(n)&&e<=t&&t<n}function oo(t,e,n,r){if(!mp(e,n,r))throw new RangeError("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function tS(t){if(t<Ls)throw new Error("expected non-negative bigint, got "+t);return t===Ls?0:t.toString(2).length}const nS=t=>(ic(t,"n"),(Ud<<BigInt(t))-Ud);function _s(t,e={},n={},r="object"){tr(t,r),tr(e,"fields"),tr(n,"optFields");function o(i,a,c){const l=r==="object"?`param "${String(i)}"`:`"${r}.${String(i)}"`,d=t[i];if(!Object.hasOwn(t,i)&&(c?d!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&d===void 0)return;const u=typeof d;if(u!==a||d===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${u}`)}const s=(i,a)=>Object.entries(i).forEach(([c,l])=>o(c,l,a));s(e,!1),s(n,!0)}const Re=BigInt(0),de=BigInt(1),dn=BigInt(2),wp=BigInt(3),ml=BigInt(4),yp=BigInt(5),rS=BigInt(7),bp=BigInt(8),oS=BigInt(9),sS=BigInt(15),vp=BigInt(16),iS=BigInt("0x10000000000000000");function le(t,e){if(e<=Re)throw new Error("mod: expected positive modulus, got "+e);const n=t%e;return n>=Re?n:e+n}function aS(t,e,n){if(n<=de)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<Re)throw new Error("invalid exponent, negatives unsupported");if(e===Re)return de;if(e===de)return t;let r=t%n;if(r<Re&&(r+=n),e<iS){let a=de;for(;e>Re;)e&de&&(a=a*r%n),r=r*r%n,e>>=de;return a}const o=[];for(;e>Re;)o.push(Number(e&sS)),e>>=ml;const s=new Array(16);s[0]=de,s[1]=r;for(let a=2;a<16;a++)s[a]=s[a-1]*r%n;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%n,i=i*i%n,i=i*i%n,i=i*i%n;const c=o[a];c!==0&&(i=i*s[c]%n)}return i}function st(t,e,n){if(n<=de)throw new Error("pow2: expected modulus > 1, got "+n);if(e<Re)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >Re;)r*=r,r%=n;return r}function $d(t,e){if(t===Re)throw new Error("invert: expected non-zero number");if(e<=de)throw new Error("invert: expected modulus > 1, got "+e);let n=le(t,e),r=e,o=Re,s=de;for(;n!==Re;){const a=r/n,c=r-n*a,l=o-s*a;r=n,n=c,o=s,s=l}if(r!==de)throw new Error("invert: does not exist");return le(o,e)}function wl(t,e,n){const r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function yl(t,e){if((t&de)===Re)throw new Error(e+": expected odd modulus, got "+t)}function Sp(t,e){const n=t,r=(n.ORDER+de)/ml,o=n.pow(e,r);return wl(n,o,e),o}function cS(t,e){const n=t,r=(n.ORDER-yp)/bp,o=n.mul(e,dn),s=n.pow(o,r),i=n.mul(e,s),a=n.mul(n.mul(i,dn),s),c=n.mul(i,n.sub(a,n.ONE));return wl(n,c,e),c}function lS(t){const e=bl(t),n=xp(t),r=n(e,e.neg(e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+rS)/vp;return((a,c)=>{const l=a;let d=l.pow(c,i),u=l.mul(d,r);const f=l.mul(d,o),h=l.mul(d,s),g=l.eql(l.sqr(u),c),m=l.eql(l.sqr(f),c);d=l.cmov(d,u,g),u=l.cmov(h,f,m);const b=l.eql(l.sqr(u),c),w=l.cmov(d,u,b);return wl(l,w,c),w})}function xp(t){if(t<wp)throw new Error("sqrt is not defined for small field");yl(t,"tonelliShanks");let e=t-de,n=0;for(;e%dn===Re;)e/=dn,n++;let r=dn;const o=bl(t);for(;Os(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Sp;let s=o.pow(r,e);const i=(e+de)/dn;return function(c,l){const d=c;if(d.is0(l))return l;if(Os(d,l)!==1)throw new Error("Cannot find square root");let u=n,f=d.mul(d.ONE,s),h=d.pow(l,e),g=d.pow(l,i);for(;!d.eql(h,d.ONE);){if(d.is0(h))throw new Error("Cannot find square root: probably non-prime P");let m=1,b=d.sqr(h);for(;!d.eql(b,d.ONE);)if(m++,b=d.sqr(b),m===u)throw new Error("Cannot find square root");const w=de<<BigInt(u-m-1),I=d.pow(f,w);u=m,f=d.sqr(I),h=d.mul(h,f),g=d.mul(g,I)}return g}}function dS(t){return yl(t,"Fp.sqrt"),t%ml===wp?Sp:t%bp===yp?cS:t%vp===oS?lS(t):xp(t)}const uS=(t,e)=>(le(t,e)&de)===de,fS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function mo(t){if(tr(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);ic(t.BYTES,"BYTES"),ic(t.BITS,"BITS");for(const e of fS)ro(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=de)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Ep(t,e,n=!1){mo(t),cp(e,"nums"),hi(n,"passZero");const r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),s=e.reduce((a,c,l)=>r.is0(c)?a:(o[l]=a,r.mul(a,c)),r.ONE),i=r.inv(s);return e.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),i),o}function Os(t,e){mo(t);const n=t;yl(n.ORDER,"FpLegendre");const r=(n.ORDER-de)/dn,o=n.pow(e,r),s=n.eql(o,n.ONE),i=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function hS(t,e){if(e!==void 0&&lp(e),t<=Re)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=tS(t);if(e!==void 0&&e<n)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${n})`);const r=e!==void 0?e:n,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}const qd=new WeakMap;class Kd{ORDER;BITS;BYTES;isLE;ZERO=Re;ONE=de;_lengths;_mod;constructor(e,n={}){if(e<=de)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:!0}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));const{nBitLength:o,nByteLength:s}=hS(e,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return le(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Re<=e&&e<this.ORDER}is0(e){return e===Re}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&de)===de}neg(e){return le(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return le(e*e,this.ORDER)}add(e,n){return le(e+n,this.ORDER)}sub(e,n){return le(e-n,this.ORDER)}mul(e,n){return le(e*n,this.ORDER)}pow(e,n){return aS(e,n,this.ORDER)}div(e,n){return le(e*$d(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 $d(e,this.ORDER)}sqrt(e){let n=qd.get(this);return n||qd.set(this,n=dS(this.ORDER)),n(this,e)}toBytes(e){return this.isLE?gp(e,this.BYTES):pp(e,this.BYTES)}fromBytes(e,n=!1){er(e);const{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);const l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?Bs(e):hp(e);if(a&&(c=le(c,i)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Ep(this,e,!0)}cmov(e,n,r){return hi(r,"condition"),r?n:e}}function bl(t,e={}){return Object.freeze(Kd.prototype),new Kd(t,e)}const vl=BigInt(0),wo=BigInt(1),pS=BigInt(4),Vi=16,zd=128,gS=5,Gd=2**31;function Sl(t){const e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);ro(e.fromAffine,"Point.fromAffine"),ro(e.fromBytes,"Point.fromBytes"),ro(e.fromHex,"Point.fromHex"),tr(e.BASE,"Point.BASE"),tr(e.ZERO,"Point.ZERO"),mo(e.Fp),mo(e.Fn)}function mS(t,e){Sl(t),Ap(e,t);const n=Ep(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function wS(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 yS(t,e){const n=t*(4*e+128);if(n>Gd)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+Gd/2**20+" MiB")}function bS(t,e){if(t!==void 0){ro(t,"randomBytes");try{const n=t(e);if(!dp(n)||n.length!==e)return}catch{return}return t}}function Ap(t,e){cp(t,"points"),t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function vS(t,e,n){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,o)=>{if(!(n===void 0?e.isValid(r):mn(r)&&r<n))throw new Error("invalid scalar at index "+o)})}const kp=new WeakMap;function Xi(t){return kp.get(t)||1}function SS(t,e){const n=t.double(),r=[t];for(let o=1;o<e;o++)r.push(r[o-1].add(n));return r}function xS(t,e){const n=2**e,r=n/2,o=BigInt(n-1),s=[];for(;t>vl;){let i=0;t&wo&&(i=Number(t&o),i>=r&&(i-=n),t-=BigInt(i)),s.push(i),t>>=wo}return s}function ES(t,e,n){const r=2**e,o=r/2,s=BigInt(r-1),i=BigInt(e),a=[];for(let c=0;c<n;c++){let l=Number(t&s);t>>=i,l>o&&(l-=r,t+=wo),a.push(l)}if(t!==vl)throw new Error("invalid wnaf");return a}function AS(t,e,n){let r=0;for(const s of n)r=Math.max(r,s.length);let o=t;for(let s=r-1;s>=0;s--){s!==r-1&&(o=o.double());for(let i=0;i<n.length;i++){const a=n[i][s];if(a){const c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}class kS{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,n){Sl(e),this.randomBytes=bS(n,Vi),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,n,r){const o=Math.ceil(r/n)+1,s=2**(n-1),i=[];let a=e;for(let c=0;c<o;c++){let l=a;for(let d=0;d<s;d++)i.push(l),l=l.add(a);a=i[i.length-1].double()}return{W:n,bits:r,windows:o,comp:i}}wnafCachedCT(e,n){const{W:r,windows:o,comp:s}=e,i=2**(r-1),a=ES(n,r,o);let c=this.ZERO,l=this.BASE;for(let d=0;d<o;d++){const u=a[d],f=d*i,h=Math.abs(u)-1;let g=s[f];for(let b=1;b<i;b++)g=b===h?s[f+b]:g;const m=g.negate();u===0?l=l.add(s[f]):c=c.add(u<0?m:g)}return{p:c,f:l}}getWnafPrecomputes(e,n,r,o){let s=this.wnafPrecomputes.get(n),i=s?.find(a=>a.W===e&&a.bits===r);return i||(i=this.buildWnafTable(n,e,r),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(n,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,n){if(this.assertPoint(e),!mp(n,wo,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,n,r,o){const s=Xi(e);return s===1?this.fixedWindowCT(e,n,r):this.wnafCachedCT(this.getWnafPrecomputes(s,e,r,o),n)}mulCT(e,n,r){return this.validateMulInput(e,n),this.runCT(e,n,this.bits,r)}mulCTBlinded(e,n,r){if(this.validateMulInput(e,n),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");const o=this.Point.Fn.BITS+zd,s=this.randomBytes(Vi);if(!dp(s)||s.length!==Vi)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;const i=n+hp(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,r)}fixedWindowCT(e,n,r){const o=gS,s=1<<o,i=nS(o),a=new Array(s);a[0]=this.ZERO;for(let d=1;d<s;d++)a[d]=a[d-1].add(e);const c=Math.ceil(r/o);let l=this.ZERO;for(let d=c-1;d>=0;d--){if(d!==c-1)for(let h=0;h<o;h++)l=l.double();const u=Number(n>>BigInt(d*o)&i);let f=a[0];for(let h=1;h<s;h++)f=h===u?a[h]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(e,n){return this.randomBytes===void 0?!1:n===wo?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,n,r,o){return this.shouldBlind(e,r)?this.mulCTBlinded(e,n,o):this.mulCT(e,n,o)}mulUnsafe(e,n,r){if(this.assertPoint(e),!mn(n))throw new Error("invalid scalar");const o=Xi(e);if(o===1||n>=this.Point.Fn.ORDER)return CS(this.Point,[e],[n],!0);const s=this.getWnafPrecomputes(o,e,this.bits,r);return this.wnafCachedCT(s,n).p}setWindowSize(e,n){this.assertPoint(e),wS(n,this.bits);const r=Math.ceil((this.bits+zd)/n)+1;yS(r*2**(n-1),this.Point.Fp.BYTES),kp.set(e,n),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Xi(e)!==1}}function CS(t,e,n,r=!1){if(Sl(t),Ap(e,t),hi(r,"allowOversized"),vS(n,t.Fn,r?t.Fn.ORDER**pS:void 0),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const o=e.map(i=>SS(i,4)),s=n.map(i=>xS(i,4));return AS(t.ZERO,o,s)}function Wd(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return mo(e),e}else return bl(t,{isLE:n})}function IS(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);_s(n);for(const c of["p","n","h"]){const l=e[c];if(!(mn(l)&&l!==vl))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Wd(e.p,n.Fp,r),s=Wd(e.n,n.Fn,r),a=["Gx","Gy","a","d"];for(const c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function RS(t,e){return function(r){const o=t(r);return{secretKey:o,publicKey:e(o)}}}const $o=BigInt(0),qo=BigInt(1),Ko=BigInt(2),TS=BigInt(4),Vd=BigInt(8);function PS(t,e,n,r){const o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function NS(t,e={}){_s(e,{},{},"extraOpts");const n=e,r=IS("edwards",t,n,n.FpFnLE),{Fp:o,Fn:s}=r;let i=r.CURVE;const{h:a}=i;if(Os(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Os(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");_s(n,{},{uvRatio:"function",randomBytes:"function"});const c=n.randomBytes===void 0?up:n.randomBytes,l=Ko<<BigInt(o.BYTES*8)-qo;function d(I){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(I)}const u=n.uvRatio===void 0?(I,y)=>{try{return{isValid:!0,value:o.sqrt(o.div(I,y))}}catch{return{isValid:!1,value:$o}}}:n.uvRatio;if(!PS(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");const f=o.eql(i.a,o.neg(o.ONE))?I=>o.neg(I):o.eql(i.a,o.ONE)?I=>I:I=>o.mul(i.a,I);function h(I,y,A=!1){const N=A?qo:$o;return oo("coordinate "+I,y,N,l),y}function g(I){if(!(I instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.Gy));static ZERO=new m(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(y,A,N,k){this.X=h("x",y),this.Y=h("y",A),this.Z=h("z",N,!0),this.T=h("t",k),Object.freeze(this)}static CURVE(){return i}static fromAffine(y){if(y instanceof m)throw new Error("extended point not allowed");const{x:A,y:N}=y||{};return h("x",A),h("y",N),new m(A,N,o.ONE,o.mul(A,N))}static fromBytes(y,A=!1){const N=o.BYTES,{a:k,d:T}=i;y=go(er(y,N,"point")),hi(A,"zip215");const S=go(y),v=y[N-1];S[N-1]=v&-129;const E=Bs(S),_=A?l:o.ORDER;oo("point.y",E,$o,_);const L=o.sqr(E),C=o.sub(L,o.ONE),x=o.sub(o.mulN(T,L),k);let{isValid:P,value:R}=u(C,x);if(!P)throw new Error("bad point: invalid y coordinate");const D=d(R),M=(v&128)!==0;if(!A&&o.is0(R)&&M)throw new Error("bad point: x=0 and x_0=1");return M!==D&&(R=o.neg(R)),m.fromAffine({x:R,y:E})}static fromHex(y,A=!1){return m.fromBytes(Jv(y),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=6,A=!0){return w.setWindowSize(this,y),A||this.multiply(Ko),this}assertValidity(){const y=this,{a:A,d:N}=i;if(y.is0())throw new Error("bad point: ZERO");const{X:k,Y:T,Z:S,T:v}=y,E=o.sqr(k),_=o.sqr(T),L=o.sqr(S),C=o.sqr(L),x=o.mul(E,A),P=o.mul(o.add(x,_),L),R=o.add(C,o.mul(N,o.mul(E,_)));if(!o.eql(P,R))throw new Error("bad point: equation left != right (1)");const D=o.mul(k,T),M=o.mul(S,v);if(!o.eql(D,M))throw new Error("bad point: equation left != right (2)")}equals(y){g(y);const{X:A,Y:N,Z:k}=this,{X:T,Y:S,Z:v}=y,E=o.mul(A,v),_=o.mul(T,k),L=o.mul(N,v),C=o.mul(S,k);return o.eql(E,_)&&o.eql(L,C)}is0(){return this.equals(m.ZERO)}negate(){return new m(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){const{X:y,Y:A,Z:N}=this,k=o.sqr(y),T=o.sqr(A),S=o.mul(o.sqr(N),Ko),v=f(k),E=o.addN(y,A),_=o.sub(o.subN(o.sqr(E),k),T),L=o.addN(v,T),C=o.subN(L,S),x=o.subN(v,T),P=o.mul(_,C),R=o.mul(L,x),D=o.mul(_,x),M=o.mul(C,L);return new m(P,R,M,D)}add(y){g(y);const{d:A}=i,{X:N,Y:k,Z:T,T:S}=this,{X:v,Y:E,Z:_,T:L}=y,C=o.mul(N,v),x=o.mul(k,E),P=o.mul(o.mulN(S,A),L),R=o.mul(T,_),D=o.sub(o.subN(o.mulN(o.addN(N,k),o.addN(v,E)),C),x),M=o.subN(R,P),F=o.addN(R,P),B=o.sub(x,f(C)),H=o.mul(D,M),$=o.mul(F,B),X=o.mul(D,B),Y=o.mul(M,F);return new m(H,$,Y,X)}subtract(y){return g(y),this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");const{p:A,f:N}=w.mulSecret(this,y,a,b);return b([A,N])[0]}multiplyUnsafe(y){if(!s.isValid(y))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return y===$o?m.ZERO:this.is0()||y===qo?this:w.mulUnsafe(this,y,b)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.mulUnsafe(this,i.n).is0()}toAffine(y){const A=this;let N=y;if(N!=null&&typeof N!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof N);const{X:k,Y:T,Z:S}=A,v=A.is0();N==null&&(N=v?o.create(Vd):o.inv(S));const E=o.mul(k,N),_=o.mul(T,N),L=o.mul(S,N);if(v)return{x:o.ZERO,y:o.ONE};if(!o.eql(L,o.ONE))throw new Error("invZ was invalid");return{x:E,y:_}}clearCofactor(){return a===qo?this:a===Ko?this.double():a===TS?this.double().double():a===Vd?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){const{x:y,y:A}=this.toAffine(),N=o.toBytes(A);return N[N.length-1]|=d(y)?128:0,N}toHex(){return Zv(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const b=I=>mS(m,I),w=new kS(m,c);return w.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}const rn=BigInt(0),Qe=BigInt(1),zo=BigInt(2);function Xd(t,e){return t+e-(e>>Qe<<Qe)}function LS(t){const e=BigInt(6)*t;return(n,r,o)=>{const s=r+o,a=((e+o-r)*n+r)%t;return{x_2:a,x_3:s-a}}}function BS(t){return _s(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...t})}function _S(t){const e=BS(t),{P:n,type:r,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=e.scalarMultBase,c=r==="x25519";if(!c&&r!=="x448")throw new Error("invalid type");const l=i===void 0?up:i,d=c?255:448,u=LS(n),f=c?32:56,h=BigInt(c?9:5),g=BigInt(c?121665:39081),m=c?zo**BigInt(254):zo**BigInt(447),b=c?BigInt(8)*(zo**BigInt(251)-Qe):BigInt(4)*(zo**BigInt(445)-Qe),w=m+b+Qe,I=R=>le(R,n),y=A(h);function A(R){return gp(I(R),f)}function N(R){const D=go(er(R,f,"uCoordinate"));return c&&(D[31]&=127),I(Bs(D))}function k(R){return Bs(o(go(er(R,f,"scalar"))))}const T=new Set(c?[rn,Qe,n-Qe,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[rn,Qe,n-Qe]);function S(R,D){const M=N(D);if(T.has(M))throw new Error("invalid private or public key received");const F=L(M,k(R));if(F===rn)throw new Error("invalid private or public key received");return A(F)}function v(R){if(a===void 0)return S(R,y);const D=k(R);oo("scalar",D,m,w);const M=I(a(D));if(M===rn)throw new Error("invalid private or public key received");return A(M)}const E=v,_=S;function L(R,D){oo("u",R,rn,n),oo("scalar",D,m,w);const M=D,F=R;let B=Qe,H=rn,$=R,X=Qe;const Y=M^M>>Qe;for(let q=BigInt(d-1);q>=rn;q--){const G=Xd(n,Y>>q);({x_2:B,x_3:$}=u(G,B,$)),{x_2:H,x_3:X}=u(G,H,X);const z=B+H,V=I(z*z),J=B-H,oe=I(J*J),ne=V-oe,ae=$+X,he=$-X,Be=I(he*z),We=I(ae*J),ke=Be+We,je=Be-We;$=I(ke*ke),X=I(F*I(je*je)),B=I(V*oe),H=I(ne*(V+I(g*ne)))}const U=Xd(n,M);({x_2:B,x_3:$}=u(U,B,$)),{x_2:H,x_3:X}=u(U,H,X);const K=s(H);return I(B*K)}const C={secretKey:f,publicKey:f,seed:f},x=R=>(R=R===void 0?l(f):R,er(R,C.seed,"seed"),R),P={randomSecretKey:x};return Object.freeze(C),Object.freeze(P),Object.freeze({keygen:RS(x,E),getSharedSecret:_,getPublicKey:E,scalarMult:S,scalarMultBase:v,utils:P,GuBytes:y.slice(),lengths:C})}const Yd=BigInt(0),OS=BigInt(1),Zd=BigInt(2),DS=BigInt(3),FS=BigInt(5),MS=BigInt(8),pi=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),jS={p:pi,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:MS,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Cp(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=pi,a=t*t%s*t%s,c=st(a,Zd,s)*a%s,l=st(c,OS,s)*t%s,d=st(l,FS,s)*l%s,u=st(d,e,s)*d%s,f=st(u,n,s)*u%s,h=st(f,r,s)*f%s,g=st(h,o,s)*h%s,m=st(g,o,s)*h%s,b=st(m,e,s)*d%s;return{pow_p_5_8:st(b,Zd,s)*t%s,b2:a}}function HS(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Jd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function US(t,e){const n=pi,r=le(e*e*e,n),o=le(r*r*e,n),s=Cp(t*o).pow_p_5_8;let i=le(t*r*s,n);const a=le(e*i*i,n),c=i,l=le(i*Jd,n),d=a===t,u=a===le(-t,n),f=a===le(-t*Jd,n);return d&&(i=c),(u||f)&&(i=l),uS(i,n)&&(i=le(-i,n)),{isValid:d||u,value:i}}const Qd=NS(jS,{uvRatio:US}),Go=(()=>{const t=pi,e=n=>{const{pow_p_5_8:r,b2:o}=Cp(n);return le(st(r,DS,t)*o,t)};return _S({P:t,type:"x25519",powPminus2:e,adjustScalarBytes:HS,scalarMultBase:n=>{const r=le(n,Qd.Fn.ORDER);if(r===Yd)return Yd;const o=Qd.BASE.multiply(r);return le((o.Z+o.Y)*e(le(o.Z-o.Y,t)),t)}})})();class eu{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,n){if(pl(e),Dt(n,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?e.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),gn(o)}update(e){return Ns(this),this.iHash.update(e),this}digestInto(e){Ns(this),sp(e,this),this.finished=!0;const n=e.subarray(0,this.outputLen);this.iHash.digestInto(n),this.oHash.update(n),this.oHash.digestInto(n),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});const{oHash:n,iHash:r,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ip=(()=>{const t=((e,n,r)=>new eu(e,n).update(r).digest());return t.create=(e,n)=>new eu(e,n),t})();function tu(){const t={};return t.promise=new Promise((e,n)=>{t.resolve=e,t.reject=n}),t}class nu{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 Yi{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new nu(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 nu(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 $S extends Error{type;code;constructor(e,n){super(e??"The operation was aborted"),this.type="aborted",this.code=n??"ABORT_ERR"}}function qS(t={}){return KS(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 KS(t,e){e=e??{};let n=e.onEnd,r=new Yi,o,s,i,a=tu();const c=async()=>{try{return r.isEmpty()?i?{done:!0}:await new Promise((b,w)=>{s=I=>{s=null,r.push(I);try{b(t(r))}catch(y){w(y)}return o}}):t(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=tu()})}},l=b=>s!=null?s(b):(r.push(b),o),d=b=>(r=new Yi,s!=null?s({error:b}):(r.push({error:b}),o)),u=b=>{if(i)return o;if(e?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:b})},f=b=>i?o:(i=!0,b!=null?d(b):l({done:!0})),h=()=>(r=new Yi,f(),{done:!0}),g=b=>(f(b),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:g,push:u,end:f,get readableLength(){return r.size},onEmpty:async b=>{const w=b?.signal;if(w?.throwIfAborted(),r.isEmpty())return;let I,y;w!=null&&(I=new Promise((A,N)=>{y=()=>{N(new $S)},w.addEventListener("abort",y)}));try{await Promise.race([a.promise,I])}finally{y!=null&&w!=null&&w?.removeEventListener("abort",y)}}},n==null)return o;const m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(b){return m.throw(b),n!=null&&(n(b),n=void 0),{done:!0}},return(){return m.return(),n!=null&&(n(),n=void 0),{done:!0}},push:u,end(b){return m.end(b),n!=null&&(n(b),n=void 0),o},get readableLength(){return m.readableLength},onEmpty:b=>m.onEmpty(b)},o}class xl extends Error{name="TimeoutError";constructor(e,n){super(e,n),Error.captureStackTrace?.(this,xl)}}const ru=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function zS(t,e){const{milliseconds:n,fallback:r,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e;let a,c;const d=new Promise((u,f)=>{if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(i?.aborted){f(ru(i));return}if(i&&(c=()=>{f(ru(i))},i.addEventListener("abort",c,{once:!0})),t.then(u,f),n===Number.POSITIVE_INFINITY)return;const h=new xl;a=s.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){f(g)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?u():o instanceof Error?f(o):(h.message=o??`Promise timed out after ${n} milliseconds`,f(h))},n)}).finally(()=>{d.clear(),c&&i&&i.removeEventListener("abort",c)});return d.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},d}const GS=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 WS(t,e,n){let r;const o=new Promise((s,i)=>{if(n={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...n},!(n.count>=0&&(n.count===Number.POSITIVE_INFINITY||Number.isInteger(n.count))))throw new TypeError("The `count` option should be at least 0 or more");n.signal?.throwIfAborted();const a=[e].flat(),c=[],{addListener:l,removeListener:d}=GS(t),u=async(...h)=>{const g=n.multiArgs?h:h[0];if(n.filter)try{if(!await n.filter(g))return}catch(m){r(),i(m);return}c.push(g),n.count===c.length&&(r(),s(c))},f=(...h)=>{r(),i(n.rejectionMultiArgs?h:h[0])};r=()=>{for(const h of a)d(h,u);for(const h of n.rejectionEvents)a.includes(h)||d(h,f)};for(const h of a)l(h,u);for(const h of n.rejectionEvents)a.includes(h)||l(h,f);n.signal&&n.signal.addEventListener("abort",()=>{f(n.signal.reason)},{once:!0}),n.resolveImmediately&&s(c)});if(o.cancel=r,typeof n.timeout=="number"){const s=zS(o,{milliseconds:n.timeout});return s.cancel=()=>{r(),s.clear()},s}return o}function VS(t,e,n){typeof n=="function"&&(n={filter:n}),n={...n,count:1,resolveImmediately:!1};const r=WS(t,e,n),o=r.then(s=>s[0]);return o.cancel=r.cancel,o}class Ds extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class XS extends Error{static name="StreamClosedError";name="StreamClosedError"}function YS(t){return t.reason}function Rp(t,e,n){if(e==null||t==null)return t;const r=YS;if(e.aborted)return t.catch(()=>{}),Promise.reject(r(e));let o;return Promise.race([t,new Promise((s,i)=>{o=()=>{i(r(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}const ZS=Math.pow(2,20)*4;class Tp extends lw{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??ZS,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new ce,this.writeBuffer=new ce,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);const n=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",n);const r=o=>{this.onDrainPromise?.reject(o.error??new XS)};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()),Rp(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;const e=qS(),n=s=>{e.push(s.data)};this.addEventListener("message",n);const r=s=>{e.end(s.error)};this.addEventListener("close",r);const o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",n),this.removeEventListener("close",r),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Lr(`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 Rv(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Lr("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 Lr("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 Lr(`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 Lr(`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 Cv;this.dispatchEvent(new Tv(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 hl))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0;const n=this.writeBuffer.byteLength;let r=0;for(;this.writeBuffer.byteLength>0;){const o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}const s=this.writeBuffer.sublist(0,o),i=new ce(s);this.writeBuffer.consume(s.byteLength);const a=this.sendData(s);if(e=a.canSendMore,r+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",r,n,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}const e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new Iv(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 Md(`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 Md(`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 JS=4194304;class ou extends Error{static name="UnwrappedError";name="UnwrappedError"}class Pp extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class QS extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class ex extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function tx(t){return typeof t?.closeRead=="function"}function nx(t){return typeof t?.close=="function"}function Zi(t){return tx(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:nx(t)?t.status!=="open":!1}function rx(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function ox(t,e){const n=e?.maxBufferSize??JS,r=new ce;let o,s=!1;if(!rx(t))throw new op("Argument should be a Stream or a Multiaddr");const i=d=>{if(r.append(d.data),r.byteLength>n){const u=r.byteLength;r.consume(r.byteLength),o?.reject(new Error(`Read buffer overflow - ${u} > ${n}`))}o?.resolve()};t.addEventListener("message",i);const a=d=>{d.error!=null?o?.reject(d.error):o?.resolve()};t.addEventListener("close",a);const c=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",c);const l={readBuffer:r,async read(d){if(s===!0)throw new ou("Stream was unwrapped");if(Zi(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 Ds(`Unexpected EOF - stream closed after reading ${r.byteLength}/${d.bytes} bytes`)}const u=d?.bytes??1;for(o=Promise.withResolvers();;){if(r.byteLength>=u){o.resolve();break}if(await Rp(o.promise,d?.signal),Zi(t)){if(r.byteLength===0&&d?.bytes==null)return null;break}o=Promise.withResolvers()}const f=d?.bytes??r.byteLength;if(r.byteLength<f){if(Zi(t))throw t.log.error("closed while reading %d/%d bytes",r.byteLength,f),new Ds(`Unexpected EOF - stream closed while reading ${r.byteLength}/${f} bytes`);return l.read(d)}const h=r.sublist(0,f);return r.consume(f),h},async write(d,u){if(s===!0)throw new ou("Stream was unwrapped");t.send(d)||await VS(t,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",i),t.removeEventListener("close",a),t.removeEventListener("remoteCloseWrite",c),r.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",r.byteLength),t.push(r))),t}};return l}function su(t,e={}){const n=ox(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Cn(e.maxDataLength));const r=e?.lengthDecoder??Mh,o=e?.lengthEncoder??d0;return{async read(i){let a=-1;const c=new ce;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 Pp("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new ex(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new QS(`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 Ds(`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 Ds(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await n.write(new ce(o(i.byteLength),i),a)},async writeV(i,a){const c=new ce(...i.flatMap(l=>[o(l.byteLength),l]));await n.write(c,a)},unwrap(){return n.unwrap()}}}const sx=1024*1024*4,ix=1024*1024*4;class ax{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new ce,this.maxBufferSize=e.maxBufferSize??sx,this.maxDataLength=e.maxDataLength??ix,this.lengthDecoder=e.lengthDecoder??Mh,this.encodingLength=e.encodingLength??Cn}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new op(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let n;try{n=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(n<0||n>this.maxDataLength)throw new Pp("Invalid message length");const r=this.encodingLength(n),o=r+n;if(this.buffer.byteLength>=o){const s=this.buffer.sublist(r,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}}var cx={};const yo=65535,iu=yo-16,Po=!!cx?.DUMP_SESSION_KEYS,au=16;function ac(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const Fs=t=>t?`"${t}" `:"";function cc(t,e=""){if(typeof t!="boolean")throw new TypeError(Fs(e)+"expected boolean, got type="+typeof t);return t}function nr(t,e=""){if(typeof t!="number")throw new TypeError(Fs(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(Fs(e)+"expected integer >= 0, got "+t);return t}function Ie(t,e,n=""){if(ac(t)&&(e===void 0||t.length===e))return t;e!==void 0&&nr(e,"length");const r=ac(t),o=e!==void 0?` of length ${e}`:"",s=r?`length=${t.length}`:`type=${typeof t}`,i=Fs(n)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}const cu=(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 lu(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function lx(t,e){Ie(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function Rt(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Jt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function dx(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const rr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ux(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function fx(t){for(let e=0;e<t.length;e++)t[e]=ux(t[e]);return t}const un=rr?t=>t:fx;function hx(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 px(t,e){if(hx(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function gx(t,e){return cu(t,"defaults"),cu(e,"opts"),Object.assign(t,e)}function mx(t,e){if(t=Ie(t),e=Ie(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 wx(t,e,n){const r=e,o=(()=>[]),s=(a,c)=>r(c,...o(a)).update(a).digest(),i=r(new Uint8Array(t),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>r(a,...c),s}const yx=(t,e)=>{function n(r,...o){if(Ie(r,void 0,"key"),t.nonceLength!==void 0){const u=o[0];Ie(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}const s=t.tagLength,i=t.nonceLength!==void 0?1:0;if(!t.withAAD){for(let u=i;u<o.length;u++)if(ac(o[u]))throw new Error("AAD not supported")}t.withAAD&&o[i]!==void 0&&Ie(o[i],void 0,"AAD");const a=e(r,...o),c=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");Ie(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,Ie(u,void 0,"data"),c(a.encrypt.length,f),a.encrypt(u,f)},decrypt(u,f){if(Ie(u,void 0,"data"),s&&u.length<s)throw new Error('"ciphertext" expected length >= tagLength='+s);return c(a.decrypt.length,f),a.decrypt(u,f)}}}return Object.assign(n,t),n};function lc(t,e,n=!0){if(e===void 0)return new Uint8Array(t);if(Ie(e,t,"output"),n&&!Ms(e))throw new Error("invalid output, must be aligned");return e}function bx(t,e,n){nr(t),nr(e),cc(n);const r=new Uint8Array(16),o=dx(r);return o.setBigUint64(0,BigInt(e),n),o.setBigUint64(8,BigInt(t),n),r}function Ms(t){return t.byteOffset%4===0}function js(t){return Uint8Array.from(Ie(t))}const Np=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),vx=un(Rt(Np("expand 16-byte k"))),Sx=un(Rt(Np("expand 32-byte k")));function re(t,e){return t<<e|t>>>32-e}const Br=64,xx=16,dc=2**32-1,du=Uint32Array.of();function Ex(t,e,n,r,o,s,i,a){const c=o.length,l=new Uint8Array(Br),d=Rt(l),u=rr&&Ms(o)&&Ms(s),f=u?Rt(o):du,h=u?Rt(s):du;if(!rr){for(let g=0;g<c;i++){if(t(e,n,r,d,i,a),un(d),i>=dc)throw new Error("arx: counter overflow");const m=Math.min(Br,c-g);for(let b=0,w;b<m;b++)w=g+b,s[w]=o[w]^l[b];g+=m}return}for(let g=0;g<c;i++){if(t(e,n,r,d,i,a),i>=dc)throw new Error("arx: counter overflow");const m=Math.min(Br,c-g);if(u&&m===Br){const b=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,I;w<xx;w++)I=b+w,h[I]=f[I]^d[w];g+=Br;continue}for(let b=0,w;b<m;b++)w=g+b,s[w]=o[w]^l[b];g+=m}}function Ax(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:s,rounds:i}=gx({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return nr(o),nr(i),cc(s),cc(n),(a,c,l,d,u=0)=>{Ie(a,void 0,"key"),Ie(c,void 0,"nonce"),Ie(l,void 0,"data");const f=l.length,h=d!==void 0;if(d=lc(f,d,!1),h&&px(l,d),nr(u),u<0||u>=dc)throw new Error("arx: counter overflow");const g=[];let m=a.length,b,w;if(m===32)g.push(b=js(a)),w=Sx;else if(m===16&&n)b=new Uint8Array(32),b.set(a),b.set(a,16),w=vx,g.push(b);else throw Ie(a,32,"arx key"),new Error("invalid key size");(!rr||!Ms(c))&&g.push(c=js(c));let I=Rt(b);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");const N=c.subarray(0,16);if(rr)r(w,I,Rt(N),I);else{const k=un(Uint32Array.from(w));r(k,I,Rt(N),I),Jt(k),un(I)}c=c.subarray(16)}else rr||un(I);const y=16-o;if(y!==c.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){const N=new Uint8Array(12);N.set(c,s?0:12-c.length),c=N,g.push(c)}const A=un(Rt(c));try{return Ex(t,w,I,A,l,d,u,i),d}finally{Jt(...g)}}}function Te(t,e){return t[e++]&255|(t[e++]&255)<<8}class kx{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=js(Ie(e,32,"key"));const n=Te(e,0),r=Te(e,2),o=Te(e,4),s=Te(e,6),i=Te(e,8),a=Te(e,10),c=Te(e,12),l=Te(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let d=0;d<8;d++)this.pad[d]=Te(e,16+2*d)}process(e,n,r=!1){const o=r?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],d=i[3],u=i[4],f=i[5],h=i[6],g=i[7],m=i[8],b=i[9],w=Te(e,n+0),I=Te(e,n+2),y=Te(e,n+4),A=Te(e,n+6),N=Te(e,n+8),k=Te(e,n+10),T=Te(e,n+12),S=Te(e,n+14);let v=s[0]+(w&8191),E=s[1]+((w>>>13|I<<3)&8191),_=s[2]+((I>>>10|y<<6)&8191),L=s[3]+((y>>>7|A<<9)&8191),C=s[4]+((A>>>4|N<<12)&8191),x=s[5]+(N>>>1&8191),P=s[6]+((N>>>14|k<<2)&8191),R=s[7]+((k>>>11|T<<5)&8191),D=s[8]+((T>>>8|S<<8)&8191),M=s[9]+(S>>>5|o),F=0,B=F+v*a+E*(5*b)+_*(5*m)+L*(5*g)+C*(5*h);F=B>>>13,B&=8191,B+=x*(5*f)+P*(5*u)+R*(5*d)+D*(5*l)+M*(5*c),F+=B>>>13,B&=8191;let H=F+v*c+E*a+_*(5*b)+L*(5*m)+C*(5*g);F=H>>>13,H&=8191,H+=x*(5*h)+P*(5*f)+R*(5*u)+D*(5*d)+M*(5*l),F+=H>>>13,H&=8191;let $=F+v*l+E*c+_*a+L*(5*b)+C*(5*m);F=$>>>13,$&=8191,$+=x*(5*g)+P*(5*h)+R*(5*f)+D*(5*u)+M*(5*d),F+=$>>>13,$&=8191;let X=F+v*d+E*l+_*c+L*a+C*(5*b);F=X>>>13,X&=8191,X+=x*(5*m)+P*(5*g)+R*(5*h)+D*(5*f)+M*(5*u),F+=X>>>13,X&=8191;let Y=F+v*u+E*d+_*l+L*c+C*a;F=Y>>>13,Y&=8191,Y+=x*(5*b)+P*(5*m)+R*(5*g)+D*(5*h)+M*(5*f),F+=Y>>>13,Y&=8191;let U=F+v*f+E*u+_*d+L*l+C*c;F=U>>>13,U&=8191,U+=x*a+P*(5*b)+R*(5*m)+D*(5*g)+M*(5*h),F+=U>>>13,U&=8191;let K=F+v*h+E*f+_*u+L*d+C*l;F=K>>>13,K&=8191,K+=x*c+P*a+R*(5*b)+D*(5*m)+M*(5*g),F+=K>>>13,K&=8191;let q=F+v*g+E*h+_*f+L*u+C*d;F=q>>>13,q&=8191,q+=x*l+P*c+R*a+D*(5*b)+M*(5*m),F+=q>>>13,q&=8191;let G=F+v*m+E*g+_*h+L*f+C*u;F=G>>>13,G&=8191,G+=x*d+P*l+R*c+D*a+M*(5*b),F+=G>>>13,G&=8191;let z=F+v*b+E*m+_*g+L*h+C*f;F=z>>>13,z&=8191,z+=x*u+P*d+R*l+D*c+M*a,F+=z>>>13,z&=8191,F=(F<<2)+F|0,F=F+B|0,B=F&8191,F=F>>>13,H+=F,s[0]=B,s[1]=H,s[2]=$,s[3]=X,s[4]=Y,s[5]=U,s[6]=K,s[7]=q,s[8]=G,s[9]=z}finalize(){const{h:e,pad:n}=this,r=new Uint16Array(10);let o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+o,o=r[a]>>>13,r[a]&=8191;r[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)r[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+n[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+n[a]|0)+(i>>>16)|0,e[a]=i&65535;Jt(r)}update(e){lu(this),Ie(e),e=js(e);const{buffer:n,blockLen:r}=this,o=e.length;for(let s=0;s<o;){const i=Math.min(r-this.pos,o-s);if(i===r){for(;r<=o-s;s+=r)this.process(e,s);continue}n.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,Jt(this.h,this.r,this.buffer,this.pad)}digestInto(e){lu(this),lx(e,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:o}=this;if(o){for(n[o++]=1;o<16;o++)n[o]=0;this.process(n,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=r[i]>>>0,e[s++]=r[i]>>>8}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}}const Cx=wx(32,t=>new kx(t));function Ix(t,e,n,r,o,s=20){let i=t[0],a=t[1],c=t[2],l=t[3],d=e[0],u=e[1],f=e[2],h=e[3],g=e[4],m=e[5],b=e[6],w=e[7],I=o,y=n[0],A=n[1],N=n[2],k=i,T=a,S=c,v=l,E=d,_=u,L=f,C=h,x=g,P=m,R=b,D=w,M=I,F=y,B=A,H=N;for(let X=0;X<s;X+=2)k=k+E|0,M=re(M^k,16),x=x+M|0,E=re(E^x,12),k=k+E|0,M=re(M^k,8),x=x+M|0,E=re(E^x,7),T=T+_|0,F=re(F^T,16),P=P+F|0,_=re(_^P,12),T=T+_|0,F=re(F^T,8),P=P+F|0,_=re(_^P,7),S=S+L|0,B=re(B^S,16),R=R+B|0,L=re(L^R,12),S=S+L|0,B=re(B^S,8),R=R+B|0,L=re(L^R,7),v=v+C|0,H=re(H^v,16),D=D+H|0,C=re(C^D,12),v=v+C|0,H=re(H^v,8),D=D+H|0,C=re(C^D,7),k=k+_|0,H=re(H^k,16),R=R+H|0,_=re(_^R,12),k=k+_|0,H=re(H^k,8),R=R+H|0,_=re(_^R,7),T=T+L|0,M=re(M^T,16),D=D+M|0,L=re(L^D,12),T=T+L|0,M=re(M^T,8),D=D+M|0,L=re(L^D,7),S=S+C|0,F=re(F^S,16),x=x+F|0,C=re(C^x,12),S=S+C|0,F=re(F^S,8),x=x+F|0,C=re(C^x,7),v=v+E|0,B=re(B^v,16),P=P+B|0,E=re(E^P,12),v=v+E|0,B=re(B^v,8),P=P+B|0,E=re(E^P,7);let $=0;r[$++]=i+k|0,r[$++]=a+T|0,r[$++]=c+S|0,r[$++]=l+v|0,r[$++]=d+E|0,r[$++]=u+_|0,r[$++]=f+L|0,r[$++]=h+C|0,r[$++]=g+x|0,r[$++]=m+P|0,r[$++]=b+R|0,r[$++]=w+D|0,r[$++]=I+M|0,r[$++]=y+F|0,r[$++]=A+B|0,r[$++]=N+H|0}const Rx=Ax(Ix,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Tx=new Uint8Array(16),uu=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(Tx.subarray(n))},Px=new Uint8Array(32);function fu(t,e,n,r,o){o!==void 0&&Ie(o,void 0,"AAD");const s=t(e,n,Px),i=bx(r.length,o?o.length:0,!0),a=Cx.create(s);o&&uu(a,o),uu(a,r),a.update(i);const c=a.digest();return Jt(s,i),c}const Nx=t=>(e,n,r)=>({encrypt(s,i){const a=s.length;i=lc(a+16,i,!1),i.set(s);const c=i.subarray(0,-16);t(e,n,c,c,1);const l=fu(t,e,n,c,r);return i.set(l,a),Jt(l),i},decrypt(s,i){i=lc(s.length-16,i,!1);const a=s.subarray(0,-16),c=s.subarray(-16),l=fu(t,e,n,a,r);if(!mx(c,l))throw Jt(l),new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,n,i,i,1),Jt(l),i}}),hu=yx({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},Nx(Rx));function Lx(t,e,n){return pl(t),n===void 0&&(n=new Uint8Array(t.outputLen)),Ip(t,n,e)}const _r=Uint8Array.of(0),Bx=Uint8Array.of();function _x(t,e,n,r=32,o){pl(t),Ot(r,"length"),Dt(e,void 0,"prk");const s=t.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(r>255*s)throw new Error("Length must be <= 255*HashLen");const i=Math.ceil(r/s);if(n===void 0?n=Bx:Dt(n,void 0,"info"),!i)return new Uint8Array;const a=new Uint8Array(i*s),{iHash:c,oHash:l}=Ip.create(t,e),d=new Uint8Array(s),u=i>1?t.create():void 0;for(let h=0;h<i-1;h++){_r[0]=h+1;const g=c._cloneInto(u);h&&g.update(d),g.update(n).update(_r).digestInto(d),l._cloneInto(u).update(d).digestInto(d),a.set(d,s*h)}if(_r[0]=i,i>1&&c.update(d),c.update(n).update(_r).digestInto(d),l.update(d).digestInto(d),a.set(d,s*(i-1)),c.destroy(),l.destroy(),u?.destroy(),d!==a&&gn(d),gn(_r),r===a.length)return a;const f=a.slice(0,r);return gn(a),f}const Lp={hashSHA256(t){return Wi(t.subarray())},getHKDF(t,e){const n=Lx(Wi,e,t),o=_x(Wi,n,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){const t=Go.utils.randomSecretKey();return{publicKey:Go.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:Go.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return Go.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,n,r){return hu(r,e,n).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,n,r,o){return hu(r,e,n).decrypt(t.subarray(),o)}},Ox=Lp;function Dx(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,n)=>t.generateX25519SharedKey(e.privateKey,n).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}const Hs=t=>{const e=Bt(2);return e[0]=t>>8,e[1]=t,e};Hs.bytes=2;const Us=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)};Us.bytes=2;function Fx(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 Bp(t,e){!e.enabled||!Po||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${te(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${te(t.privateKey,"hex")}`)):e("Missing local static keys."))}function _p(t,e){!e.enabled||!Po||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${te(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${te(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Mx(t,e){!e.enabled||!Po||e(t?`REMOTE_STATIC_PUBLIC_KEY ${te(t.subarray(),"hex")}`:"Missing remote static public key.")}function Op(t,e){!e.enabled||!Po||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${te(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Dp(t,e,n){!n.enabled||!Po||(n(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&te(t.k,"hex")}`),n(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&te(e.k,"hex")}`))}class so extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=so.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}const jx=0,Hx=4294967295,Ux="Cipherstate has reached maximum n, a new handshake must be performed";class $x{n;bytes;view;constructor(e=jx){this.n=e,this.bytes=qe(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>Hx)throw new Error(Ux)}}const or=qe(0);class Wo{k;n;crypto;constructor(e,n=void 0,r=0){this.crypto=e,this.k=n,this.n=new $x(r)}hasKey(){return!!this.k}encryptWithAd(e,n){if(!this.hasKey())return n;this.n.assertValue();const r=this.crypto.encrypt(n,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,n,r){if(!this.hasKey())return n;this.n.assertValue();const o=this.crypto.decrypt(n,this.n.getBytes(),e,this.k,r);return this.n.increment(),o}}class qx{cs;ck;h;crypto;constructor(e,n){this.crypto=e;const r=Se(n,"utf-8");this.h=zx(e,r),this.ck=this.h,this.cs=new Wo(e)}mixKey(e){const[n,r]=this.crypto.hkdf(this.ck,e);this.ck=n,this.cs=new Wo(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new ce(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,or);return[new Wo(this.crypto,e),new Wo(this.crypto,n)]}}class Kx{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:n,protocolName:r,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=n,this.ss=new qx(n,r),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,n=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<n+32)throw new Error("message is not long enough");this.re=e.sublist(n,n+32),this.ss.mixHash(this.re)}readS(e,n=0){if(this.rs)throw new Error("remote static public key is already set");const r=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<n+r)throw new Error("message is not long enough");const o=e.sublist(n,n+r);return this.rs=this.ss.decryptAndHash(o),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class Fp extends Kx{writeMessageA(e){return new ce(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const n=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new ce(n,r,this.ss.encryptAndHash(e))}writeMessageC(e){const n=this.writeS();return this.writeSE(),new ce(n,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(n){throw new so(`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 so(`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 so(`handshake stage 2 validation fail: ${n.message}`)}}}function zx(t,e){if(e.length<=32){const n=qe(32);return n.set(e),n}else return t.hash(e)}var $s;(function(t){let e;t.codec=()=>(e==null&&(e=ui((n,r,o={})=>{if(o.lengthDelimited!==!1&&r.fork(),n.webtransportCerthashes!=null)for(const s of n.webtransportCerthashes)r.uint32(10),r.bytes(s);if(n.streamMuxers!=null)for(const s of n.streamMuxers)r.uint32(18),r.string(s);o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={webtransportCerthashes:[],streamMuxers:[]},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new _d('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(n.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new _d('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(n.string());break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>di(n,t.codec()),t.decode=(n,r)=>li(n,t.codec(),r)})($s||($s={}));var qs;(function(t){let e;t.codec=()=>(e==null&&(e=ui((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.identityKey!=null&&n.identityKey.byteLength>0&&(r.uint32(10),r.bytes(n.identityKey)),n.identitySig!=null&&n.identitySig.byteLength>0&&(r.uint32(18),r.bytes(n.identitySig)),n.extensions!=null&&(r.uint32(34),$s.codec().encode(n.extensions,r)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={identityKey:qe(0),identitySig:qe(0)},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{s.identityKey=n.bytes();break}case 2:{s.identitySig=n.bytes();break}case 4:{s.extensions=$s.codec().decode(n,n.uint32(),{limits:o.limits?.extensions});break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>di(n,t.codec()),t.decode=(n,r)=>li(n,t.codec(),r)})(qs||(qs={}));async function Mp(t,e,n){const r=await t.sign(Hp(e));return qs.encode({identityKey:fi(t.publicKey),identitySig:r,extensions:n})}async function jp(t,e,n){try{const r=qs.decode(t),o=rc(r.identityKey);if(n?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${n}`);if(!e)throw new Error("Remote static does not exist");const s=Hp(e);if(!await o.verify(s,r.identitySig))throw new Error("Invalid payload signature");return r}catch(r){throw new nw(r.message)}}function Hp(t){const e=Se("noise-libp2p-static-key:");return t instanceof Uint8Array?Ga([e,t],e.length+t.length):(t.prepend(e),t)}class Gx extends Tp{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 ax({lengthDecoder:Us,maxBufferSize:16*1024*1024,encodingLength:()=>2});const o=c=>{try{for(const l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);const s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);const i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);const a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){const n=new ce;for(let r=0;r<e.byteLength;r+=iu){let o=r+iu;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(r,o)):s=this.handshake.encrypt(e.sublist(r,o)),this.metrics?.encryptedPackets.increment(),n.append(Hs(s.byteLength)),n.append(s)}return n}decrypt(e){const n=new ce;for(let r=0;r<e.byteLength;r+=yo){let o=r+yo;if(o>e.byteLength&&(o=e.byteLength),o-au<r)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(r,o):s=e.sublist(r,o);const i=e.subarray(r,o-au);try{const a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),n.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return n}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}}function pu(t,e,n){return new Gx(t,e,n)}async function Wx(t,e){const{log:n,connection:r,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Mp(s,a.publicKey,l),u=new Fp({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Bp(u.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(u.writeMessageA(or),e),n.trace("Stage 0 - Initiator finished sending first message."),_p(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."),Op(u.re,n),Mx(u.rs,n),n.trace("Initiator going to check remote's signature...");const h=await jp(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 Dp(g,m,n),{payload:h,encrypt:b=>g.encryptWithAd(or,b),decrypt:(b,w)=>m.decryptWithAd(or,b,w)}}async function Vx(t,e){const{log:n,connection:r,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Mp(s,a.publicKey,l),u=new Fp({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Bp(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."),Op(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."),_p(u.e,n),n.trace("Stage 2 - Responder waiting for third handshake message...");const f=u.readMessageC(await r.read(e));n.trace("Stage 2 - Responder received the message, finished handshake.");const h=await jp(f,u.rs,c),[g,m]=u.ss.split();return Dp(g,m,n),{payload:h,encrypt:b=>m.encryptWithAd(or,b),decrypt:(b,w)=>g.decryptWithAd(or,b,w)}}class Xx{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,n={}){const{staticNoiseKey:r,extensions:o,crypto:s,prologueBytes:i}=n,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");const c=s??Ox;this.crypto=Dx(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Fx(a):void 0,r?this.staticKey=c.generateX25519KeyPairFromSeed(r):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??qe(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[dw]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,n){const r=e.log?.newScope("noise")??this.log,o=su(e,{lengthEncoder:Hs,lengthDecoder:Us,maxDataLength:yo}),s=await this.performHandshakeInitiator(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=rc(s.payload.identityKey);return{connection:pu(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:fr(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;const n=this.components.upgrader.getStreamMuxers();if(n!=null)for(const r of e){const o=n.get(r);if(o!=null)return o}if(e.length)throw new rw("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,n){const r=e.log?.newScope("noise")??this.log,o=su(e,{lengthEncoder:Hs,lengthDecoder:Us,maxDataLength:yo}),s=await this.performHandshakeResponder(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=rc(s.payload.identityKey);return{connection:pu(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:fr(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,n,r,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Wx({connection:e,privateKey:n,remoteIdentityKey:o,log:r.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,n,r,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Vx({connection:e,privateKey:n,remoteIdentityKey:o,log:r.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}}function Yx(t={}){return e=>new Xx(e,t)}const Zx="termdock-e2ee-v1",uc=3600*1e3,gu=512*1024*1024,fc=4*1024*1024,is=()=>{},gi=Object.assign(is,{enabled:!1,error:is,trace:is,newScope:()=>gi});Object.freeze(gi);async function Up(){const t=await gv();return{privateKey:t,peerId:fr(t.publicKey).toString()}}function Jx(t){return btoa(String.fromCharCode(...yv(t.privateKey)))}function mu(t){if(t.length>512||!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Invalid identity encoding");const e=wv(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:fr(e.publicKey).toString()}}class $p{constructor(e=is){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>fc)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 Qx extends Tp{constructor(e,n){super({log:gi,direction:n?"outbound":"inbound",maxReadBufferLength:fc,maxWriteBufferLength:fc}),this.duplex=e,this.finished=e.sink(this.outgoing).catch(r=>{this.abort(hr(r))}),this.readTransport()}duplex;outgoing=new $p(()=>this.onMuxerDrain());finished;async readTransport(){try{for await(const e of this.duplex.source)this.onData(e.slice());this.onTransportClosed()}catch(e){this.onTransportClosed(hr(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 hr(t){return t instanceof Error?t:new Error("Secure transport failed")}class eE extends Error{code="E2EE_REHANDSHAKE_REQUIRED";constructor(){super("Encrypted connection lifetime reached; establish a new handshake without replaying pending input")}}function tE(t){const e=t?.maxAgeMs??uc,n=t?.maxBytesPerDirection??gu;if(!Number.isSafeInteger(e)||e<=0||e>uc||!Number.isSafeInteger(n)||n<=0||n>gu)throw new Error("Encrypted connection limits cannot exceed the production maximum");return{maxAgeMs:e,maxBytesPerDirection:n}}async function nE(t){const{identity:e,duplex:n,initiator:r,targetPinnedPeerId:o,signal:s}=t,i=tE(t.limits);if(typeof Reflect.get(Promise,"withResolvers")!="function"||typeof globalThis.crypto?.getRandomValues!="function")throw new Error("End-to-end encryption requires Node.js 22+ or a modern browser with Promise.withResolvers and secure random support");if(r&&!o)throw new Error("A pinned target identity is required");const a=o?xv(o):void 0;if(a&&a.type!=="Ed25519")throw new Error("Only Ed25519 target identities are supported");if(e.peerId!==fr(e.privateKey.publicKey).toString())throw new Error("Local identity mismatch");if(s?.aborted)throw s.reason??new Error("Connection aborted");const c=new Qx(n,r),l=new AbortController,d=setTimeout(()=>{const h=new Error("Encrypted handshake timed out");l.abort(h),c.abort(h)},15e3),u=()=>{l.abort(s?.reason),c.abort(hr(s?.reason))};s?.addEventListener("abort",u,{once:!0}),c.addEventListener("close",()=>s?.removeEventListener("abort",u),{once:!0});const f=Yx({crypto:Lp,prologueBytes:new TextEncoder().encode(Zx)})({privateKey:e.privateKey,peerId:fr(e.privateKey.publicKey),logger:{forComponent:()=>gi},upgrader:{getStreamMuxers:()=>new Map}});try{const h=await(r?f.secureOutbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}):f.secureInbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}));if(h.remotePeer.type!=="Ed25519")throw new Error("Unsupported remote identity");return{authenticatedPeerId:h.remotePeer.toString(),duplex:rE(h.connection,i)}}catch(h){throw c.abort(hr(h)),h}finally{clearTimeout(d),s?.removeEventListener("abort",u)}}function rE(t,e){const n=new $p,r=performance.now(),o=Date.now();let s=0,i=0,a;const c=()=>(a??=new eE,n.end(a),t.abort(a),a),l=setTimeout(c,e.maxAgeMs);typeof l=="object"&&l.unref?.();const d=(f,h)=>{if(a)throw a;if(Math.max(performance.now()-r,Date.now()-o)>=e.maxAgeMs||f+h>=e.maxBytesPerDirection)throw c()};t.addEventListener("message",f=>{try{d(i,f.data.byteLength),i+=f.data.byteLength,n.push(f.data.subarray())}catch(h){t.abort(hr(h))}}),t.addEventListener("close",f=>{clearTimeout(l),n.end(f.error)},{once:!0});let u=!1;return{source:n,async sink(f){if(u)throw new Error("Secure sink already consumed");u=!0;try{for await(const h of f)d(s,h.byteLength),s+=h.byteLength,t.send(h)||await t.onDrain()}catch(h){throw t.abort(hr(h)),h}},close(f){f?t.abort(f):t.close()}}}const qp=1012,Kp="Encrypted transport renewed";class El{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 Ji=2*1024*1024,oE=new TextEncoder,sE=new TextDecoder("utf-8",{fatal:!0});class iE{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 El(256);outgoingBytes=0;get hasPendingWrites(){return this.outgoingBytes>0}done;send(e){const n=oE.encode(JSON.stringify(e));if(n.length>Ji)throw new Error("Record too large");const r=new Uint8Array(n.length+4);if(new DataView(r.buffer).setUint32(0,n.length),r.set(n,4),this.outgoingBytes+r.byteLength>4*1024*1024)throw new Error("Record queue byte budget exceeded");this.outgoingBytes+=r.byteLength;try{this.outgoing.push(r)}catch(o){throw this.outgoingBytes-=r.byteLength,o}}close(e){this.outgoing.end(e),this.duplex.close?.(e)}async*read(){let e=new Uint8Array(0);for await(const n of this.duplex.source){if(e.length+n.length>Ji*2+8)throw new Error("Record buffer exceeded");const r=new Uint8Array(e.length+n.length);for(r.set(e),r.set(n,e.length),e=r;e.length>=4;){const o=new DataView(e.buffer,e.byteOffset,4).getUint32(0);if(o>Ji||o===0)throw new Error("Invalid record size");if(e.length<o+4)break;const s=JSON.parse(sE.decode(e.subarray(4,o+4)));if(!s||typeof s!="object"||typeof s.id!="string"||typeof s.type!="string")throw new Error("Invalid record");yield s,e=e.slice(o+4)}}if(e.length)throw new Error("Truncated record")}}function zp(t){let e="";for(let n=0;n<t.length;n+=8192)e+=String.fromCharCode(...t.subarray(n,n+8192));return btoa(e)}function Gp(t){const e=atob(t);return Uint8Array.from(e,n=>n.charCodeAt(0))}function aE(t){const e=new El(64);t.binaryType="arraybuffer";const n=r=>{e.end(r),t.close(1e3)};return t.addEventListener("message",r=>{try{if(!(r.data instanceof ArrayBuffer)||r.data.byteLength>1024*1024)throw new Error("Invalid encrypted frame");e.push(new Uint8Array(r.data))}catch{n(new Error("Encrypted transport rejected frame"))}}),t.addEventListener("close",()=>e.end()),t.addEventListener("error",()=>e.end(new Error("Encrypted transport disconnected"))),{source:e,close:n,async sink(r){try{for await(const o of r)for(let s=0;s<o.length;s+=64*1024){const i=Date.now();for(;t.bufferedAmount>256*1024;){if(t.readyState!==1||Date.now()-i>15e3)throw new Error("Encrypted transport congested");await new Promise(a=>setTimeout(a,10))}if(t.readyState!==1)throw new Error("Encrypted transport closed");t.send(o.subarray(s,s+64*1024))}}catch(o){throw n(o instanceof Error?o:new Error("Encrypted transport failed")),o}}}}const Wp=8,Vp=128,cE=5*1024*1024,lE=Vp+Wp+8,dE=256,Vo=3e4,Or=64*1024;function Gt(t){return t instanceof Error?t:new Error(String(t??"Secure connection closed"))}function wu(t){if(!t.startsWith("/")||t.startsWith("//")||t.includes("#"))throw new Error("A local API path is required");return t}class Xp 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="";getConnectionDiagnostics;createdAt=performance.now();openedAfterMs;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.openedAfterMs=performance.now()-this.createdAt,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(Gt(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 uE{constructor(e,n,r){this.channel=e,this.identity=n,this.targetPeerId=r,this.read().catch(o=>this.close(Gt(o))),e.done.catch(o=>this.close(Gt(o)))}channel;identity;targetPeerId;transportDiagnostics;establishedAt=performance.now();establishedWallTime=Date.now();lastInputAt=-1/0;pending=new Map;waiting=[];stopped=!1;closeReason;get canSwitchTransport(){return!this.channel.hasPendingWrites&&performance.now()-this.lastInputAt>=2e3&&![...this.pending.values()].some(e=>e.kind!=="socket")&&!this.waiting.some(e=>e.kind!=="socket")}get renewalDue(){return!this.stopped&&Math.max(performance.now()-this.establishedAt,Date.now()-this.establishedWallTime)>=uc-5*6e4}get closed(){return this.stopped}hasCapacity(e){if(this.pending.size>=lE)return!1;const n=[...this.pending.values()].filter(r=>r.kind===e).length;return e==="http"?n<Wp:e==="socket"?n<Vp:!0}allocate(e){if(this.stopped)throw this.closeReason??new Error("Secure connection closed");const n=crypto.randomUUID(),r=new El(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>=dE?Promise.reject(new Error("连接繁忙,请稍后重试。")):new Promise((r,o)=>{const s=l=>{this.waiting=this.waiting.filter(d=>d!==c),c.cleanup(),o(l)},i=()=>s(n?.reason??new Error("Request aborted")),a=setTimeout(()=>s(new Error("连接等待超时,请重试。")),Vo),c={kind:e,resolve:r,reject:o,cleanup:()=>{clearTimeout(a),n?.removeEventListener("abort",i)}};this.waiting.push(c),n?.addEventListener("abort",i,{once:!0})})}dispatchWaiting(){if(!this.stopped)for(let e=0;e<this.waiting.length;){const n=this.waiting[e];if(!this.hasCapacity(n.kind)){e++;continue}this.waiting.splice(e,1),n.cleanup(),n.resolve(this.allocate(n.kind))}}async read(){try{for await(const e of this.channel.read()){const n=this.pending.get(e.id);n&&(n.socket?(n.socket.accept(e),(e.type==="ws-close"||e.type==="error")&&this.release(e.id)):(n.queue.push(e),(e.type==="end"||e.type==="error")&&(n.cancelUpload?.(),this.release(e.id))))}}finally{this.close(new Error("Secure connection closed"))}}release(e){this.pending.get(e)?.queue.end(),this.pending.delete(e),this.dispatchWaiting()}async request(e,n){const{id:r,queue:o}=await this.reserve("request"),s=setTimeout(()=>this.close(new Error("Secure connection timed out")),Math.max(1e3,Math.min(Vo,n?.timeoutMs??Vo)));try{if(this.stopped)throw this.closeReason;this.channel.send({...e,id:r});const i=(await o[Symbol.asyncIterator]().next()).value;if(!i)throw new Error("Secure request closed");if(i.type==="error")throw Gt(i.error);return i}finally{clearTimeout(s),this.release(r)}}openSocket(e){wu(e);let n;const r=new AbortController,o=new Xp(e,i=>{if(n){try{JSON.parse(i)?.type==="input"&&(this.lastInputAt=performance.now())}catch{}this.channel.send({id:n,type:"ws-data",data:i})}},()=>{if(r.abort(),n)try{this.channel.send({id:n,type:"ws-close"})}finally{this.release(n)}});let s;return o.getConnectionDiagnostics=()=>{const i=this.transportDiagnostics?.();return i?{...i,socketOpenMs:o.openedAfterMs,socketQueueMs:s,pendingWrites:this.channel.hasPendingWrites,activeRequests:[...this.pending.values()].filter(a=>a.kind!=="socket").length,waitingRequests:this.waiting.length}:void 0},this.reserve("socket",r.signal).then(i=>{if(s=performance.now()-o.createdAt,n=i.id,o.readyState===3){this.release(n);return}const a=this.pending.get(n);if(!a)throw new Error("Secure connection closed");a.socket=o,this.channel.send({id:n,type:"ws-open",path:e})}).catch(i=>{n&&this.release(n),o.fail(Gt(i))}),o}async fetch(e,n){const r=typeof location>"u"?"https://termdock.invalid":location.origin,o=e instanceof Request?e:null,s=new URL(o?.url??String(e),r);if(s.origin!==r)throw new Error("Only current-service API requests are supported");const i=new Request(s,o?new Request(o,n):n),a=i.method.toUpperCase(),c=wu(s.pathname+s.search),l=s.pathname==="/api/terminal/fs/upload"?110*1024*1024:cE;if(i.signal.aborted)throw i.signal.reason;const d={};i.headers.forEach((A,N)=>{["cookie","authorization","host","connection","content-length"].includes(N)||(d[N]=A)});const{id:u,queue:f}=await this.reserve("http",i.signal),h=f[Symbol.asyncIterator]();let g;const m=()=>{g?.cancel().catch(()=>{})},b=this.pending.get(u);if(!b)throw new Error("Secure connection closed");b.cancelUpload=m;const w=()=>{m();try{this.channel.send({id:u,type:"cancel"})}catch{}f.end(Gt(i.signal.reason??"Request aborted")),this.release(u)};i.signal.addEventListener("abort",w,{once:!0});const I=()=>{i.signal.removeEventListener("abort",w),this.release(u)},y=async()=>{let A;try{const N=(await Promise.race([h.next(),new Promise((k,T)=>{A=setTimeout(()=>T(new Error("服务响应超时,请重试。")),Vo)})])).value;if(!N)throw new Error("Secure response ended unexpectedly");if(N.type==="error")throw Gt(N.error);return N}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 S=i.body.getReader();g=S;let v=0,E=0;try{for(;;){const{done:_,value:L}=await S.read();if(_)break;if(v+=L.byteLength,v>l)throw new Error("Request body exceeds upload limit");for(let C=0;C<L.byteLength;C+=Or){if(this.channel.send({id:u,type:"upload",data:zp(L.subarray(C,C+Or))}),(await y()).type!=="upload-ack")throw new Error("Invalid upload acknowledgement");E+=Math.min(Or,L.byteLength-C),n?.onUploadProgress?.(E)}}}catch(_){throw await S.cancel(_).catch(()=>{}),_}finally{g=void 0,S.releaseLock()}}if(i.signal.aborted||this.stopped)throw new Error("Request aborted");this.channel.send({id:u,type:"upload-end"});const A=await y();if(A.type!=="head"||typeof A.status!="number")throw new Error("Invalid response header");const N=new Headers(A.headers);if(a==="HEAD"||[204,205,304].includes(A.status)){if((await y()).type!=="end")throw new Error("Unexpected response body");return I(),new Response(null,{status:A.status,headers:N})}let k=!1;const T=new ReadableStream({pull:async S=>{try{k&&(this.channel.send({id:u,type:"ack"}),k=!1);const v=await y();if(v.type==="end"){S.close(),I();return}if(v.type!=="chunk"||typeof v.data!="string")throw new Error("Invalid response chunk");const E=Gp(v.data);if(E.length>Or)throw new Error("Response chunk exceeds budget");S.enqueue(E),k=!0}catch(v){S.error(v),w(),I()}},cancel:()=>{w(),I()}},{highWaterMark:Or,size:S=>S.byteLength});return new Response(T,{status:A.status,headers:N})}catch(A){throw w(),I(),A}}retire(){for(const e of this.pending.values())e.socket?.accept({id:"",type:"ws-close",code:qp,reason:Kp});this.close()}close(e=new Error("Secure connection closed")){if(!this.stopped){this.stopped=!0,this.closeReason=e;for(const n of this.waiting.splice(0))n.cleanup(),n.reject(e);for(const n of this.pending.values())n.queue.end(e),n.cancelUpload?.(),n.socket?.fail(e);this.pending.clear(),this.channel.close(e)}}}async function Sn(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 Up(),r=performance.now(),o=(t.socketFactory??(l=>new WebSocket(l)))(e.href),s=aE(o),i=new AbortController,a=setTimeout(()=>i.abort(new Error("Secure handshake timed out")),2e4),c=t.signal?AbortSignal.any([t.signal,i.signal]):i.signal;try{await new Promise((m,b)=>{if(c.aborted){b(c.reason);return}const w=()=>{c.removeEventListener("abort",A),o.removeEventListener("open",I),o.removeEventListener("error",y),o.removeEventListener("close",y)},I=()=>{w(),m()},y=()=>{w(),b(new Error("Secure transport unavailable"))},A=()=>{w(),b(c.reason)};c.addEventListener("abort",A,{once:!0}),o.addEventListener("open",I),o.addEventListener("error",y),o.addEventListener("close",y),o.readyState===1&&I()});const l=performance.now(),d=await nE({identity:n,duplex:s,initiator:!0,targetPinnedPeerId:t.targetPeerId,signal:c}),u=new uE(new iE(d.duplex),n,d.authenticatedPeerId),f=performance.now(),h=Date.now(),g=o.connectionTimings;if(u.transportDiagnostics=()=>({endpoint:e.host,path:g?"relay":"direct",targetPeerId:d.authenticatedPeerId,transportOpenMs:l-r,handshakeMs:f-l,establishedAt:h,relay:g?{...g}:void 0,bufferedBytes:o.bufferedAmount,pendingWrites:!1,activeRequests:0,waitingRequests:0}),t.pairingCode)try{await u.request({type:"pair",code:t.pairingCode})}catch(m){throw u.close(Gt(m)),m}return u}catch(l){throw o.close(),l}finally{clearTimeout(a)}}const yu=256*1024,fE=1024*1024;class hE extends EventTarget{constructor(e,n,r=o=>new WebSocket(o)){if(super(),this.url=e,!/^[a-zA-Z0-9_.:-]{1,160}$/.test(n))throw new Error("Invalid target identity");const o=performance.now();let s;this.upstream=r(e),this.upstream.addEventListener("open",()=>{this.connectionTimings.entryOpenMs=performance.now()-o}),this.deadline=setTimeout(()=>this.fail("Relay connection timed out"),2e4),this.upstream.addEventListener("message",i=>{if(this.readyState!==3)try{if(typeof i.data!="string"||new TextEncoder().encode(i.data).length>yu)throw new Error("Invalid relay envelope");const a=JSON.parse(i.data);if(a.type==="ready"&&!this.requested){s=performance.now(),this.requested=!0,this.transmit({type:"open",streamId:this.streamId,serviceId:n});return}if(a.streamId!==this.streamId)return;if(a.type==="opened"&&this.readyState===0){this.connectionTimings.routeOpenMs=s===void 0?null:performance.now()-s,clearTimeout(this.deadline),this.readyState=1;const u=new Event("open");this.dispatchEvent(u),this.onopen?.(u);return}if(a.type==="close"){this.finish(1001,"Relay route closed"),this.upstream.close();return}if(a.type!=="data"||this.readyState!==1||a.encoding!=="base64"||typeof a.payload!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(a.payload))throw new Error("Invalid ciphertext relay frame");const c=Gp(a.payload),l=this.binaryType==="blob"?new Blob([c]):c.buffer,d=new MessageEvent("message",{data:l});this.dispatchEvent(d),this.onmessage?.(d)}catch{this.fail("Relay protocol rejected frame")}}),this.upstream.addEventListener("close",i=>this.finish(i.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;connectionTimings={entryOpenMs:null,routeOpenMs: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>fE||n.length>yu)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:zp(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 Yp(t){return e=>new hE(e,t)}function pE(t){if(typeof t!="string"||!t.startsWith("/api/")||/[\\\x00-\x20\x7f#]/.test(t))return null;const e=t.split("?")[0];if(e.includes("//"))return null;try{const r=e.split("/").map((o,s)=>{if(s===0||o===""&&s===e.split("/").length-1)return o;const i=decodeURIComponent(o);if(!i||i==="."||i===".."||/[\\/\x00-\x1f\x7f]/.test(i)||/%[a-f0-9]{2}/i.test(i))throw new Error("Ambiguous API path");return i}).join("/");return r.endsWith("/")&&!r.startsWith("/api/terminal/fs/preview/")?null:r}catch{return null}}function gE(t){if(!("serviceWorker"in navigator))return()=>{};const e=new Set,n=r=>{if(r.source!==navigator.serviceWorker.controller||r.data?.type!=="termdock-secure-fetch"||r.ports.length!==1)return;const o=r.ports[0],{path:s,method:i,headers:a,body:c,expectedTargetPeerId:l,previewPrefix:d}=r.data;let u;try{u=new URL(s,location.origin)}catch{o.close();return}if(u.origin!==location.origin||!u.pathname.startsWith("/api/")||e.size>=32||typeof i!="string"||c!==void 0&&(!(c instanceof ArrayBuffer)||c.byteLength>5*1024*1024)){o.postMessage({type:"error"}),o.close();return}if(d!==void 0&&(typeof d!="string"||!d.endsWith("/")||!/^\/api\/terminal\/fs\/preview\/[a-f0-9]{32}\//.test(d)||!["GET","HEAD"].includes(i)||!pE(u.pathname)?.startsWith(d))){o.postMessage({type:"error"}),o.close();return}const f=new AbortController;let h,g,m=!1,b=!1;const w=()=>{b||(b=!0,e.delete(w),f.abort(),h?.cancel().catch(()=>{}),o.close())};e.add(w),o.onmessage=I=>{if(I.data?.type==="cancel"){w();return}I.data?.type!=="pull"||m||b||(m=!0,(async()=>{if(!h){o.postMessage({type:"end"}),w();return}if(!g?.length){const A=await h.read();if(A.done){o.postMessage({type:"end"}),w();return}g=A.value}const y=g.slice(0,64*1024);g=g.subarray(y.length),o.postMessage({type:"chunk",data:y.buffer},[y.buffer])})().catch(()=>{o.postMessage({type:"error"}),w()}).finally(()=>{m=!1}))},o.onmessageerror=w,o.start(),(async()=>{const I=await t();if(b)return;if(l&&l!==I.targetPeerId)throw new Error("Preview target changed");const y=await I.fetch(u.pathname+u.search,{method:i,headers:a,body:["GET","HEAD"].includes(i)?void 0:c,signal:f.signal});if(b){await y.body?.cancel();return}h=y.body?.getReader();const A={};y.headers.forEach((N,k)=>{A[k]=N}),o.postMessage({type:"head",status:y.status,headers:A,bodyless:!h,targetPeerId:I.targetPeerId})})().catch(()=>{b||(o.postMessage({type:"error"}),w())})};return navigator.serviceWorker.addEventListener("message",n),()=>{navigator.serviceWorker.removeEventListener("message",n);for(const r of[...e])r()}}class tt extends Error{constructor(){super("Device authorization expired or revoked")}}const Xo=new WeakMap;function vr(t,e={}){const n=Xo.get(t);if(!t.closed&&n&&(!n.settled||Date.now()-n.at<(e.maxAgeMs??1e3)))return n.pending;const r={at:Date.now(),settled:!1,pending:void 0},o=mE(t,e.timeoutMs??5e3).then(s=>(r.at=Date.now(),r.settled=!0,s),s=>{throw Xo.get(t)===r&&Xo.delete(t),s});return r.pending=o,Xo.set(t,r),o}async function mE(t,e){const n=await t.request({type:"permissions"},{timeoutMs:e});if(n.type!=="result"||typeof n.fullService!="boolean"||!Array.isArray(n.grants))throw new Error("Invalid permission response");const r=n.grants,o=n.fullService===!0;if(!o&&r.length===0)throw new tt;return{fullService:o,grants:r,canManage:o&&r.length>0||r.some(s=>s.actions.includes("authorization.manage"))}}const Zp="termdock-secure-last-path:",wE=10*6e4;function Jp(t){try{const e=JSON.parse(sessionStorage.getItem(Zp+t)||"null");return e&&typeof e.key=="string"&&Date.now()-e.at<wE?e.key:void 0}catch{return}}function hc(t,e){try{sessionStorage.setItem(Zp+t,JSON.stringify({key:e,at:Date.now()}))}catch{}}function Qp(t,e,n=!1){return new Promise((r,o)=>{let s=0,i=0,a=!1,c,l;const d=new Set,u=()=>{clearTimeout(l);for(const h of d)h.abort();d.clear()},f=()=>{if(a)return;if(s>=t.length){i||(a=!0,u(),o(c||new Error("没有可用的连接路线。")));return}if(i>=(n?1:2))return;const h=t[s++],g=performance.now(),m=w=>{performance.getEntriesByName("termdock:connection-path").length>64&&performance.clearMeasures("termdock:connection-path"),performance.measure("termdock:connection-path",{start:g,end:performance.now(),detail:{path:h.key.startsWith("relay:")?"relay":"direct",ok:w}})},b=new AbortController;d.add(b),i++,h.run(b.signal).then(w=>{if(m(!0),d.delete(b),a){e(w);return}a=!0,u(),r({value:w,key:h.key})},w=>{if(m(!1),d.delete(b),i--,!a){if(c=w,w instanceof tt){a=!0,u(),o(w);return}f()}}),clearTimeout(l),!n&&s<t.length&&(l=setTimeout(f,400))};f()})}const yE=3,bE=1/0,vE=10,eg="termdock-secure-workspace-limit";function tg(t){return t===1/0||Number.isInteger(t)&&t>=3&&t<=vE}function SE(){try{const t=localStorage.getItem(eg),e=t==="unlimited"?1/0:Number(t);if(tg(e))return e}catch{}return navigator.maxTouchPoints>0?yE:bE}function xE(t,e,n,r){if(t.length<=r)return t;const o=new Set(["root",e,...n?[n]:[]]),s=[...t].reverse().sort((i,a)=>a.touchedAt-i.touchedAt);for(const i of s){if(o.size>=r)break;o.add(i.key)}return t.filter(i=>o.has(i.key))}const ng="termdock-workspace",bo="termdock:workspace-visibility",pc="termdock:workspace-activate";function mi(){return window.parent!==window&&location.pathname==="/workspace.html"&&new URLSearchParams(location.search).get(ng)||"root"}let bu,vu;function wt(){try{if(window.parent===window)return window.__termdockWorkspaceHost;const t=window.parent.__termdockWorkspaceHost;return t&&t!==bu&&(bu=t,vu={...t,subscribe(e){const n=t.subscribe(e,mi()),r=o=>{o.persisted||n()};return window.addEventListener("pagehide",r),()=>{n(),window.removeEventListener("pagehide",r)}}}),t?vu:void 0}catch{return}}function as(){const t=wt();return!t||t.snapshot().activeKey===mi()}function Ks(t,e=!0){return wt()?.activate(t,e)??!1}function $n(t){wt()?.report(mi(),t)}const gc="termdock-secure-workspace-session:",rg="termdock-secure-last-workspace";function EE(){for(const t of["sessionStorage","localStorage"])try{const e=window[t].getItem(rg);if(e)return e}catch{}return null}function AE(t){for(const e of["sessionStorage","localStorage"])try{window[e].setItem(rg,t)}catch{}}function FR(t){if(t)try{const e=JSON.parse(localStorage.getItem(gc+t)||"null");return localStorage.removeItem(gc+t),e&&typeof e.sessionId=="string"&&Date.now()-e.at<6e4?e.sessionId:void 0}catch{return}}function kE(t){if(window.parent!==window||window.termdockDesktop)return;if(window.__termdockWorkspaceHost)return window.__termdockWorkspaceHost;let e={activeKey:"root",items:[{key:"root",service:t,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]};try{const u=EE(),f=t&&u!==t.targetPeerId?yn().find(h=>h.targetPeerId===u):void 0;f?.targetPeerId&&(e={activeKey:f.targetPeerId,items:[...e.items,{key:f.targetPeerId,service:f,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]})}catch{}let n=SE(),r=e.activeKey==="root"?"root":null;const o=new Map,s=new Map([["root",window]]),i=new Set,a=()=>{for(const u of[...o.keys()])u()},c=()=>{const u=xE(e.items,e.activeKey,r,n),f=new Set(u.map(h=>h.key));e={...e,items:u};for(const[h,g]of o)g&&!f.has(g)&&o.delete(h);for(const h of s.keys())f.has(h)||s.delete(h);for(const h of i)f.has(h)||i.delete(h)},l=(u,f)=>{try{const h=f.document.createEvent("CustomEvent");if(h.initCustomEvent(bo,!1,!1,{active:e.activeKey===u}),f.dispatchEvent(h),e.activeKey===u){const g=f.document.createEvent("Event");if(g.initEvent("resize",!1,!1),f.dispatchEvent(g),i.delete(u)){const m=f.document.createEvent("Event");m.initEvent(pc,!1,!1),f.dispatchEvent(m)}}else f.document.activeElement?.blur?.()}catch{}},d={snapshot:()=>e,subscribe:(u,f)=>(o.set(u,f),()=>{o.delete(u)}),present(u){r=u},retentionLimit:()=>n,setRetentionLimit(u){if(tg(u)){n=u;try{localStorage.setItem(eg,u===1/0?"unlimited":String(u))}catch{}c(),a()}},activate(u,f=!0){const h=ti(u);if(!h?.targetPeerId)return!1;const g=e.items.find(w=>w.service?.targetPeerId===h.targetPeerId),m=g?.key||h.targetPeerId,b=g?{...g,service:h,touchedAt:Date.now()}:{key:m,service:h,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()};e={activeKey:m,items:g?e.items.map(w=>w===g?b:w):[...e.items,b]},c(),AE(h.targetPeerId),f&&i.add(m),a();for(const[w,I]of s)l(w,I);return!0},report(u,f){const h=e.items.find(m=>m.key===u);if(!h||f.service&&h.service?.targetPeerId&&f.service.targetPeerId!==h.service.targetPeerId)return;const g={...h,...f};JSON.stringify(g)!==JSON.stringify(h)&&(e={...e,items:e.items.map(m=>m===h?g:m)},a())},attach(u,f){f&&e.items.some(h=>h.key===u)?(s.set(u,f),l(u,f)):s.delete(u)},focusSession(u,f){const h=yn().find(m=>m.targetPeerId===u);if(!h)return!1;try{localStorage.setItem(gc+u,JSON.stringify({sessionId:f,at:Date.now()}))}catch{return!1}d.activate(h,!1);const g=s.get(e.activeKey);if(g){const m=g.document.createEvent("CustomEvent");m.initCustomEvent("termdock:workspace-session",!1,!1,null),g.dispatchEvent(m)}return!0}};return window.__termdockWorkspaceHost=d,d}let Qi;async function nt(){return Qi||(Qi=(async()=>{const t=await new Promise((e,n)=>{const r=indexedDB.open("termdock-device-identity",1);r.onupgradeneeded=()=>r.result.createObjectStore("keys"),r.onsuccess=()=>e(r.result),r.onerror=()=>n(r.error)});try{const e=await new Promise((o,s)=>{const i=t.transaction("keys").objectStore("keys").get("identity");i.onsuccess=()=>o(i.result),i.onerror=()=>s(i.error)});if(e)return mu(e);const n=await Up();let r=n;return await new Promise((o,s)=>{const i=t.transaction("keys","readwrite"),a=i.objectStore("keys"),c=a.get("identity");c.onsuccess=()=>{typeof c.result=="string"?r=mu(c.result):a.put(Jx(n),"identity")},i.oncomplete=()=>o(),i.onerror=()=>s(i.error)}),r}finally{t.close()}})()),Qi}const et="termdock:secure-state";let Q,qn,Ue,pr="direct",cs=!1,Su=0,ls=!1,xu=-1/0;const gr=globalThis.fetch.bind(globalThis);function se(){return fo()}function Vt(){return Q}function CE(){return Ue}function og(){Q?.close(),Ue?.close(),Q=void 0,Ue=void 0}async function sg(){const t=await gr("/api/auth/status",{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error("Failed to query auth status");return t.json()}async function IE(){if(se()){await it();return}if((await sg()).enabled)return;const t=await gr("/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 ct({url:location.origin,targetPeerId:e,serviceName:location.hostname})}async function RE(t,e){const{startPasswordBootstrap:n,finishPasswordBootstrap:r}=await tn(async()=>{const{startPasswordBootstrap:l,finishPasswordBootstrap:d}=await import("./passwordBootstrap-C6YjAkMT.js");return{startPasswordBootstrap:l,finishPasswordBootstrap:d}},__vite__mapDeps([0,1,2,3])),o=l=>t===location.origin?l:new URL(l,t).href,s=async(l,d)=>{const u=await gr(o(l),{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(15e3),...d?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}:{}});if(!u.ok)throw new Error(u.status===429?"尝试次数较多,请稍后再试。":u.status===401?"密码不正确,请重新输入。":"暂时无法登录这台服务,请稍后重试。");return u.json()},{saltHex:i}=await s("/api/auth/password/parameters"),a=await nt(),c=await n(e,i);try{const l=await s("/api/auth/password/start",{startLoginRequest:c.startLoginRequest,clientIdentity:a.peerId});let d;try{d=await r(c,l,{clientIdentity:a.peerId,origin:location.origin})}catch{throw new Error("密码不正确,或服务身份无法验证。请检查后重试。")}return await s("/api/auth/password/finish",{attemptId:d.attemptId,finishLoginRequest:d.finishLoginRequest}),{url:t,targetPeerId:d.serverIdentity,serviceName:new URL(t).host,serviceOrigin:t}}finally{c.passwordKey=""}}async function Al(t,e){const n=se();if(n&&(n.serviceOrigin||n.url)===t)return await mc(n,e),n;try{return await RE(t,e)}catch(r){if(!(r instanceof TypeError)&&!(r instanceof DOMException))throw r;const o=(await Ge()).find(i=>i.targetPeerId&&(i.serviceOrigin||i.url)===t);if(!o?.targetPeerId)throw new Error("暂时连不上这台服务,请检查地址和网络。");const s={...o,targetPeerId:o.targetPeerId,serviceName:o.label};return await mc(s,e),s}}async function mc(t,e){const n=await kl(t),{startPasswordBootstrap:r,finishPasswordBootstrap:o}=await tn(async()=>{const{startPasswordBootstrap:i,finishPasswordBootstrap:a}=await import("./passwordBootstrap-C6YjAkMT.js");return{startPasswordBootstrap:i,finishPasswordBootstrap:a}},__vite__mapDeps([0,1,2,3]));let s;try{const i=await n.request({type:"password-parameters"},{timeoutMs:5e3});s=await r(e,String(i.saltHex));const a=await n.request({type:"password-start",startLoginRequest:s.startLoginRequest,origin:location.origin}),c=await o(s,a,{clientIdentity:(await nt()).peerId,origin:location.origin});if(c.serverIdentity!==t.targetPeerId)throw new Error("服务身份发生变化。");await n.request({type:"password-finish",attemptId:c.attemptId,finishLoginRequest:c.finishLoginRequest})}catch{throw new Error("暂时无法登录,请检查目标服务密码与入口授权后重试。")}finally{s&&(s.passwordKey=""),n.close()}}async function TE(t){try{const e=se(),n=e?.serviceOrigin||location.origin,r=await Al(n,t);return await ct({...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 Eu(t,e){const n=Me(t),r=(await Ge()).find(i=>(i.serviceOrigin||i.url)===n&&i.targetPeerId);if(e===void 0&&r?.targetPeerId)try{return await ct({...r,targetPeerId:r.targetPeerId,serviceName:r.label}),{}}catch(i){if(!(i instanceof tt))throw i}if(e!==void 0){const i=await Al(n,e);if(r?.targetPeerId&&r.targetPeerId!==i.targetPeerId)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await ct({...i,routes:r?.routes,serviceName:r?.label||i.serviceName}),{}}const o=await gr(new URL("/api/auth/open/parameters",n).href,{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(1e4)}).catch(()=>{throw new Error("暂时连不上这台服务,请检查地址和网络后重试。")});if(o.status===403)return{passwordRequired:!0};if(!o.ok)throw new Error("这台服务暂时不可用,请稍后重试。");const{serviceIdentity:s}=await o.json();if(typeof s!="string"||!s)throw new Error("这不是可连接的 Termdock 服务。");if(r?.targetPeerId&&r.targetPeerId!==s)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await ct({url:n,targetPeerId:s,serviceName:r?.label||new URL(n).host,serviceOrigin:n}),{}}function en(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(Wc)||"null");n&&n.targetPeerId!==t.targetPeerId&&new URL(n.url).host===new URL(t.url).host&&e.push(n)}catch{}return e.flatMap((n,r)=>{try{return n.targetPeerId&&n.targetPeerId!==t.targetPeerId&&e.findIndex(o=>o.targetPeerId===n.targetPeerId)===r?[{url:Me(n.url),targetPeerId:n.targetPeerId}]:[]}catch{return[]}}).slice(0,4)}function Sr(t){const e=en(t),n=[t.serviceOrigin||t.url,...(t.routes||[]).slice(0,4).filter(o=>o.targetPeerId===t.targetPeerId).map(o=>o.url)],r=new Set;for(const o of n)try{const s=Me(o);e.some(i=>i.url===s)||r.add(s)}catch{}return[...r]}function xn(t){const e=new URL("/api/federation/secure",Me(t));return e.protocol=e.protocol==="https:"?"wss:":"ws:",e.href}async function nn(t,e){return Sn({url:xn(t.url),targetPeerId:t.targetPeerId,identity:await nt(),signal:e?AbortSignal.any([e,AbortSignal.timeout(5e3)]):AbortSignal.timeout(5e3)})}async function kl(t,e){const n=await nt(),r=Sr(t).map(i=>({key:`direct:${i}`,run:a=>Sn({url:xn(i),targetPeerId:t.targetPeerId,identity:n,signal:AbortSignal.any([a,AbortSignal.timeout(8e3),...e?[e]:[]])})}));for(const i of en(t))r.push({key:`relay:${i.targetPeerId}:${i.url}`,run:async a=>{e&&(a=AbortSignal.any([a,e]));const c=[Q,Ue].find(d=>d&&!d.closed&&d.targetPeerId===i.targetPeerId),l=c||await nn(i,a);try{if(a.aborted)throw a.reason;const d=await l.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(a.aborted)throw a.reason;if(typeof d.routeToken!="string")throw new Error("入口未允许此设备连接该服务。");const u=new URL(xn(i.url));return u.pathname="/api/federation/relay",u.searchParams.set("routeToken",d.routeToken),await Sn({url:u.href,targetPeerId:t.targetPeerId,identity:n,socketFactory:Yp(t.targetPeerId),signal:AbortSignal.any([a,AbortSignal.timeout(8e3)])})}finally{c||l.close()}}});const o=Jp(t.targetPeerId);r.sort((i,a)=>+(a.key===o)-+(i.key===o));const s=await Qp(r,i=>i.close());return hc(t.targetPeerId,s.key),s.value}async function PE(t,e){const n=await kl(t,e);try{const o=(await n.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node;if(o?.serviceId!==t.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");return{...o,serviceId:t.targetPeerId}}finally{n.close()}}async function NE(t,e){const n=await kl(t,e),r=()=>n.close();e.addEventListener("abort",r,{once:!0});try{if(e.aborted||(await vr(n,{timeoutMs:3e3}),e.aborted))throw e.reason;return n}catch(o){throw n.close(),o}finally{e.removeEventListener("abort",r)}}async function ct(t,e={}){const n=Q,r=Ue,o=await nt(),s=Me(t.serviceOrigin||t.url),i=(await Ge()).find(w=>w.targetPeerId===t.targetPeerId),a={...t,routes:t.routes??i?.routes},c=en(a),l=Sr(a);let d,u,f=t.pairingCode,h="direct";const g=new Set,m=new Map,b=async(w,I)=>{if(n&&!n.closed&&n.targetPeerId===w.targetPeerId)return n;if(r&&!r.closed&&r.targetPeerId===w.targetPeerId)return r;const y=m.get(w.targetPeerId);if(y&&!y.closed)return y;const A=await nn(w,I);return g.add(A),m.set(w.targetPeerId,A),A};try{if(t.routeCode&&t.entryServiceId){const S=c.find(_=>_.targetPeerId===t.entryServiceId);if(!S)throw new Error("邀请缺少入口信息。");if((await(await b(S)).request({type:"route-pair",code:t.routeCode})).serviceId!==t.targetPeerId)throw new Error("邀请的目标服务不一致。");t.routeOnly&&await Lt({id:t.targetPeerId,url:s,label:t.serviceName||new URL(s).host,targetPeerId:t.targetPeerId,serviceOrigin:s,routes:c})}const w=[],I=async(S,v)=>{const E=()=>S.close();v.addEventListener("abort",E,{once:!0});try{if(v.aborted||(await vr(S),v.aborted))throw v.reason}catch(_){throw S.close(),_}finally{v.removeEventListener("abort",E)}};for(const S of l)w.push({key:`direct:${S}`,run:async v=>{const E=await Sn({url:xn(S),targetPeerId:t.targetPeerId,pairingCode:f,identity:o,signal:AbortSignal.any([v,AbortSignal.timeout(8e3)])});return f=void 0,await I(E,v),{client:E,path:"direct"}}});for(const S of c)w.push({key:`relay:${S.targetPeerId}:${S.url}`,run:async v=>{let E,_;try{if(E=await b(S,v),v.aborted)throw v.reason;const L=await E.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(v.aborted)throw v.reason;if(typeof L.routeToken!="string"||!L.routeToken)throw new Error("入口未允许此设备连接该服务。");const C=new URL(xn(S.url));return C.pathname="/api/federation/relay",C.searchParams.set("routeToken",L.routeToken),_=await Sn({url:C.href,targetPeerId:t.targetPeerId,pairingCode:f,identity:o,socketFactory:Yp(t.targetPeerId),signal:AbortSignal.any([v,AbortSignal.timeout(8e3)])}),f=void 0,await I(_,v),{client:_,entry:E,path:"relay"}}catch(L){throw _?.close(),E&&E!==r&&E!==n&&E.close(),L}}});const y=Jp(t.targetPeerId);w.sort((S,v)=>+(v.key===y)-+(S.key===y));const A=await Qp(w,S=>{S.client.close(),S.entry&&S.entry!==n&&S.entry!==r&&S.entry.close()},!!f);if(d=A.value.client,u=A.value.entry,h=A.value.path,e.renewIfCurrent){if(Q!==e.renewIfCurrent||n!==e.renewIfCurrent||n.closed||!n.canSwitchTransport||se()?.targetPeerId!==t.targetPeerId){d.close();for(const S of g)S!==Ue&&S!==Q&&S.close();return Q??n}Q=d,pr=h,Ue=u,hc(t.targetPeerId,A.key),n.retire();for(const S of new Set([r,...g]))S&&S!==n&&S!==d&&S!==u&&S.close();return window.dispatchEvent(new Event(et)),d}if(hc(t.targetPeerId,A.key),Q!==n&&Q&&!Q.closed&&Q.targetPeerId===t.targetPeerId){d.close();for(const S of g)S!==Ue&&S.close();return Q}h==="direct"&&new URL(s).host===location.host&&Jm(t.targetPeerId);const N=(await Ge()).find(S=>S.targetPeerId===t.targetPeerId||!S.targetPeerId&&(S.serviceOrigin||S.url)===s),k=N?.label||t.serviceName||new URL(s).host,T={url:s,targetPeerId:t.targetPeerId,serviceName:k,serviceOrigin:s,routes:a.routes??c};if(await(e.rememberOnly?ew:Lt)({id:N?.id||t.targetPeerId,...T,label:k}),Vn!=="unpaired"&&Vn!==t.targetPeerId&&wt()&&Ks({id:N?.id||t.targetPeerId,...T,label:k})){d.close();for(const S of g)S!==n&&S!==r&&S.close();return n||d}Hf(T),Q=d,pr=h,Ue=u;for(const S of new Set([n,r,...g]))S&&S!==d&&S!==u&&S.close();return Vn!==t.targetPeerId?(location.reload(),new Promise(()=>{})):(window.dispatchEvent(new Event(et)),d)}catch(w){d?.close();for(const I of g)I!==r&&I.close();throw w}}async function LE(){const t=Q,e=se();if(!(ls||cs||qn||!t?.renewalDue||!t.canSwitchTransport||!e||performance.now()-xu<3e4)){xu=performance.now(),ls=!0;try{await ct(e,{renewIfCurrent:t})}catch(n){console.debug("[connection] renewal deferred",{reason:n instanceof Error?n.message:"unknown"})}finally{ls=!1}}}async function BE(){const t=Q,e=se();if(Date.now()-Su<6e4||ls||cs||pr!=="relay"||!t||t.closed||!t.canSwitchTransport||!e?.serviceOrigin)return;cs=!0,Su=Date.now();let n;try{for(const o of Sr(e))try{n=await Sn({url:xn(o),targetPeerId:e.targetPeerId,identity:await nt(),signal:AbortSignal.timeout(3e3)}),await vr(n);break}catch(s){if(n?.close(),n=void 0,s instanceof tt)throw s}if(!n||Q!==t||!t.canSwitchTransport)return;const r=Ue;Q=n,n=void 0,Ue=void 0,pr="direct",t.close(),r?.close(),window.dispatchEvent(new Event(et))}catch(r){r instanceof tt&&Q===t&&(og(),window.dispatchEvent(new Event("auth:unauthorized")))}finally{n?.close(),cs=!1}}function _E(){return pr}async function OE(t){return t?(t.throwIfAborted(),new Promise((e,n)=>{const r=()=>n(t.reason);t.addEventListener("abort",r,{once:!0}),it().then(o=>{t.removeEventListener("abort",r),t.aborted?n(t.reason):e(o)},o=>{t.removeEventListener("abort",r),n(o)})})):it()}async function it(){if(Q&&!Q.closed){const e=Q;return LE(),e}if(Q=void 0,qn)return qn;const t=se();if(!t)throw new Error("DEVICE_PAIRING_REQUIRED");return qn=ct(t,{rememberOnly:!0}).catch(e=>{if(Q&&!Q.closed&&Q.targetPeerId===t.targetPeerId)return Q;throw e}).finally(()=>{qn=void 0}),qn}function ig(t){const e=new URL(t,location.href);if(Q&&!Q.closed)return Q.openSocket(e.pathname+e.search);let n;const r=new Xp(t,o=>n?.send(o),()=>n?.close());return it().then(o=>{r.readyState!==3&&(n=o.openSocket(e.pathname+e.search),r.getConnectionDiagnostics=()=>{const s=n?.getConnectionDiagnostics?.();return s?{...s,socketOpenMs:r.openedAfterMs}:void 0},n.onopen=()=>r.accept({type:"ws-ready",id:""}),n.onmessage=s=>r.accept({type:"ws-data",id:"",data:s.data}),n.onclose=s=>r.accept({type:"ws-close",id:"",code:s.code,reason:s.reason}),n.onerror=()=>r.fail(new Error("Encrypted connection unavailable")))}).catch(o=>r.fail(o)),r}function DE(){gE(it),window.fetch=async(t,e)=>{const n=new URL(t instanceof Request?t.url:String(t),location.href);if(!n.pathname.startsWith("/api/"))return gr(t,e);if(n.origin!==location.origin)throw new Error("Remote business API requires a paired encrypted service");if(n.pathname==="/api/meta")return gr(t,e);if(n.pathname==="/api/auth/status"){if(!se()){const s=await sg();return Response.json({enabled:s.enabled,authenticated:!1})}try{const s=await vr(await it());return Response.json({enabled:s.grants.length>0,authenticated:!0})}catch(s){if(s instanceof tt)return Response.json({enabled:!0,authenticated:!1});throw s}}if(n.pathname==="/api/auth/login"){const i=await new Request(t instanceof Request?t:n.href,e).json();return TE(typeof i.password=="string"?i.password:"")}if(n.pathname==="/api/csrf-token")return Response.json({csrfToken:"encrypted-device-channel"});if(n.pathname==="/api/auth/logout")return Q&&!Q.closed&&await Q.request({type:"logout"}),Q?.close(),Ue?.close(),Q=void 0,Ue=void 0,Zm(),location.reload(),Response.json({ok:!0});const r=e?.signal!==void 0?e.signal:t instanceof Request?t.signal:void 0,o=await OE(r);return t instanceof Request?o.fetch(t,e):o.fetch(n.pathname+n.search,e)}}async function FE(t){if(!t.targetPeerId)throw new Error("请先连接这台服务,再查看可中转的服务。");for(const e of Sr({...t,targetPeerId:t.targetPeerId})){let n;const r={url:e,targetPeerId:t.targetPeerId};try{n=await nn(r)}catch{continue}try{const o=await n.request({type:"route-targets"},{timeoutMs:5e3});if(!Array.isArray(o.items))throw new Error("入口服务需要更新后才能查看中转列表。");return{route:r,canManage:o.canManage===!0,items:o.items}}catch(o){throw o instanceof Error&&/UNKNOWN|UNSUPPORTED/i.test(o.message)?new Error("入口服务需要更新后才能查看中转列表。"):o}finally{n.close()}}throw new Error("暂时连不上中转入口,请检查地址和网络后重试。")}async function ME(t,e){const n=await nn(t);try{const r=await n.request({type:"route-targets"},{timeoutMs:5e3}),o=(Array.isArray(r.items)?r.items:[]).find(c=>c.serviceId===e);if(!o)throw new Error("该服务已不可见,请刷新列表或请入口管理员授权。");if(!o.available)throw new Error("入口暂时无法中转到这台服务,请稍后重试。");const s=(await Ge()).find(c=>c.targetPeerId===o.serviceId),i=[t,...(s?.routes||[]).filter(c=>c.targetPeerId!==t.targetPeerId)];if(i.length>4)throw new Error("这台服务已保存 4 个备用连接,请先移除一个后重试。");if(!o.authorized){if(!r.canManage)throw new Error("请先让入口管理员授权此设备。");await n.request({type:"route-grant",serviceId:o.serviceId,subjectId:(await nt()).peerId})}const a=s?.serviceOrigin||s?.url||o.url||t.url;return{url:a,serviceOrigin:a,targetPeerId:o.serviceId,serviceName:s?.label||o.label||(o.url?new URL(o.url).host:`中转服务 ${o.serviceId.slice(0,8)}`),routes:i}}finally{n.close()}}async function jE(t,e){const n=await nn(t);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),o=(await nt()).peerId;return{canManage:r.canManage===!0,grants:(Array.isArray(r.grants)?r.grants:[]).filter(s=>s.subjectId===o&&s.targetServiceId===e)}}finally{n.close()}}async function HE(t,e,n){if(n!==void 0&&(await Al(Me(e.url),n)).targetPeerId!==e.targetPeerId)throw new Error("入口服务的身份已改变,请重新连接并确认。");const r=await nn(e);try{await r.request({type:"route-grant",serviceId:t.targetPeerId,subjectId:(await nt()).peerId,url:Me(t.serviceOrigin||t.url)})}finally{r.close()}}async function UE(t,e){const n=await nn(e);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),o=(await nt()).peerId,s=(Array.isArray(r.grants)?r.grants:[]).filter(i=>i.subjectId===o&&i.targetServiceId===t&&i.active);for(const i of s)await n.request({type:"route-revoke",grantId:i.id})}finally{n.close()}}async function ag(t,e){const n=await nn(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 ds(t,e){const n=(await Ge()).find(o=>o.id===t.id||t.targetPeerId&&o.targetPeerId===t.targetPeerId)||t;await Lt({...n,url:n.serviceOrigin||n.url,entryServiceId:void 0,routes:e});const r=se();r&&r.targetPeerId===t.targetPeerId&&Hf({...r,url:r.serviceOrigin||r.url,entryServiceId:void 0,routes:e})}async function $E(t,e){const n=t.targetPeerId;if(!n)throw new Error("请先连接这台服务,再添加备用地址。");let r;try{r=Me(e)}catch{throw new Error("请输入有效的 HTTPS 地址,例如 https://电脑地址:9834。")}const o=async()=>(await Ge()).find(a=>a.targetPeerId===n)||t,s=a=>{const c=a.routes??en({...a,targetPeerId:n});if(Me(a.serviceOrigin||a.url)===r||c.some(l=>Me(l.url)===r))throw new Error("这个地址已经在连接列表中。");if(c.length>=4)throw new Error("最多保存 4 个备用地址或入口,请先移除不再使用的连接。");return[...c,{url:r,targetPeerId:n}]};s(await o());let i;try{try{i=await Sn({url:xn(r),targetPeerId:n,identity:await nt(),signal:AbortSignal.timeout(5e3)}),await vr(i)}catch(l){throw l instanceof tt?new Error("这台服务尚未授权当前设备,请先恢复设备授权。"):new Error("无法验证这个地址。请确认能访问该地址、HTTPS 证书受信任,且运行的是同一台 Termdock 服务。")}const a=await o(),c=s(a);if(await ds(a,c),se()?.targetPeerId===n&&Vn===n&&(!Q||Q.closed)){const l=Q,d=Ue;Q=i,i=void 0,Ue=void 0,pr="direct",l?.close(),d?.close(),window.dispatchEvent(new Event(et))}return c}finally{i?.close()}}async function Au(t,e){await mc(t,e),await ct({...t,pairingCode:void 0,routeCode:void 0})}function qE(){let t=!1,e=!1,n=!1,r;const o=new Map,s=new Set,i=new Map,a=async(f,h,g)=>{const m=JSON.stringify(g);if(o.get(h.serviceId)===m)return;const b=AbortSignal.timeout(1e4),w=await f.fetch("/api/csrf-token",{signal:b});if(!w.ok)throw new Error("CONNECTION_AUTHORIZATION_REQUIRED");const I=await w.json();if(typeof I.csrfToken!="string")throw new Error("INVALID_CSRF_TOKEN");const y=await f.fetch("/api/terminal/operations/collaboration-connections",{method:"POST",signal:b,headers:{"Content-Type":"application/json","X-XSRF-TOKEN":I.csrfToken},body:JSON.stringify({origin:h.origin,nodes:g})});if(!y.ok){const A=await y.json().catch(()=>({}));throw new Error(A.error||`HTTP_${y.status}`)}o.set(h.serviceId,m)},c=async()=>{if(t){n=!0;return}const f=se(),h=Vt();if(!(e||!f||!h||h.closed)){t=!0,n=!1;try{let g;const m=await Promise.race([Ge(),new Promise((N,k)=>{g=setTimeout(()=>k(new Error("SERVICE_DIRECTORY_TIMEOUT")),8e3)})]).finally(()=>clearTimeout(g));m.some(N=>N.targetPeerId===f.targetPeerId)||m.push({...f,id:f.targetPeerId,label:f.serviceName||f.url});const b=[...new Map(m.filter(N=>!!N.targetPeerId).map(N=>[N.targetPeerId,N])).values()].slice(0,64);if(b.length<2)return;const w=[];for(const N of b)try{const k=`${N.targetPeerId}:${N.serviceOrigin||N.url}`;let T=i.get(k);if(!T){const S=N.targetPeerId===f.targetPeerId?(await h.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node:await PE({...N,targetPeerId:N.targetPeerId},AbortSignal.timeout(8e3));if(S?.serviceId!==N.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");const v=S.origin||N.serviceOrigin||N.url,E=new URL(v);if(E.protocol!=="https:"||E.origin!==v)throw new Error("INVALID_SERVICE_ORIGIN");T={serviceId:S.serviceId,origin:v,...S.caFingerprint256?{caFingerprint256:S.caFingerprint256}:{}},i.set(k,T)}w.push({service:N,node:T})}catch{}if(e||Vt()!==h||se()?.targetPeerId!==f.targetPeerId)return;const I=w.find(N=>N.node.serviceId===f.targetPeerId);if(!I||w.length<2){l(3e4);return}const y=w.map(N=>N.node).sort((N,k)=>N.serviceId.localeCompare(k.serviceId));await a(h,I.node,y);let A=w.length<b.length;for(const N of w){if(N===I||o.get(N.node.serviceId)===JSON.stringify(y))continue;let k;try{k=await NE({...N.service,targetPeerId:N.node.serviceId},AbortSignal.timeout(8e3)),await a(k,N.node,y)}catch{let T=s.has(N.node.serviceId);if(!T&&k)try{(await k.request({type:"collaboration-scoped-peer",origin:N.node.origin,node:I.node},{timeoutMs:8e3})).type==="result"&&(s.add(N.node.serviceId),T=!0)}catch{}T||(A=!0)}finally{k?.close()}}window.dispatchEvent(new CustomEvent("termdock:collaboration-enrollment",{detail:{ok:!0}})),A&&l(3e4)}catch(g){window.dispatchEvent(new CustomEvent("termdock:collaboration-enrollment",{detail:{ok:!1,error:g instanceof Error?g.message:"CONNECTION_ENROLLMENT_FAILED"}})),l(3e4)}finally{t=!1,n&&l(100)}}};function l(f=100){e||(clearTimeout(r),r=setTimeout(()=>{c()},f))}const d=()=>{l()},u=ni(d);window.addEventListener(et,d),window.addEventListener("termdock:collaboration-enroll",d),window.addEventListener("online",d),window.addEventListener("pageshow",d),window.addEventListener("pagehide",f=>{f.persisted||(e=!0,clearTimeout(r),u(),window.removeEventListener("termdock:collaboration-enroll",d),window.removeEventListener(et,d),window.removeEventListener("online",d),window.removeEventListener("pageshow",d))}),l()}var Yo={},ku;function KE(){if(ku)return Yo;ku=1;var t=$m();return Yo.createRoot=t.createRoot,Yo.hydrateRoot=t.hydrateRoot,Yo}var zE=KE();const GE=jf(zE);function $e({size:t=16,className:e="",...n}){const r=!!(n["aria-label"]||n["aria-labelledby"]);return p.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none","aria-hidden":r?void 0:!0,role:r?"img":void 0,focusable:"false",...n,className:`td-loading-spinner animate-spin ${e.replace(/\b(?:animate-spin|service-spinning)\b/g,"")}`,children:p.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2.5",strokeDasharray:"18 44.8",strokeLinecap:"round"})})}function WE(){return p.jsx("span",{className:"td-loading-dots","aria-hidden":"true",children:[0,1,2].map(t=>p.jsx("span",{style:{animationDelay:`${(t-3)*400}ms`}},t))})}function MR({label:t,className:e="",dots:n=!1}){return p.jsxs("div",{role:"status","aria-live":"polite","aria-atomic":"true",className:`flex items-center justify-center gap-2 text-sm text-muted-foreground ${e}`,children:[n?p.jsx(WE,{}):p.jsx($e,{size:18}),p.jsx("span",{children:t})]})}const cg=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim();const VE=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const XE=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,r)=>r?r.toUpperCase():n.toLowerCase());const Cu=t=>{const e=XE(t);return e.charAt(0).toUpperCase()+e.slice(1)};var ea={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 YE=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1},ZE=O.createContext({}),JE=()=>O.useContext(ZE),QE=O.forwardRef(({color:t,size:e,strokeWidth:n,absoluteStrokeWidth:r,className:o="",children:s,iconNode:i,...a},c)=>{const{size:l=24,strokeWidth:d=2,absoluteStrokeWidth:u=!1,color:f="currentColor",className:h=""}=JE()??{},g=r??u?Number(n??d)*24/Number(e??l):n??d;return O.createElement("svg",{ref:c,...ea,width:e??l??ea.width,height:e??l??ea.height,stroke:t??f,strokeWidth:g,className:cg("lucide",h,o),...!s&&!YE(a)&&{"aria-hidden":"true"},...a},[...i.map(([m,b])=>O.createElement(m,b)),...Array.isArray(s)?s:[s]])});const Le=(t,e)=>{const n=O.forwardRef(({className:r,...o},s)=>O.createElement(QE,{ref:s,iconNode:e,className:cg(`lucide-${VE(Cu(t))}`,`lucide-${t}`,r),...o}));return n.displayName=Cu(t),n};const e1=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],lg=Le("arrow-left",e1);const t1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],n1=Le("arrow-right",t1);const r1=[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]],o1=Le("arrow-up-right",r1);const s1=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M11.68 2.009A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673c-.824-.85-1.678-1.731-2.21-3.348",key:"xaq59h"}],["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}]],dg=Le("bell-dot",s1);const i1=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],zs=Le("check",i1);const a1=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],ug=Le("chevron-down",a1);const c1=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],En=Le("chevron-right",c1);const l1=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],d1=Le("chevron-up",l1);const u1=[["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"}]],fg=Le("copy",u1);const f1=[["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"}]],hg=Le("ellipsis",f1);const h1=[["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"}]],p1=Le("monitor",h1);const g1=[["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"}]],m1=Le("pencil",g1);const w1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],pg=Le("plus",w1);const y1=[["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"}]],wi=Le("server",y1);const b1=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],gg=Le("smartphone",b1);const v1=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],S1=Le("terminal",v1);const x1=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],mg=Le("x",x1),E1={},Iu=t=>{let e;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(e):d;if(!Object.is(f,e)){const h=e;e=u??(typeof f!="object"||f===null)?f:Object.assign({},e,f),n.forEach(g=>g(e,h))}},o=()=>e,c={setState:r,getState:o,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(E1?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},l=e=t(r,o,c);return c},A1=t=>t?Iu(t):Iu;var ta={exports:{}},na={},ra={exports:{}},oa={};var Ru;function k1(){if(Ru)return oa;Ru=1;var t=zc();function e(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var n=typeof Object.is=="function"?Object.is:e,r=t.useState,o=t.useEffect,s=t.useLayoutEffect,i=t.useDebugValue;function a(u,f){var h=f(),g=r({inst:{value:h,getSnapshot:f}}),m=g[0].inst,b=g[1];return s(function(){m.value=h,m.getSnapshot=f,c(m)&&b({inst:m})},[u,h,f]),o(function(){return c(m)&&b({inst:m}),u(function(){c(m)&&b({inst:m})})},[u]),i(h),h}function c(u){var f=u.getSnapshot;u=u.value;try{var h=f();return!n(u,h)}catch{return!0}}function l(u,f){return f()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?l:a;return oa.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:d,oa}var Tu;function C1(){return Tu||(Tu=1,ra.exports=k1()),ra.exports}var Pu;function I1(){if(Pu)return na;Pu=1;var t=zc(),e=C1();function n(l,d){return l===d&&(l!==0||1/l===1/d)||l!==l&&d!==d}var r=typeof Object.is=="function"?Object.is:n,o=e.useSyncExternalStore,s=t.useRef,i=t.useEffect,a=t.useMemo,c=t.useDebugValue;return na.useSyncExternalStoreWithSelector=function(l,d,u,f,h){var g=s(null);if(g.current===null){var m={hasValue:!1,value:null};g.current=m}else m=g.current;g=a(function(){function w(k){if(!I){if(I=!0,y=k,k=f(k),h!==void 0&&m.hasValue){var T=m.value;if(h(T,k))return A=T}return A=k}if(T=A,r(y,k))return T;var S=f(k);return h!==void 0&&h(T,S)?(y=k,T):(y=k,A=S)}var I=!1,y,A,N=u===void 0?null:u;return[function(){return w(d())},N===null?void 0:function(){return w(N())}]},[d,u,f,h]);var b=o(l,g[0],g[1]);return i(function(){m.hasValue=!0,m.value=b},[b]),c(b),b},na}var Nu;function R1(){return Nu||(Nu=1,ta.exports=I1()),ta.exports}var T1=R1();const P1=jf(T1),wg={},{useDebugValue:N1}=Ye,{useSyncExternalStoreWithSelector:L1}=P1;let Lu=!1;const B1=t=>t;function _1(t,e=B1,n){(wg?"production":void 0)!=="production"&&n&&!Lu&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),Lu=!0);const r=L1(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,n);return N1(r),r}const Bu=t=>{(wg?"production":void 0)!=="production"&&typeof t!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof t=="function"?A1(t):t,n=(r,o)=>_1(e,r,o);return Object.assign(n,e),n},yi=t=>t?Bu(t):Bu,Cl=t=>`@collaboration:${t}`,yg=yi(t=>({activePaneId:null,setActivePane:e=>t({activePaneId:e}),docks:{},hosts:{},setDock:(e,n)=>t(r=>{const o={...r.docks};return n?o[e]=n:delete o[e],{docks:o,...!n&&r.activePaneId===Cl(e)?{activePaneId:r.docks[e]?.sessionId??null}:{}}}),setHost:(e,n)=>t(r=>{const o={...r.hosts};return n?o[e]=n:delete o[e],{hosts:o}})})),fn=new Map;let io;function bg(){const t=yg.getState().activePaneId;for(const[n,r]of fn)if(r.requiresFocus&&t===Cl(n))return r.receive;const e=fn.get(io??"");return e&&!e.requiresFocus?e.receive:void 0}function jR(t){const e=fn.get(t);e&&(e.requiresFocus?yg.getState().setActivePane(Cl(t)):io=t)}function O1(t){const e=bg();return!e||!t?!1:(e(t),!0)}function HR(t,e="default",n=!1){fn.set(e,{receive:t,requiresFocus:n}),n||(io=e);const r=o=>{const{text:s,nonce:i}=o.detail??{};!s||bg()!==t||(t(s),o.stopImmediatePropagation(),i&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:i,ok:!0}})))};return window.addEventListener("termdock-insert-reference",r,!0),()=>{fn.get(e)?.receive===t&&(fn.delete(e),io===e&&(io=[...fn.keys()].at(-1))),window.removeEventListener("termdock-insert-reference",r,!0)}}const D1=/^[A-Za-z0-9_@%+=:,./-]$/;function F1(t){return Array.from(t,e=>(e.codePointAt(0)??0)>127||D1.test(e)?e:`\\${e}`).join("")}function M1(t,e){if(!e)return!1;try{const n=new URL(e.serviceOrigin||e.url);return n.origin===t&&/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})$/.test(n.hostname)&&!(e.routes??[]).some(r=>r.targetPeerId!==e.targetPeerId)}catch{return!1}}function j1(t){const e=s=>s.target instanceof Element?s.target.closest("[data-termdock-terminal-dropzone]"):null,n=()=>!M1(location.origin,fo()),r=s=>{const i=e(s);!i||!n()||!s.dataTransfer?.types.includes("Files")||(s.preventDefault(),s.stopImmediatePropagation(),s.dataTransfer.dropEffect="copy",i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="remote")},o=s=>{const i=e(s),a=Array.from(s.dataTransfer?.files??[]);if(!i||!a.length||!n())return;s.preventDefault(),s.stopImmediatePropagation();const c=i.dataset.termdockTerminalDropzone??"";i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="uploading",tn(async()=>{const{uploadFiles:l}=await Promise.resolve().then(()=>aI);return{uploadFiles:l}},void 0).then(({uploadFiles:l})=>l("/tmp",a)).then(l=>{if(l.files.length!==a.length||l.files.some(d=>!d.path))throw new Error("Upload did not return every file path");delete i.dataset.nativeFileDrag,delete i.dataset.nativeFileDropState,t({sessionKey:c,paths:l.files.map(d=>d.path)})}).catch(l=>{i.dataset.nativeFileDropState="error",i.dispatchEvent(new CustomEvent("termdock:file-drop-error",{bubbles:!0,detail:l instanceof Error?l.message:"File upload failed"})),window.setTimeout(()=>{i.dataset.nativeFileDropState==="error"&&(delete i.dataset.nativeFileDrag,delete i.dataset.nativeFileDropState)},3e3)})};return window.addEventListener("dragover",r,!0),window.addEventListener("drop",o,!0),()=>{window.removeEventListener("dragover",r,!0),window.removeEventListener("drop",o,!0)}}function rt(){return typeof window>"u"?null:window.termdockDesktop??null}const sa=new Set;let _u=!1;function UR(t){const e=rt();if(!e)return()=>{};if(sa.add(t),!_u){const n=r=>{if(!O1(r.paths.map(F1).join(" ")+" "))for(const o of sa)o(r)};j1(n),e.onNativeFileDrop(n),_u=!0}return()=>{sa.delete(t)}}function vg(t=navigator.userAgent,e=navigator.maxTouchPoints){const n=/iPad/.test(t)||/Macintosh/.test(t)&&e>1?"iPad":/iPhone/.test(t)?"iPhone":/Android/.test(t)?"Android":/Windows/.test(t)?"Windows":/Macintosh|Mac OS X/.test(t)?"Mac":/Linux/.test(t)?"Linux":"设备",r=/Electron/.test(t)?"Termdock":/Edg\//.test(t)?"Edge":/Firefox|FxiOS/.test(t)?"Firefox":/Chrome|CriOS/.test(t)?"Chrome":/Safari/.test(t)?"Safari":"浏览器";return`${n} · ${r}`}let H1;function U1(){return H1??=(async()=>{const t=navigator.userAgent,[e,n]=vg().split(" · "),r=/(?:Edg|Firefox|FxiOS|Chrome|CriOS|Version)\/([\d.]+)/g,o=[...t.matchAll(r)],s=/(?:CPU (?:iPhone )?OS |Mac OS X |Android )([\d._]+)/.exec(t)?.[1]?.replaceAll("_","."),i={system:`${e}${s?` ${s}`:""}`,client:`${n}${o.length?` ${o.at(-1)[1]}`:""}`,mode:matchMedia("(display-mode: standalone)").matches||navigator.standalone?"已安装的网页应用":"网页"},a=rt();if(a){i.mode="桌面客户端";const l=/Electron\/([\d.]+)/.exec(t)?.[1];i.client=l?`Termdock(Electron ${l})`:"Termdock";try{Object.assign(i,await a.deviceInfo?.())}catch{}return i}const c=navigator.userAgentData;try{const l=await c?.getHighEntropyValues(["model","architecture","bitness","platformVersion"]);typeof l?.model=="string"&&l.model&&(i.model=l.model),typeof l?.architecture=="string"&&l.architecture&&(i.arch=`${l.architecture}${l.bitness?` ${l.bitness} 位`:""}`)}catch{}return i})()}function $1({service:t,onBusyChange:e,onConnect:n,onConnectWithPassword:r}){const[o,s]=O.useState(),[i,a]=O.useState(!0),[c,l]=O.useState(!1),[d,u]=O.useState(""),[f,h]=O.useState(0),[g,m]=O.useState(),[b,w]=O.useState("");O.useEffect(()=>{let A=!1,N=!1,k;a(!0),u(""),s(void 0);const T=async S=>{try{const v=await FE(t);if(A)return;N=!0,s(v),u("")}catch(v){!A&&(!N||S)&&u(v instanceof Error?v.message:"暂时无法读取中转列表,请重试。")}finally{A||(a(!1),k=setTimeout(()=>{T(!1)},2e3))}};return T(!0),()=>{A=!0,clearTimeout(k)}},[t.id,t.url,f]);const I=async A=>{if(!c){l(!0),e(!0),u("");try{await A()}catch(N){u(N instanceof Error?N.message:"暂时无法连接,请重试。")}finally{l(!1),e(!1)}}},y=async A=>{const N=await ME(o.route,A.serviceId);try{await n(N)}catch(k){if(!(k instanceof tt))throw k;m(N)}};return p.jsxs("div",{className:"service-form",children:[g?p.jsxs("form",{className:"service-form",onSubmit:A=>{A.preventDefault(),I(async()=>{try{await r?.(g,b)}finally{w("")}})},children:[p.jsxs("p",{className:"service-help",children:["已通过“",t.label,"”连接到“",g.serviceName,"”。请登录目标服务,完成此设备的访问授权。"]}),r?p.jsxs(p.Fragment,{children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"目标服务密码"}),p.jsx("input",{type:"password",autoFocus:!0,required:!0,autoComplete:"current-password",value:b,disabled:c,onChange:A=>w(A.target.value)})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:c||!b,children:c?"正在登录…":"登录并连接"})]}):p.jsx("p",{className:"service-help",children:"请让目标服务管理员邀请此设备后再连接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>{m(void 0),w(""),u(""),h(A=>A+1)},children:"返回中转列表"})]}):p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["通过“",t.label,"”连接下方服务。",o?.canManage?"选择未授权的服务会授权此设备使用该中转。":"这里只显示已授权给此设备的中转。","目标服务会单独验证访问权限。"]}),i?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx($e,{size:16,className:"service-spinning"}),"正在读取可中转的服务…"]}):o&&p.jsxs("div",{className:"service-list",children:[o.items.map(A=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:c||!A.available,onClick:()=>{I(()=>y(A))},children:[p.jsx("span",{className:"service-icon",children:p.jsx(wi,{size:19})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:A.label||(A.url?new URL(A.url).host:`中转服务 ${A.serviceId.slice(0,8)}`)}),p.jsx("span",{className:"service-description",children:A.available?A.authorized?"已获中转授权 · 连接":"授权此设备并连接":"中转暂不可用"})]}),p.jsx(En,{size:16})]},A.serviceId)),o.items.length===0&&p.jsx("p",{className:"service-empty",children:o.canManage?"暂无可中转的服务。可在本机 Mac 客户端连接目标服务,或在目标服务的“备用连接”中启用本入口。":"暂无已授权的中转服务,请让入口管理员分享备用连接邀请。"})]}),c&&p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx($e,{size:16,className:"service-spinning"}),"正在授权并连接目标服务…"]}),!i&&p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>h(A=>A+1),children:"刷新列表"})]}),d&&p.jsx("p",{className:"service-error",role:"alert",children:d})]})}const wc="#termdock-invite=";function Sg(t){const e=new URL(t.entryUrl);e.hash="",e.search="",e.pathname="/";const n=new TextEncoder().encode(JSON.stringify(t));return e.hash=wc.slice(1)+btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.href}function Gs(t){const e=new URL(t);if(!["https:","http:"].includes(e.protocol)||!e.hash.startsWith(wc))throw new Error("这不是有效的 Termdock 邀请链接");const n=e.hash.slice(wc.length);if(n.length>8192)throw new Error("邀请链接过长");let r;try{const i=n.replace(/-/g,"+").replace(/_/g,"/");r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(atob(i),a=>a.charCodeAt(0))))}catch{throw new Error("邀请链接不完整,请重新复制")}if(r.v!==1||typeof r.serviceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(r.serviceId)||r.routeOnly!==!0&&(typeof r.code!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(r.code)))throw new Error("邀请信息无效或版本不兼容");const o=new URL(r.entryUrl);if(o.origin!==e.origin||o.username||o.password||!["https:","http:"].includes(o.protocol))throw new Error("邀请地址与服务不一致");if(o.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(o.hostname))throw new Error("远程邀请需要 HTTPS");if(r.entryServiceId!==void 0&&(typeof r.entryServiceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(r.entryServiceId)))throw new Error("邀请入口身份无效");if(r.routeCode!==void 0&&(typeof r.routeCode!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(r.routeCode)||!r.entryServiceId))throw new Error("邀请入口权限无效");if(r.routeOnly===!0&&(!r.entryServiceId||!r.routeCode||r.code!==void 0))throw new Error("备用连接邀请不完整");let s=o.origin;if(r.serviceUrl!==void 0){const i=new URL(r.serviceUrl);if(!["https:","http:"].includes(i.protocol)||i.username||i.password)throw new Error("目标服务地址无效");s=r.entryServiceId&&r.entryServiceId!==r.serviceId?i.origin:o.origin}return{url:o.origin,targetPeerId:r.serviceId,pairingCode:r.code,...r.routeOnly===!0?{routeOnly:!0}:{},serviceOrigin:s,serviceName:typeof r.name=="string"?r.name.slice(0,120):void 0,entryServiceId:r.entryServiceId,routeCode:r.routeCode}}function q1({service:t,onBusyChange:e}){const n={...t,targetPeerId:t.targetPeerId,serviceName:t.label},[r,o]=O.useState(()=>t.routes??en(n)),[s,i]=O.useState([]),[a,c]=O.useState(!0),[l,d]=O.useState(!1),[u,f]=O.useState(""),h=B=>{d(B),e(B)},[g,m]=O.useState(),[b,w]=O.useState(""),[I,y]=O.useState(""),[A,N]=O.useState(""),[k,T]=O.useState(!1),[S,v]=O.useState(),[E,_]=O.useState(),[L,C]=O.useState(!1);O.useEffect(()=>{let B=!1;return Ge().then(H=>{B||i(H.filter($=>$.targetPeerId&&$.targetPeerId!==t.targetPeerId))}).catch(()=>{B||f("暂时无法读取可用服务。")}).finally(()=>{B||c(!1)}),()=>{B=!0}},[t.targetPeerId]);const x=B=>s.find(H=>H.targetPeerId===B.targetPeerId)?.label||new URL(B.url).host,P=async B=>{h(!0),f(""),N("");try{await B()}catch(H){const $=H instanceof Error?H.message:"";f(/AUTHORIZATION|DENIED/.test($)?"当前设备没有入口管理权限。请让管理员分享备用连接邀请,或使用入口密码授权。":"暂时无法完成。请确认入口能连接目标服务,且目标地址、证书和授权有效。")}finally{h(!1)}},R=async(B,H)=>{const $={url:B.serviceOrigin||B.url,targetPeerId:B.targetPeerId};await P(async()=>{const X=await jE($,n.targetPeerId);if(!X.grants.some(U=>U.active)){if(!X.canManage&&H===void 0){m(B);return}await HE(n,$,H)}const Y=[...r.filter(U=>U.targetPeerId!==$.targetPeerId),$];await ds(t,Y),o(Y),m(void 0),w("")})};if(E)return p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["把链接发给需要使用此备用连接的人。它只允许通过入口连接“",t.label,"”,对方仍需获得目标服务的访问权限。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用连接邀请"}),p.jsx("input",{readOnly:!0,value:E,onFocus:B=>B.target.select()})]}),p.jsxs("button",{type:"button",className:"service-button service-primary",onClick:()=>{navigator.clipboard.writeText(E).then(()=>C(!0)).catch(()=>f("无法自动复制,请长按链接复制。"))},children:[p.jsx(fg,{size:16}),L?"已复制":"复制邀请链接"]}),p.jsx("button",{type:"button",className:"service-button service-secondary",onClick:()=>{_(void 0),C(!1)},children:"返回备用连接"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});if(g)return p.jsxs("form",{className:"service-form",onSubmit:B=>{B.preventDefault(),R(g,b).finally(()=>w(""))},children:[p.jsxs("p",{className:"service-help",children:["需要“",g.label,"”的管理员授权。若这是你的服务,可以使用它的密码;否则请管理员分享备用连接邀请。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"入口服务密码"}),p.jsx("input",{type:"password",required:!0,value:b,onChange:B=>w(B.target.value),autoComplete:"current-password",disabled:l,autoFocus:!0})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||!b,children:l?"正在授权…":"授权并启用"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{m(void 0),w("")},children:"取消"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});const D=r.filter(B=>B.targetPeerId===n.targetPeerId),M=r.filter(B=>B.targetPeerId!==n.targetPeerId),F=async()=>{if(!l){h(!0),T(!0),f(""),N("");try{o(await $E({...t,routes:r},I)),y(""),N("备用地址已验证并保存。")}catch(B){f(B instanceof Error?B.message:"暂时无法添加地址,请重试。")}finally{h(!1),T(!1)}}};return p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"电脑换了网络?添加它在新网络下的地址,原地址连不上时会自动尝试。只接受同一台服务。"}),p.jsxs("form",{className:"service-form",onSubmit:B=>{B.preventDefault(),F()},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用地址"}),p.jsx("input",{value:I,onChange:B=>{y(B.target.value),f(""),N("")},required:!0,disabled:l||r.length>=4,inputMode:"url",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:192.168.10.20:9834"})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||r.length>=4||!I.trim(),children:k?p.jsxs(p.Fragment,{children:[p.jsx($e,{size:16,className:"service-spinning"}),"正在验证…"]}):"验证并添加"})]}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u}),A&&p.jsx("p",{role:"status",className:"service-help",children:A}),r.length>=4&&p.jsx("p",{className:"service-help",children:"已保存 4 个备用连接。移除不再使用的地址或入口后,可以继续添加。"}),p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"首选地址"}),p.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url})]}),D.length>0&&p.jsx("div",{className:"service-list",children:D.map(B=>p.jsxs("div",{className:"service-route-item",children:[p.jsxs("div",{className:"service-route-line",children:[p.jsx("span",{className:"service-address service-route-address",children:B.url}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`移除地址 ${B.url}`,disabled:l,onClick:()=>v(B),children:"移除"})]}),S?.targetPeerId===B.targetPeerId&&S.url===B.url&&p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"从备用连接中移除此地址?不会停止正在运行的终端。"}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>v(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{P(async()=>{const H=r.filter($=>$.targetPeerId!==B.targetPeerId||$.url!==B.url);await ds(t,H),o(H),v(void 0)})},children:"确认移除"})]})]})]},B.url))}),p.jsxs("details",{className:"service-relay-options",children:[p.jsxs("summary",{children:["通过其他服务中转",M.length?`(${M.length})`:""]}),p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"所有直连地址都不可用时,尝试下方已授权入口;直连恢复后自动切回。"}),M.length>0&&p.jsx("div",{className:"service-list",children:M.map(B=>p.jsxs("div",{className:"service-route-item",children:[p.jsxs("div",{className:"service-route-line",children:[p.jsx("span",{className:"service-icon",children:p.jsx(wi,{size:18})}),p.jsx("span",{className:"service-name",children:x(B)}),p.jsx(zs,{size:16,className:"service-selected"})]}),S?.targetPeerId===B.targetPeerId?p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["撤销此设备经“",x(B),"”连接目标的权限?如当前无法直连,目标服务将断开。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>v(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{P(async()=>{await UE(n.targetPeerId,B);const H=r.filter($=>$.targetPeerId!==B.targetPeerId);await ds(t,H),o(H),v(void 0)})},children:"确认撤销"})]})]}):p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{P(async()=>{const H=await ag(n,B);_(Sg({v:1,routeOnly:!0,serviceId:n.targetPeerId,name:t.label,serviceUrl:t.serviceOrigin||t.url,entryUrl:B.url,entryServiceId:B.targetPeerId,routeCode:H.routeCode}))})},children:"分享备用连接"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>v(B),children:"撤销授权"})]})]},B.targetPeerId))}),a?p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx($e,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"添加中转入口"}),s.filter(B=>!r.some(H=>H.targetPeerId===B.targetPeerId)).map(B=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:l||r.length>=4,onClick:()=>{R(B)},children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:B.label}),p.jsx("span",{className:"service-description",children:"验证并授权后启用"})]}),p.jsx(En,{size:16})]},B.id)),s.length===0&&p.jsx("p",{className:"service-empty",children:"添加并登录另一台服务后,可以将它设为中转入口。"})]})]})]}),l&&!k&&p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx($e,{size:16,className:"service-spinning"}),"正在验证连接与授权…"]})]})}function K1({current:t,renderRoutes:e,renderRelayServices:n,onOpen:r,onAdd:o,onInvite:s,hideHeader:i,onNavigation:a,onBusyChange:c,initiallyAdding:l=!1}){const[d,u]=O.useState([]),[f,h]=O.useState(!0),[g,m]=O.useState(l?{kind:"add"}:{kind:"list"}),[b,w]=O.useState(!1),I=O.useCallback(C=>{w(C),c?.(C)},[c]),[y,A]=O.useState(""),N=O.useCallback(()=>{m(C=>C.kind==="routes"||C.kind==="relay-services"?{kind:"edit",service:C.service}:{kind:"list"}),A("")},[]),k=g.kind==="add"?"添加服务":g.kind==="edit"?"服务设置":g.kind==="routes"?"备用连接":g.kind==="relay-services"?"可中转的服务":void 0;O.useEffect(()=>{a?.({title:k,...k?{back:N}:{}})},[k,N,a]),O.useEffect(()=>{let C=!1,x=0;const P=async()=>{const D=++x;try{const M=await Ge();!C&&x===D&&(u(M),A(""))}catch{!C&&x===D&&A("暂时无法读取服务列表,请重试。")}finally{!C&&x===D&&h(!1)}};P();const R=ni(()=>{P()});return()=>{C=!0,R()}},[]);const T=async C=>{if(!b){I(!0),A("");try{await C()}catch(x){A(x instanceof Error?x.message:"暂时无法完成,请重试。")}finally{I(!1)}}},S=g.kind==="edit"||g.kind==="routes"||g.kind==="relay-services"?d.find(C=>Ct(C,g.service))||g.service:void 0,v=t?d.find(C=>Ct(C,t))||t:void 0,E=d.filter(C=>!t||!Ct(C,t)),_=v?[v,...E]:E,L=p.jsxs(p.Fragment,{children:[f?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx($e,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{className:"service-list",children:[_.map(C=>{const x=!!t&&Ct(C,t);return p.jsxs("div",{className:"service-row",children:[p.jsxs("button",{type:"button",className:"service-row-open",disabled:b||x,onClick:()=>{T(async()=>{(await r(C))?.passwordRequired&&m({kind:"add",input:C.serviceOrigin||C.url,passwordRequired:!0})})},"aria-label":x?`当前服务 ${C.label}`:`打开 ${C.label}`,children:[p.jsx("span",{className:"service-icon",children:p.jsx(wi,{size:20})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:C.label}),p.jsx("span",{className:"service-description",children:x?"当前服务":new URL(C.serviceOrigin||C.url).host})]}),x?p.jsx(zs,{size:17,className:"service-selected"}):p.jsx(En,{size:16,className:"service-muted"})]}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`管理 ${C.label}`,disabled:b,onClick:()=>{m({kind:"edit",service:C}),A("")},children:p.jsx(hg,{size:19})})]},C.id)}),_.length===0&&p.jsx("p",{className:"service-empty",children:"还没有添加服务。连接你的电脑,或粘贴收到的邀请链接。"})]}),p.jsxs("div",{className:`service-actions${s?" service-actions-pair":""}`,children:[p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:b,onClick:()=>{m({kind:"add"}),A("")},children:[p.jsx(pg,{size:16}),"添加服务"]}),s&&p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:b,onClick:s,children:[p.jsx(gg,{size:16}),"邀请设备"]})]})]});return p.jsxs("div",{className:"service-manager",children:[!i&&p.jsxs("div",{className:"service-heading",children:[k&&p.jsx("button",{type:"button",className:"service-icon-button","aria-label":"返回服务",disabled:b,onClick:N,children:p.jsx(lg,{size:20})}),p.jsx("h2",{children:k||"服务"})]}),g.kind==="relay-services"?n?.(S,I):g.kind==="routes"?e?.(S,I):g.kind==="list"?L:g.kind==="add"?p.jsx(z1,{onSave:C=>T(async()=>{const x=Me(C);u(await Lt({id:x,url:x,label:new URL(x).host})),N()}),initialInput:g.input,passwordRequired:g.passwordRequired,busy:b,onSubmit:async(C,x)=>{let P;return await T(async()=>{P=await o(C,x),P?.passwordRequired||N()}),P}}):p.jsx(G1,{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:S,busy:b,canRemove:!t||!Ct(g.service,t),onSave:C=>{T(async()=>{u(await Lt({...S,label:C})),N()})},onRemove:()=>{T(async()=>{u(await tw(g.service.id)),N()})}}),y&&p.jsx("p",{className:"service-error",role:"alert",children:y})]})}function z1({busy:t,onSubmit:e,onSave:n,initialInput:r="",passwordRequired:o=!1}){const[s,i]=O.useState(r),[a,c]=O.useState(""),[l,d]=O.useState(o);return p.jsxs("form",{className:"service-form",onSubmit:async u=>{u.preventDefault(),(await e(s.trim(),l?a:void 0))?.passwordRequired&&d(!0),c("")},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务地址或邀请链接"}),p.jsx("input",{value:s,onChange:u=>{i(u.target.value),d(!1),c("")},disabled:t,required:!0,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:电脑地址:9834 或 https://…"})]}),l?p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务密码"}),p.jsx("input",{type:"password",value:a,onChange:u=>c(u.target.value),disabled:t,required:!0,autoFocus:!0,autoComplete:"current-password",placeholder:"输入这台服务的密码"})]}):p.jsx("p",{className:"service-help",children:"连接自己的服务,输入地址即可;收到邀请时,粘贴完整链接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:t||!s.trim()||s.includes("#termdock-invite="),onClick:()=>{n(s.trim())},children:"仅保存,不连接"}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:t||!s.trim()||l&&!a,children:t?p.jsxs(p.Fragment,{children:[p.jsx($e,{size:16,className:"service-spinning"}),"正在连接…"]}):l?"登录并连接":"继续"})]})}function G1({service:t,busy:e,canRemove:n,onSave:r,onRemove:o,onRoutes:s,onRelayServices:i}){const[a,c]=O.useState(t.label),[l,d]=O.useState(!1);return p.jsxs("form",{className:"service-form",onSubmit:u=>{u.preventDefault(),r(a.trim())},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务名称"}),p.jsx("input",{value:a,onChange:u=>c(u.target.value),disabled:e,required:!0,maxLength:120,placeholder:"例如:办公室电脑"})]}),p.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:e||!a.trim(),children:"保存名称"}),i&&p.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:i,children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:"可中转的服务"}),p.jsx("span",{className:"service-description",children:"通过这台服务连接其他电脑"})]}),p.jsx(En,{size:16})]}),s&&p.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:s,children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:"备用连接"}),p.jsx("span",{className:"service-description",children:"添加其他网络地址或授权入口"})]}),p.jsx(En,{size:16})]}),n&&p.jsx("div",{className:"service-remove",children:l?p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["从列表移除“",t.label,"”?不会停止服务或删除终端。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:e,onClick:()=>d(!1),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:o,children:"确认移除"})]})]}):p.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:()=>d(!0),children:"移除服务"})})]})}var Mn={},ia,Ou;function W1(){return Ou||(Ou=1,ia=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),ia}var aa={},Kt={},Du;function In(){if(Du)return Kt;Du=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 Kt.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},Kt.getSymbolTotalCodewords=function(r){return e[r]},Kt.getBCHDigit=function(n){let r=0;for(;n!==0;)r++,n>>>=1;return r},Kt.setToSJISFunction=function(r){if(typeof r!="function")throw new Error('"toSJISFunc" is not a valid function.');t=r},Kt.isKanjiModeEnabled=function(){return typeof t<"u"},Kt.toSJIS=function(r){return t(r)},Kt}var ca={},Fu;function Il(){return Fu||(Fu=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+n)}}t.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},t.from=function(r,o){if(t.isValid(r))return r;try{return e(r)}catch{return o}}})(ca)),ca}var la,Mu;function V1(){if(Mu)return la;Mu=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++}},la=t,la}var da,ju;function X1(){if(ju)return da;ju=1;function t(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return t.prototype.set=function(e,n,r,o){const s=e*this.size+n;this.data[s]=r,o&&(this.reservedBit[s]=!0)},t.prototype.get=function(e,n){return this.data[e*this.size+n]},t.prototype.xor=function(e,n,r){this.data[e*this.size+n]^=r},t.prototype.isReserved=function(e,n){return this.reservedBit[e*this.size+n]},da=t,da}var ua={},Hu;function Y1(){return Hu||(Hu=1,(function(t){const e=In().getSymbolSize;t.getRowColCoords=function(r){if(r===1)return[];const o=Math.floor(r/7)+2,s=e(r),i=s===145?26:Math.ceil((s-13)/(2*o-2))*2,a=[s-7];for(let c=1;c<o-1;c++)a[c]=a[c-1]-i;return a.push(6),a.reverse()},t.getPositions=function(r){const o=[],s=t.getRowColCoords(r),i=s.length;for(let a=0;a<i;a++)for(let c=0;c<i;c++)a===0&&c===0||a===0&&c===i-1||a===i-1&&c===0||o.push([s[a],s[c]]);return o}})(ua)),ua}var fa={},Uu;function Z1(){if(Uu)return fa;Uu=1;const t=In().getSymbolSize,e=7;return fa.getPositions=function(r){const o=t(r);return[[0,0],[o-e,0],[0,o-e]]},fa}var ha={},$u;function J1(){return $u||($u=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},t.from=function(o){return t.isValid(o)?parseInt(o,10):void 0},t.getPenaltyN1=function(o){const s=o.size;let i=0,a=0,c=0,l=null,d=null;for(let u=0;u<s;u++){a=c=0,l=d=null;for(let f=0;f<s;f++){let h=o.get(u,f);h===l?a++:(a>=5&&(i+=e.N1+(a-5)),l=h,a=1),h=o.get(f,u),h===d?c++:(c>=5&&(i+=e.N1+(c-5)),d=h,c=1)}a>=5&&(i+=e.N1+(a-5)),c>=5&&(i+=e.N1+(c-5))}return i},t.getPenaltyN2=function(o){const s=o.size;let i=0;for(let a=0;a<s-1;a++)for(let c=0;c<s-1;c++){const l=o.get(a,c)+o.get(a,c+1)+o.get(a+1,c)+o.get(a+1,c+1);(l===4||l===0)&&i++}return i*e.N2},t.getPenaltyN3=function(o){const s=o.size;let i=0,a=0,c=0;for(let l=0;l<s;l++){a=c=0;for(let d=0;d<s;d++)a=a<<1&2047|o.get(l,d),d>=10&&(a===1488||a===93)&&i++,c=c<<1&2047|o.get(d,l),d>=10&&(c===1488||c===93)&&i++}return i*e.N3},t.getPenaltyN4=function(o){let s=0;const i=o.data.length;for(let c=0;c<i;c++)s+=o.data[c];return Math.abs(Math.ceil(s*100/i/5)-10)*e.N4};function n(r,o,s){switch(r){case t.Patterns.PATTERN000:return(o+s)%2===0;case t.Patterns.PATTERN001:return o%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(o+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return o*s%2+o*s%3===0;case t.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case t.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}t.applyMask=function(o,s){const i=s.size;for(let a=0;a<i;a++)for(let c=0;c<i;c++)s.isReserved(c,a)||s.xor(c,a,n(o,c,a))},t.getBestMask=function(o,s){const i=Object.keys(t.Patterns).length;let a=0,c=1/0;for(let l=0;l<i;l++){s(l),t.applyMask(l,o);const d=t.getPenaltyN1(o)+t.getPenaltyN2(o)+t.getPenaltyN3(o)+t.getPenaltyN4(o);t.applyMask(l,o),d<c&&(c=d,a=l)}return a}})(ha)),ha}var Zo={},qu;function xg(){if(qu)return Zo;qu=1;const t=Il(),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 Zo.getBlocksCount=function(o,s){switch(s){case t.L:return e[(o-1)*4+0];case t.M:return e[(o-1)*4+1];case t.Q:return e[(o-1)*4+2];case t.H:return e[(o-1)*4+3];default:return}},Zo.getTotalCodewordsCount=function(o,s){switch(s){case t.L:return n[(o-1)*4+0];case t.M:return n[(o-1)*4+1];case t.Q:return n[(o-1)*4+2];case t.H:return n[(o-1)*4+3];default:return}},Zo}var pa={},Dr={},Ku;function Q1(){if(Ku)return Dr;Ku=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let r=1;for(let o=0;o<255;o++)t[o]=r,e[r]=o,r<<=1,r&256&&(r^=285);for(let o=255;o<512;o++)t[o]=t[o-255]})(),Dr.log=function(r){if(r<1)throw new Error("log("+r+")");return e[r]},Dr.exp=function(r){return t[r]},Dr.mul=function(r,o){return r===0||o===0?0:t[e[r]+e[o]]},Dr}var zu;function eA(){return zu||(zu=1,(function(t){const e=Q1();t.mul=function(r,o){const s=new Uint8Array(r.length+o.length-1);for(let i=0;i<r.length;i++)for(let a=0;a<o.length;a++)s[i+a]^=e.mul(r[i],o[a]);return s},t.mod=function(r,o){let s=new Uint8Array(r);for(;s.length-o.length>=0;){const i=s[0];for(let c=0;c<o.length;c++)s[c]^=e.mul(o[c],i);let a=0;for(;a<s.length&&s[a]===0;)a++;s=s.slice(a)}return s},t.generateECPolynomial=function(r){let o=new Uint8Array([1]);for(let s=0;s<r;s++)o=t.mul(o,new Uint8Array([1,e.exp(s)]));return o}})(pa)),pa}var ga,Gu;function tA(){if(Gu)return ga;Gu=1;const t=eA();function e(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(r){this.degree=r,this.genPoly=t.generateECPolynomial(this.degree)},e.prototype.encode=function(r){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(r.length+this.degree);o.set(r);const s=t.mod(o,this.genPoly),i=this.degree-s.length;if(i>0){const a=new Uint8Array(this.degree);return a.set(s,i),a}return s},ga=e,ga}var ma={},wa={},ya={},Wu;function Eg(){return Wu||(Wu=1,ya.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),ya}var pt={},Vu;function Ag(){if(Vu)return pt;Vu=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-C-wELkSK.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/App-B6IcjDoE.js","assets/gestureArbiter-rtOG53-b.js","assets/gestureArbiter-C2J0D0kV.css","assets/triangle-alert-Qoe61fzS.js","assets/referenceLongPress-Dwy-aM4B.js","assets/DagPlayground-B0RDj7Hc.js","assets/ChangeWalkthroughPanel-DrFaKK1O.js","assets/sparkles-Dleyh-x5.js","assets/DiffLab-CPYmWsZm.js","assets/DiffViewer-Bf310S35.js","assets/DiffViewer-T3uj2-aP.css","assets/DiffReviewLab-COARnMyi.js","assets/DiffReview-DTcdS9M-.js"])))=>i.map(i=>d[i]);
2
+ import{r as zc,a as $m,g as jf}from"./react-XDCjal2T.js";import{b as O,R as Ye,r as Gc}from"./dnd-BCFAPC0L.js";import{L as qm,l as Km}from"./terminal-C7X98Amf.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const i of s.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(o){if(o.ep)return;o.ep=!0;const s=n(o);fetch(o.href,s)}})();const zm="modulepreload",Gm=function(t){return"/"+t},rd={},tn=function(e,n,r){let o=Promise.resolve();if(n&&n.length>0){let c=function(l){return Promise.all(l.map(d=>Promise.resolve(d).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),a=i?.nonce||i?.getAttribute("nonce");o=c(n.map(l=>{if(l=Gm(l),l in rd)return;rd[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":zm,d||(f.as="script"),f.crossOrigin="",f.href=l,a&&f.setAttribute("nonce",a),document.head.appendChild(f),d)return new Promise((h,g)=>{f.addEventListener("load",h),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${l}`)))})}))}function s(i){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=i,window.dispatchEvent(a),!a.defaultPrevented)throw i}return o.then(i=>{for(const a of i||[])a.status==="rejected"&&s(a.reason);return e().catch(s)})};var Bi={exports:{}},Ir={};var od;function Wm(){if(od)return Ir;od=1;var t=zc(),e=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function i(a,c,l){var d,u={},f=null,h=null;l!==void 0&&(f=""+l),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(h=c.ref);for(d in c)r.call(c,d)&&!s.hasOwnProperty(d)&&(u[d]=c[d]);if(a&&a.defaultProps)for(d in c=a.defaultProps,c)u[d]===void 0&&(u[d]=c[d]);return{$$typeof:e,type:a,key:f,ref:h,props:u,_owner:o.current}}return Ir.Fragment=n,Ir.jsx=i,Ir.jsxs=i,Ir}var sd;function Vm(){return sd||(sd=1,Bi.exports=Wm()),Bi.exports}var p=Vm();const wn="termdock-secure-target-v1",Wc="termdock-secure-entry-v1",Xm=new Set([wn,Wc,"termdock-color-theme","termdock:locale","termdock.federation.connections.v1"]),Bo=typeof Storage>"u"?void 0:Storage.prototype.getItem,_i=typeof Storage>"u"?void 0:Storage.prototype.setItem,id="termdock-secure-legacy-owner",Js=typeof window<"u"&&window.parent!==window&&location.pathname==="/workspace.html";function Ym(){if(typeof window>"u")return null;try{if(Js){const e=new URLSearchParams(location.search).get("termdock-workspace"),n=JSON.parse(localStorage.getItem("termdock.federation.connections.v1")||"[]"),r=Array.isArray(n)?n.find(o=>o?.targetPeerId===e):void 0;return r&&typeof r.url=="string"&&typeof r.targetPeerId=="string"?{...r,serviceName:r.label||r.serviceName}:null}const t=JSON.parse(sessionStorage.getItem(wn)??localStorage.getItem(wn)??"null");return t&&typeof t.url=="string"&&typeof t.targetPeerId=="string"?t:null}catch{return null}}let Qs=Ym();const Vn=Qs?.targetPeerId??"unpaired";function fo(){return Qs}function Hf(t){if(Qs=t,Js)return;const e=JSON.stringify(t);sessionStorage.setItem(wn,e),localStorage.setItem(wn,e)}function Zm(){Qs=null,!Js&&(localStorage.removeItem(wn),sessionStorage.removeItem(wn),localStorage.removeItem(Wc))}function to(t,e=Vn){return Xm.has(t)||t.startsWith("termdock-secure-")?t:`termdock-service:${e}:${t}`}function Jm(t){if(!(!Bo||!_i))try{if(Bo.call(localStorage,id))return;_i.call(localStorage,id,t);for(const n of[localStorage,sessionStorage]){const r=Array.from({length:n.length},(o,s)=>n.key(s)).filter(o=>!!o);for(const o of r){if(o.startsWith("termdock-service:")||to(o,t)===o)continue;const s=to(o,t),i=Bo.call(n,o);i!==null&&Bo.call(n,s)===null&&_i.call(n,s,i)}}}catch{}}let ad=!1;function Qm(){if(ad||typeof Storage>"u")return;ad=!0;const t=Storage.prototype.getItem,e=Storage.prototype.setItem,n=Storage.prototype.removeItem;Storage.prototype.getItem=function(r){return t.call(this,to(String(r)))},Storage.prototype.setItem=function(r,o){e.call(this,to(String(r)),o)},Storage.prototype.removeItem=function(r){n.call(this,to(String(r)))}}Qm();const ei="termdock.federation.connections.v1",Ua="termdock:services-changed",Vc="termdock-secure-removed-services",bs=t=>[t.id,t.targetPeerId,t.serviceOrigin||t.url].filter(e=>!!e);function Xc(){try{const t=JSON.parse(localStorage.getItem(Vc)||"[]");return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}catch{return[]}}function Me(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 ti(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.url=="string")try{const n=Me(e.url),r=typeof e.targetPeerId=="string"&&e.targetPeerId?e.targetPeerId:void 0,o=(typeof e.label=="string"?e.label:typeof e.serviceName=="string"?e.serviceName:"").trim().slice(0,120)||new URL(n).host;return{id:typeof e.id=="string"&&e.id?e.id:r||n,url:n,label:o,...r?{targetPeerId:r}:{},...typeof e.serviceOrigin=="string"?{serviceOrigin:Me(e.serviceOrigin)}:{},...typeof e.entryServiceId=="string"&&e.entryServiceId?{entryServiceId:e.entryServiceId}:{},...Array.isArray(e.routes)?{routes:e.routes.slice(0,4).flatMap(s=>{try{return s&&typeof s.targetPeerId=="string"&&s.targetPeerId?[{url:Me(s.url),targetPeerId:s.targetPeerId}]:[]}catch{return[]}})}:{}}}catch{return}}function Ct(t,e){return t.targetPeerId&&e.targetPeerId?t.targetPeerId===e.targetPeerId:(t.serviceOrigin||t.url)===(e.serviceOrigin||e.url)}function Uf(t){const e=[];for(const n of t){const r=e.findIndex(o=>Ct(o,n));r<0?e.push(n):e[r]={...e[r],...n,id:e[r].id}}return e}function xo(){return typeof window>"u"?void 0:window.termdockDesktop}function yn(){try{const t=JSON.parse(localStorage.getItem(ei)||"[]");return Array.isArray(t)?Uf(t.map(ti).filter(e=>!!e)):[]}catch{return[]}}function $f(t){localStorage.setItem(ei,JSON.stringify(t.map(e=>({...e,serviceName:e.label})))),window.dispatchEvent(new Event(Ua))}let Rr;async function Ge(){const t=xo();if(!t?.serviceConnections||!t.saveServiceConnection)return yn();if(Rr)return Rr;Rr=(async()=>{let e=await t.serviceConnections();const n=yn();for(const r of n)e.some(o=>Ct(o,r))||(e=await(t.importServiceConnection||t.saveServiceConnection)(r));return n.length&&localStorage.removeItem(ei),e})();try{return await Rr}finally{Rr=void 0}}async function Lt(t){const e=ti(t);if(!e)throw new Error("服务地址无效。");const n=xo();if(n?.saveServiceConnection)return n.saveServiceConnection(e);const r=yn(),o=r.find(a=>a.id===e.id||Ct(a,e)),s=new Set([...bs(e),...o?bs(o):[]]);localStorage.setItem(Vc,JSON.stringify(Xc().filter(a=>!s.has(a))));const i=Uf([...r.filter(a=>a!==o),{...o,...e,id:o?.id||e.id}]);return $f(i),i}async function ew(t){const e=ti(t);if(!e)throw new Error("服务地址无效。");const n=xo();if(n?.importServiceConnection)return n.importServiceConnection(e);if(n?.serviceConnections){const r=await n.serviceConnections();return r.some(o=>Ct(o,e))?Lt(e):r}return bs(e).some(r=>Xc().includes(r))?yn():Lt(e)}async function tw(t){const e=xo();if(e?.removeServiceConnection)return e.removeServiceConnection(t);const n=yn(),r=n.find(s=>s.id===t);r&&localStorage.setItem(Vc,JSON.stringify([...new Set([...Xc(),...bs(r)])].slice(-768)));const o=n.filter(s=>s.id!==t);return $f(o),o}function ni(t){const e=r=>{(r.key===ei||r.key===null)&&t()};window.addEventListener(Ua,t),window.addEventListener("storage",e);const n=xo()?.onServiceConnections?.(t);return()=>{window.removeEventListener(Ua,t),window.removeEventListener("storage",e),n?.()}}class nw extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}let rw=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},lt=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};class qf extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class Kf extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}}class ow extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class sw extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class ri extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}const zf=Symbol.for("@libp2p/peer-id");function iw(t){return typeof t?.handleEvent=="function"}function aw(t){return t===!0||t===!1}function cw(t){return aw(t)?t:t?.capture??!1}function $a(t){const e={capture:cw(t),once:!!t?.once};return t?.passive!=null&&(e.passive=t?.passive),t?.signal!=null&&(e.signal=t?.signal),e}function cd(t,e){return $a(t).capture===$a(e).capture}class lw extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const n=this.#e.get(e);return n==null?0:n.length}addEventListener(e,n,r){const o=$a(r);if(o?.signal?.aborted===!0)return;const s=l=>{o.once&&this.removeEventListener(e,n,o),iw(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:cd(l.options,o)))return;super.addEventListener(e,s,o);const c=()=>{this.removeEventListener(e,n,o)};o.signal?.addEventListener("abort",c),i.push({callback:n,wrapper:s,options:o,onAbort:c})}removeEventListener(e,n,r){const o=this.#e.get(e);if(o==null){super.removeEventListener(e,n??null,r);return}this.#e.set(e,o.filter(s=>s.callback===n&&cd(s.options,r)?(super.removeEventListener(e,s.wrapper,r),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,n={}){return this.dispatchEvent(new CustomEvent(e,n))}}const dw=Symbol.for("@libp2p/service-capabilities");function uw(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 oi(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 fw(t){return new TextEncoder().encode(t)}function hw(t){return new TextDecoder().decode(t)}function pw(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(n[i]!==255)throw new TypeError(s+" is ambiguous");n[i]=o}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),d=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var m=0,b=0,w=0,I=g.length;w!==I&&g[w]===0;)w++,m++;for(var y=(I-w)*d+1>>>0,A=new Uint8Array(y);w!==I;){for(var N=g[w],k=0,T=y-1;(N!==0||k<b)&&T!==-1;T--,k++)N+=256*A[T]>>>0,A[T]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");b=k,w++}for(var S=y-b;S!==y&&A[S]===0;)S++;for(var v=c.repeat(m);S<y;++S)v+=t.charAt(A[S]);return v}function f(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var m=0;if(g[m]!==" "){for(var b=0,w=0;g[m]===c;)b++,m++;for(var I=(g.length-m)*l+1>>>0,y=new Uint8Array(I);g[m];){var A=n[g.charCodeAt(m)];if(A===255)return;for(var N=0,k=I-1;(A!==0||N<w)&&k!==-1;k--,N++)A+=a*y[k]>>>0,y[k]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");w=N,m++}if(g[m]!==" "){for(var T=I-w;T!==I&&y[T]===0;)T++;for(var S=new Uint8Array(b+(I-T)),v=b;T!==I;)S[v++]=y[T++];return S}}}function h(g){var m=f(g);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:f,decode:h}}var gw=pw,mw=gw;class ww{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 yw{name;prefix;baseDecode;prefixCodePoint;constructor(e,n,r){this.name=e,this.prefix=n;const o=n.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Gf(this,e)}}class bw{decoders;constructor(e){this.decoders=e}or(e){return Gf(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 Gf(t,e){return new bw({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class vw{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,n,r,o){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=o,this.encoder=new ww(e,n,r),this.decoder=new yw(e,n,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function si({name:t,prefix:e,encode:n,decode:r}){return new vw(t,e,n,r)}function Eo({name:t,prefix:e,alphabet:n}){const{encode:r,decode:o}=mw(n,t);return si({prefix:e,name:t,encode:r,decode:s=>oi(o(s))})}function Sw(t,e,n,r){let o=t.length;for(;t[o-1]==="=";)--o;const s=new Uint8Array(o*n/8|0);let i=0,a=0,c=0;for(let l=0;l<o;++l){const d=e[t[l]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<n|d,i+=n,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=n||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function xw(t,e,n){const r=e[e.length-1]==="=",o=(1<<n)-1;let s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>n;)i-=n,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<n-i]),r)for(;(s.length*n&7)!==0;)s+="=";return s}function Ew(t){const e={};for(let n=0;n<t.length;++n)e[t[n]]=n;return e}function Ne({name:t,prefix:e,bitsPerChar:n,alphabet:r}){const o=Ew(r);return si({prefix:e,name:t,encode(s){return xw(s,r,n)},decode(s){return Sw(s,o,n,t)}})}const He=Eo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Aw=Eo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),kw=Object.freeze(Object.defineProperty({__proto__:null,base58btc:He,base58flickr:Aw},Symbol.toStringTag,{value:"Module"})),no=Ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Cw=Ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Iw=Ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Rw=Ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Tw=Ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Pw=Ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Nw=Ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Lw=Ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Bw=Ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),_w=Object.freeze(Object.defineProperty({__proto__:null,base32:no,base32hex:Tw,base32hexpad:Nw,base32hexpadupper:Lw,base32hexupper:Pw,base32pad:Iw,base32padupper:Rw,base32upper:Cw,base32z:Bw},Symbol.toStringTag,{value:"Module"})),os=Eo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ow=Eo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Dw=Object.freeze(Object.defineProperty({__proto__:null,base36:os,base36upper:Ow},Symbol.toStringTag,{value:"Module"}));var Fw=Wf,ld=128,Mw=-128,jw=Math.pow(2,31);function Wf(t,e,n){e=e||[],n=n||0;for(var r=n;t>=jw;)e[n++]=t&255|ld,t/=128;for(;t&Mw;)e[n++]=t&255|ld,t>>>=7;return e[n]=t|0,Wf.bytes=n-r+1,e}var Hw=qa,Uw=128,dd=127;function qa(t,r){var n=0,r=r||0,o=0,s=r,i,a=t.length;do{if(s>=a)throw qa.bytes=0,new RangeError("Could not decode varint");i=t[s++],n+=o<28?(i&dd)<<o:(i&dd)*Math.pow(2,o),o+=7}while(i>=Uw);return qa.bytes=s-r,n}var $w=Math.pow(2,7),qw=Math.pow(2,14),Kw=Math.pow(2,21),zw=Math.pow(2,28),Gw=Math.pow(2,35),Ww=Math.pow(2,42),Vw=Math.pow(2,49),Xw=Math.pow(2,56),Yw=Math.pow(2,63),Zw=function(t){return t<$w?1:t<qw?2:t<Kw?3:t<zw?4:t<Gw?5:t<Ww?6:t<Vw?7:t<Xw?8:t<Yw?9:10},Jw={encode:Fw,decode:Hw,encodingLength:Zw},vs=Jw;function Ka(t,e=0){return[vs.decode(t,e),vs.decode.bytes]}function Ss(t,e,n=0){return vs.encode(t,e,n),e}function xs(t){return vs.encodingLength(t)}function Ao(t,e){const n=e.byteLength,r=xs(t),o=r+xs(n),s=new Uint8Array(o+n);return Ss(t,s,0),Ss(n,s,r),s.set(e,o),new Yc(t,n,e,s)}function Vf(t){const e=oi(t),[n,r]=Ka(e),[o,s]=Ka(e.subarray(r)),i=e.subarray(r+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Yc(n,o,i,e)}function Qw(t,e){if(t===e)return!0;{const n=e;return t.code===n.code&&t.size===n.size&&n.bytes instanceof Uint8Array&&uw(t.bytes,n.bytes)}}class Yc{code;size;digest;bytes;constructor(e,n,r,o){this.code=e,this.size=n,this.digest=r,this.bytes=o}}function ud(t,e){const{bytes:n,version:r}=t;return r===0?ty(n,za(t),e??He.encoder):ny(n,za(t),e??no.encoder)}const fd=new WeakMap;function za(t){const e=fd.get(t);if(e==null){const n=new Map;return fd.set(t,n),n}return e}class ue{code;version;multihash;bytes;"/";constructor(e,n,r,o){this.code=n,this.version=e,this.multihash=r,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:e,multihash:n}=this;if(e!==Tr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==ry)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ue.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=Ao(e,n);return ue.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 ue.equals(this,e)}static equals(e,n){const r=n;return r!=null&&e.code===r.code&&e.version===r.version&&Qw(e.multihash,r.multihash)}toString(e){return ud(this,e)}toJSON(){return{"/":ud(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 ue)return n;if(n["/"]!=null&&n["/"]===n.bytes||n.asCID===n){const{version:r,code:o,multihash:s,bytes:i}=n;return new ue(r,o,s,i??hd(r,o,s.bytes))}else if(n[oy]===!0){const{version:r,multihash:o,code:s}=n,i=Vf(o);return ue.create(r,s,i)}else return null}static create(e,n,r){if(typeof n!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(n!==Tr)throw new Error(`Version 0 CID must use dag-pb (code: ${Tr}) block encoding`);return new ue(e,n,r,r.bytes)}case 1:{const o=hd(e,n,r.bytes);return new ue(e,n,r,o)}default:throw new Error("Invalid version")}}static createV0(e){return ue.create(0,Tr,e)}static createV1(e,n){return ue.create(1,e,n)}static decode(e){const[n,r]=ue.decodeFirst(e);if(r.length!==0)throw new Error("Incorrect length");return n}static decodeFirst(e){const n=ue.inspectBytes(e),r=n.size-n.multihashSize,o=oi(e.subarray(r,r+n.multihashSize));if(o.byteLength!==n.multihashSize)throw new Error("Incorrect length");const s=o.subarray(n.multihashSize-n.digestSize),i=new Yc(n.multihashCode,n.digestSize,s,o);return[n.version===0?ue.createV0(i):ue.createV1(n.codec,i),e.subarray(n.size)]}static inspectBytes(e){let n=0;const r=()=>{const[u,f]=Ka(e.subarray(n));return n+=f,u};let o=r(),s=Tr;if(o===18?(o=0,n=0):s=r(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);const i=n,a=r(),c=r(),l=n+c,d=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:l}}static parse(e,n){const[r,o]=ey(e,n),s=ue.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return za(s).set(r,e),s}}function ey(t,e){switch(t[0]){case"Q":{const n=e??He;return[He.prefix,n.decode(`${He.prefix}${t}`)]}case He.prefix:{const n=e??He;return[He.prefix,n.decode(t)]}case no.prefix:{const n=e??no;return[no.prefix,n.decode(t)]}case os.prefix:{const n=e??os;return[os.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 ty(t,e,n){const{prefix:r}=n;if(r!==He.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);const o=e.get(r);if(o==null){const s=n.encode(t).slice(1);return e.set(r,s),s}else return o}function ny(t,e,n){const{prefix:r}=n,o=e.get(r);if(o==null){const s=n.encode(t);return e.set(r,s),s}else return o}const Tr=112,ry=18;function hd(t,e,n){const r=xs(t),o=r+xs(e),s=new Uint8Array(o+n.byteLength);return Ss(t,s,0),Ss(e,s,r),s.set(n,o),s}const oy=Symbol.for("@ipld/js-cid/CID"),Xf=0,sy="identity",Yf=oi;function iy(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 Ao(Xf,Yf(t))}const ko={code:Xf,name:sy,encode:Yf,digest:iy};function dt(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 qe(t=0){return new Uint8Array(t)}function Bt(t=0){return new Uint8Array(t)}function Ga(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));const n=Bt(e);let r=0;for(const o of t)n.set(o,r),r+=o.length;return n}const Zf=Symbol.for("@achingbrain/uint8arraylist");function pd(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let n=0;for(const r of t){const o=n+r.byteLength;if(e<o)return{buf:r,index:e-n};n=o}throw new RangeError("index is out of bounds")}function _o(t){return!!t?.[Zf]}class ce{bufs;length;[Zf]=!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(_o(r)){n+=r.byteLength;for(const o of r.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=n}prepend(...e){this.prependAll(e)}prependAll(e){let n=0;for(const r of e.reverse())if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.unshift(r);else if(_o(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=pd(this.bufs,e);return n.buf[n.index]}set(e,n){const r=pd(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(_o(e))for(let r=0;r<e.length;r++)this.set(n+r,e.get(r));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,n){const{bufs:r,length:o}=this._subList(e,n);return Ga(r,o)}subarray(e,n){const{bufs:r,length:o}=this._subList(e,n);return r.length===1?r[0]:Ga(r,o)}sublist(e,n){const{bufs:r,length:o}=this._subList(e,n),s=new ce;return s.length=o,s.bufs=r,s}_subList(e,n){if(e=e??0,n=n??this.length,e<0&&(e=this.length+e),n<0&&(n=this.length+n),e<0||n>this.length)throw new RangeError("index is out of bounds");if(e===n)return{bufs:[],length:0};if(e===0&&n===this.length)return{bufs:[...this.bufs],length:this.length};const r=[];let o=0;for(let s=0;s<this.bufs.length;s++){const i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;const l=e>=a&&e<c,d=n>a&&n<=c;if(l&&d){if(e===a&&n===c){r.push(i);break}const u=e-a;r.push(i.subarray(u,u+(n-e)));break}if(l){if(e===0){r.push(i);continue}r.push(i.subarray(e-a));continue}if(d){if(n===c){r.push(i);break}r.push(i.subarray(0,n-a));break}r.push(i)}return{bufs:r,length:n-e}}indexOf(e,n=0){if(!_o(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(n=Number(n??0),isNaN(n)&&(n=0),n<0&&(n=this.length+n),n<0&&(n=0),e.length===0)return n>this.length?this.length:n;const o=r.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");const s=256,i=new Int32Array(s);for(let u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[r[u]]=u;const a=i,c=this.byteLength-r.byteLength,l=r.byteLength-1;let d;for(let u=n;u<=c;u+=d){d=0;for(let f=l;f>=0;f--){const h=this.get(u+f);if(r[f]!==h){d=Math.max(1,f-a[h]);break}}if(d===0)return u}return-1}getInt8(e){const n=this.subarray(e,e+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt8(0)}setInt8(e,n){const r=Bt(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,n),this.write(r,e)}getInt16(e,n){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,n)}setInt16(e,n,r){const o=qe(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,n,r),this.write(o,e)}getInt32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,n)}setInt32(e,n,r){const o=qe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,n,r),this.write(o,e)}getBigInt64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,n)}setBigInt64(e,n,r){const o=qe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,n,r),this.write(o,e)}getUint8(e){const n=this.subarray(e,e+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint8(0)}setUint8(e,n){const r=Bt(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,n),this.write(r,e)}getUint16(e,n){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,n)}setUint16(e,n,r){const o=qe(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,n,r),this.write(o,e)}getUint32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,n)}setUint32(e,n,r){const o=qe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,n,r),this.write(o,e)}getBigUint64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,n)}setBigUint64(e,n,r){const o=qe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,n,r),this.write(o,e)}getFloat32(e,n){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,n)}setFloat32(e,n,r){const o=qe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,n,r),this.write(o,e)}getFloat64(e,n){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,n)}setFloat64(e,n,r){const o=qe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,n,r),this.write(o,e)}equals(e){if(e==null||!(e instanceof ce)||e.bufs.length!==this.bufs.length)return!1;for(let n=0;n<this.bufs.length;n++)if(!dt(this.bufs[n],e.bufs[n]))return!1;return!0}static fromUint8Arrays(e,n){const r=new ce;return r.bufs=e,n==null&&(n=e.reduce((o,s)=>o+s.byteLength,0)),r.length=n,r}}const ay=Eo({prefix:"9",name:"base10",alphabet:"0123456789"}),cy=Object.freeze(Object.defineProperty({__proto__:null,base10:ay},Symbol.toStringTag,{value:"Module"})),ly=Ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),dy=Ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),uy=Object.freeze(Object.defineProperty({__proto__:null,base16:ly,base16upper:dy},Symbol.toStringTag,{value:"Module"})),fy=Ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),hy=Object.freeze(Object.defineProperty({__proto__:null,base2:fy},Symbol.toStringTag,{value:"Module"})),Jf=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),py=Jf.reduce((t,e,n)=>(t[n]=e,t),[]),gy=Jf.reduce((t,e,n)=>{const r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return t[r]=n,t},[]);function my(t){return t.reduce((e,n)=>(e+=py[n],e),"")}function wy(t){const e=[];for(const n of t){const r=n.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${n}`);const o=gy[r];if(o==null)throw new Error(`Non-base256emoji character: ${n}`);e.push(o)}return new Uint8Array(e)}const yy=si({prefix:"🚀",name:"base256emoji",encode:my,decode:wy}),by=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:yy},Symbol.toStringTag,{value:"Module"})),vy=Ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Sy=Ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),xy=Ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ey=Ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Ay=Object.freeze(Object.defineProperty({__proto__:null,base64:vy,base64pad:Sy,base64url:xy,base64urlpad:Ey},Symbol.toStringTag,{value:"Module"})),ky=Ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Cy=Object.freeze(Object.defineProperty({__proto__:null,base8:ky},Symbol.toStringTag,{value:"Module"})),Iy=si({prefix:"\0",name:"identity",encode:t=>hw(t),decode:t=>fw(t)}),Ry=Object.freeze(Object.defineProperty({__proto__:null,identity:Iy},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const Ty=20;function Py({name:t,code:e,encode:n,minDigestLength:r,maxDigestLength:o}){return new Ny(t,e,n,r,o)}class Ny{name;code;encode;minDigestLength;maxDigestLength;constructor(e,n,r,o,s){this.name=e,this.code=n,this.encode=r,this.minDigestLength=o??Ty,this.maxDigestLength=s}digest(e,n){if(n?.truncate!=null){if(n.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&n.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?gd(r,this.code,n?.truncate):r.then(o=>gd(o,this.code,n?.truncate))}else throw Error("Unknown type, must be binary type")}}function gd(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 Ao(e,t)}function Ly(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}const Zc=Py({name:"sha2-256",code:18,encode:Ly("SHA-256")}),md={...Ry,...hy,...Cy,...cy,...uy,..._w,...Dw,...kw,...Ay,...by};function Qf(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const wd=Qf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Oi=Qf("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=Bt(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),eh={utf8:wd,"utf-8":wd,hex:md.base16,latin1:Oi,ascii:Oi,binary:Oi,...md};function Se(t,e="utf8"){const n=eh[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.decoder.decode(`${n.prefix}${t}`)}function te(t,e="utf8"){const n=eh[e];if(n==null)throw new Error(`Unsupported encoding "${e}"`);return n.encoder.encode(t).substring(1)}const By=parseInt("11111",2),Wa=parseInt("10000000",2),_y=parseInt("01111111",2),yd={0:Pr,1:Pr,2:Oy,3:My,4:jy,5:Fy,6:Dy,16:Pr,22:Pr,48:Pr};function br(t,e={offset:0}){const n=t[e.offset]&By;if(e.offset++,yd[n]!=null)return yd[n](t,e);throw new Error("No decoder for tag "+n)}function Co(t,e){let n=0;if((t[e.offset]&Wa)===Wa){const r=t[e.offset]&_y;let o="0x";e.offset++;for(let s=0;s<r;s++,e.offset++)o+=t[e.offset].toString(16).padStart(2,"0");n=parseInt(o,16)}else n=t[e.offset],e.offset++;return n}function Pr(t,e){Co(t,e);const n=[];for(;!(e.offset>=t.byteLength);){const r=br(t,e);if(r===null)break;n.push(r)}return n}function Oy(t,e){const n=Co(t,e),r=e.offset,o=e.offset+n,s=[];for(let i=r;i<o;i++)i===r&&t[i]===0||s.push(t[i]);return e.offset+=n,Uint8Array.from(s)}function Dy(t,e){const n=Co(t,e),r=e.offset+n,o=t[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<r;){const l=t[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let d=0;for(let u=0;u<c.length;u++)d+=c[u]<<u*7;a+=`.${d}`,c=[]}}return a}function Fy(t,e){return e.offset++,null}function My(t,e){const n=Co(t,e),r=t[e.offset];e.offset++;const o=t.subarray(e.offset,e.offset+n-1);if(e.offset+=n,r!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function jy(t,e){const n=Co(t,e),r=t.subarray(e.offset,e.offset+n);return e.offset+=n,r}function Hy(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);const n=new ce;for(let r=0;r<e.length;r+=2)n.append(Uint8Array.from([parseInt(`${e[r]}${e[r+1]}`,16)]));return n}function ii(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);const e=Hy(t.byteLength);return new ce(Uint8Array.from([e.byteLength|Wa]),e)}function Xe(t){const e=new ce,n=128;return(t.subarray()[0]&n)===n&&e.append(Uint8Array.from([0])),e.append(t),new ce(Uint8Array.from([2]),ii(e),e)}function Jc(t){const e=Uint8Array.from([0]),n=new ce(e,t);return new ce(Uint8Array.from([3]),ii(n),n)}function Uy(t){return new ce(Uint8Array.from([4]),ii(t),t)}function Pt(t,e=48){const n=new ce;for(const r of t)n.append(r);return new ce(Uint8Array.from([e]),ii(n),n)}async function $y(t,e,n){const r=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["sign"]);n?.signal?.throwIfAborted();const o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function qy(t,e,n,r){const o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();const s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,n.subarray());return r?.signal?.throwIfAborted(),s}const Ky=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),zy=Uint8Array.from([6,5,43,129,4,0,34]),Gy=Uint8Array.from([6,5,43,129,4,0,35]),th={ext:!0,kty:"EC",crv:"P-256"},nh={ext:!0,kty:"EC",crv:"P-384"},rh={ext:!0,kty:"EC",crv:"P-521"},Xn=32,Yn=48,Zn=66;function Wy(t){const e=br(t);return Vy(e)}function Vy(t){const e=t[1],n=te(e,"base64url"),r=t[2][1][0],o=1;let s,i;if(e.byteLength===Xn)return s=te(r.subarray(o,o+Xn),"base64url"),i=te(r.subarray(o+Xn),"base64url"),new Di({...th,key_ops:["sign"],d:n,x:s,y:i});if(e.byteLength===Yn)return s=te(r.subarray(o,o+Yn),"base64url"),i=te(r.subarray(o+Yn),"base64url"),new Di({...nh,key_ops:["sign"],d:n,x:s,y:i});if(e.byteLength===Zn)return s=te(r.subarray(o,o+Zn),"base64url"),i=te(r.subarray(o+Zn),"base64url"),new Di({...rh,key_ops:["sign"],d:n,x:s,y:i});throw new lt(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function oh(t){const e=br(t);return Xy(e)}function Xy(t){const e=t[1][1][0],n=1;let r,o;if(e.byteLength===Xn*2+1)return r=te(e.subarray(n,n+Xn),"base64url"),o=te(e.subarray(n+Xn),"base64url"),new ss({...th,key_ops:["verify"],x:r,y:o});if(e.byteLength===Yn*2+1)return r=te(e.subarray(n,n+Yn),"base64url"),o=te(e.subarray(n+Yn),"base64url"),new ss({...nh,key_ops:["verify"],x:r,y:o});if(e.byteLength===Zn*2+1)return r=te(e.subarray(n,n+Zn),"base64url"),o=te(e.subarray(n+Zn),"base64url"),new ss({...rh,key_ops:["verify"],x:r,y:o});throw new lt(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Yy(t){return Pt([Xe(Uint8Array.from([1])),Uy(Se(t.d??"","base64url")),Pt([sh(t.crv)],160),Pt([Jc(new ce(Uint8Array.from([4]),Se(t.x??"","base64url"),Se(t.y??"","base64url")))],161)]).subarray()}function Zy(t){return Pt([Xe(Uint8Array.from([1])),Pt([sh(t.crv)],160),Pt([Jc(new ce(Uint8Array.from([4]),Se(t.x??"","base64url"),Se(t.y??"","base64url")))],161)]).subarray()}function sh(t){if(t==="P-256")return Ky;if(t==="P-384")return zy;if(t==="P-521")return Gy;throw new lt(`Invalid curve ${t}`)}class ss{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Zy(this.jwk)),this._raw}toMultihash(){return ko.digest(fi(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return He.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:dt(this.raw,e.raw)}async verify(e,n,r){return qy(this.jwk,n,e,r)}}class Di{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new ss({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=Yy(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:dt(this.raw,e.raw)}async sign(e,n){return $y(this.jwk,e,n)}}const On=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Io(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Va(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function An(t,...e){if(!Io(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 ih(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Va(t.outputLen),Va(t.blockLen)}function Es(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 Jy(t,e){An(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function dr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Fi(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function ft(t,e){return t<<32-e|t>>>e}const ah=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qy=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function hn(t){if(An(t),ah)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Qy[t[n]];return e}const vt={_0:48,_9:57,A:65,F:70,a:97,f:102};function bd(t){if(t>=vt._0&&t<=vt._9)return t-vt._0;if(t>=vt.A&&t<=vt.F)return t-(vt.A-10);if(t>=vt.a&&t<=vt.f)return t-(vt.a-10)}function As(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(ah)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){const i=bd(t.charCodeAt(s)),a=bd(t.charCodeAt(s+1));if(i===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a}return r}function eb(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Qc(t){return typeof t=="string"&&(t=eb(t)),An(t),t}function mt(...t){let e=0;for(let r=0;r<t.length;r++){const o=t[r];An(o),e+=o.length}const n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){const s=t[r];n.set(s,o),o+=s.length}return n}class ch{}function lh(t){const e=r=>t().update(Qc(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function el(t=32){if(On&&typeof On.getRandomValues=="function")return On.getRandomValues(new Uint8Array(t));if(On&&typeof On.randomBytes=="function")return Uint8Array.from(On.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function tb(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const o=BigInt(32),s=BigInt(4294967295),i=Number(n>>o&s),a=Number(n&s),c=r?4:0,l=r?0:4;t.setUint32(e+c,i,r),t.setUint32(e+l,a,r)}function nb(t,e,n){return t&e^~t&n}function rb(t,e,n){return t&e^t&n^e&n}let dh=class extends ch{constructor(e,n,r,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Fi(this.buffer)}update(e){Es(this),e=Qc(e),An(e);const{view:n,buffer:r,blockLen:o}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(o-this.pos,s-i);if(a===o){const c=Fi(e);for(;o<=s-i;i+=o)this.process(c,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Es(this),Jy(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:o,isLE:s}=this;let{pos:i}=this;n[i++]=128,dr(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(r,0),i=0);for(let u=i;u<o;u++)n[u]=0;tb(r,o-8,BigInt(this.length*8),s),this.process(r,0);const a=Fi(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}};const Mt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),_e=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Oo=BigInt(2**32-1),vd=BigInt(32);function ob(t,e=!1){return e?{h:Number(t&Oo),l:Number(t>>vd&Oo)}:{h:Number(t>>vd&Oo)|0,l:Number(t&Oo)|0}}function sb(t,e=!1){const n=t.length;let r=new Uint32Array(n),o=new Uint32Array(n);for(let s=0;s<n;s++){const{h:i,l:a}=ob(t[s],e);[r[s],o[s]]=[i,a]}return[r,o]}const Sd=(t,e,n)=>t>>>n,xd=(t,e,n)=>t<<32-n|e>>>n,Dn=(t,e,n)=>t>>>n|e<<32-n,Fn=(t,e,n)=>t<<32-n|e>>>n,Do=(t,e,n)=>t<<64-n|e>>>n-32,Fo=(t,e,n)=>t>>>n-32|e<<64-n;function St(t,e,n,r){const o=(e>>>0)+(r>>>0);return{h:t+n+(o/2**32|0)|0,l:o|0}}const ib=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),ab=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,cb=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),lb=(t,e,n,r,o)=>e+n+r+o+(t/2**32|0)|0,db=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),ub=(t,e,n,r,o,s)=>e+n+r+o+s+(t/2**32|0)|0,fb=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]),jt=new Uint32Array(64);class hb extends dh{constructor(e=32){super(64,e,8,!1),this.A=Mt[0]|0,this.B=Mt[1]|0,this.C=Mt[2]|0,this.D=Mt[3]|0,this.E=Mt[4]|0,this.F=Mt[5]|0,this.G=Mt[6]|0,this.H=Mt[7]|0}get(){const{A:e,B:n,C:r,D:o,E:s,F:i,G:a,H:c}=this;return[e,n,r,o,s,i,a,c]}set(e,n,r,o,s,i,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,n){for(let u=0;u<16;u++,n+=4)jt[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const f=jt[u-15],h=jt[u-2],g=ft(f,7)^ft(f,18)^f>>>3,m=ft(h,17)^ft(h,19)^h>>>10;jt[u]=m+jt[u-7]+g+jt[u-16]|0}let{A:r,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=ft(a,6)^ft(a,11)^ft(a,25),h=d+f+nb(a,c,l)+fb[u]+jt[u]|0,m=(ft(r,2)^ft(r,13)^ft(r,22))+rb(r,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=r,r=h+m|0}r=r+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,s,i,a,c,l,d)}roundClean(){dr(jt)}destroy(){this.set(0,0,0,0,0,0,0,0),dr(this.buffer)}}const uh=sb(["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))),pb=uh[0],gb=uh[1],Ht=new Uint32Array(80),Ut=new Uint32Array(80);class mb extends dh{constructor(e=64){super(128,e,16,!1),this.Ah=_e[0]|0,this.Al=_e[1]|0,this.Bh=_e[2]|0,this.Bl=_e[3]|0,this.Ch=_e[4]|0,this.Cl=_e[5]|0,this.Dh=_e[6]|0,this.Dl=_e[7]|0,this.Eh=_e[8]|0,this.El=_e[9]|0,this.Fh=_e[10]|0,this.Fl=_e[11]|0,this.Gh=_e[12]|0,this.Gl=_e[13]|0,this.Hh=_e[14]|0,this.Hl=_e[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:f,Gh:h,Gl:g,Hh:m,Hl:b}=this;return[e,n,r,o,s,i,a,c,l,d,u,f,h,g,m,b]}set(e,n,r,o,s,i,a,c,l,d,u,f,h,g,m,b){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=d|0,this.Fh=u|0,this.Fl=f|0,this.Gh=h|0,this.Gl=g|0,this.Hh=m|0,this.Hl=b|0}process(e,n){for(let y=0;y<16;y++,n+=4)Ht[y]=e.getUint32(n),Ut[y]=e.getUint32(n+=4);for(let y=16;y<80;y++){const A=Ht[y-15]|0,N=Ut[y-15]|0,k=Dn(A,N,1)^Dn(A,N,8)^Sd(A,N,7),T=Fn(A,N,1)^Fn(A,N,8)^xd(A,N,7),S=Ht[y-2]|0,v=Ut[y-2]|0,E=Dn(S,v,19)^Do(S,v,61)^Sd(S,v,6),_=Fn(S,v,19)^Fo(S,v,61)^xd(S,v,6),L=cb(T,_,Ut[y-7],Ut[y-16]),C=lb(L,k,E,Ht[y-7],Ht[y-16]);Ht[y]=C|0,Ut[y]=L|0}let{Ah:r,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:f,Fh:h,Fl:g,Gh:m,Gl:b,Hh:w,Hl:I}=this;for(let y=0;y<80;y++){const A=Dn(u,f,14)^Dn(u,f,18)^Do(u,f,41),N=Fn(u,f,14)^Fn(u,f,18)^Fo(u,f,41),k=u&h^~u&m,T=f&g^~f&b,S=db(I,N,T,gb[y],Ut[y]),v=ub(S,w,A,k,pb[y],Ht[y]),E=S|0,_=Dn(r,o,28)^Do(r,o,34)^Do(r,o,39),L=Fn(r,o,28)^Fo(r,o,34)^Fo(r,o,39),C=r&s^r&a^s&a,x=o&i^o&c^i&c;w=m|0,I=b|0,m=h|0,b=g|0,h=u|0,g=f|0,{h:u,l:f}=St(l|0,d|0,v|0,E|0),l=a|0,d=c|0,a=s|0,c=i|0,s=r|0,i=o|0;const P=ib(E,L,x);r=ab(P,v,_,C),o=P|0}({h:r,l:o}=St(this.Ah|0,this.Al|0,r|0,o|0)),{h:s,l:i}=St(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=St(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=St(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:f}=St(this.Eh|0,this.El|0,u|0,f|0),{h,l:g}=St(this.Fh|0,this.Fl|0,h|0,g|0),{h:m,l:b}=St(this.Gh|0,this.Gl|0,m|0,b|0),{h:w,l:I}=St(this.Hh|0,this.Hl|0,w|0,I|0),this.set(r,o,s,i,a,c,l,d,u,f,h,g,m,b,w,I)}roundClean(){dr(Ht,Ut)}destroy(){dr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const fh=lh(()=>new hb),wb=lh(()=>new mb);const tl=BigInt(0),Xa=BigInt(1);function bn(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function at(t,e,n=""){const r=Io(t),o=t?.length,s=e!==void 0;if(!r||s&&o!==e){const i=n&&`"${n}" `,a=s?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function Mo(t){const e=t.toString(16);return e.length&1?"0"+e:e}function hh(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?tl:BigInt("0x"+t)}function ai(t){return hh(hn(t))}function ho(t){return An(t),hh(hn(Uint8Array.from(t).reverse()))}function nl(t,e){return As(t.toString(16).padStart(e*2,"0"))}function ph(t,e){return nl(t,e).reverse()}function ge(t,e,n){let r;if(typeof e=="string")try{r=As(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Io(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const o=r.length;if(typeof n=="number"&&o!==n)throw new Error(t+" of length "+n+" expected, got "+o);return r}function Ed(t){return Uint8Array.from(t)}const Mi=t=>typeof t=="bigint"&&tl<=t;function yb(t,e,n){return Mi(t)&&Mi(e)&&Mi(n)&&e<=t&&t<n}function Ya(t,e,n,r){if(!yb(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function gh(t){let e;for(e=0;t>tl;t>>=Xa,e+=1);return e}const Ro=t=>(Xa<<BigInt(t))-Xa;function bb(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=h=>new Uint8Array(h),o=h=>Uint8Array.of(h);let s=r(t),i=r(t),a=0;const c=()=>{s.fill(1),i.fill(0),a=0},l=(...h)=>n(i,s,...h),d=(h=r(0))=>{i=l(o(0),h),s=l(),h.length!==0&&(i=l(o(1),h),s=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const g=[];for(;h<e;){s=l();const m=s.slice();g.push(m),h+=s.length}return mt(...g)};return(h,g)=>{c(),d(h);let m;for(;!(m=g(u()));)d();return c(),m}}function To(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(o,s,i){const a=t[o];if(i&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([o,s])=>r(o,s,!1)),Object.entries(n).forEach(([o,s])=>r(o,s,!0))}function ks(t){const e=new WeakMap;return(n,...r)=>{const o=e.get(n);if(o!==void 0)return o;const s=t(n,...r);return e.set(n,s),s}}const Ke=BigInt(0),Pe=BigInt(1),an=BigInt(2),mh=BigInt(3),wh=BigInt(4),yh=BigInt(5),vb=BigInt(7),bh=BigInt(8),Sb=BigInt(9),vh=BigInt(16);function xe(t,e){const n=t%e;return n>=Ke?n:e+n}function pe(t,e,n){let r=t;for(;e-- >Ke;)r*=r,r%=n;return r}function Ad(t,e){if(t===Ke)throw new Error("invert: expected non-zero number");if(e<=Ke)throw new Error("invert: expected positive modulus, got "+e);let n=xe(t,e),r=e,o=Ke,s=Pe;for(;n!==Ke;){const a=r/n,c=r%n,l=o-s*a;r=n,n=c,o=s,s=l}if(r!==Pe)throw new Error("invert: does not exist");return xe(o,e)}function rl(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Sh(t,e){const n=(t.ORDER+Pe)/wh,r=t.pow(e,n);return rl(t,r,e),r}function xb(t,e){const n=(t.ORDER-yh)/bh,r=t.mul(e,an),o=t.pow(r,n),s=t.mul(e,o),i=t.mul(t.mul(s,an),o),a=t.mul(s,t.sub(i,t.ONE));return rl(t,a,e),a}function Eb(t){const e=kn(t),n=xh(t),r=n(e,e.neg(e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+vb)/vh;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,r);const u=a.mul(l,o),f=a.mul(l,s),h=a.eql(a.sqr(d),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,d,h),d=a.cmov(f,u,g);const m=a.eql(a.sqr(d),c),b=a.cmov(l,d,m);return rl(a,b,c),b}}function xh(t){if(t<mh)throw new Error("sqrt is not defined for small field");let e=t-Pe,n=0;for(;e%an===Ke;)e/=an,n++;let r=an;const o=kn(t);for(;kd(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Sh;let s=o.pow(r,e);const i=(e+Pe)/an;return function(c,l){if(c.is0(l))return l;if(kd(c,l)!==1)throw new Error("Cannot find square root");let d=n,u=c.mul(c.ONE,s),f=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let g=1,m=c.sqr(f);for(;!c.eql(m,c.ONE);)if(g++,m=c.sqr(m),g===d)throw new Error("Cannot find square root");const b=Pe<<BigInt(d-g-1),w=c.pow(u,b);d=g,u=c.sqr(w),f=c.mul(f,u),h=c.mul(h,w)}return h}}function Ab(t){return t%wh===mh?Sh:t%bh===yh?xb:t%vh===Sb?Eb(t):xh(t)}const kb=(t,e)=>(xe(t,e)&Pe)===Pe,Cb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ib(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=Cb.reduce((r,o)=>(r[o]="function",r),e);return To(t,n),t}function Rb(t,e,n){if(n<Ke)throw new Error("invalid exponent, negatives unsupported");if(n===Ke)return t.ONE;if(n===Pe)return e;let r=t.ONE,o=e;for(;n>Ke;)n&Pe&&(r=t.mul(r,o)),o=t.sqr(o),n>>=Pe;return r}function Eh(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),o=e.reduce((i,a,c)=>t.is0(a)?i:(r[c]=i,t.mul(i,a)),t.ONE),s=t.inv(o);return e.reduceRight((i,a,c)=>t.is0(a)?i:(r[c]=t.mul(i,r[c]),t.mul(i,a)),s),r}function kd(t,e){const n=(t.ORDER-Pe)/an,r=t.pow(e,n),o=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),i=t.eql(r,t.neg(t.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function Ah(t,e){e!==void 0&&Va(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function kn(t,e,n=!1,r={}){if(t<=Ke)throw new Error("invalid field: expected ORDER > 0, got "+t);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const f=e;f.BITS&&(o=f.BITS),f.sqrt&&(s=f.sqrt),typeof f.isLE=="boolean"&&(n=f.isLE),typeof f.modFromBytes=="boolean"&&(i=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(o=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:l}=Ah(t,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:l,MASK:Ro(c),ZERO:Ke,ONE:Pe,allowedLengths:a,create:f=>xe(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return Ke<=f&&f<t},is0:f=>f===Ke,isValidNot0:f=>!u.is0(f)&&u.isValid(f),isOdd:f=>(f&Pe)===Pe,neg:f=>xe(-f,t),eql:(f,h)=>f===h,sqr:f=>xe(f*f,t),add:(f,h)=>xe(f+h,t),sub:(f,h)=>xe(f-h,t),mul:(f,h)=>xe(f*h,t),pow:(f,h)=>Rb(u,f,h),div:(f,h)=>xe(f*Ad(h,t),t),sqrN:f=>f*f,addN:(f,h)=>f+h,subN:(f,h)=>f-h,mulN:(f,h)=>f*h,inv:f=>Ad(f,t),sqrt:s||(f=>(d||(d=Ab(t)),d(u,f))),toBytes:f=>n?ph(f,l):nl(f,l),fromBytes:(f,h=!0)=>{if(a){if(!a.includes(f.length)||f.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);const m=new Uint8Array(l);m.set(f,n?0:m.length-f.length),f=m}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let g=n?ho(f):ai(f);if(i&&(g=xe(g,t)),!h&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:f=>Eh(u,f),cmov:(f,h,g)=>g?h:f});return Object.freeze(u)}function kh(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 Ch(t){const e=kh(t);return e+Math.ceil(e/2)}function Tb(t,e,n=!1){const r=t.length,o=kh(e),s=Ch(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const i=n?ho(t):ai(t),a=xe(i,e-Pe)+Pe;return n?ph(a,o):nl(a,o)}const ur=BigInt(0),cn=BigInt(1);function Cs(t,e){const n=e.negate();return t?n:e}function ln(t,e){const n=Eh(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function Ih(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ji(t,e){Ih(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,s=Ro(t),i=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:o,shiftBy:i}}function Cd(t,e,n){const{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n;let a=Number(t&o),c=t>>i;a>r&&(a-=s,c+=cn);const l=e*r,d=l+Math.abs(a)-1,u=a===0,f=a<0,h=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:f,isNegF:h,offsetF:l}}function Pb(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 Nb(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 Hi=new WeakMap,Rh=new WeakMap;function Ui(t){return Rh.get(t)||1}function Id(t){if(t!==ur)throw new Error("invalid wNAF")}class Th{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>ur;)n&cn&&(r=r.add(o)),o=o.double(),n>>=cn;return r}precomputeWindow(e,n){const{windows:r,windowSize:o}=ji(n,this.bits),s=[];let i=e,a=i;for(let c=0;c<r;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE;const i=ji(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:f,offsetF:h}=Cd(r,a,i);r=c,d?s=s.add(Cs(f,n[h])):o=o.add(Cs(u,n[l]))}return Id(r),{p:o,f:s}}wNAFUnsafe(e,n,r,o=this.ZERO){const s=ji(e,this.bits);for(let i=0;i<s.windows&&r!==ur;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=Cd(r,i,s);if(r=a,!l){const u=n[c];o=o.add(d?u.negate():u)}}return Id(r),o}getPrecomputes(e,n,r){let o=Hi.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Hi.set(n,o))),o}cached(e,n,r){const o=Ui(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){const s=Ui(e);return s===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,o)}createCache(e,n){Ih(n,this.bits),Rh.set(e,n),Hi.delete(e)}hasCache(e){return Ui(e)!==1}}function Lb(t,e,n,r){let o=e,s=t.ZERO,i=t.ZERO;for(;n>ur||r>ur;)n&cn&&(s=s.add(o)),r&cn&&(i=i.add(o)),o=o.double(),n>>=cn,r>>=cn;return{p1:s,p2:i}}function Ph(t,e,n,r){Pb(n,t),Nb(r,e);const o=n.length,s=r.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,a=gh(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Ro(c),d=new Array(Number(l)+1).fill(i),u=Math.floor((e.BITS-1)/c)*c;let f=i;for(let h=u;h>=0;h-=c){d.fill(i);for(let m=0;m<s;m++){const b=r[m],w=Number(b>>BigInt(h)&l);d[w]=d[w].add(n[m])}let g=i;for(let m=d.length-1,b=i;m>0;m--)b=b.add(d[m]),g=g.add(b);if(f=f.add(g),h!==0)for(let m=0;m<c;m++)f=f.double()}return f}function Rd(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ib(e),e}else return kn(t,{isLE:n})}function Nh(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>ur))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Rd(e.p,n.Fp,r),s=Rd(e.n,n.Fn,r),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}const $t=BigInt(0),Ce=BigInt(1),$i=BigInt(2),Bb=BigInt(8);function _b(t,e,n,r){const o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function Ob(t,e={}){const n=Nh("edwards",t,e,e.FpFnLE),{Fp:r,Fn:o}=n;let s=n.CURVE;const{h:i}=s;To(e,{},{uvRatio:"function"});const a=$i<<BigInt(o.BYTES*8)-Ce,c=b=>r.create(b),l=e.uvRatio||((b,w)=>{try{return{isValid:!0,value:r.sqrt(r.div(b,w))}}catch{return{isValid:!1,value:$t}}});if(!_b(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(b,w,I=!1){const y=I?Ce:$t;return Ya("coordinate "+b,w,y,a),w}function u(b){if(!(b instanceof g))throw new Error("ExtendedPoint expected")}const f=ks((b,w)=>{const{X:I,Y:y,Z:A}=b,N=b.is0();w==null&&(w=N?Bb:r.inv(A));const k=c(I*w),T=c(y*w),S=r.mul(A,w);if(N)return{x:$t,y:Ce};if(S!==Ce)throw new Error("invZ was invalid");return{x:k,y:T}}),h=ks(b=>{const{a:w,d:I}=s;if(b.is0())throw new Error("bad point: ZERO");const{X:y,Y:A,Z:N,T:k}=b,T=c(y*y),S=c(A*A),v=c(N*N),E=c(v*v),_=c(T*w),L=c(v*c(_+S)),C=c(E+c(I*c(T*S)));if(L!==C)throw new Error("bad point: equation left != right (1)");const x=c(y*A),P=c(N*k);if(x!==P)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(w,I,y,A){this.X=d("x",w),this.Y=d("y",I),this.Z=d("z",y,!0),this.T=d("t",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(w){if(w instanceof g)throw new Error("extended point not allowed");const{x:I,y}=w||{};return d("x",I),d("y",y),new g(I,y,Ce,c(I*y))}static fromBytes(w,I=!1){const y=r.BYTES,{a:A,d:N}=s;w=Ed(at(w,y,"point")),bn(I,"zip215");const k=Ed(w),T=w[y-1];k[y-1]=T&-129;const S=ho(k),v=I?a:r.ORDER;Ya("point.y",S,$t,v);const E=c(S*S),_=c(E-Ce),L=c(N*E-A);let{isValid:C,value:x}=l(_,L);if(!C)throw new Error("bad point: invalid y coordinate");const P=(x&Ce)===Ce,R=(T&128)!==0;if(!I&&x===$t&&R)throw new Error("bad point: x=0 and x_0=1");return R!==P&&(x=c(-x)),g.fromAffine({x,y:S})}static fromHex(w,I=!1){return g.fromBytes(ge("point",w),I)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,I=!0){return m.createCache(this,w),I||this.multiply($i),this}assertValidity(){h(this)}equals(w){u(w);const{X:I,Y:y,Z:A}=this,{X:N,Y:k,Z:T}=w,S=c(I*T),v=c(N*A),E=c(y*T),_=c(k*A);return S===v&&E===_}is0(){return this.equals(g.ZERO)}negate(){return new g(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:w}=s,{X:I,Y:y,Z:A}=this,N=c(I*I),k=c(y*y),T=c($i*c(A*A)),S=c(w*N),v=I+y,E=c(c(v*v)-N-k),_=S+k,L=_-T,C=S-k,x=c(E*L),P=c(_*C),R=c(E*C),D=c(L*_);return new g(x,P,D,R)}add(w){u(w);const{a:I,d:y}=s,{X:A,Y:N,Z:k,T}=this,{X:S,Y:v,Z:E,T:_}=w,L=c(A*S),C=c(N*v),x=c(T*y*_),P=c(k*E),R=c((A+N)*(S+v)-L-C),D=P-x,M=P+x,F=c(C-I*L),B=c(R*D),H=c(M*F),$=c(R*F),X=c(D*M);return new g(B,H,X,$)}subtract(w){return this.add(w.negate())}multiply(w){if(!o.isValidNot0(w))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:I,f:y}=m.cached(this,w,A=>ln(g,A));return ln(g,[I,y])[0]}multiplyUnsafe(w,I=g.ZERO){if(!o.isValid(w))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return w===$t?g.ZERO:this.is0()||w===Ce?this:m.unsafe(this,w,y=>ln(g,y),I)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(w){return f(this,w)}clearCofactor(){return i===Ce?this:this.multiplyUnsafe(i)}toBytes(){const{x:w,y:I}=this.toAffine(),y=r.toBytes(I);return y[y.length-1]|=w&Ce?128:0,y}toHex(){return hn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(w){return ln(g,w)}static msm(w,I){return Ph(g,o,w,I)}_setWindowSize(w){this.precompute(w)}toRawBytes(){return this.toBytes()}}g.BASE=new g(s.Gx,s.Gy,Ce,c(s.Gx*s.Gy)),g.ZERO=new g($t,Ce,Ce,$t),g.Fp=r,g.Fn=o;const m=new Th(g,o.BITS);return g.BASE.precompute(8),g}function Db(t,e,n={}){if(typeof e!="function")throw new Error('"hash" function param is required');To(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:o,Fp:s,Fn:i}=t,a=n.randomBytes||el,c=n.adjustScalarBytes||(v=>v),l=n.domain||((v,E,_)=>{if(bn(_,"phflag"),E.length||_)throw new Error("Contexts/pre-hash are not supported");return v});function d(v){return i.create(ho(v))}function u(v){const E=y.secretKey;v=ge("private key",v,E);const _=ge("hashed private key",e(v),2*E),L=c(_.slice(0,E)),C=_.slice(E,2*E),x=d(L);return{head:L,prefix:C,scalar:x}}function f(v){const{head:E,prefix:_,scalar:L}=u(v),C=o.multiply(L),x=C.toBytes();return{head:E,prefix:_,scalar:L,point:C,pointBytes:x}}function h(v){return f(v).pointBytes}function g(v=Uint8Array.of(),...E){const _=mt(...E);return d(e(l(_,ge("context",v),!!r)))}function m(v,E,_={}){v=ge("message",v),r&&(v=r(v));const{prefix:L,scalar:C,pointBytes:x}=f(E),P=g(_.context,L,v),R=o.multiply(P).toBytes(),D=g(_.context,R,x,v),M=i.create(P+D*C);if(!i.isValid(M))throw new Error("sign failed: invalid s");const F=mt(R,i.toBytes(M));return at(F,y.signature,"result")}const b={zip215:!0};function w(v,E,_,L=b){const{context:C,zip215:x}=L,P=y.signature;v=ge("signature",v,P),E=ge("message",E),_=ge("publicKey",_,y.publicKey),x!==void 0&&bn(x,"zip215"),r&&(E=r(E));const R=P/2,D=v.subarray(0,R),M=ho(v.subarray(R,P));let F,B,H;try{F=t.fromBytes(_,x),B=t.fromBytes(D,x),H=o.multiplyUnsafe(M)}catch{return!1}if(!x&&F.isSmallOrder())return!1;const $=g(C,B.toBytes(),F.toBytes(),E);return B.add(F.multiplyUnsafe($)).subtract(H).clearCofactor().is0()}const I=s.BYTES,y={secretKey:I,publicKey:I,signature:2*I,seed:I};function A(v=a(y.seed)){return at(v,y.seed,"seed")}function N(v){const E=S.randomSecretKey(v);return{secretKey:E,publicKey:h(E)}}function k(v){return Io(v)&&v.length===i.BYTES}function T(v,E){try{return!!t.fromBytes(v,E)}catch{return!1}}const S={getExtendedPublicKey:f,randomSecretKey:A,isValidSecretKey:k,isValidPublicKey:T,toMontgomery(v){const{y:E}=t.fromBytes(v),_=y.publicKey,L=_===32;if(!L&&_!==57)throw new Error("only defined for 25519 and 448");const C=L?s.div(Ce+E,Ce-E):s.div(E-Ce,E+Ce);return s.toBytes(C)},toMontgomerySecret(v){const E=y.secretKey;at(v,E);const _=e(v.subarray(0,E));return c(_).subarray(0,E)},randomPrivateKey:A,precompute(v=8,E=t.BASE){return E.precompute(v,!1)}};return Object.freeze({keygen:N,getPublicKey:h,sign:m,verify:w,utils:S,Point:t,lengths:y})}function Fb(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=kn(e.n,t.nBitLength,!0),o={Fp:n,Fn:r,uvRatio:t.uvRatio},s={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:o,hash:t.hash,eddsaOpts:s}}function Mb(t,e){const n=e.Point;return Object.assign({},e,{ExtendedPoint:n,CURVE:t,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function jb(t){const{CURVE:e,curveOpts:n,hash:r,eddsaOpts:o}=Fb(t),s=Ob(e,n),i=Db(s,r,o);return Mb(t,i)}const Hb=BigInt(1),Td=BigInt(2);BigInt(3);const Ub=BigInt(5),$b=BigInt(8),ol=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Lh={p:ol,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:$b,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function qb(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=ol,a=t*t%s*t%s,c=pe(a,Td,s)*a%s,l=pe(c,Hb,s)*t%s,d=pe(l,Ub,s)*l%s,u=pe(d,e,s)*d%s,f=pe(u,n,s)*u%s,h=pe(f,r,s)*f%s,g=pe(h,o,s)*h%s,m=pe(g,o,s)*h%s,b=pe(m,e,s)*d%s;return{pow_p_5_8:pe(b,Td,s)*t%s,b2:a}}function Kb(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Pd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function zb(t,e){const n=ol,r=xe(e*e*e,n),o=xe(r*r*e,n),s=qb(t*o).pow_p_5_8;let i=xe(t*r*s,n);const a=xe(e*i*i,n),c=i,l=xe(i*Pd,n),d=a===t,u=a===xe(-t,n),f=a===xe(-t*Pd,n);return d&&(i=c),(u||f)&&(i=l),kb(i,n)&&(i=xe(-i,n)),{isValid:d||u,value:i}}const Gb=kn(Lh.p,{isLE:!0}),Wb={...Lh,Fp:Gb,hash:wb,adjustScalarBytes:Kb,uvRatio:zb},Is=jb(Wb);class Nd extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}}class Ld extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class Vb extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}const _t={get(t=globalThis){const e=t.crypto;if(e?.subtle==null)throw new Vb("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}},Rs=32,At=64,Za=32;let Jn;const Bh=(async()=>{try{return await _t.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Xb(){const t=Is.utils.randomPrivateKey(),e=Is.getPublicKey(t);return{privateKey:n0(t,e),publicKey:e}}async function Yb(t,e){let n;t.length===At?n=t.subarray(0,32):n=t;const r={crv:"Ed25519",kty:"OKP",x:te(t.subarray(32),"base64url"),d:te(n,"base64url"),ext:!0,key_ops:["sign"]},o=await _t.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),s=await _t.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function Zb(t,e){const n=t.subarray(0,Za);return Is.sign(e instanceof Uint8Array?e:e.subarray(),n)}async function Jb(t,e){return Jn==null&&(Jn=await Bh),Jn?Yb(t,e):Zb(t,e)}async function Qb(t,e,n){if(t.buffer instanceof ArrayBuffer){const r=await _t.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await _t.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 e0(t,e,n){return Is.verify(e,n instanceof Uint8Array?n:n.subarray(),t)}async function t0(t,e,n){return Jn==null&&(Jn=await Bh),Jn?Qb(t,e,n):e0(t,e,n)}function n0(t,e){const n=new Uint8Array(At);for(let r=0;r<Za;r++)n[r]=t[r],n[Za+r]=e[r];return n}function ci(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}class _h{type="Ed25519";raw;constructor(e){this.raw=po(e,Rs)}toMultihash(){return ko.digest(fi(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return He.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:dt(this.raw,e.raw)}verify(e,n,r){r?.signal?.throwIfAborted();const o=t0(this.raw,n,e);return ci(o)?o.then(s=>(r?.signal?.throwIfAborted(),s)):o}}class Ja{type="Ed25519";raw;publicKey;constructor(e,n){this.raw=po(e,At),this.publicKey=new _h(n)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:dt(this.raw,e.raw)}sign(e,n){n?.signal?.throwIfAborted();const r=Jb(this.raw,e);return ci(r)?r.then(o=>(n?.signal?.throwIfAborted(),o)):(n?.signal?.throwIfAborted(),r)}}function r0(t){if(t.length>At){t=po(t,At+Rs);const r=t.subarray(0,At),o=t.subarray(At,t.length);return new Ja(r,o)}t=po(t,At);const e=t.subarray(0,At),n=t.subarray(Rs);return new Ja(e,n)}function Oh(t){return t=po(t,Rs),new _h(t)}async function o0(){const{privateKey:t,publicKey:e}=Xb();return new Ja(t,e)}function po(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new lt(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}const s0=Math.pow(2,7),i0=Math.pow(2,14),a0=Math.pow(2,21),sl=Math.pow(2,28),il=Math.pow(2,35),al=Math.pow(2,42),cl=Math.pow(2,49),ie=128,Oe=127;function Cn(t){if(t<s0)return 1;if(t<i0)return 2;if(t<a0)return 3;if(t<sl)return 4;if(t<il)return 5;if(t<al)return 6;if(t<cl)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Dh(t,e,n=0){switch(Cn(t)){case 8:e[n++]=t&255|ie,t/=128;case 7:e[n++]=t&255|ie,t/=128;case 6:e[n++]=t&255|ie,t/=128;case 5:e[n++]=t&255|ie,t/=128;case 4:e[n++]=t&255|ie,t>>>=7;case 3:e[n++]=t&255|ie,t>>>=7;case 2:e[n++]=t&255|ie,t>>>=7;case 1:{e[n++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function c0(t,e,n=0){switch(Cn(t)){case 8:e.set(n++,t&255|ie),t/=128;case 7:e.set(n++,t&255|ie),t/=128;case 6:e.set(n++,t&255|ie),t/=128;case 5:e.set(n++,t&255|ie),t/=128;case 4:e.set(n++,t&255|ie),t>>>=7;case 3:e.set(n++,t&255|ie),t>>>=7;case 2:e.set(n++,t&255|ie),t>>>=7;case 1:{e.set(n++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function Fh(t,e){let n=t[e],r=0;if(r+=n&Oe,n<ie||(n=t[e+1],r+=(n&Oe)<<7,n<ie)||(n=t[e+2],r+=(n&Oe)<<14,n<ie)||(n=t[e+3],r+=(n&Oe)<<21,n<ie)||(n=t[e+4],r+=(n&Oe)*sl,n<ie)||(n=t[e+5],r+=(n&Oe)*il,n<ie)||(n=t[e+6],r+=(n&Oe)*al,n<ie)||(n=t[e+7],r+=(n&Oe)*cl,n<ie))return r;throw new RangeError("Could not decode varint")}function l0(t,e){let n=t.get(e),r=0;if(r+=n&Oe,n<ie||(n=t.get(e+1),r+=(n&Oe)<<7,n<ie)||(n=t.get(e+2),r+=(n&Oe)<<14,n<ie)||(n=t.get(e+3),r+=(n&Oe)<<21,n<ie)||(n=t.get(e+4),r+=(n&Oe)*sl,n<ie)||(n=t.get(e+5),r+=(n&Oe)*il,n<ie)||(n=t.get(e+6),r+=(n&Oe)*al,n<ie)||(n=t.get(e+7),r+=(n&Oe)*cl,n<ie))return r;throw new RangeError("Could not decode varint")}function d0(t,e,n=0){return e==null&&(e=Bt(Cn(t))),e instanceof Uint8Array?Dh(t,e,n):c0(t,e,n)}function Mh(t,e=0){return t instanceof Uint8Array?Fh(t,e):l0(t,e)}const ll=new Float32Array([-0]),Zt=new Uint8Array(ll.buffer);function u0(t,e,n){ll[0]=t,e[n]=Zt[0],e[n+1]=Zt[1],e[n+2]=Zt[2],e[n+3]=Zt[3]}function f0(t,e){return Zt[0]=t[e],Zt[1]=t[e+1],Zt[2]=t[e+2],Zt[3]=t[e+3],ll[0]}const dl=new Float64Array([-0]),De=new Uint8Array(dl.buffer);function h0(t,e,n){dl[0]=t,e[n]=De[0],e[n+1]=De[1],e[n+2]=De[2],e[n+3]=De[3],e[n+4]=De[4],e[n+5]=De[5],e[n+6]=De[6],e[n+7]=De[7]}function p0(t,e){return De[0]=t[e],De[1]=t[e+1],De[2]=t[e+2],De[3]=t[e+3],De[4]=t[e+4],De[5]=t[e+5],De[6]=t[e+6],De[7]=t[e+7],dl[0]}const g0=BigInt(Number.MAX_SAFE_INTEGER),m0=BigInt(Number.MIN_SAFE_INTEGER);class Fe{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 pn;if(e<g0&&e>m0)return this.fromNumber(Number(e));const n=e<0n;n&&(e=-e);let r=e>>32n,o=e-(r<<32n);return n&&(r=~r|0n,o=~o|0n,++o>Bd&&(o=0n,++r>Bd&&(r=0n))),new Fe(Number(o),Number(r))}static fromNumber(e){if(e===0)return pn;const n=e<0;n&&(e=-e);let r=e>>>0,o=(e-r)/4294967296>>>0;return n&&(o=~o>>>0,r=~r>>>0,++r>4294967295&&(r=0,++o>4294967295&&(o=0))),new Fe(r,o)}static from(e){return typeof e=="number"?Fe.fromNumber(e):typeof e=="bigint"?Fe.fromBigInt(e):typeof e=="string"?Fe.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new Fe(e.low>>>0,e.high>>>0):pn}}const pn=new Fe(0,0);pn.toBigInt=function(){return 0n};pn.zzEncode=pn.zzDecode=function(){return this};pn.length=function(){return 1};const Bd=4294967296n;function w0(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 y0(t,e,n){if(n-e<1)return"";let o;const s=[];let i=0,a;for(;e<n;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function jh(t,e,n){const r=n;let o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[n++]=o:o<2048?(e[n++]=o>>6|192,e[n++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[n++]=o>>18|240,e[n++]=o>>12&63|128,e[n++]=o>>6&63|128,e[n++]=o&63|128):(e[n++]=o>>12|224,e[n++]=o>>6&63|128,e[n++]=o&63|128);return n-r}function ot(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function jo(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}class b0{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,ot(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 ot(this,4);return jo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ot(this,4);return jo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ot(this,4);const e=f0(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ot(this,4);const e=p0(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 ot(this,e);return this.pos+=e,n===r?new Uint8Array(0):this.buf.subarray(n,r)}string(){const e=this.bytes();return y0(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ot(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ot(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 Fe(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 ot(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 ot(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 ot(this,8);const e=jo(this.buf,this.pos+=4),n=jo(this.buf,this.pos+=4);return new Fe(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=Fh(this.buf,this.pos);return this.pos+=Cn(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 v0(t){return new b0(t instanceof Uint8Array?t:t.subarray())}function li(t,e,n){const r=v0(t);return e.decode(r,void 0,n)}function S0(t){let r,o=8192;return function(i){if(i<1||i>4096)return Bt(i);o+i>8192&&(r=Bt(8192),o=0);const a=r.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}class Yr{fn;len;next;val;constructor(e,n,r){this.fn=e,this.len=n,this.next=void 0,this.val=r}}function qi(){}class x0{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const E0=S0();function A0(t){return globalThis.Buffer!=null?Bt(t):E0(t)}class Qa{len;head;tail;states;constructor(){this.len=0,this.head=new Yr(qi,0,0),this.tail=this.head,this.states=null}_push(e,n,r){return this.tail=this.tail.next=new Yr(e,n,r),this.len+=n,this}uint32(e){return this.len+=(this.tail=this.tail.next=new C0((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(Ho,10,Fe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const n=Fe.fromBigInt(e);return this._push(Ho,n.length(),n)}uint64Number(e){return this._push(Dh,Cn(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=Fe.fromBigInt(e).zzEncode();return this._push(Ho,n.length(),n)}sint64Number(e){const n=Fe.fromNumber(e).zzEncode();return this._push(Ho,n.length(),n)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ki,1,e?1:0)}fixed32(e){return this._push(Nr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const n=Fe.fromBigInt(e);return this._push(Nr,4,n.lo)._push(Nr,4,n.hi)}fixed64Number(e){const n=Fe.fromNumber(e);return this._push(Nr,4,n.lo)._push(Nr,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(u0,4,e)}double(e){return this._push(h0,8,e)}bytes(e){const n=e.length>>>0;return n===0?this._push(Ki,1,0):this.uint32(n)._push(I0,n,e)}string(e){const n=w0(e);return n!==0?this.uint32(n)._push(jh,n,e):this._push(Ki,1,0)}fork(){return this.states=new x0(this),this.head=this.tail=new Yr(qi,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 Yr(qi,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=A0(this.len);let r=0;for(;e!=null;)e.fn(e.val,n,r),r+=e.len,e=e.next;return n}}function Ki(t,e,n){e[n]=t&255}function k0(t,e,n){for(;t>127;)e[n++]=t&127|128,t>>>=7;e[n]=t}class C0 extends Yr{next;constructor(e,n){super(k0,e,n),this.next=void 0}}function Ho(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 Nr(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 I0(t,e,n){e.set(t,n)}globalThis.Buffer!=null&&(Qa.prototype.bytes=function(t){const e=t.length>>>0;return this.uint32(e),e>0&&this._push(R0,e,t),this},Qa.prototype.string=function(t){const e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(T0,e,t),this});function R0(t,e,n){e.set(t,n)}function T0(t,e,n){t.length<40?jh(t,e,n):e.utf8Write!=null?e.utf8Write(t,n):e.set(Se(t),n)}function P0(){return new Qa}function di(t,e){const n=P0();return e.encode(t,n,{lengthDelimited:!1}),n.finish()}var Ts;(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"})(Ts||(Ts={}));function Hh(t,e,n,r){return{name:t,type:e,encode:n,decode:r}}function N0(t){function e(o){if(t[o.toString()]==null)throw new Error("Invalid enum value");return t[o]}const n=function(s,i){const a=e(s);i.int32(a)},r=function(s){const i=s.int32();return e(i)};return Hh("enum",Ts.VARINT,n,r)}function ui(t,e){return Hh("message",Ts.LENGTH_DELIMITED,t,e)}class _d extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var fe;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(fe||(fe={}));var ec;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(ec||(ec={}));(function(t){t.codec=()=>N0(ec)})(fe||(fe={}));var vn;(function(t){let e;t.codec=()=>(e==null&&(e=ui((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),fe.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(n);break}case 2:{s.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>di(n,t.codec()),t.decode=(n,r)=>li(n,t.codec(),r)})(vn||(vn={}));var Ps;(function(t){let e;t.codec=()=>(e==null&&(e=ui((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),fe.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{s.Type=fe.codec().decode(n);break}case 2:{s.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>di(n,t.codec()),t.decode=(n,r)=>li(n,t.codec(),r)})(Ps||(Ps={}));const Uh=fh;class $h{type="RSA";jwk;_raw;_multihash;constructor(e,n){this.jwk=e,this._multihash=n}get raw(){return this._raw==null&&(this._raw=Kh(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ue.createV1(114,this._multihash)}toString(){return He.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:dt(this.raw,e.raw)}verify(e,n,r){return G0(this.jwk,n,e,r)}}class L0{type="RSA";jwk;_raw;publicKey;constructor(e,n){this.jwk=e,this.publicKey=n}get raw(){return this._raw==null&&(this._raw=F0(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:dt(this.raw,e.raw)}sign(e,n){return z0(this.jwk,e,n)}}const B0=8192,qh=18,_0=1062,O0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function D0(t){return{n:te(t[1],"base64url"),e:te(t[2],"base64url"),d:te(t[3],"base64url"),p:te(t[4],"base64url"),q:te(t[5],"base64url"),dp:te(t[6],"base64url"),dq:te(t[7],"base64url"),qi:te(t[8],"base64url"),kty:"RSA"}}function F0(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 lt("JWK was missing components");return Pt([Xe(Uint8Array.from([0])),Xe(Se(t.n,"base64url")),Xe(Se(t.e,"base64url")),Xe(Se(t.d,"base64url")),Xe(Se(t.p,"base64url")),Xe(Se(t.q,"base64url")),Xe(Se(t.dp,"base64url")),Xe(Se(t.dq,"base64url")),Xe(Se(t.qi,"base64url"))]).subarray()}function M0(t){const e=br(t[1],{offset:0});return{kty:"RSA",n:te(e[0],"base64url"),e:te(e[1],"base64url")}}function Kh(t){if(t.n==null||t.e==null)throw new lt("JWK was missing components");return Pt([O0,Jc(Pt([Xe(Se(t.n,"base64url")),Xe(Se(t.e,"base64url"))]))]).subarray()}function j0(t){const e=br(t);return H0(e)}function H0(t){const e=D0(t);return q0(e)}function U0(t,e){if(t.byteLength>=_0)throw new qf("Key size is too large");const n=br(t,{offset:0});return $0(n,t,e)}function $0(t,e,n){const r=M0(t);if(n==null){const o=Uh(vn.encode({Type:fe.RSA,Data:e}));n=Ao(qh,o)}return new $h(r,n)}function q0(t){if(W0(t)>B0)throw new lt("Key size is too large");const e=K0(t),n=Uh(vn.encode({Type:fe.RSA,Data:Kh(e.publicKey)})),r=Ao(qh,n);return new L0(e.privateKey,new $h(e.publicKey,r))}function K0(t){if(t==null)throw new lt("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function z0(t,e,n){const r=await _t.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);n?.signal?.throwIfAborted();const o=await _t.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,e instanceof Uint8Array?e:e.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function G0(t,e,n,r){const o=await _t.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const s=await _t.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,n instanceof Uint8Array?n:n.subarray());return r?.signal?.throwIfAborted(),s}function W0(t){if(t.kty!=="RSA")throw new lt("invalid key type");if(t.n==null)throw new lt("invalid key modulus");return Se(t.n,"base64url").length*8}class zh extends ch{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,ih(e);const r=Qc(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const o=this.blockLen,s=new Uint8Array(o);s.set(r.length>o?e.create().update(r).digest():r);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),dr(s)}update(e){return Es(this),this.iHash.update(e),this}digestInto(e){Es(this),An(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Gh=(t,e,n)=>new zh(t,e).update(n).digest();Gh.create=(t,e)=>new zh(t,e);const Od=(t,e)=>(t+(t>=0?e:-e)/Wh)/e;function V0(t,e,n){const[[r,o],[s,i]]=e,a=Od(i*t,n),c=Od(-o*t,n);let l=t-a*r-c*s,d=-a*o-c*i;const u=l<It,f=d<It;u&&(l=-l),f&&(d=-d);const h=Ro(Math.ceil(gh(n)/2))+Qn;if(l<It||l>=h||d<It||d>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:f,k2:d}}function tc(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function zi(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return bn(n.lowS,"lowS"),bn(n.prehash,"prehash"),n.format!==void 0&&tc(n.format),n}class X0 extends Error{constructor(e=""){super(e)}}const kt={Err:X0,_tlv:{encode:(t,e)=>{const{Err:n}=kt;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,o=Mo(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Mo(o.length/2|128):"";return Mo(t)+s+o+e},decode(t,e){const{Err:n}=kt;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const o=e[r++],s=!!(o&128);let i=0;if(!s)i=o;else{const c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(r+=c,i<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+i);if(a.length!==i)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+i)}}},_int:{encode(t){const{Err:e}=kt;if(t<It)throw new e("integer: negative integers are not allowed");let n=Mo(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}=kt;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 ai(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=kt,o=ge("signature",t),{v:s,l:i}=r.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:l,l:d}=r.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){const{_tlv:e,_int:n}=kt,r=e.encode(2,n.encode(t.r)),o=e.encode(2,n.encode(t.s)),s=r+o;return e.encode(48,s)}},It=BigInt(0),Qn=BigInt(1),Wh=BigInt(2),Uo=BigInt(3),Y0=BigInt(4);function zn(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let o=ge("private key",e);try{r=t.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function Z0(t,e={}){const n=Nh("weierstrass",t,e),{Fp:r,Fn:o}=n;let s=n.CURVE;const{h:i,n:a}=s;To(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Xh(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(L,C,x){const{x:P,y:R}=C.toAffine(),D=r.toBytes(P);if(bn(x,"isCompressed"),x){d();const M=!r.isOdd(R);return mt(Vh(M),D)}else return mt(Uint8Array.of(4),D,r.toBytes(R))}function f(L){at(L,void 0,"Point");const{publicKey:C,publicKeyUncompressed:x}=l,P=L.length,R=L[0],D=L.subarray(1);if(P===C&&(R===2||R===3)){const M=r.fromBytes(D);if(!r.isValid(M))throw new Error("bad point: is not on curve, wrong x");const F=m(M);let B;try{B=r.sqrt(F)}catch(X){const Y=X instanceof Error?": "+X.message:"";throw new Error("bad point: is not on curve, sqrt error"+Y)}d();const H=r.isOdd(B);return(R&1)===1!==H&&(B=r.neg(B)),{x:M,y:B}}else if(P===x&&R===4){const M=r.BYTES,F=r.fromBytes(D.subarray(0,M)),B=r.fromBytes(D.subarray(M,M*2));if(!b(F,B))throw new Error("bad point: is not on curve");return{x:F,y:B}}else throw new Error(`bad point: got length ${P}, expected compressed=${C} or uncompressed=${x}`)}const h=e.toBytes||u,g=e.fromBytes||f;function m(L){const C=r.sqr(L),x=r.mul(C,L);return r.add(r.add(x,r.mul(L,s.a)),s.b)}function b(L,C){const x=r.sqr(C),P=m(L);return r.eql(x,P)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const w=r.mul(r.pow(s.a,Uo),Y0),I=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(w,I)))throw new Error("bad curve params: a or b");function y(L,C,x=!1){if(!r.isValid(C)||x&&r.is0(C))throw new Error(`bad point coordinate ${L}`);return C}function A(L){if(!(L instanceof v))throw new Error("ProjectivePoint expected")}function N(L){if(!c||!c.basises)throw new Error("no endo");return V0(L,c.basises,o.ORDER)}const k=ks((L,C)=>{const{X:x,Y:P,Z:R}=L;if(r.eql(R,r.ONE))return{x,y:P};const D=L.is0();C==null&&(C=D?r.ONE:r.inv(R));const M=r.mul(x,C),F=r.mul(P,C),B=r.mul(R,C);if(D)return{x:r.ZERO,y:r.ZERO};if(!r.eql(B,r.ONE))throw new Error("invZ was invalid");return{x:M,y:F}}),T=ks(L=>{if(L.is0()){if(e.allowInfinityPoint&&!r.is0(L.Y))return;throw new Error("bad point: ZERO")}const{x:C,y:x}=L.toAffine();if(!r.isValid(C)||!r.isValid(x))throw new Error("bad point: x or y not field elements");if(!b(C,x))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(L,C,x,P,R){return x=new v(r.mul(x.X,L),x.Y,x.Z),C=Cs(P,C),x=Cs(R,x),C.add(x)}class v{constructor(C,x,P){this.X=y("x",C),this.Y=y("y",x,!0),this.Z=y("z",P),Object.freeze(this)}static CURVE(){return s}static fromAffine(C){const{x,y:P}=C||{};if(!C||!r.isValid(x)||!r.isValid(P))throw new Error("invalid affine point");if(C instanceof v)throw new Error("projective point not allowed");return r.is0(x)&&r.is0(P)?v.ZERO:new v(x,P,r.ONE)}static fromBytes(C){const x=v.fromAffine(g(at(C,void 0,"point")));return x.assertValidity(),x}static fromHex(C){return v.fromBytes(ge("pointHex",C))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(C=8,x=!0){return _.createCache(this,C),x||this.multiply(Uo),this}assertValidity(){T(this)}hasEvenY(){const{y:C}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(C)}equals(C){A(C);const{X:x,Y:P,Z:R}=this,{X:D,Y:M,Z:F}=C,B=r.eql(r.mul(x,F),r.mul(D,R)),H=r.eql(r.mul(P,F),r.mul(M,R));return B&&H}negate(){return new v(this.X,r.neg(this.Y),this.Z)}double(){const{a:C,b:x}=s,P=r.mul(x,Uo),{X:R,Y:D,Z:M}=this;let F=r.ZERO,B=r.ZERO,H=r.ZERO,$=r.mul(R,R),X=r.mul(D,D),Y=r.mul(M,M),U=r.mul(R,D);return U=r.add(U,U),H=r.mul(R,M),H=r.add(H,H),F=r.mul(C,H),B=r.mul(P,Y),B=r.add(F,B),F=r.sub(X,B),B=r.add(X,B),B=r.mul(F,B),F=r.mul(U,F),H=r.mul(P,H),Y=r.mul(C,Y),U=r.sub($,Y),U=r.mul(C,U),U=r.add(U,H),H=r.add($,$),$=r.add(H,$),$=r.add($,Y),$=r.mul($,U),B=r.add(B,$),Y=r.mul(D,M),Y=r.add(Y,Y),$=r.mul(Y,U),F=r.sub(F,$),H=r.mul(Y,X),H=r.add(H,H),H=r.add(H,H),new v(F,B,H)}add(C){A(C);const{X:x,Y:P,Z:R}=this,{X:D,Y:M,Z:F}=C;let B=r.ZERO,H=r.ZERO,$=r.ZERO;const X=s.a,Y=r.mul(s.b,Uo);let U=r.mul(x,D),K=r.mul(P,M),q=r.mul(R,F),G=r.add(x,P),z=r.add(D,M);G=r.mul(G,z),z=r.add(U,K),G=r.sub(G,z),z=r.add(x,R);let V=r.add(D,F);return z=r.mul(z,V),V=r.add(U,q),z=r.sub(z,V),V=r.add(P,R),B=r.add(M,F),V=r.mul(V,B),B=r.add(K,q),V=r.sub(V,B),$=r.mul(X,z),B=r.mul(Y,q),$=r.add(B,$),B=r.sub(K,$),$=r.add(K,$),H=r.mul(B,$),K=r.add(U,U),K=r.add(K,U),q=r.mul(X,q),z=r.mul(Y,z),K=r.add(K,q),q=r.sub(U,q),q=r.mul(X,q),z=r.add(z,q),U=r.mul(K,z),H=r.add(H,U),U=r.mul(V,z),B=r.mul(G,B),B=r.sub(B,U),U=r.mul(G,K),$=r.mul(V,$),$=r.add($,U),new v(B,H,$)}subtract(C){return this.add(C.negate())}is0(){return this.equals(v.ZERO)}multiply(C){const{endo:x}=e;if(!o.isValidNot0(C))throw new Error("invalid scalar: out of range");let P,R;const D=M=>_.cached(this,M,F=>ln(v,F));if(x){const{k1neg:M,k1:F,k2neg:B,k2:H}=N(C),{p:$,f:X}=D(F),{p:Y,f:U}=D(H);R=X.add(U),P=S(x.beta,$,Y,M,B)}else{const{p:M,f:F}=D(C);P=M,R=F}return ln(v,[P,R])[0]}multiplyUnsafe(C){const{endo:x}=e,P=this;if(!o.isValid(C))throw new Error("invalid scalar: out of range");if(C===It||P.is0())return v.ZERO;if(C===Qn)return P;if(_.hasCache(this))return this.multiply(C);if(x){const{k1neg:R,k1:D,k2neg:M,k2:F}=N(C),{p1:B,p2:H}=Lb(v,P,D,F);return S(x.beta,B,H,R,M)}else return _.unsafe(P,C)}multiplyAndAddUnsafe(C,x,P){const R=this.multiplyUnsafe(x).add(C.multiplyUnsafe(P));return R.is0()?void 0:R}toAffine(C){return k(this,C)}isTorsionFree(){const{isTorsionFree:C}=e;return i===Qn?!0:C?C(v,this):_.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:C}=e;return i===Qn?this:C?C(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(C=!0){return bn(C,"isCompressed"),this.assertValidity(),h(v,this,C)}toHex(C=!0){return hn(this.toBytes(C))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(C=!0){return this.toBytes(C)}_setWindowSize(C){this.precompute(C)}static normalizeZ(C){return ln(v,C)}static msm(C,x){return Ph(v,o,C,x)}static fromPrivateKey(C){return v.BASE.multiply(zn(o,C))}}v.BASE=new v(s.Gx,s.Gy,r.ONE),v.ZERO=new v(r.ZERO,r.ONE,r.ZERO),v.Fp=r,v.Fn=o;const E=o.BITS,_=new Th(v,e.endo?Math.ceil(E/2):E);return v.BASE.precompute(8),v}function Vh(t){return Uint8Array.of(t?2:3)}function Xh(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function J0(t,e={}){const{Fn:n}=t,r=e.randomBytes||el,o=Object.assign(Xh(t.Fp,n),{seed:Ch(n.ORDER)});function s(h){try{return!!zn(n,h)}catch{return!1}}function i(h,g){const{publicKey:m,publicKeyUncompressed:b}=o;try{const w=h.length;return g===!0&&w!==m||g===!1&&w!==b?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=r(o.seed)){return Tb(at(h,o.seed,"seed"),n.ORDER)}function c(h,g=!0){return t.BASE.multiply(zn(n,h)).toBytes(g)}function l(h){const g=a(h);return{secretKey:g,publicKey:c(g)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:g,publicKey:m,publicKeyUncompressed:b}=o;if(n.allowedLengths||g===m)return;const w=ge("key",h).length;return w===m||w===b}function u(h,g,m=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(g)===!1)throw new Error("second arg must be public key");const b=zn(n,h);return t.fromHex(g).multiply(b).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>zn(n,h),precompute(h=8,g=t.BASE){return g.precompute(h,!1)}},lengths:o})}function Q0(t,e,n={}){ih(e),To(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||el,o=n.hmac||((x,...P)=>Gh(e,x,mt(...P))),{Fp:s,Fn:i}=t,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h}=J0(t,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function b(x){const P=a>>Qn;return x>P}function w(x,P){if(!i.isValidNot0(P))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return P}function I(x,P){tc(P);const R=h.signature,D=P==="compact"?R:P==="recovered"?R+1:void 0;return at(x,D,`${P} signature`)}class y{constructor(P,R,D){this.r=w("r",P),this.s=w("s",R),D!=null&&(this.recovery=D),Object.freeze(this)}static fromBytes(P,R=m){I(P,R);let D;if(R==="der"){const{r:H,s:$}=kt.toSig(at(P));return new y(H,$)}R==="recovered"&&(D=P[0],R="compact",P=P.subarray(1));const M=i.BYTES,F=P.subarray(0,M),B=P.subarray(M,M*2);return new y(i.fromBytes(F),i.fromBytes(B),D)}static fromHex(P,R){return this.fromBytes(As(P),R)}addRecoveryBit(P){return new y(this.r,this.s,P)}recoverPublicKey(P){const R=s.ORDER,{r:D,s:M,recovery:F}=this;if(F==null||![0,1,2,3].includes(F))throw new Error("recovery id invalid");if(a*Wh<R&&F>1)throw new Error("recovery id is ambiguous for h>1 curve");const H=F===2||F===3?D+a:D;if(!s.isValid(H))throw new Error("recovery id 2 or 3 invalid");const $=s.toBytes(H),X=t.fromBytes(mt(Vh((F&1)===0),$)),Y=i.inv(H),U=N(ge("msgHash",P)),K=i.create(-U*Y),q=i.create(M*Y),G=t.BASE.multiplyUnsafe(K).add(X.multiplyUnsafe(q));if(G.is0())throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return b(this.s)}toBytes(P=m){if(tc(P),P==="der")return As(kt.hexFromSig(this));const R=i.toBytes(this.r),D=i.toBytes(this.s);if(P==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return mt(Uint8Array.of(this.recovery),R,D)}return mt(R,D)}toHex(P){return hn(this.toBytes(P))}assertValidity(){}static fromCompact(P){return y.fromBytes(ge("sig",P),"compact")}static fromDER(P){return y.fromBytes(ge("sig",P),"der")}normalizeS(){return this.hasHighS()?new y(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return hn(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return hn(this.toBytes("compact"))}}const A=n.bits2int||function(P){if(P.length>8192)throw new Error("input is too large");const R=ai(P),D=P.length*8-c;return D>0?R>>BigInt(D):R},N=n.bits2int_modN||function(P){return i.create(A(P))},k=Ro(c);function T(x){return Ya("num < 2^"+c,x,It,k),i.toBytes(x)}function S(x,P){return at(x,void 0,"message"),P?at(e(x),void 0,"prehashed message"):x}function v(x,P,R){if(["recovered","canonical"].some(K=>K in R))throw new Error("sign() legacy options not supported");const{lowS:D,prehash:M,extraEntropy:F}=zi(R,g);x=S(x,M);const B=N(x),H=zn(i,P),$=[T(H),T(B)];if(F!=null&&F!==!1){const K=F===!0?r(h.secretKey):F;$.push(ge("extraEntropy",K))}const X=mt(...$),Y=B;function U(K){const q=A(K);if(!i.isValidNot0(q))return;const G=i.inv(q),z=t.BASE.multiply(q).toAffine(),V=i.create(z.x);if(V===It)return;const J=i.create(G*i.create(Y+V*H));if(J===It)return;let oe=(z.x===V?0:2)|Number(z.y&Qn),ne=J;return D&&b(J)&&(ne=i.neg(J),oe^=1),new y(V,ne,oe)}return{seed:X,k2sig:U}}function E(x,P,R={}){x=ge("message",x);const{seed:D,k2sig:M}=v(x,P,R);return bb(e.outputLen,i.BYTES,o)(D,M)}function _(x){let P;const R=typeof x=="string"||Io(x),D=!R&&x!==null&&typeof x=="object"&&typeof x.r=="bigint"&&typeof x.s=="bigint";if(!R&&!D)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(D)P=new y(x.r,x.s);else if(R){try{P=y.fromBytes(ge("sig",x),"der")}catch(M){if(!(M instanceof kt.Err))throw M}if(!P)try{P=y.fromBytes(ge("sig",x),"compact")}catch{return!1}}return P||!1}function L(x,P,R,D={}){const{lowS:M,prehash:F,format:B}=zi(D,g);if(R=ge("publicKey",R),P=S(ge("message",P),F),"strict"in D)throw new Error("options.strict was renamed to lowS");const H=B===void 0?_(x):y.fromBytes(ge("sig",x),B);if(H===!1)return!1;try{const $=t.fromBytes(R);if(M&&H.hasHighS())return!1;const{r:X,s:Y}=H,U=N(P),K=i.inv(Y),q=i.create(U*K),G=i.create(X*K),z=t.BASE.multiplyUnsafe(q).add($.multiplyUnsafe(G));return z.is0()?!1:i.create(z.x)===X}catch{return!1}}function C(x,P,R={}){const{prehash:D}=zi(R,g);return P=S(P,D),y.fromBytes(x,"recovered").recoverPublicKey(P).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h,Point:t,sign:E,verify:L,recoverPublicKey:C,Signature:y,hash:e})}function ev(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp;let r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0;const o=kn(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),s={Fp:n,Fn:o,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function tv(t){const{CURVE:e,curveOpts:n}=ev(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 nv(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,Ah(n.Fn.ORDER,n.Fn.BITS))})}function rv(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:o}=tv(t),s=Z0(e,n),i=Q0(s,r,o);return nv(t,i)}function ov(t,e){const n=r=>rv({...t,hash:r});return{...n(e),create:n}}const ul={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},sv={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Dd=BigInt(2);function iv(t){const e=ul.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,u=pe(d,n,e)*d%e,f=pe(u,n,e)*d%e,h=pe(f,Dd,e)*l%e,g=pe(h,o,e)*h%e,m=pe(g,s,e)*g%e,b=pe(m,a,e)*m%e,w=pe(b,c,e)*b%e,I=pe(w,a,e)*m%e,y=pe(I,n,e)*d%e,A=pe(y,i,e)*g%e,N=pe(A,r,e)*l%e,k=pe(N,Dd,e);if(!nc.eql(nc.sqr(k),t))throw new Error("Cannot find square root");return k}const nc=kn(ul.p,{sqrt:iv}),Qt=ov({...ul,Fp:nc,lowS:!0,endo:sv},fh);function av(t,e,n){const r=Zc.digest(e instanceof Uint8Array?e:e.subarray());if(ci(r))return r.then(({digest:o})=>(n?.signal?.throwIfAborted(),Qt.sign(o,t).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new Nd(String(o))});try{return Qt.sign(r.digest,t).toDERRawBytes()}catch(o){throw new Nd(String(o))}}function cv(t,e,n,r){const o=Zc.digest(n instanceof Uint8Array?n:n.subarray());if(ci(o))return o.then(({digest:s})=>(r?.signal?.throwIfAborted(),Qt.verify(e,s,t))).catch(s=>{throw s.name==="AbortError"?s:new Ld(String(s))});try{return r?.signal?.throwIfAborted(),Qt.verify(e,o.digest,t)}catch(s){throw new Ld(String(s))}}class Yh{type="secp256k1";raw;_key;constructor(e){this._key=hv(e),this.raw=uv(this._key)}toMultihash(){return ko.digest(fi(this))}toCID(){return ue.createV1(114,this.toMultihash())}toString(){return He.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:dt(this.raw,e.raw)}verify(e,n,r){return cv(this._key,n,e,r)}}class lv{type="secp256k1";raw;publicKey;constructor(e,n){this.raw=fv(e),this.publicKey=new Yh(n??pv(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:dt(this.raw,e.raw)}sign(e,n){return av(this.raw,e,n)}}function dv(t){return new lv(t)}function Zh(t){return new Yh(t)}function uv(t){return Qt.ProjectivePoint.fromHex(t).toRawBytes(!0)}function fv(t){try{return Qt.getPublicKey(t,!0),t}catch(e){throw new Kf(String(e))}}function hv(t){try{return Qt.ProjectivePoint.fromHex(t),t}catch(e){throw new qf(String(e))}}function pv(t){try{return Qt.getPublicKey(t,!0)}catch(e){throw new Kf(String(e))}}async function gv(t,e){return o0()}function rc(t,e){const{Type:n,Data:r}=vn.decode(t),o=r??new Uint8Array;switch(n){case fe.RSA:return U0(o,e);case fe.Ed25519:return Oh(o);case fe.secp256k1:return Zh(o);case fe.ECDSA:return oh(o);default:throw new ri}}function mv(t){const{Type:e,Data:n}=vn.decode(t.digest),r=n??new Uint8Array;switch(e){case fe.Ed25519:return Oh(r);case fe.secp256k1:return Zh(r);case fe.ECDSA:return oh(r);default:throw new ri}}function fi(t){return vn.encode({Type:fe[t.type],Data:t.raw})}function wv(t){const e=Ps.decode(t),n=e.Data??new Uint8Array;switch(e.Type){case fe.RSA:return j0(n);case fe.Ed25519:return r0(n);case fe.secp256k1:return dv(n);case fe.ECDSA:return Wy(n);default:throw new ri}}function yv(t){return Ps.encode({Type:fe[t.type],Data:t.raw})}const Jh=Symbol.for("nodejs.util.inspect.custom"),bv=114;class fl{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()})`}[zf]=!0;toString(){return this.string==null&&(this.string=He.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ue.createV1(bv,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return dt(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return dt(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Jh](){return`PeerId(${this.toString()})`}}class Qh extends fl{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class ep extends fl{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class tp extends fl{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}const vv=2336;class np{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ko.digest(Se(this.url))}[Jh](){return`PeerId(${this.url})`}[zf]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ue.createV1(vv,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=te(e)),e.toString()===this.toString())}}const Sv=114,Fd=2336;function xv(t,e){let n;if(t.charAt(0)==="1"||t.charAt(0)==="Q")n=Vf(He.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return Ev(ue.parse(t));throw new lt('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return rp(n)}function fr(t){if(t.type==="Ed25519")return new ep({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new tp({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new Qh({multihash:t.toCID().multihash,publicKey:t});throw new ri}function rp(t){if(kv(t))return new Qh({multihash:t});if(Av(t))try{const e=mv(t);if(e.type==="Ed25519")return new ep({multihash:t,publicKey:e});if(e.type==="secp256k1")return new tp({multihash:t,publicKey:e})}catch{const n=te(t.digest);return new np(new URL(n))}throw new sw("Supplied PeerID Multihash is invalid")}function Ev(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==Sv&&t.code!==Fd)throw new ow("Supplied PeerID CID is invalid");if(t.code===Fd){const e=te(t.multihash.digest);return new np(new URL(e))}return rp(t.multihash)}function Av(t){return t.code===ko.code}function kv(t){return t.code===Zc.code}class op extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class Cv extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class Lr extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class Md extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}}class Iv extends Event{data;constructor(e,n){super("message",n),this.data=e}}class hl extends Event{error;local;constructor(e,n,r){super("close",r),this.error=n,this.local=e}}class Rv extends hl{constructor(e,n){super(!0,e,n)}}class Tv extends hl{constructor(e,n){super(!1,e,n)}}const Pv=t=>t/2**32|0,Nv=t=>t>>>0;function Lv(t,e,n,r){const o=Pv(n),s=Nv(n);t.setUint32(e,r?s:o,r),t.setUint32(e+4,r?o:s,r)}function oc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const sc=t=>t?`"${t}" `:"";function Ot(t,e=""){if(typeof t!="number")throw new TypeError(sc(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(sc(e)+"expected integer >= 0, got "+t);return t}function Dt(t,e,n=""){if(oc(t)&&(e===void 0||t.length===e))return t;e!==void 0&&Ot(e,"length");const r=oc(t),o=e!==void 0?` of length ${e}`:"",s=r?`length=${t.length}`:`type=${typeof t}`,i=sc(n)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}function pl(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Ot(t.outputLen),Ot(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}const Bv=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)},jd=(t,e)=>{Bv(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 Ns(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function sp(t,e){Dt(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function LR(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function gn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Gi(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function ht(t,e){return t<<32-e|t>>>e}function BR(t,e){return t<<e|t>>>32-e>>>0}const _v=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Ov(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Dv(t){for(let e=0;e<t.length;e++)t[e]=Ov(t[e]);return t}const _R=_v?t=>t:Dv,ip=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Fv=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function gl(t){if(Dt(t),ip)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Fv[t[n]];return e}function Hd(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function ap(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(ip)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}const e=t.length,n=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let o=0,s=0;o<n;o++,s+=2){const i=Hd(t.charCodeAt(s)),a=Hd(t.charCodeAt(s+1));if(i===void 0||a===void 0){const c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}r[o]=i*16+a}return r}function Mv(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 OR(t,e,n,r){if(Ot(t,"iters"),Ot(e,"tick"),typeof n!="function")throw new TypeError("callback must be a function");let o=Date.now();for(let s=0;s<t;s++){n(s);const i=Date.now()-o;i>=0&&i<e||(await Mv(r),o=Date.now())}}function jv(t){if(typeof t!="string")throw new TypeError("string expected");const e=new TextEncoder().encode(t);try{return new Uint8Array(e)}finally{gn(e)}}function DR(t,e=""){return typeof t=="string"?jv(t):Dt(t,void 0,e)}function Hv(t,e,n="opts"){return jd(t,"defaults"),e!==void 0&&jd(e,n),Object.assign(Object.create(null),t,e)}function Uv(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=Hv({},e,"info");const n=(o,s)=>t(s).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function $v(t=32){Ot(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 qv=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Kv(t,e,n){return t&e^~t&n}function zv(t,e,n){return t&e^t&n^e&n}class Gv{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,n,r,o){this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Gi(this.buffer)}update(e){Ns(this),Dt(e);const{view:n,buffer:r,blockLen:o}=this,s=e.length;let i=!1;for(let a=0;a<s;){const c=Math.min(o-this.pos,s-a);if(c===o){const l=Gi(e);for(;o<=s-a;a+=o)this.process(l,a);i=!0;continue}r.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(n,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){Ns(this),sp(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:o,isLE:s}=this;let{pos:i}=this;n[i++]=128,n.fill(0,i),this.padOffset>o-i&&(this.process(r,0),n.fill(0)),Lv(r,o-8,this.length*8,s),this.process(r,0),this.roundClean();const a=e===n?r:Gi(e),c=this.outputLen,l=c/4,d=this.get();if(c%4||l>d.length)throw new Error("invalid outputLen");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneIntoMeta(e){const{buffer:n,length:r,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=r,e.pos=i,i&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Wv=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Vv=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]),qt=new Uint32Array(64);class Xv extends Gv{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,n){super(64,e,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){const{A:e,B:n,C:r,D:o,E:s,F:i,G:a,H:c}=this;return[e,n,r,o,s,i,a,c]}set(e,n,r,o,s,i,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,n){for(let u=0;u<16;u++,n+=4)qt[u]=e.getUint32(n,!1);for(let u=16;u<64;u++){const f=qt[u-15],h=qt[u-2],g=ht(f,7)^ht(f,18)^f>>>3,m=ht(h,17)^ht(h,19)^h>>>10;qt[u]=m+qt[u-7]+g+qt[u-16]|0}let{A:r,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=ht(a,6)^ht(a,11)^ht(a,25),h=d+f+Kv(a,c,l)+Vv[u]+qt[u]|0,m=(ht(r,2)^ht(r,13)^ht(r,22))+zv(r,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=r,r=h+m|0}r=r+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,s,i,a,c,l,d)}roundClean(){gn(qt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),gn(this.buffer)}}class Yv extends Xv{constructor(){super(32,Wv)}}const Wi=Uv(()=>new Yv,qv(1));function cp(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 er=(t,e,n)=>Dt(t,e,n),lp=Ot;function tr(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 ro(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}const Zv=gl,Jv=t=>ap(t),dp=oc,up=t=>$v(t),Ls=BigInt(0),Ud=BigInt(1),Qv=t=>t?`"${t}" `:"";function hi(t,e=""){if(typeof t!="boolean")throw new TypeError(Qv(e)+"expected boolean, got type="+typeof t);return t}function eS(t){if(typeof t=="bigint"){if(!mn(t))throw new RangeError("positive bigint expected, got "+t)}else lp(t);return t}function ic(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 fp(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Ls:BigInt("0x"+t)}function hp(t){return fp(gl(t))}function Bs(t){return fp(gl(go(Dt(t)).reverse()))}function pp(t,e){if(Ot(e),e===0)throw new Error("zero output length is invalid");t=eS(t);const n=e*2,r=t.toString(16);if(r.length>n)throw new RangeError("number is too large");return ap(r.padStart(n,"0"))}function gp(t,e){return pp(t,e).reverse()}function go(t){return Uint8Array.from(er(t))}function mn(t){return typeof t=="bigint"&&Ls<=t}function mp(t,e,n){return mn(t)&&mn(e)&&mn(n)&&e<=t&&t<n}function oo(t,e,n,r){if(!mp(e,n,r))throw new RangeError("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function tS(t){if(t<Ls)throw new Error("expected non-negative bigint, got "+t);return t===Ls?0:t.toString(2).length}const nS=t=>(ic(t,"n"),(Ud<<BigInt(t))-Ud);function _s(t,e={},n={},r="object"){tr(t,r),tr(e,"fields"),tr(n,"optFields");function o(i,a,c){const l=r==="object"?`param "${String(i)}"`:`"${r}.${String(i)}"`,d=t[i];if(!Object.hasOwn(t,i)&&(c?d!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&d===void 0)return;const u=typeof d;if(u!==a||d===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${u}`)}const s=(i,a)=>Object.entries(i).forEach(([c,l])=>o(c,l,a));s(e,!1),s(n,!0)}const Re=BigInt(0),de=BigInt(1),dn=BigInt(2),wp=BigInt(3),ml=BigInt(4),yp=BigInt(5),rS=BigInt(7),bp=BigInt(8),oS=BigInt(9),sS=BigInt(15),vp=BigInt(16),iS=BigInt("0x10000000000000000");function le(t,e){if(e<=Re)throw new Error("mod: expected positive modulus, got "+e);const n=t%e;return n>=Re?n:e+n}function aS(t,e,n){if(n<=de)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<Re)throw new Error("invalid exponent, negatives unsupported");if(e===Re)return de;if(e===de)return t;let r=t%n;if(r<Re&&(r+=n),e<iS){let a=de;for(;e>Re;)e&de&&(a=a*r%n),r=r*r%n,e>>=de;return a}const o=[];for(;e>Re;)o.push(Number(e&sS)),e>>=ml;const s=new Array(16);s[0]=de,s[1]=r;for(let a=2;a<16;a++)s[a]=s[a-1]*r%n;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%n,i=i*i%n,i=i*i%n,i=i*i%n;const c=o[a];c!==0&&(i=i*s[c]%n)}return i}function st(t,e,n){if(n<=de)throw new Error("pow2: expected modulus > 1, got "+n);if(e<Re)throw new Error("pow2: expected non-negative exponent, got "+e);let r=t;for(;e-- >Re;)r*=r,r%=n;return r}function $d(t,e){if(t===Re)throw new Error("invert: expected non-zero number");if(e<=de)throw new Error("invert: expected modulus > 1, got "+e);let n=le(t,e),r=e,o=Re,s=de;for(;n!==Re;){const a=r/n,c=r-n*a,l=o-s*a;r=n,n=c,o=s,s=l}if(r!==de)throw new Error("invert: does not exist");return le(o,e)}function wl(t,e,n){const r=t;if(!r.eql(r.sqr(e),n))throw new Error("Cannot find square root")}function yl(t,e){if((t&de)===Re)throw new Error(e+": expected odd modulus, got "+t)}function Sp(t,e){const n=t,r=(n.ORDER+de)/ml,o=n.pow(e,r);return wl(n,o,e),o}function cS(t,e){const n=t,r=(n.ORDER-yp)/bp,o=n.mul(e,dn),s=n.pow(o,r),i=n.mul(e,s),a=n.mul(n.mul(i,dn),s),c=n.mul(i,n.sub(a,n.ONE));return wl(n,c,e),c}function lS(t){const e=bl(t),n=xp(t),r=n(e,e.neg(e.ONE)),o=n(e,r),s=n(e,e.neg(r)),i=(t+rS)/vp;return((a,c)=>{const l=a;let d=l.pow(c,i),u=l.mul(d,r);const f=l.mul(d,o),h=l.mul(d,s),g=l.eql(l.sqr(u),c),m=l.eql(l.sqr(f),c);d=l.cmov(d,u,g),u=l.cmov(h,f,m);const b=l.eql(l.sqr(u),c),w=l.cmov(d,u,b);return wl(l,w,c),w})}function xp(t){if(t<wp)throw new Error("sqrt is not defined for small field");yl(t,"tonelliShanks");let e=t-de,n=0;for(;e%dn===Re;)e/=dn,n++;let r=dn;const o=bl(t);for(;Os(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Sp;let s=o.pow(r,e);const i=(e+de)/dn;return function(c,l){const d=c;if(d.is0(l))return l;if(Os(d,l)!==1)throw new Error("Cannot find square root");let u=n,f=d.mul(d.ONE,s),h=d.pow(l,e),g=d.pow(l,i);for(;!d.eql(h,d.ONE);){if(d.is0(h))throw new Error("Cannot find square root: probably non-prime P");let m=1,b=d.sqr(h);for(;!d.eql(b,d.ONE);)if(m++,b=d.sqr(b),m===u)throw new Error("Cannot find square root");const w=de<<BigInt(u-m-1),I=d.pow(f,w);u=m,f=d.sqr(I),h=d.mul(h,f),g=d.mul(g,I)}return g}}function dS(t){return yl(t,"Fp.sqrt"),t%ml===wp?Sp:t%bp===yp?cS:t%vp===oS?lS(t):xp(t)}const uS=(t,e)=>(le(t,e)&de)===de,fS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function mo(t){if(tr(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);ic(t.BYTES,"BYTES"),ic(t.BITS,"BITS");for(const e of fS)ro(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=de)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Ep(t,e,n=!1){mo(t),cp(e,"nums"),hi(n,"passZero");const r=t,o=new Array(e.length).fill(n?r.ZERO:void 0),s=e.reduce((a,c,l)=>r.is0(c)?a:(o[l]=a,r.mul(a,c)),r.ONE),i=r.inv(s);return e.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),i),o}function Os(t,e){mo(t);const n=t;yl(n.ORDER,"FpLegendre");const r=(n.ORDER-de)/dn,o=n.pow(e,r),s=n.eql(o,n.ONE),i=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function hS(t,e){if(e!==void 0&&lp(e),t<=Re)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=tS(t);if(e!==void 0&&e<n)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${n})`);const r=e!==void 0?e:n,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}const qd=new WeakMap;class Kd{ORDER;BITS;BYTES;isLE;ZERO=Re;ONE=de;_lengths;_mod;constructor(e,n={}){if(e<=de)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:!0}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));const{nBitLength:o,nByteLength:s}=hS(e,r);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return le(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Re<=e&&e<this.ORDER}is0(e){return e===Re}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&de)===de}neg(e){return le(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return le(e*e,this.ORDER)}add(e,n){return le(e+n,this.ORDER)}sub(e,n){return le(e-n,this.ORDER)}mul(e,n){return le(e*n,this.ORDER)}pow(e,n){return aS(e,n,this.ORDER)}div(e,n){return le(e*$d(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 $d(e,this.ORDER)}sqrt(e){let n=qd.get(this);return n||qd.set(this,n=dS(this.ORDER)),n(this,e)}toBytes(e){return this.isLE?gp(e,this.BYTES):pp(e,this.BYTES)}fromBytes(e,n=!1){er(e);const{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);const l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?Bs(e):hp(e);if(a&&(c=le(c,i)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Ep(this,e,!0)}cmov(e,n,r){return hi(r,"condition"),r?n:e}}function bl(t,e={}){return Object.freeze(Kd.prototype),new Kd(t,e)}const vl=BigInt(0),wo=BigInt(1),pS=BigInt(4),Vi=16,zd=128,gS=5,Gd=2**31;function Sl(t){const e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);ro(e.fromAffine,"Point.fromAffine"),ro(e.fromBytes,"Point.fromBytes"),ro(e.fromHex,"Point.fromHex"),tr(e.BASE,"Point.BASE"),tr(e.ZERO,"Point.ZERO"),mo(e.Fp),mo(e.Fn)}function mS(t,e){Sl(t),Ap(e,t);const n=Ep(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function wS(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 yS(t,e){const n=t*(4*e+128);if(n>Gd)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+Gd/2**20+" MiB")}function bS(t,e){if(t!==void 0){ro(t,"randomBytes");try{const n=t(e);if(!dp(n)||n.length!==e)return}catch{return}return t}}function Ap(t,e){cp(t,"points"),t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function vS(t,e,n){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,o)=>{if(!(n===void 0?e.isValid(r):mn(r)&&r<n))throw new Error("invalid scalar at index "+o)})}const kp=new WeakMap;function Xi(t){return kp.get(t)||1}function SS(t,e){const n=t.double(),r=[t];for(let o=1;o<e;o++)r.push(r[o-1].add(n));return r}function xS(t,e){const n=2**e,r=n/2,o=BigInt(n-1),s=[];for(;t>vl;){let i=0;t&wo&&(i=Number(t&o),i>=r&&(i-=n),t-=BigInt(i)),s.push(i),t>>=wo}return s}function ES(t,e,n){const r=2**e,o=r/2,s=BigInt(r-1),i=BigInt(e),a=[];for(let c=0;c<n;c++){let l=Number(t&s);t>>=i,l>o&&(l-=r,t+=wo),a.push(l)}if(t!==vl)throw new Error("invalid wnaf");return a}function AS(t,e,n){let r=0;for(const s of n)r=Math.max(r,s.length);let o=t;for(let s=r-1;s>=0;s--){s!==r-1&&(o=o.double());for(let i=0;i<n.length;i++){const a=n[i][s];if(a){const c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}class kS{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,n){Sl(e),this.randomBytes=bS(n,Vi),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,n,r){const o=Math.ceil(r/n)+1,s=2**(n-1),i=[];let a=e;for(let c=0;c<o;c++){let l=a;for(let d=0;d<s;d++)i.push(l),l=l.add(a);a=i[i.length-1].double()}return{W:n,bits:r,windows:o,comp:i}}wnafCachedCT(e,n){const{W:r,windows:o,comp:s}=e,i=2**(r-1),a=ES(n,r,o);let c=this.ZERO,l=this.BASE;for(let d=0;d<o;d++){const u=a[d],f=d*i,h=Math.abs(u)-1;let g=s[f];for(let b=1;b<i;b++)g=b===h?s[f+b]:g;const m=g.negate();u===0?l=l.add(s[f]):c=c.add(u<0?m:g)}return{p:c,f:l}}getWnafPrecomputes(e,n,r,o){let s=this.wnafPrecomputes.get(n),i=s?.find(a=>a.W===e&&a.bits===r);return i||(i=this.buildWnafTable(n,e,r),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(n,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,n){if(this.assertPoint(e),!mp(n,wo,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,n,r,o){const s=Xi(e);return s===1?this.fixedWindowCT(e,n,r):this.wnafCachedCT(this.getWnafPrecomputes(s,e,r,o),n)}mulCT(e,n,r){return this.validateMulInput(e,n),this.runCT(e,n,this.bits,r)}mulCTBlinded(e,n,r){if(this.validateMulInput(e,n),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");const o=this.Point.Fn.BITS+zd,s=this.randomBytes(Vi);if(!dp(s)||s.length!==Vi)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;const i=n+hp(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,r)}fixedWindowCT(e,n,r){const o=gS,s=1<<o,i=nS(o),a=new Array(s);a[0]=this.ZERO;for(let d=1;d<s;d++)a[d]=a[d-1].add(e);const c=Math.ceil(r/o);let l=this.ZERO;for(let d=c-1;d>=0;d--){if(d!==c-1)for(let h=0;h<o;h++)l=l.double();const u=Number(n>>BigInt(d*o)&i);let f=a[0];for(let h=1;h<s;h++)f=h===u?a[h]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(e,n){return this.randomBytes===void 0?!1:n===wo?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,n,r,o){return this.shouldBlind(e,r)?this.mulCTBlinded(e,n,o):this.mulCT(e,n,o)}mulUnsafe(e,n,r){if(this.assertPoint(e),!mn(n))throw new Error("invalid scalar");const o=Xi(e);if(o===1||n>=this.Point.Fn.ORDER)return CS(this.Point,[e],[n],!0);const s=this.getWnafPrecomputes(o,e,this.bits,r);return this.wnafCachedCT(s,n).p}setWindowSize(e,n){this.assertPoint(e),wS(n,this.bits);const r=Math.ceil((this.bits+zd)/n)+1;yS(r*2**(n-1),this.Point.Fp.BYTES),kp.set(e,n),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Xi(e)!==1}}function CS(t,e,n,r=!1){if(Sl(t),Ap(e,t),hi(r,"allowOversized"),vS(n,t.Fn,r?t.Fn.ORDER**pS:void 0),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const o=e.map(i=>SS(i,4)),s=n.map(i=>xS(i,4));return AS(t.ZERO,o,s)}function Wd(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return mo(e),e}else return bl(t,{isLE:n})}function IS(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);_s(n);for(const c of["p","n","h"]){const l=e[c];if(!(mn(l)&&l!==vl))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Wd(e.p,n.Fp,r),s=Wd(e.n,n.Fn,r),a=["Gx","Gy","a","d"];for(const c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function RS(t,e){return function(r){const o=t(r);return{secretKey:o,publicKey:e(o)}}}const $o=BigInt(0),qo=BigInt(1),Ko=BigInt(2),TS=BigInt(4),Vd=BigInt(8);function PS(t,e,n,r){const o=t.sqr(n),s=t.sqr(r),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function NS(t,e={}){_s(e,{},{},"extraOpts");const n=e,r=IS("edwards",t,n,n.FpFnLE),{Fp:o,Fn:s}=r;let i=r.CURVE;const{h:a}=i;if(Os(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Os(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");_s(n,{},{uvRatio:"function",randomBytes:"function"});const c=n.randomBytes===void 0?up:n.randomBytes,l=Ko<<BigInt(o.BYTES*8)-qo;function d(I){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(I)}const u=n.uvRatio===void 0?(I,y)=>{try{return{isValid:!0,value:o.sqrt(o.div(I,y))}}catch{return{isValid:!1,value:$o}}}:n.uvRatio;if(!PS(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");const f=o.eql(i.a,o.neg(o.ONE))?I=>o.neg(I):o.eql(i.a,o.ONE)?I=>I:I=>o.mul(i.a,I);function h(I,y,A=!1){const N=A?qo:$o;return oo("coordinate "+I,y,N,l),y}function g(I){if(!(I instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.Gy));static ZERO=new m(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(y,A,N,k){this.X=h("x",y),this.Y=h("y",A),this.Z=h("z",N,!0),this.T=h("t",k),Object.freeze(this)}static CURVE(){return i}static fromAffine(y){if(y instanceof m)throw new Error("extended point not allowed");const{x:A,y:N}=y||{};return h("x",A),h("y",N),new m(A,N,o.ONE,o.mul(A,N))}static fromBytes(y,A=!1){const N=o.BYTES,{a:k,d:T}=i;y=go(er(y,N,"point")),hi(A,"zip215");const S=go(y),v=y[N-1];S[N-1]=v&-129;const E=Bs(S),_=A?l:o.ORDER;oo("point.y",E,$o,_);const L=o.sqr(E),C=o.sub(L,o.ONE),x=o.sub(o.mulN(T,L),k);let{isValid:P,value:R}=u(C,x);if(!P)throw new Error("bad point: invalid y coordinate");const D=d(R),M=(v&128)!==0;if(!A&&o.is0(R)&&M)throw new Error("bad point: x=0 and x_0=1");return M!==D&&(R=o.neg(R)),m.fromAffine({x:R,y:E})}static fromHex(y,A=!1){return m.fromBytes(Jv(y),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=6,A=!0){return w.setWindowSize(this,y),A||this.multiply(Ko),this}assertValidity(){const y=this,{a:A,d:N}=i;if(y.is0())throw new Error("bad point: ZERO");const{X:k,Y:T,Z:S,T:v}=y,E=o.sqr(k),_=o.sqr(T),L=o.sqr(S),C=o.sqr(L),x=o.mul(E,A),P=o.mul(o.add(x,_),L),R=o.add(C,o.mul(N,o.mul(E,_)));if(!o.eql(P,R))throw new Error("bad point: equation left != right (1)");const D=o.mul(k,T),M=o.mul(S,v);if(!o.eql(D,M))throw new Error("bad point: equation left != right (2)")}equals(y){g(y);const{X:A,Y:N,Z:k}=this,{X:T,Y:S,Z:v}=y,E=o.mul(A,v),_=o.mul(T,k),L=o.mul(N,v),C=o.mul(S,k);return o.eql(E,_)&&o.eql(L,C)}is0(){return this.equals(m.ZERO)}negate(){return new m(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){const{X:y,Y:A,Z:N}=this,k=o.sqr(y),T=o.sqr(A),S=o.mul(o.sqr(N),Ko),v=f(k),E=o.addN(y,A),_=o.sub(o.subN(o.sqr(E),k),T),L=o.addN(v,T),C=o.subN(L,S),x=o.subN(v,T),P=o.mul(_,C),R=o.mul(L,x),D=o.mul(_,x),M=o.mul(C,L);return new m(P,R,M,D)}add(y){g(y);const{d:A}=i,{X:N,Y:k,Z:T,T:S}=this,{X:v,Y:E,Z:_,T:L}=y,C=o.mul(N,v),x=o.mul(k,E),P=o.mul(o.mulN(S,A),L),R=o.mul(T,_),D=o.sub(o.subN(o.mulN(o.addN(N,k),o.addN(v,E)),C),x),M=o.subN(R,P),F=o.addN(R,P),B=o.sub(x,f(C)),H=o.mul(D,M),$=o.mul(F,B),X=o.mul(D,B),Y=o.mul(M,F);return new m(H,$,Y,X)}subtract(y){return g(y),this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");const{p:A,f:N}=w.mulSecret(this,y,a,b);return b([A,N])[0]}multiplyUnsafe(y){if(!s.isValid(y))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return y===$o?m.ZERO:this.is0()||y===qo?this:w.mulUnsafe(this,y,b)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.mulUnsafe(this,i.n).is0()}toAffine(y){const A=this;let N=y;if(N!=null&&typeof N!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof N);const{X:k,Y:T,Z:S}=A,v=A.is0();N==null&&(N=v?o.create(Vd):o.inv(S));const E=o.mul(k,N),_=o.mul(T,N),L=o.mul(S,N);if(v)return{x:o.ZERO,y:o.ONE};if(!o.eql(L,o.ONE))throw new Error("invZ was invalid");return{x:E,y:_}}clearCofactor(){return a===qo?this:a===Ko?this.double():a===TS?this.double().double():a===Vd?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){const{x:y,y:A}=this.toAffine(),N=o.toBytes(A);return N[N.length-1]|=d(y)?128:0,N}toHex(){return Zv(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const b=I=>mS(m,I),w=new kS(m,c);return w.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}const rn=BigInt(0),Qe=BigInt(1),zo=BigInt(2);function Xd(t,e){return t+e-(e>>Qe<<Qe)}function LS(t){const e=BigInt(6)*t;return(n,r,o)=>{const s=r+o,a=((e+o-r)*n+r)%t;return{x_2:a,x_3:s-a}}}function BS(t){return _s(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...t})}function _S(t){const e=BS(t),{P:n,type:r,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=e.scalarMultBase,c=r==="x25519";if(!c&&r!=="x448")throw new Error("invalid type");const l=i===void 0?up:i,d=c?255:448,u=LS(n),f=c?32:56,h=BigInt(c?9:5),g=BigInt(c?121665:39081),m=c?zo**BigInt(254):zo**BigInt(447),b=c?BigInt(8)*(zo**BigInt(251)-Qe):BigInt(4)*(zo**BigInt(445)-Qe),w=m+b+Qe,I=R=>le(R,n),y=A(h);function A(R){return gp(I(R),f)}function N(R){const D=go(er(R,f,"uCoordinate"));return c&&(D[31]&=127),I(Bs(D))}function k(R){return Bs(o(go(er(R,f,"scalar"))))}const T=new Set(c?[rn,Qe,n-Qe,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[rn,Qe,n-Qe]);function S(R,D){const M=N(D);if(T.has(M))throw new Error("invalid private or public key received");const F=L(M,k(R));if(F===rn)throw new Error("invalid private or public key received");return A(F)}function v(R){if(a===void 0)return S(R,y);const D=k(R);oo("scalar",D,m,w);const M=I(a(D));if(M===rn)throw new Error("invalid private or public key received");return A(M)}const E=v,_=S;function L(R,D){oo("u",R,rn,n),oo("scalar",D,m,w);const M=D,F=R;let B=Qe,H=rn,$=R,X=Qe;const Y=M^M>>Qe;for(let q=BigInt(d-1);q>=rn;q--){const G=Xd(n,Y>>q);({x_2:B,x_3:$}=u(G,B,$)),{x_2:H,x_3:X}=u(G,H,X);const z=B+H,V=I(z*z),J=B-H,oe=I(J*J),ne=V-oe,ae=$+X,he=$-X,Be=I(he*z),We=I(ae*J),ke=Be+We,je=Be-We;$=I(ke*ke),X=I(F*I(je*je)),B=I(V*oe),H=I(ne*(V+I(g*ne)))}const U=Xd(n,M);({x_2:B,x_3:$}=u(U,B,$)),{x_2:H,x_3:X}=u(U,H,X);const K=s(H);return I(B*K)}const C={secretKey:f,publicKey:f,seed:f},x=R=>(R=R===void 0?l(f):R,er(R,C.seed,"seed"),R),P={randomSecretKey:x};return Object.freeze(C),Object.freeze(P),Object.freeze({keygen:RS(x,E),getSharedSecret:_,getPublicKey:E,scalarMult:S,scalarMultBase:v,utils:P,GuBytes:y.slice(),lengths:C})}const Yd=BigInt(0),OS=BigInt(1),Zd=BigInt(2),DS=BigInt(3),FS=BigInt(5),MS=BigInt(8),pi=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),jS={p:pi,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:MS,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Cp(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),s=pi,a=t*t%s*t%s,c=st(a,Zd,s)*a%s,l=st(c,OS,s)*t%s,d=st(l,FS,s)*l%s,u=st(d,e,s)*d%s,f=st(u,n,s)*u%s,h=st(f,r,s)*f%s,g=st(h,o,s)*h%s,m=st(g,o,s)*h%s,b=st(m,e,s)*d%s;return{pow_p_5_8:st(b,Zd,s)*t%s,b2:a}}function HS(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Jd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function US(t,e){const n=pi,r=le(e*e*e,n),o=le(r*r*e,n),s=Cp(t*o).pow_p_5_8;let i=le(t*r*s,n);const a=le(e*i*i,n),c=i,l=le(i*Jd,n),d=a===t,u=a===le(-t,n),f=a===le(-t*Jd,n);return d&&(i=c),(u||f)&&(i=l),uS(i,n)&&(i=le(-i,n)),{isValid:d||u,value:i}}const Qd=NS(jS,{uvRatio:US}),Go=(()=>{const t=pi,e=n=>{const{pow_p_5_8:r,b2:o}=Cp(n);return le(st(r,DS,t)*o,t)};return _S({P:t,type:"x25519",powPminus2:e,adjustScalarBytes:HS,scalarMultBase:n=>{const r=le(n,Qd.Fn.ORDER);if(r===Yd)return Yd;const o=Qd.BASE.multiply(r);return le((o.Z+o.Y)*e(le(o.Z-o.Y,t)),t)}})})();class eu{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,n){if(pl(e),Dt(n,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?e.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),gn(o)}update(e){return Ns(this),this.iHash.update(e),this}digestInto(e){Ns(this),sp(e,this),this.finished=!0;const n=e.subarray(0,this.outputLen);this.iHash.digestInto(n),this.oHash.update(n),this.oHash.digestInto(n),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});const{oHash:n,iHash:r,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ip=(()=>{const t=((e,n,r)=>new eu(e,n).update(r).digest());return t.create=(e,n)=>new eu(e,n),t})();function tu(){const t={};return t.promise=new Promise((e,n)=>{t.resolve=e,t.reject=n}),t}class nu{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 Yi{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new nu(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 nu(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 $S extends Error{type;code;constructor(e,n){super(e??"The operation was aborted"),this.type="aborted",this.code=n??"ABORT_ERR"}}function qS(t={}){return KS(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 KS(t,e){e=e??{};let n=e.onEnd,r=new Yi,o,s,i,a=tu();const c=async()=>{try{return r.isEmpty()?i?{done:!0}:await new Promise((b,w)=>{s=I=>{s=null,r.push(I);try{b(t(r))}catch(y){w(y)}return o}}):t(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=tu()})}},l=b=>s!=null?s(b):(r.push(b),o),d=b=>(r=new Yi,s!=null?s({error:b}):(r.push({error:b}),o)),u=b=>{if(i)return o;if(e?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:b})},f=b=>i?o:(i=!0,b!=null?d(b):l({done:!0})),h=()=>(r=new Yi,f(),{done:!0}),g=b=>(f(b),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:g,push:u,end:f,get readableLength(){return r.size},onEmpty:async b=>{const w=b?.signal;if(w?.throwIfAborted(),r.isEmpty())return;let I,y;w!=null&&(I=new Promise((A,N)=>{y=()=>{N(new $S)},w.addEventListener("abort",y)}));try{await Promise.race([a.promise,I])}finally{y!=null&&w!=null&&w?.removeEventListener("abort",y)}}},n==null)return o;const m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(b){return m.throw(b),n!=null&&(n(b),n=void 0),{done:!0}},return(){return m.return(),n!=null&&(n(),n=void 0),{done:!0}},push:u,end(b){return m.end(b),n!=null&&(n(b),n=void 0),o},get readableLength(){return m.readableLength},onEmpty:b=>m.onEmpty(b)},o}class xl extends Error{name="TimeoutError";constructor(e,n){super(e,n),Error.captureStackTrace?.(this,xl)}}const ru=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function zS(t,e){const{milliseconds:n,fallback:r,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e;let a,c;const d=new Promise((u,f)=>{if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(i?.aborted){f(ru(i));return}if(i&&(c=()=>{f(ru(i))},i.addEventListener("abort",c,{once:!0})),t.then(u,f),n===Number.POSITIVE_INFINITY)return;const h=new xl;a=s.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){f(g)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?u():o instanceof Error?f(o):(h.message=o??`Promise timed out after ${n} milliseconds`,f(h))},n)}).finally(()=>{d.clear(),c&&i&&i.removeEventListener("abort",c)});return d.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},d}const GS=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 WS(t,e,n){let r;const o=new Promise((s,i)=>{if(n={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...n},!(n.count>=0&&(n.count===Number.POSITIVE_INFINITY||Number.isInteger(n.count))))throw new TypeError("The `count` option should be at least 0 or more");n.signal?.throwIfAborted();const a=[e].flat(),c=[],{addListener:l,removeListener:d}=GS(t),u=async(...h)=>{const g=n.multiArgs?h:h[0];if(n.filter)try{if(!await n.filter(g))return}catch(m){r(),i(m);return}c.push(g),n.count===c.length&&(r(),s(c))},f=(...h)=>{r(),i(n.rejectionMultiArgs?h:h[0])};r=()=>{for(const h of a)d(h,u);for(const h of n.rejectionEvents)a.includes(h)||d(h,f)};for(const h of a)l(h,u);for(const h of n.rejectionEvents)a.includes(h)||l(h,f);n.signal&&n.signal.addEventListener("abort",()=>{f(n.signal.reason)},{once:!0}),n.resolveImmediately&&s(c)});if(o.cancel=r,typeof n.timeout=="number"){const s=zS(o,{milliseconds:n.timeout});return s.cancel=()=>{r(),s.clear()},s}return o}function VS(t,e,n){typeof n=="function"&&(n={filter:n}),n={...n,count:1,resolveImmediately:!1};const r=WS(t,e,n),o=r.then(s=>s[0]);return o.cancel=r.cancel,o}class Ds extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class XS extends Error{static name="StreamClosedError";name="StreamClosedError"}function YS(t){return t.reason}function Rp(t,e,n){if(e==null||t==null)return t;const r=YS;if(e.aborted)return t.catch(()=>{}),Promise.reject(r(e));let o;return Promise.race([t,new Promise((s,i)=>{o=()=>{i(r(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}const ZS=Math.pow(2,20)*4;class Tp extends lw{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??ZS,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new ce,this.writeBuffer=new ce,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);const n=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",n);const r=o=>{this.onDrainPromise?.reject(o.error??new XS)};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()),Rp(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;const e=qS(),n=s=>{e.push(s.data)};this.addEventListener("message",n);const r=s=>{e.end(s.error)};this.addEventListener("close",r);const o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",n),this.removeEventListener("close",r),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Lr(`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 Rv(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Lr("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 Lr("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 Lr(`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 Lr(`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 Cv;this.dispatchEvent(new Tv(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 hl))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0;const n=this.writeBuffer.byteLength;let r=0;for(;this.writeBuffer.byteLength>0;){const o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}const s=this.writeBuffer.sublist(0,o),i=new ce(s);this.writeBuffer.consume(s.byteLength);const a=this.sendData(s);if(e=a.canSendMore,r+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",r,n,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}const e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new Iv(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 Md(`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 Md(`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 JS=4194304;class ou extends Error{static name="UnwrappedError";name="UnwrappedError"}class Pp extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class QS extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class ex extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function tx(t){return typeof t?.closeRead=="function"}function nx(t){return typeof t?.close=="function"}function Zi(t){return tx(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:nx(t)?t.status!=="open":!1}function rx(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function ox(t,e){const n=e?.maxBufferSize??JS,r=new ce;let o,s=!1;if(!rx(t))throw new op("Argument should be a Stream or a Multiaddr");const i=d=>{if(r.append(d.data),r.byteLength>n){const u=r.byteLength;r.consume(r.byteLength),o?.reject(new Error(`Read buffer overflow - ${u} > ${n}`))}o?.resolve()};t.addEventListener("message",i);const a=d=>{d.error!=null?o?.reject(d.error):o?.resolve()};t.addEventListener("close",a);const c=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",c);const l={readBuffer:r,async read(d){if(s===!0)throw new ou("Stream was unwrapped");if(Zi(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 Ds(`Unexpected EOF - stream closed after reading ${r.byteLength}/${d.bytes} bytes`)}const u=d?.bytes??1;for(o=Promise.withResolvers();;){if(r.byteLength>=u){o.resolve();break}if(await Rp(o.promise,d?.signal),Zi(t)){if(r.byteLength===0&&d?.bytes==null)return null;break}o=Promise.withResolvers()}const f=d?.bytes??r.byteLength;if(r.byteLength<f){if(Zi(t))throw t.log.error("closed while reading %d/%d bytes",r.byteLength,f),new Ds(`Unexpected EOF - stream closed while reading ${r.byteLength}/${f} bytes`);return l.read(d)}const h=r.sublist(0,f);return r.consume(f),h},async write(d,u){if(s===!0)throw new ou("Stream was unwrapped");t.send(d)||await VS(t,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",i),t.removeEventListener("close",a),t.removeEventListener("remoteCloseWrite",c),r.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",r.byteLength),t.push(r))),t}};return l}function su(t,e={}){const n=ox(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Cn(e.maxDataLength));const r=e?.lengthDecoder??Mh,o=e?.lengthEncoder??d0;return{async read(i){let a=-1;const c=new ce;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 Pp("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new ex(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new QS(`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 Ds(`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 Ds(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await n.write(new ce(o(i.byteLength),i),a)},async writeV(i,a){const c=new ce(...i.flatMap(l=>[o(l.byteLength),l]));await n.write(c,a)},unwrap(){return n.unwrap()}}}const sx=1024*1024*4,ix=1024*1024*4;class ax{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new ce,this.maxBufferSize=e.maxBufferSize??sx,this.maxDataLength=e.maxDataLength??ix,this.lengthDecoder=e.lengthDecoder??Mh,this.encodingLength=e.encodingLength??Cn}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new op(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let n;try{n=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(n<0||n>this.maxDataLength)throw new Pp("Invalid message length");const r=this.encodingLength(n),o=r+n;if(this.buffer.byteLength>=o){const s=this.buffer.sublist(r,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}}var cx={};const yo=65535,iu=yo-16,Po=!!cx?.DUMP_SESSION_KEYS,au=16;function ac(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const Fs=t=>t?`"${t}" `:"";function cc(t,e=""){if(typeof t!="boolean")throw new TypeError(Fs(e)+"expected boolean, got type="+typeof t);return t}function nr(t,e=""){if(typeof t!="number")throw new TypeError(Fs(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(Fs(e)+"expected integer >= 0, got "+t);return t}function Ie(t,e,n=""){if(ac(t)&&(e===void 0||t.length===e))return t;e!==void 0&&nr(e,"length");const r=ac(t),o=e!==void 0?` of length ${e}`:"",s=r?`length=${t.length}`:`type=${typeof t}`,i=Fs(n)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}const cu=(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 lu(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function lx(t,e){Ie(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function Rt(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Jt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function dx(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const rr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ux(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function fx(t){for(let e=0;e<t.length;e++)t[e]=ux(t[e]);return t}const un=rr?t=>t:fx;function hx(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 px(t,e){if(hx(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function gx(t,e){return cu(t,"defaults"),cu(e,"opts"),Object.assign(t,e)}function mx(t,e){if(t=Ie(t),e=Ie(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 wx(t,e,n){const r=e,o=(()=>[]),s=(a,c)=>r(c,...o(a)).update(a).digest(),i=r(new Uint8Array(t),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>r(a,...c),s}const yx=(t,e)=>{function n(r,...o){if(Ie(r,void 0,"key"),t.nonceLength!==void 0){const u=o[0];Ie(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}const s=t.tagLength,i=t.nonceLength!==void 0?1:0;if(!t.withAAD){for(let u=i;u<o.length;u++)if(ac(o[u]))throw new Error("AAD not supported")}t.withAAD&&o[i]!==void 0&&Ie(o[i],void 0,"AAD");const a=e(r,...o),c=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");Ie(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,Ie(u,void 0,"data"),c(a.encrypt.length,f),a.encrypt(u,f)},decrypt(u,f){if(Ie(u,void 0,"data"),s&&u.length<s)throw new Error('"ciphertext" expected length >= tagLength='+s);return c(a.decrypt.length,f),a.decrypt(u,f)}}}return Object.assign(n,t),n};function lc(t,e,n=!0){if(e===void 0)return new Uint8Array(t);if(Ie(e,t,"output"),n&&!Ms(e))throw new Error("invalid output, must be aligned");return e}function bx(t,e,n){nr(t),nr(e),cc(n);const r=new Uint8Array(16),o=dx(r);return o.setBigUint64(0,BigInt(e),n),o.setBigUint64(8,BigInt(t),n),r}function Ms(t){return t.byteOffset%4===0}function js(t){return Uint8Array.from(Ie(t))}const Np=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),vx=un(Rt(Np("expand 16-byte k"))),Sx=un(Rt(Np("expand 32-byte k")));function re(t,e){return t<<e|t>>>32-e}const Br=64,xx=16,dc=2**32-1,du=Uint32Array.of();function Ex(t,e,n,r,o,s,i,a){const c=o.length,l=new Uint8Array(Br),d=Rt(l),u=rr&&Ms(o)&&Ms(s),f=u?Rt(o):du,h=u?Rt(s):du;if(!rr){for(let g=0;g<c;i++){if(t(e,n,r,d,i,a),un(d),i>=dc)throw new Error("arx: counter overflow");const m=Math.min(Br,c-g);for(let b=0,w;b<m;b++)w=g+b,s[w]=o[w]^l[b];g+=m}return}for(let g=0;g<c;i++){if(t(e,n,r,d,i,a),i>=dc)throw new Error("arx: counter overflow");const m=Math.min(Br,c-g);if(u&&m===Br){const b=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,I;w<xx;w++)I=b+w,h[I]=f[I]^d[w];g+=Br;continue}for(let b=0,w;b<m;b++)w=g+b,s[w]=o[w]^l[b];g+=m}}function Ax(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:s,rounds:i}=gx({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return nr(o),nr(i),cc(s),cc(n),(a,c,l,d,u=0)=>{Ie(a,void 0,"key"),Ie(c,void 0,"nonce"),Ie(l,void 0,"data");const f=l.length,h=d!==void 0;if(d=lc(f,d,!1),h&&px(l,d),nr(u),u<0||u>=dc)throw new Error("arx: counter overflow");const g=[];let m=a.length,b,w;if(m===32)g.push(b=js(a)),w=Sx;else if(m===16&&n)b=new Uint8Array(32),b.set(a),b.set(a,16),w=vx,g.push(b);else throw Ie(a,32,"arx key"),new Error("invalid key size");(!rr||!Ms(c))&&g.push(c=js(c));let I=Rt(b);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");const N=c.subarray(0,16);if(rr)r(w,I,Rt(N),I);else{const k=un(Uint32Array.from(w));r(k,I,Rt(N),I),Jt(k),un(I)}c=c.subarray(16)}else rr||un(I);const y=16-o;if(y!==c.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){const N=new Uint8Array(12);N.set(c,s?0:12-c.length),c=N,g.push(c)}const A=un(Rt(c));try{return Ex(t,w,I,A,l,d,u,i),d}finally{Jt(...g)}}}function Te(t,e){return t[e++]&255|(t[e++]&255)<<8}class kx{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=js(Ie(e,32,"key"));const n=Te(e,0),r=Te(e,2),o=Te(e,4),s=Te(e,6),i=Te(e,8),a=Te(e,10),c=Te(e,12),l=Te(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let d=0;d<8;d++)this.pad[d]=Te(e,16+2*d)}process(e,n,r=!1){const o=r?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],d=i[3],u=i[4],f=i[5],h=i[6],g=i[7],m=i[8],b=i[9],w=Te(e,n+0),I=Te(e,n+2),y=Te(e,n+4),A=Te(e,n+6),N=Te(e,n+8),k=Te(e,n+10),T=Te(e,n+12),S=Te(e,n+14);let v=s[0]+(w&8191),E=s[1]+((w>>>13|I<<3)&8191),_=s[2]+((I>>>10|y<<6)&8191),L=s[3]+((y>>>7|A<<9)&8191),C=s[4]+((A>>>4|N<<12)&8191),x=s[5]+(N>>>1&8191),P=s[6]+((N>>>14|k<<2)&8191),R=s[7]+((k>>>11|T<<5)&8191),D=s[8]+((T>>>8|S<<8)&8191),M=s[9]+(S>>>5|o),F=0,B=F+v*a+E*(5*b)+_*(5*m)+L*(5*g)+C*(5*h);F=B>>>13,B&=8191,B+=x*(5*f)+P*(5*u)+R*(5*d)+D*(5*l)+M*(5*c),F+=B>>>13,B&=8191;let H=F+v*c+E*a+_*(5*b)+L*(5*m)+C*(5*g);F=H>>>13,H&=8191,H+=x*(5*h)+P*(5*f)+R*(5*u)+D*(5*d)+M*(5*l),F+=H>>>13,H&=8191;let $=F+v*l+E*c+_*a+L*(5*b)+C*(5*m);F=$>>>13,$&=8191,$+=x*(5*g)+P*(5*h)+R*(5*f)+D*(5*u)+M*(5*d),F+=$>>>13,$&=8191;let X=F+v*d+E*l+_*c+L*a+C*(5*b);F=X>>>13,X&=8191,X+=x*(5*m)+P*(5*g)+R*(5*h)+D*(5*f)+M*(5*u),F+=X>>>13,X&=8191;let Y=F+v*u+E*d+_*l+L*c+C*a;F=Y>>>13,Y&=8191,Y+=x*(5*b)+P*(5*m)+R*(5*g)+D*(5*h)+M*(5*f),F+=Y>>>13,Y&=8191;let U=F+v*f+E*u+_*d+L*l+C*c;F=U>>>13,U&=8191,U+=x*a+P*(5*b)+R*(5*m)+D*(5*g)+M*(5*h),F+=U>>>13,U&=8191;let K=F+v*h+E*f+_*u+L*d+C*l;F=K>>>13,K&=8191,K+=x*c+P*a+R*(5*b)+D*(5*m)+M*(5*g),F+=K>>>13,K&=8191;let q=F+v*g+E*h+_*f+L*u+C*d;F=q>>>13,q&=8191,q+=x*l+P*c+R*a+D*(5*b)+M*(5*m),F+=q>>>13,q&=8191;let G=F+v*m+E*g+_*h+L*f+C*u;F=G>>>13,G&=8191,G+=x*d+P*l+R*c+D*a+M*(5*b),F+=G>>>13,G&=8191;let z=F+v*b+E*m+_*g+L*h+C*f;F=z>>>13,z&=8191,z+=x*u+P*d+R*l+D*c+M*a,F+=z>>>13,z&=8191,F=(F<<2)+F|0,F=F+B|0,B=F&8191,F=F>>>13,H+=F,s[0]=B,s[1]=H,s[2]=$,s[3]=X,s[4]=Y,s[5]=U,s[6]=K,s[7]=q,s[8]=G,s[9]=z}finalize(){const{h:e,pad:n}=this,r=new Uint16Array(10);let o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+o,o=r[a]>>>13,r[a]&=8191;r[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)r[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+n[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+n[a]|0)+(i>>>16)|0,e[a]=i&65535;Jt(r)}update(e){lu(this),Ie(e),e=js(e);const{buffer:n,blockLen:r}=this,o=e.length;for(let s=0;s<o;){const i=Math.min(r-this.pos,o-s);if(i===r){for(;r<=o-s;s+=r)this.process(e,s);continue}n.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,Jt(this.h,this.r,this.buffer,this.pad)}digestInto(e){lu(this),lx(e,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:o}=this;if(o){for(n[o++]=1;o<16;o++)n[o]=0;this.process(n,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=r[i]>>>0,e[s++]=r[i]>>>8}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}}const Cx=wx(32,t=>new kx(t));function Ix(t,e,n,r,o,s=20){let i=t[0],a=t[1],c=t[2],l=t[3],d=e[0],u=e[1],f=e[2],h=e[3],g=e[4],m=e[5],b=e[6],w=e[7],I=o,y=n[0],A=n[1],N=n[2],k=i,T=a,S=c,v=l,E=d,_=u,L=f,C=h,x=g,P=m,R=b,D=w,M=I,F=y,B=A,H=N;for(let X=0;X<s;X+=2)k=k+E|0,M=re(M^k,16),x=x+M|0,E=re(E^x,12),k=k+E|0,M=re(M^k,8),x=x+M|0,E=re(E^x,7),T=T+_|0,F=re(F^T,16),P=P+F|0,_=re(_^P,12),T=T+_|0,F=re(F^T,8),P=P+F|0,_=re(_^P,7),S=S+L|0,B=re(B^S,16),R=R+B|0,L=re(L^R,12),S=S+L|0,B=re(B^S,8),R=R+B|0,L=re(L^R,7),v=v+C|0,H=re(H^v,16),D=D+H|0,C=re(C^D,12),v=v+C|0,H=re(H^v,8),D=D+H|0,C=re(C^D,7),k=k+_|0,H=re(H^k,16),R=R+H|0,_=re(_^R,12),k=k+_|0,H=re(H^k,8),R=R+H|0,_=re(_^R,7),T=T+L|0,M=re(M^T,16),D=D+M|0,L=re(L^D,12),T=T+L|0,M=re(M^T,8),D=D+M|0,L=re(L^D,7),S=S+C|0,F=re(F^S,16),x=x+F|0,C=re(C^x,12),S=S+C|0,F=re(F^S,8),x=x+F|0,C=re(C^x,7),v=v+E|0,B=re(B^v,16),P=P+B|0,E=re(E^P,12),v=v+E|0,B=re(B^v,8),P=P+B|0,E=re(E^P,7);let $=0;r[$++]=i+k|0,r[$++]=a+T|0,r[$++]=c+S|0,r[$++]=l+v|0,r[$++]=d+E|0,r[$++]=u+_|0,r[$++]=f+L|0,r[$++]=h+C|0,r[$++]=g+x|0,r[$++]=m+P|0,r[$++]=b+R|0,r[$++]=w+D|0,r[$++]=I+M|0,r[$++]=y+F|0,r[$++]=A+B|0,r[$++]=N+H|0}const Rx=Ax(Ix,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Tx=new Uint8Array(16),uu=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(Tx.subarray(n))},Px=new Uint8Array(32);function fu(t,e,n,r,o){o!==void 0&&Ie(o,void 0,"AAD");const s=t(e,n,Px),i=bx(r.length,o?o.length:0,!0),a=Cx.create(s);o&&uu(a,o),uu(a,r),a.update(i);const c=a.digest();return Jt(s,i),c}const Nx=t=>(e,n,r)=>({encrypt(s,i){const a=s.length;i=lc(a+16,i,!1),i.set(s);const c=i.subarray(0,-16);t(e,n,c,c,1);const l=fu(t,e,n,c,r);return i.set(l,a),Jt(l),i},decrypt(s,i){i=lc(s.length-16,i,!1);const a=s.subarray(0,-16),c=s.subarray(-16),l=fu(t,e,n,a,r);if(!mx(c,l))throw Jt(l),new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,n,i,i,1),Jt(l),i}}),hu=yx({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},Nx(Rx));function Lx(t,e,n){return pl(t),n===void 0&&(n=new Uint8Array(t.outputLen)),Ip(t,n,e)}const _r=Uint8Array.of(0),Bx=Uint8Array.of();function _x(t,e,n,r=32,o){pl(t),Ot(r,"length"),Dt(e,void 0,"prk");const s=t.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(r>255*s)throw new Error("Length must be <= 255*HashLen");const i=Math.ceil(r/s);if(n===void 0?n=Bx:Dt(n,void 0,"info"),!i)return new Uint8Array;const a=new Uint8Array(i*s),{iHash:c,oHash:l}=Ip.create(t,e),d=new Uint8Array(s),u=i>1?t.create():void 0;for(let h=0;h<i-1;h++){_r[0]=h+1;const g=c._cloneInto(u);h&&g.update(d),g.update(n).update(_r).digestInto(d),l._cloneInto(u).update(d).digestInto(d),a.set(d,s*h)}if(_r[0]=i,i>1&&c.update(d),c.update(n).update(_r).digestInto(d),l.update(d).digestInto(d),a.set(d,s*(i-1)),c.destroy(),l.destroy(),u?.destroy(),d!==a&&gn(d),gn(_r),r===a.length)return a;const f=a.slice(0,r);return gn(a),f}const Lp={hashSHA256(t){return Wi(t.subarray())},getHKDF(t,e){const n=Lx(Wi,e,t),o=_x(Wi,n,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){const t=Go.utils.randomSecretKey();return{publicKey:Go.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:Go.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return Go.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,n,r){return hu(r,e,n).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,n,r,o){return hu(r,e,n).decrypt(t.subarray(),o)}},Ox=Lp;function Dx(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,n)=>t.generateX25519SharedKey(e.privateKey,n).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}const Hs=t=>{const e=Bt(2);return e[0]=t>>8,e[1]=t,e};Hs.bytes=2;const Us=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)};Us.bytes=2;function Fx(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 Bp(t,e){!e.enabled||!Po||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${te(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${te(t.privateKey,"hex")}`)):e("Missing local static keys."))}function _p(t,e){!e.enabled||!Po||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${te(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${te(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Mx(t,e){!e.enabled||!Po||e(t?`REMOTE_STATIC_PUBLIC_KEY ${te(t.subarray(),"hex")}`:"Missing remote static public key.")}function Op(t,e){!e.enabled||!Po||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${te(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Dp(t,e,n){!n.enabled||!Po||(n(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&te(t.k,"hex")}`),n(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&te(e.k,"hex")}`))}class so extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=so.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}const jx=0,Hx=4294967295,Ux="Cipherstate has reached maximum n, a new handshake must be performed";class $x{n;bytes;view;constructor(e=jx){this.n=e,this.bytes=qe(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>Hx)throw new Error(Ux)}}const or=qe(0);class Wo{k;n;crypto;constructor(e,n=void 0,r=0){this.crypto=e,this.k=n,this.n=new $x(r)}hasKey(){return!!this.k}encryptWithAd(e,n){if(!this.hasKey())return n;this.n.assertValue();const r=this.crypto.encrypt(n,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,n,r){if(!this.hasKey())return n;this.n.assertValue();const o=this.crypto.decrypt(n,this.n.getBytes(),e,this.k,r);return this.n.increment(),o}}class qx{cs;ck;h;crypto;constructor(e,n){this.crypto=e;const r=Se(n,"utf-8");this.h=zx(e,r),this.ck=this.h,this.cs=new Wo(e)}mixKey(e){const[n,r]=this.crypto.hkdf(this.ck,e);this.ck=n,this.cs=new Wo(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new ce(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,or);return[new Wo(this.crypto,e),new Wo(this.crypto,n)]}}class Kx{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:n,protocolName:r,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=n,this.ss=new qx(n,r),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,n=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<n+32)throw new Error("message is not long enough");this.re=e.sublist(n,n+32),this.ss.mixHash(this.re)}readS(e,n=0){if(this.rs)throw new Error("remote static public key is already set");const r=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<n+r)throw new Error("message is not long enough");const o=e.sublist(n,n+r);return this.rs=this.ss.decryptAndHash(o),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class Fp extends Kx{writeMessageA(e){return new ce(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const n=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new ce(n,r,this.ss.encryptAndHash(e))}writeMessageC(e){const n=this.writeS();return this.writeSE(),new ce(n,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(n){throw new so(`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 so(`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 so(`handshake stage 2 validation fail: ${n.message}`)}}}function zx(t,e){if(e.length<=32){const n=qe(32);return n.set(e),n}else return t.hash(e)}var $s;(function(t){let e;t.codec=()=>(e==null&&(e=ui((n,r,o={})=>{if(o.lengthDelimited!==!1&&r.fork(),n.webtransportCerthashes!=null)for(const s of n.webtransportCerthashes)r.uint32(10),r.bytes(s);if(n.streamMuxers!=null)for(const s of n.streamMuxers)r.uint32(18),r.string(s);o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={webtransportCerthashes:[],streamMuxers:[]},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new _d('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(n.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new _d('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(n.string());break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>di(n,t.codec()),t.decode=(n,r)=>li(n,t.codec(),r)})($s||($s={}));var qs;(function(t){let e;t.codec=()=>(e==null&&(e=ui((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.identityKey!=null&&n.identityKey.byteLength>0&&(r.uint32(10),r.bytes(n.identityKey)),n.identitySig!=null&&n.identitySig.byteLength>0&&(r.uint32(18),r.bytes(n.identitySig)),n.extensions!=null&&(r.uint32(34),$s.codec().encode(n.extensions,r)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const s={identityKey:qe(0),identitySig:qe(0)},i=r==null?n.len:n.pos+r;for(;n.pos<i;){const a=n.uint32();switch(a>>>3){case 1:{s.identityKey=n.bytes();break}case 2:{s.identitySig=n.bytes();break}case 4:{s.extensions=$s.codec().decode(n,n.uint32(),{limits:o.limits?.extensions});break}default:{n.skipType(a&7);break}}}return s})),e),t.encode=n=>di(n,t.codec()),t.decode=(n,r)=>li(n,t.codec(),r)})(qs||(qs={}));async function Mp(t,e,n){const r=await t.sign(Hp(e));return qs.encode({identityKey:fi(t.publicKey),identitySig:r,extensions:n})}async function jp(t,e,n){try{const r=qs.decode(t),o=rc(r.identityKey);if(n?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${n}`);if(!e)throw new Error("Remote static does not exist");const s=Hp(e);if(!await o.verify(s,r.identitySig))throw new Error("Invalid payload signature");return r}catch(r){throw new nw(r.message)}}function Hp(t){const e=Se("noise-libp2p-static-key:");return t instanceof Uint8Array?Ga([e,t],e.length+t.length):(t.prepend(e),t)}class Gx extends Tp{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 ax({lengthDecoder:Us,maxBufferSize:16*1024*1024,encodingLength:()=>2});const o=c=>{try{for(const l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);const s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);const i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);const a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){const n=new ce;for(let r=0;r<e.byteLength;r+=iu){let o=r+iu;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(r,o)):s=this.handshake.encrypt(e.sublist(r,o)),this.metrics?.encryptedPackets.increment(),n.append(Hs(s.byteLength)),n.append(s)}return n}decrypt(e){const n=new ce;for(let r=0;r<e.byteLength;r+=yo){let o=r+yo;if(o>e.byteLength&&(o=e.byteLength),o-au<r)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(r,o):s=e.sublist(r,o);const i=e.subarray(r,o-au);try{const a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),n.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return n}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}}function pu(t,e,n){return new Gx(t,e,n)}async function Wx(t,e){const{log:n,connection:r,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Mp(s,a.publicKey,l),u=new Fp({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Bp(u.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(u.writeMessageA(or),e),n.trace("Stage 0 - Initiator finished sending first message."),_p(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."),Op(u.re,n),Mx(u.rs,n),n.trace("Initiator going to check remote's signature...");const h=await jp(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 Dp(g,m,n),{payload:h,encrypt:b=>g.encryptWithAd(or,b),decrypt:(b,w)=>m.decryptWithAd(or,b,w)}}async function Vx(t,e){const{log:n,connection:r,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Mp(s,a.publicKey,l),u=new Fp({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Bp(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."),Op(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."),_p(u.e,n),n.trace("Stage 2 - Responder waiting for third handshake message...");const f=u.readMessageC(await r.read(e));n.trace("Stage 2 - Responder received the message, finished handshake.");const h=await jp(f,u.rs,c),[g,m]=u.ss.split();return Dp(g,m,n),{payload:h,encrypt:b=>m.encryptWithAd(or,b),decrypt:(b,w)=>g.decryptWithAd(or,b,w)}}class Xx{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,n={}){const{staticNoiseKey:r,extensions:o,crypto:s,prologueBytes:i}=n,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");const c=s??Ox;this.crypto=Dx(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Fx(a):void 0,r?this.staticKey=c.generateX25519KeyPairFromSeed(r):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??qe(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[dw]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,n){const r=e.log?.newScope("noise")??this.log,o=su(e,{lengthEncoder:Hs,lengthDecoder:Us,maxDataLength:yo}),s=await this.performHandshakeInitiator(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=rc(s.payload.identityKey);return{connection:pu(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:fr(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;const n=this.components.upgrader.getStreamMuxers();if(n!=null)for(const r of e){const o=n.get(r);if(o!=null)return o}if(e.length)throw new rw("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,n){const r=e.log?.newScope("noise")??this.log,o=su(e,{lengthEncoder:Hs,lengthDecoder:Us,maxDataLength:yo}),s=await this.performHandshakeResponder(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),i=rc(s.payload.identityKey);return{connection:pu(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:fr(i),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,n,r,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Wx({connection:e,privateKey:n,remoteIdentityKey:o,log:r.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,n,r,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Vx({connection:e,privateKey:n,remoteIdentityKey:o,log:r.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}}function Yx(t={}){return e=>new Xx(e,t)}const Zx="termdock-e2ee-v1",uc=3600*1e3,gu=512*1024*1024,fc=4*1024*1024,is=()=>{},gi=Object.assign(is,{enabled:!1,error:is,trace:is,newScope:()=>gi});Object.freeze(gi);async function Up(){const t=await gv();return{privateKey:t,peerId:fr(t.publicKey).toString()}}function Jx(t){return btoa(String.fromCharCode(...yv(t.privateKey)))}function mu(t){if(t.length>512||!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Invalid identity encoding");const e=wv(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:fr(e.publicKey).toString()}}class $p{constructor(e=is){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>fc)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 Qx extends Tp{constructor(e,n){super({log:gi,direction:n?"outbound":"inbound",maxReadBufferLength:fc,maxWriteBufferLength:fc}),this.duplex=e,this.finished=e.sink(this.outgoing).catch(r=>{this.abort(hr(r))}),this.readTransport()}duplex;outgoing=new $p(()=>this.onMuxerDrain());finished;async readTransport(){try{for await(const e of this.duplex.source)this.onData(e.slice());this.onTransportClosed()}catch(e){this.onTransportClosed(hr(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 hr(t){return t instanceof Error?t:new Error("Secure transport failed")}class eE extends Error{code="E2EE_REHANDSHAKE_REQUIRED";constructor(){super("Encrypted connection lifetime reached; establish a new handshake without replaying pending input")}}function tE(t){const e=t?.maxAgeMs??uc,n=t?.maxBytesPerDirection??gu;if(!Number.isSafeInteger(e)||e<=0||e>uc||!Number.isSafeInteger(n)||n<=0||n>gu)throw new Error("Encrypted connection limits cannot exceed the production maximum");return{maxAgeMs:e,maxBytesPerDirection:n}}async function nE(t){const{identity:e,duplex:n,initiator:r,targetPinnedPeerId:o,signal:s}=t,i=tE(t.limits);if(typeof Reflect.get(Promise,"withResolvers")!="function"||typeof globalThis.crypto?.getRandomValues!="function")throw new Error("End-to-end encryption requires Node.js 22+ or a modern browser with Promise.withResolvers and secure random support");if(r&&!o)throw new Error("A pinned target identity is required");const a=o?xv(o):void 0;if(a&&a.type!=="Ed25519")throw new Error("Only Ed25519 target identities are supported");if(e.peerId!==fr(e.privateKey.publicKey).toString())throw new Error("Local identity mismatch");if(s?.aborted)throw s.reason??new Error("Connection aborted");const c=new Qx(n,r),l=new AbortController,d=setTimeout(()=>{const h=new Error("Encrypted handshake timed out");l.abort(h),c.abort(h)},15e3),u=()=>{l.abort(s?.reason),c.abort(hr(s?.reason))};s?.addEventListener("abort",u,{once:!0}),c.addEventListener("close",()=>s?.removeEventListener("abort",u),{once:!0});const f=Yx({crypto:Lp,prologueBytes:new TextEncoder().encode(Zx)})({privateKey:e.privateKey,peerId:fr(e.privateKey.publicKey),logger:{forComponent:()=>gi},upgrader:{getStreamMuxers:()=>new Map}});try{const h=await(r?f.secureOutbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}):f.secureInbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}));if(h.remotePeer.type!=="Ed25519")throw new Error("Unsupported remote identity");return{authenticatedPeerId:h.remotePeer.toString(),duplex:rE(h.connection,i)}}catch(h){throw c.abort(hr(h)),h}finally{clearTimeout(d),s?.removeEventListener("abort",u)}}function rE(t,e){const n=new $p,r=performance.now(),o=Date.now();let s=0,i=0,a;const c=()=>(a??=new eE,n.end(a),t.abort(a),a),l=setTimeout(c,e.maxAgeMs);typeof l=="object"&&l.unref?.();const d=(f,h)=>{if(a)throw a;if(Math.max(performance.now()-r,Date.now()-o)>=e.maxAgeMs||f+h>=e.maxBytesPerDirection)throw c()};t.addEventListener("message",f=>{try{d(i,f.data.byteLength),i+=f.data.byteLength,n.push(f.data.subarray())}catch(h){t.abort(hr(h))}}),t.addEventListener("close",f=>{clearTimeout(l),n.end(f.error)},{once:!0});let u=!1;return{source:n,async sink(f){if(u)throw new Error("Secure sink already consumed");u=!0;try{for await(const h of f)d(s,h.byteLength),s+=h.byteLength,t.send(h)||await t.onDrain()}catch(h){throw t.abort(hr(h)),h}},close(f){f?t.abort(f):t.close()}}}const qp=1012,Kp="Encrypted transport renewed";class El{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 Ji=2*1024*1024,oE=new TextEncoder,sE=new TextDecoder("utf-8",{fatal:!0});class iE{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 El(256);outgoingBytes=0;get hasPendingWrites(){return this.outgoingBytes>0}done;send(e){const n=oE.encode(JSON.stringify(e));if(n.length>Ji)throw new Error("Record too large");const r=new Uint8Array(n.length+4);if(new DataView(r.buffer).setUint32(0,n.length),r.set(n,4),this.outgoingBytes+r.byteLength>4*1024*1024)throw new Error("Record queue byte budget exceeded");this.outgoingBytes+=r.byteLength;try{this.outgoing.push(r)}catch(o){throw this.outgoingBytes-=r.byteLength,o}}close(e){this.outgoing.end(e),this.duplex.close?.(e)}async*read(){let e=new Uint8Array(0);for await(const n of this.duplex.source){if(e.length+n.length>Ji*2+8)throw new Error("Record buffer exceeded");const r=new Uint8Array(e.length+n.length);for(r.set(e),r.set(n,e.length),e=r;e.length>=4;){const o=new DataView(e.buffer,e.byteOffset,4).getUint32(0);if(o>Ji||o===0)throw new Error("Invalid record size");if(e.length<o+4)break;const s=JSON.parse(sE.decode(e.subarray(4,o+4)));if(!s||typeof s!="object"||typeof s.id!="string"||typeof s.type!="string")throw new Error("Invalid record");yield s,e=e.slice(o+4)}}if(e.length)throw new Error("Truncated record")}}function zp(t){let e="";for(let n=0;n<t.length;n+=8192)e+=String.fromCharCode(...t.subarray(n,n+8192));return btoa(e)}function Gp(t){const e=atob(t);return Uint8Array.from(e,n=>n.charCodeAt(0))}function aE(t){const e=new El(64);t.binaryType="arraybuffer";const n=r=>{e.end(r),t.close(1e3)};return t.addEventListener("message",r=>{try{if(!(r.data instanceof ArrayBuffer)||r.data.byteLength>1024*1024)throw new Error("Invalid encrypted frame");e.push(new Uint8Array(r.data))}catch{n(new Error("Encrypted transport rejected frame"))}}),t.addEventListener("close",()=>e.end()),t.addEventListener("error",()=>e.end(new Error("Encrypted transport disconnected"))),{source:e,close:n,async sink(r){try{for await(const o of r)for(let s=0;s<o.length;s+=64*1024){const i=Date.now();for(;t.bufferedAmount>256*1024;){if(t.readyState!==1||Date.now()-i>15e3)throw new Error("Encrypted transport congested");await new Promise(a=>setTimeout(a,10))}if(t.readyState!==1)throw new Error("Encrypted transport closed");t.send(o.subarray(s,s+64*1024))}}catch(o){throw n(o instanceof Error?o:new Error("Encrypted transport failed")),o}}}}const Wp=8,Vp=128,cE=5*1024*1024,lE=Vp+Wp+8,dE=256,Vo=3e4,Or=64*1024;function Gt(t){return t instanceof Error?t:new Error(String(t??"Secure connection closed"))}function wu(t){if(!t.startsWith("/")||t.startsWith("//")||t.includes("#"))throw new Error("A local API path is required");return t}class Xp 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="";getConnectionDiagnostics;createdAt=performance.now();openedAfterMs;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.openedAfterMs=performance.now()-this.createdAt,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(Gt(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 uE{constructor(e,n,r){this.channel=e,this.identity=n,this.targetPeerId=r,this.read().catch(o=>this.close(Gt(o))),e.done.catch(o=>this.close(Gt(o)))}channel;identity;targetPeerId;transportDiagnostics;establishedAt=performance.now();establishedWallTime=Date.now();lastInputAt=-1/0;pending=new Map;waiting=[];stopped=!1;closeReason;get canSwitchTransport(){return!this.channel.hasPendingWrites&&performance.now()-this.lastInputAt>=2e3&&![...this.pending.values()].some(e=>e.kind!=="socket")&&!this.waiting.some(e=>e.kind!=="socket")}get renewalDue(){return!this.stopped&&Math.max(performance.now()-this.establishedAt,Date.now()-this.establishedWallTime)>=uc-5*6e4}get closed(){return this.stopped}hasCapacity(e){if(this.pending.size>=lE)return!1;const n=[...this.pending.values()].filter(r=>r.kind===e).length;return e==="http"?n<Wp:e==="socket"?n<Vp:!0}allocate(e){if(this.stopped)throw this.closeReason??new Error("Secure connection closed");const n=crypto.randomUUID(),r=new El(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>=dE?Promise.reject(new Error("连接繁忙,请稍后重试。")):new Promise((r,o)=>{const s=l=>{this.waiting=this.waiting.filter(d=>d!==c),c.cleanup(),o(l)},i=()=>s(n?.reason??new Error("Request aborted")),a=setTimeout(()=>s(new Error("连接等待超时,请重试。")),Vo),c={kind:e,resolve:r,reject:o,cleanup:()=>{clearTimeout(a),n?.removeEventListener("abort",i)}};this.waiting.push(c),n?.addEventListener("abort",i,{once:!0})})}dispatchWaiting(){if(!this.stopped)for(let e=0;e<this.waiting.length;){const n=this.waiting[e];if(!this.hasCapacity(n.kind)){e++;continue}this.waiting.splice(e,1),n.cleanup(),n.resolve(this.allocate(n.kind))}}async read(){try{for await(const e of this.channel.read()){const n=this.pending.get(e.id);n&&(n.socket?(n.socket.accept(e),(e.type==="ws-close"||e.type==="error")&&this.release(e.id)):(n.queue.push(e),(e.type==="end"||e.type==="error")&&(n.cancelUpload?.(),this.release(e.id))))}}finally{this.close(new Error("Secure connection closed"))}}release(e){this.pending.get(e)?.queue.end(),this.pending.delete(e),this.dispatchWaiting()}async request(e,n){const{id:r,queue:o}=await this.reserve("request"),s=setTimeout(()=>this.close(new Error("Secure connection timed out")),Math.max(1e3,Math.min(Vo,n?.timeoutMs??Vo)));try{if(this.stopped)throw this.closeReason;this.channel.send({...e,id:r});const i=(await o[Symbol.asyncIterator]().next()).value;if(!i)throw new Error("Secure request closed");if(i.type==="error")throw Gt(i.error);return i}finally{clearTimeout(s),this.release(r)}}openSocket(e){wu(e);let n;const r=new AbortController,o=new Xp(e,i=>{if(n){try{JSON.parse(i)?.type==="input"&&(this.lastInputAt=performance.now())}catch{}this.channel.send({id:n,type:"ws-data",data:i})}},()=>{if(r.abort(),n)try{this.channel.send({id:n,type:"ws-close"})}finally{this.release(n)}});let s;return o.getConnectionDiagnostics=()=>{const i=this.transportDiagnostics?.();return i?{...i,socketOpenMs:o.openedAfterMs,socketQueueMs:s,pendingWrites:this.channel.hasPendingWrites,activeRequests:[...this.pending.values()].filter(a=>a.kind!=="socket").length,waitingRequests:this.waiting.length}:void 0},this.reserve("socket",r.signal).then(i=>{if(s=performance.now()-o.createdAt,n=i.id,o.readyState===3){this.release(n);return}const a=this.pending.get(n);if(!a)throw new Error("Secure connection closed");a.socket=o,this.channel.send({id:n,type:"ws-open",path:e})}).catch(i=>{n&&this.release(n),o.fail(Gt(i))}),o}async fetch(e,n){const r=typeof location>"u"?"https://termdock.invalid":location.origin,o=e instanceof Request?e:null,s=new URL(o?.url??String(e),r);if(s.origin!==r)throw new Error("Only current-service API requests are supported");const i=new Request(s,o?new Request(o,n):n),a=i.method.toUpperCase(),c=wu(s.pathname+s.search),l=s.pathname==="/api/terminal/fs/upload"?110*1024*1024:cE;if(i.signal.aborted)throw i.signal.reason;const d={};i.headers.forEach((A,N)=>{["cookie","authorization","host","connection","content-length"].includes(N)||(d[N]=A)});const{id:u,queue:f}=await this.reserve("http",i.signal),h=f[Symbol.asyncIterator]();let g;const m=()=>{g?.cancel().catch(()=>{})},b=this.pending.get(u);if(!b)throw new Error("Secure connection closed");b.cancelUpload=m;const w=()=>{m();try{this.channel.send({id:u,type:"cancel"})}catch{}f.end(Gt(i.signal.reason??"Request aborted")),this.release(u)};i.signal.addEventListener("abort",w,{once:!0});const I=()=>{i.signal.removeEventListener("abort",w),this.release(u)},y=async()=>{let A;try{const N=(await Promise.race([h.next(),new Promise((k,T)=>{A=setTimeout(()=>T(new Error("服务响应超时,请重试。")),Vo)})])).value;if(!N)throw new Error("Secure response ended unexpectedly");if(N.type==="error")throw Gt(N.error);return N}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 S=i.body.getReader();g=S;let v=0,E=0;try{for(;;){const{done:_,value:L}=await S.read();if(_)break;if(v+=L.byteLength,v>l)throw new Error("Request body exceeds upload limit");for(let C=0;C<L.byteLength;C+=Or){if(this.channel.send({id:u,type:"upload",data:zp(L.subarray(C,C+Or))}),(await y()).type!=="upload-ack")throw new Error("Invalid upload acknowledgement");E+=Math.min(Or,L.byteLength-C),n?.onUploadProgress?.(E)}}}catch(_){throw await S.cancel(_).catch(()=>{}),_}finally{g=void 0,S.releaseLock()}}if(i.signal.aborted||this.stopped)throw new Error("Request aborted");this.channel.send({id:u,type:"upload-end"});const A=await y();if(A.type!=="head"||typeof A.status!="number")throw new Error("Invalid response header");const N=new Headers(A.headers);if(a==="HEAD"||[204,205,304].includes(A.status)){if((await y()).type!=="end")throw new Error("Unexpected response body");return I(),new Response(null,{status:A.status,headers:N})}let k=!1;const T=new ReadableStream({pull:async S=>{try{k&&(this.channel.send({id:u,type:"ack"}),k=!1);const v=await y();if(v.type==="end"){S.close(),I();return}if(v.type!=="chunk"||typeof v.data!="string")throw new Error("Invalid response chunk");const E=Gp(v.data);if(E.length>Or)throw new Error("Response chunk exceeds budget");S.enqueue(E),k=!0}catch(v){S.error(v),w(),I()}},cancel:()=>{w(),I()}},{highWaterMark:Or,size:S=>S.byteLength});return new Response(T,{status:A.status,headers:N})}catch(A){throw w(),I(),A}}retire(){for(const e of this.pending.values())e.socket?.accept({id:"",type:"ws-close",code:qp,reason:Kp});this.close()}close(e=new Error("Secure connection closed")){if(!this.stopped){this.stopped=!0,this.closeReason=e;for(const n of this.waiting.splice(0))n.cleanup(),n.reject(e);for(const n of this.pending.values())n.queue.end(e),n.cancelUpload?.(),n.socket?.fail(e);this.pending.clear(),this.channel.close(e)}}}async function Sn(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 Up(),r=performance.now(),o=(t.socketFactory??(l=>new WebSocket(l)))(e.href),s=aE(o),i=new AbortController,a=setTimeout(()=>i.abort(new Error("Secure handshake timed out")),2e4),c=t.signal?AbortSignal.any([t.signal,i.signal]):i.signal;try{await new Promise((m,b)=>{if(c.aborted){b(c.reason);return}const w=()=>{c.removeEventListener("abort",A),o.removeEventListener("open",I),o.removeEventListener("error",y),o.removeEventListener("close",y)},I=()=>{w(),m()},y=()=>{w(),b(new Error("Secure transport unavailable"))},A=()=>{w(),b(c.reason)};c.addEventListener("abort",A,{once:!0}),o.addEventListener("open",I),o.addEventListener("error",y),o.addEventListener("close",y),o.readyState===1&&I()});const l=performance.now(),d=await nE({identity:n,duplex:s,initiator:!0,targetPinnedPeerId:t.targetPeerId,signal:c}),u=new uE(new iE(d.duplex),n,d.authenticatedPeerId),f=performance.now(),h=Date.now(),g=o.connectionTimings;if(u.transportDiagnostics=()=>({endpoint:e.host,path:g?"relay":"direct",targetPeerId:d.authenticatedPeerId,transportOpenMs:l-r,handshakeMs:f-l,establishedAt:h,relay:g?{...g}:void 0,bufferedBytes:o.bufferedAmount,pendingWrites:!1,activeRequests:0,waitingRequests:0}),t.pairingCode)try{await u.request({type:"pair",code:t.pairingCode})}catch(m){throw u.close(Gt(m)),m}return u}catch(l){throw o.close(),l}finally{clearTimeout(a)}}const yu=256*1024,fE=1024*1024;class hE extends EventTarget{constructor(e,n,r=o=>new WebSocket(o)){if(super(),this.url=e,!/^[a-zA-Z0-9_.:-]{1,160}$/.test(n))throw new Error("Invalid target identity");const o=performance.now();let s;this.upstream=r(e),this.upstream.addEventListener("open",()=>{this.connectionTimings.entryOpenMs=performance.now()-o}),this.deadline=setTimeout(()=>this.fail("Relay connection timed out"),2e4),this.upstream.addEventListener("message",i=>{if(this.readyState!==3)try{if(typeof i.data!="string"||new TextEncoder().encode(i.data).length>yu)throw new Error("Invalid relay envelope");const a=JSON.parse(i.data);if(a.type==="ready"&&!this.requested){s=performance.now(),this.requested=!0,this.transmit({type:"open",streamId:this.streamId,serviceId:n});return}if(a.streamId!==this.streamId)return;if(a.type==="opened"&&this.readyState===0){this.connectionTimings.routeOpenMs=s===void 0?null:performance.now()-s,clearTimeout(this.deadline),this.readyState=1;const u=new Event("open");this.dispatchEvent(u),this.onopen?.(u);return}if(a.type==="close"){this.finish(1001,"Relay route closed"),this.upstream.close();return}if(a.type!=="data"||this.readyState!==1||a.encoding!=="base64"||typeof a.payload!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(a.payload))throw new Error("Invalid ciphertext relay frame");const c=Gp(a.payload),l=this.binaryType==="blob"?new Blob([c]):c.buffer,d=new MessageEvent("message",{data:l});this.dispatchEvent(d),this.onmessage?.(d)}catch{this.fail("Relay protocol rejected frame")}}),this.upstream.addEventListener("close",i=>this.finish(i.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;connectionTimings={entryOpenMs:null,routeOpenMs: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>fE||n.length>yu)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:zp(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 Yp(t){return e=>new hE(e,t)}function pE(t){if(typeof t!="string"||!t.startsWith("/api/")||/[\\\x00-\x20\x7f#]/.test(t))return null;const e=t.split("?")[0];if(e.includes("//"))return null;try{const r=e.split("/").map((o,s)=>{if(s===0||o===""&&s===e.split("/").length-1)return o;const i=decodeURIComponent(o);if(!i||i==="."||i===".."||/[\\/\x00-\x1f\x7f]/.test(i)||/%[a-f0-9]{2}/i.test(i))throw new Error("Ambiguous API path");return i}).join("/");return r.endsWith("/")&&!r.startsWith("/api/terminal/fs/preview/")?null:r}catch{return null}}function gE(t){if(!("serviceWorker"in navigator))return()=>{};const e=new Set,n=r=>{if(r.source!==navigator.serviceWorker.controller||r.data?.type!=="termdock-secure-fetch"||r.ports.length!==1)return;const o=r.ports[0],{path:s,method:i,headers:a,body:c,expectedTargetPeerId:l,previewPrefix:d}=r.data;let u;try{u=new URL(s,location.origin)}catch{o.close();return}if(u.origin!==location.origin||!u.pathname.startsWith("/api/")||e.size>=32||typeof i!="string"||c!==void 0&&(!(c instanceof ArrayBuffer)||c.byteLength>5*1024*1024)){o.postMessage({type:"error"}),o.close();return}if(d!==void 0&&(typeof d!="string"||!d.endsWith("/")||!/^\/api\/terminal\/fs\/preview\/[a-f0-9]{32}\//.test(d)||!["GET","HEAD"].includes(i)||!pE(u.pathname)?.startsWith(d))){o.postMessage({type:"error"}),o.close();return}const f=new AbortController;let h,g,m=!1,b=!1;const w=()=>{b||(b=!0,e.delete(w),f.abort(),h?.cancel().catch(()=>{}),o.close())};e.add(w),o.onmessage=I=>{if(I.data?.type==="cancel"){w();return}I.data?.type!=="pull"||m||b||(m=!0,(async()=>{if(!h){o.postMessage({type:"end"}),w();return}if(!g?.length){const A=await h.read();if(A.done){o.postMessage({type:"end"}),w();return}g=A.value}const y=g.slice(0,64*1024);g=g.subarray(y.length),o.postMessage({type:"chunk",data:y.buffer},[y.buffer])})().catch(()=>{o.postMessage({type:"error"}),w()}).finally(()=>{m=!1}))},o.onmessageerror=w,o.start(),(async()=>{const I=await t();if(b)return;if(l&&l!==I.targetPeerId)throw new Error("Preview target changed");const y=await I.fetch(u.pathname+u.search,{method:i,headers:a,body:["GET","HEAD"].includes(i)?void 0:c,signal:f.signal});if(b){await y.body?.cancel();return}h=y.body?.getReader();const A={};y.headers.forEach((N,k)=>{A[k]=N}),o.postMessage({type:"head",status:y.status,headers:A,bodyless:!h,targetPeerId:I.targetPeerId})})().catch(()=>{b||(o.postMessage({type:"error"}),w())})};return navigator.serviceWorker.addEventListener("message",n),()=>{navigator.serviceWorker.removeEventListener("message",n);for(const r of[...e])r()}}class tt extends Error{constructor(){super("Device authorization expired or revoked")}}const Xo=new WeakMap;function vr(t,e={}){const n=Xo.get(t);if(!t.closed&&n&&(!n.settled||Date.now()-n.at<(e.maxAgeMs??1e3)))return n.pending;const r={at:Date.now(),settled:!1,pending:void 0},o=mE(t,e.timeoutMs??5e3).then(s=>(r.at=Date.now(),r.settled=!0,s),s=>{throw Xo.get(t)===r&&Xo.delete(t),s});return r.pending=o,Xo.set(t,r),o}async function mE(t,e){const n=await t.request({type:"permissions"},{timeoutMs:e});if(n.type!=="result"||typeof n.fullService!="boolean"||!Array.isArray(n.grants))throw new Error("Invalid permission response");const r=n.grants,o=n.fullService===!0;if(!o&&r.length===0)throw new tt;return{fullService:o,grants:r,canManage:o&&r.length>0||r.some(s=>s.actions.includes("authorization.manage"))}}const Zp="termdock-secure-last-path:",wE=10*6e4;function Jp(t){try{const e=JSON.parse(sessionStorage.getItem(Zp+t)||"null");return e&&typeof e.key=="string"&&Date.now()-e.at<wE?e.key:void 0}catch{return}}function hc(t,e){try{sessionStorage.setItem(Zp+t,JSON.stringify({key:e,at:Date.now()}))}catch{}}function Qp(t,e,n=!1){return new Promise((r,o)=>{let s=0,i=0,a=!1,c,l;const d=new Set,u=()=>{clearTimeout(l);for(const h of d)h.abort();d.clear()},f=()=>{if(a)return;if(s>=t.length){i||(a=!0,u(),o(c||new Error("没有可用的连接路线。")));return}if(i>=(n?1:2))return;const h=t[s++],g=performance.now(),m=w=>{performance.getEntriesByName("termdock:connection-path").length>64&&performance.clearMeasures("termdock:connection-path"),performance.measure("termdock:connection-path",{start:g,end:performance.now(),detail:{path:h.key.startsWith("relay:")?"relay":"direct",ok:w}})},b=new AbortController;d.add(b),i++,h.run(b.signal).then(w=>{if(m(!0),d.delete(b),a){e(w);return}a=!0,u(),r({value:w,key:h.key})},w=>{if(m(!1),d.delete(b),i--,!a){if(c=w,w instanceof tt){a=!0,u(),o(w);return}f()}}),clearTimeout(l),!n&&s<t.length&&(l=setTimeout(f,400))};f()})}const yE=3,bE=1/0,vE=10,eg="termdock-secure-workspace-limit";function tg(t){return t===1/0||Number.isInteger(t)&&t>=3&&t<=vE}function SE(){try{const t=localStorage.getItem(eg),e=t==="unlimited"?1/0:Number(t);if(tg(e))return e}catch{}return navigator.maxTouchPoints>0?yE:bE}function xE(t,e,n,r){if(t.length<=r)return t;const o=new Set(["root",e,...n?[n]:[]]),s=[...t].reverse().sort((i,a)=>a.touchedAt-i.touchedAt);for(const i of s){if(o.size>=r)break;o.add(i.key)}return t.filter(i=>o.has(i.key))}const ng="termdock-workspace",bo="termdock:workspace-visibility",pc="termdock:workspace-activate";function mi(){return window.parent!==window&&location.pathname==="/workspace.html"&&new URLSearchParams(location.search).get(ng)||"root"}let bu,vu;function wt(){try{if(window.parent===window)return window.__termdockWorkspaceHost;const t=window.parent.__termdockWorkspaceHost;return t&&t!==bu&&(bu=t,vu={...t,subscribe(e){const n=t.subscribe(e,mi()),r=o=>{o.persisted||n()};return window.addEventListener("pagehide",r),()=>{n(),window.removeEventListener("pagehide",r)}}}),t?vu:void 0}catch{return}}function as(){const t=wt();return!t||t.snapshot().activeKey===mi()}function Ks(t,e=!0){return wt()?.activate(t,e)??!1}function $n(t){wt()?.report(mi(),t)}const gc="termdock-secure-workspace-session:",rg="termdock-secure-last-workspace";function EE(){for(const t of["sessionStorage","localStorage"])try{const e=window[t].getItem(rg);if(e)return e}catch{}return null}function AE(t){for(const e of["sessionStorage","localStorage"])try{window[e].setItem(rg,t)}catch{}}function FR(t){if(t)try{const e=JSON.parse(localStorage.getItem(gc+t)||"null");return localStorage.removeItem(gc+t),e&&typeof e.sessionId=="string"&&Date.now()-e.at<6e4?e.sessionId:void 0}catch{return}}function kE(t){if(window.parent!==window||window.termdockDesktop)return;if(window.__termdockWorkspaceHost)return window.__termdockWorkspaceHost;let e={activeKey:"root",items:[{key:"root",service:t,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]};try{const u=EE(),f=t&&u!==t.targetPeerId?yn().find(h=>h.targetPeerId===u):void 0;f?.targetPeerId&&(e={activeKey:f.targetPeerId,items:[...e.items,{key:f.targetPeerId,service:f,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]})}catch{}let n=SE(),r=e.activeKey==="root"?"root":null;const o=new Map,s=new Map([["root",window]]),i=new Set,a=()=>{for(const u of[...o.keys()])u()},c=()=>{const u=xE(e.items,e.activeKey,r,n),f=new Set(u.map(h=>h.key));e={...e,items:u};for(const[h,g]of o)g&&!f.has(g)&&o.delete(h);for(const h of s.keys())f.has(h)||s.delete(h);for(const h of i)f.has(h)||i.delete(h)},l=(u,f)=>{try{const h=f.document.createEvent("CustomEvent");if(h.initCustomEvent(bo,!1,!1,{active:e.activeKey===u}),f.dispatchEvent(h),e.activeKey===u){const g=f.document.createEvent("Event");if(g.initEvent("resize",!1,!1),f.dispatchEvent(g),i.delete(u)){const m=f.document.createEvent("Event");m.initEvent(pc,!1,!1),f.dispatchEvent(m)}}else f.document.activeElement?.blur?.()}catch{}},d={snapshot:()=>e,subscribe:(u,f)=>(o.set(u,f),()=>{o.delete(u)}),present(u){r=u},retentionLimit:()=>n,setRetentionLimit(u){if(tg(u)){n=u;try{localStorage.setItem(eg,u===1/0?"unlimited":String(u))}catch{}c(),a()}},activate(u,f=!0){const h=ti(u);if(!h?.targetPeerId)return!1;const g=e.items.find(w=>w.service?.targetPeerId===h.targetPeerId),m=g?.key||h.targetPeerId,b=g?{...g,service:h,touchedAt:Date.now()}:{key:m,service:h,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()};e={activeKey:m,items:g?e.items.map(w=>w===g?b:w):[...e.items,b]},c(),AE(h.targetPeerId),f&&i.add(m),a();for(const[w,I]of s)l(w,I);return!0},report(u,f){const h=e.items.find(m=>m.key===u);if(!h||f.service&&h.service?.targetPeerId&&f.service.targetPeerId!==h.service.targetPeerId)return;const g={...h,...f};JSON.stringify(g)!==JSON.stringify(h)&&(e={...e,items:e.items.map(m=>m===h?g:m)},a())},attach(u,f){f&&e.items.some(h=>h.key===u)?(s.set(u,f),l(u,f)):s.delete(u)},focusSession(u,f){const h=yn().find(m=>m.targetPeerId===u);if(!h)return!1;try{localStorage.setItem(gc+u,JSON.stringify({sessionId:f,at:Date.now()}))}catch{return!1}d.activate(h,!1);const g=s.get(e.activeKey);if(g){const m=g.document.createEvent("CustomEvent");m.initCustomEvent("termdock:workspace-session",!1,!1,null),g.dispatchEvent(m)}return!0}};return window.__termdockWorkspaceHost=d,d}let Qi;async function nt(){return Qi||(Qi=(async()=>{const t=await new Promise((e,n)=>{const r=indexedDB.open("termdock-device-identity",1);r.onupgradeneeded=()=>r.result.createObjectStore("keys"),r.onsuccess=()=>e(r.result),r.onerror=()=>n(r.error)});try{const e=await new Promise((o,s)=>{const i=t.transaction("keys").objectStore("keys").get("identity");i.onsuccess=()=>o(i.result),i.onerror=()=>s(i.error)});if(e)return mu(e);const n=await Up();let r=n;return await new Promise((o,s)=>{const i=t.transaction("keys","readwrite"),a=i.objectStore("keys"),c=a.get("identity");c.onsuccess=()=>{typeof c.result=="string"?r=mu(c.result):a.put(Jx(n),"identity")},i.oncomplete=()=>o(),i.onerror=()=>s(i.error)}),r}finally{t.close()}})()),Qi}const et="termdock:secure-state";let Q,qn,Ue,pr="direct",cs=!1,Su=0,ls=!1,xu=-1/0;const gr=globalThis.fetch.bind(globalThis);function se(){return fo()}function Vt(){return Q}function CE(){return Ue}function og(){Q?.close(),Ue?.close(),Q=void 0,Ue=void 0}async function sg(){const t=await gr("/api/auth/status",{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error("Failed to query auth status");return t.json()}async function IE(){if(se()){await it();return}if((await sg()).enabled)return;const t=await gr("/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 ct({url:location.origin,targetPeerId:e,serviceName:location.hostname})}async function RE(t,e){const{startPasswordBootstrap:n,finishPasswordBootstrap:r}=await tn(async()=>{const{startPasswordBootstrap:l,finishPasswordBootstrap:d}=await import("./passwordBootstrap-C-wELkSK.js");return{startPasswordBootstrap:l,finishPasswordBootstrap:d}},__vite__mapDeps([0,1,2,3])),o=l=>t===location.origin?l:new URL(l,t).href,s=async(l,d)=>{const u=await gr(o(l),{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(15e3),...d?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}:{}});if(!u.ok)throw new Error(u.status===429?"尝试次数较多,请稍后再试。":u.status===401?"密码不正确,请重新输入。":"暂时无法登录这台服务,请稍后重试。");return u.json()},{saltHex:i}=await s("/api/auth/password/parameters"),a=await nt(),c=await n(e,i);try{const l=await s("/api/auth/password/start",{startLoginRequest:c.startLoginRequest,clientIdentity:a.peerId});let d;try{d=await r(c,l,{clientIdentity:a.peerId,origin:location.origin})}catch{throw new Error("密码不正确,或服务身份无法验证。请检查后重试。")}return await s("/api/auth/password/finish",{attemptId:d.attemptId,finishLoginRequest:d.finishLoginRequest}),{url:t,targetPeerId:d.serverIdentity,serviceName:new URL(t).host,serviceOrigin:t}}finally{c.passwordKey=""}}async function Al(t,e){const n=se();if(n&&(n.serviceOrigin||n.url)===t)return await mc(n,e),n;try{return await RE(t,e)}catch(r){if(!(r instanceof TypeError)&&!(r instanceof DOMException))throw r;const o=(await Ge()).find(i=>i.targetPeerId&&(i.serviceOrigin||i.url)===t);if(!o?.targetPeerId)throw new Error("暂时连不上这台服务,请检查地址和网络。");const s={...o,targetPeerId:o.targetPeerId,serviceName:o.label};return await mc(s,e),s}}async function mc(t,e){const n=await kl(t),{startPasswordBootstrap:r,finishPasswordBootstrap:o}=await tn(async()=>{const{startPasswordBootstrap:i,finishPasswordBootstrap:a}=await import("./passwordBootstrap-C-wELkSK.js");return{startPasswordBootstrap:i,finishPasswordBootstrap:a}},__vite__mapDeps([0,1,2,3]));let s;try{const i=await n.request({type:"password-parameters"},{timeoutMs:5e3});s=await r(e,String(i.saltHex));const a=await n.request({type:"password-start",startLoginRequest:s.startLoginRequest,origin:location.origin}),c=await o(s,a,{clientIdentity:(await nt()).peerId,origin:location.origin});if(c.serverIdentity!==t.targetPeerId)throw new Error("服务身份发生变化。");await n.request({type:"password-finish",attemptId:c.attemptId,finishLoginRequest:c.finishLoginRequest})}catch{throw new Error("暂时无法登录,请检查目标服务密码与入口授权后重试。")}finally{s&&(s.passwordKey=""),n.close()}}async function TE(t){try{const e=se(),n=e?.serviceOrigin||location.origin,r=await Al(n,t);return await ct({...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 Eu(t,e){const n=Me(t),r=(await Ge()).find(i=>(i.serviceOrigin||i.url)===n&&i.targetPeerId);if(e===void 0&&r?.targetPeerId)try{return await ct({...r,targetPeerId:r.targetPeerId,serviceName:r.label}),{}}catch(i){if(!(i instanceof tt))throw i}if(e!==void 0){const i=await Al(n,e);if(r?.targetPeerId&&r.targetPeerId!==i.targetPeerId)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await ct({...i,routes:r?.routes,serviceName:r?.label||i.serviceName}),{}}const o=await gr(new URL("/api/auth/open/parameters",n).href,{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(1e4)}).catch(()=>{throw new Error("暂时连不上这台服务,请检查地址和网络后重试。")});if(o.status===403)return{passwordRequired:!0};if(!o.ok)throw new Error("这台服务暂时不可用,请稍后重试。");const{serviceIdentity:s}=await o.json();if(typeof s!="string"||!s)throw new Error("这不是可连接的 Termdock 服务。");if(r?.targetPeerId&&r.targetPeerId!==s)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await ct({url:n,targetPeerId:s,serviceName:r?.label||new URL(n).host,serviceOrigin:n}),{}}function en(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(Wc)||"null");n&&n.targetPeerId!==t.targetPeerId&&new URL(n.url).host===new URL(t.url).host&&e.push(n)}catch{}return e.flatMap((n,r)=>{try{return n.targetPeerId&&n.targetPeerId!==t.targetPeerId&&e.findIndex(o=>o.targetPeerId===n.targetPeerId)===r?[{url:Me(n.url),targetPeerId:n.targetPeerId}]:[]}catch{return[]}}).slice(0,4)}function Sr(t){const e=en(t),n=[t.serviceOrigin||t.url,...(t.routes||[]).slice(0,4).filter(o=>o.targetPeerId===t.targetPeerId).map(o=>o.url)],r=new Set;for(const o of n)try{const s=Me(o);e.some(i=>i.url===s)||r.add(s)}catch{}return[...r]}function xn(t){const e=new URL("/api/federation/secure",Me(t));return e.protocol=e.protocol==="https:"?"wss:":"ws:",e.href}async function nn(t,e){return Sn({url:xn(t.url),targetPeerId:t.targetPeerId,identity:await nt(),signal:e?AbortSignal.any([e,AbortSignal.timeout(5e3)]):AbortSignal.timeout(5e3)})}async function kl(t,e){const n=await nt(),r=Sr(t).map(i=>({key:`direct:${i}`,run:a=>Sn({url:xn(i),targetPeerId:t.targetPeerId,identity:n,signal:AbortSignal.any([a,AbortSignal.timeout(8e3),...e?[e]:[]])})}));for(const i of en(t))r.push({key:`relay:${i.targetPeerId}:${i.url}`,run:async a=>{e&&(a=AbortSignal.any([a,e]));const c=[Q,Ue].find(d=>d&&!d.closed&&d.targetPeerId===i.targetPeerId),l=c||await nn(i,a);try{if(a.aborted)throw a.reason;const d=await l.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(a.aborted)throw a.reason;if(typeof d.routeToken!="string")throw new Error("入口未允许此设备连接该服务。");const u=new URL(xn(i.url));return u.pathname="/api/federation/relay",u.searchParams.set("routeToken",d.routeToken),await Sn({url:u.href,targetPeerId:t.targetPeerId,identity:n,socketFactory:Yp(t.targetPeerId),signal:AbortSignal.any([a,AbortSignal.timeout(8e3)])})}finally{c||l.close()}}});const o=Jp(t.targetPeerId);r.sort((i,a)=>+(a.key===o)-+(i.key===o));const s=await Qp(r,i=>i.close());return hc(t.targetPeerId,s.key),s.value}async function PE(t,e){const n=await kl(t,e);try{const o=(await n.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node;if(o?.serviceId!==t.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");return{...o,serviceId:t.targetPeerId}}finally{n.close()}}async function NE(t,e){const n=await kl(t,e),r=()=>n.close();e.addEventListener("abort",r,{once:!0});try{if(e.aborted||(await vr(n,{timeoutMs:3e3}),e.aborted))throw e.reason;return n}catch(o){throw n.close(),o}finally{e.removeEventListener("abort",r)}}async function ct(t,e={}){const n=Q,r=Ue,o=await nt(),s=Me(t.serviceOrigin||t.url),i=(await Ge()).find(w=>w.targetPeerId===t.targetPeerId),a={...t,routes:t.routes??i?.routes},c=en(a),l=Sr(a);let d,u,f=t.pairingCode,h="direct";const g=new Set,m=new Map,b=async(w,I)=>{if(n&&!n.closed&&n.targetPeerId===w.targetPeerId)return n;if(r&&!r.closed&&r.targetPeerId===w.targetPeerId)return r;const y=m.get(w.targetPeerId);if(y&&!y.closed)return y;const A=await nn(w,I);return g.add(A),m.set(w.targetPeerId,A),A};try{if(t.routeCode&&t.entryServiceId){const S=c.find(_=>_.targetPeerId===t.entryServiceId);if(!S)throw new Error("邀请缺少入口信息。");if((await(await b(S)).request({type:"route-pair",code:t.routeCode})).serviceId!==t.targetPeerId)throw new Error("邀请的目标服务不一致。");t.routeOnly&&await Lt({id:t.targetPeerId,url:s,label:t.serviceName||new URL(s).host,targetPeerId:t.targetPeerId,serviceOrigin:s,routes:c})}const w=[],I=async(S,v)=>{const E=()=>S.close();v.addEventListener("abort",E,{once:!0});try{if(v.aborted||(await vr(S),v.aborted))throw v.reason}catch(_){throw S.close(),_}finally{v.removeEventListener("abort",E)}};for(const S of l)w.push({key:`direct:${S}`,run:async v=>{const E=await Sn({url:xn(S),targetPeerId:t.targetPeerId,pairingCode:f,identity:o,signal:AbortSignal.any([v,AbortSignal.timeout(8e3)])});return f=void 0,await I(E,v),{client:E,path:"direct"}}});for(const S of c)w.push({key:`relay:${S.targetPeerId}:${S.url}`,run:async v=>{let E,_;try{if(E=await b(S,v),v.aborted)throw v.reason;const L=await E.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(v.aborted)throw v.reason;if(typeof L.routeToken!="string"||!L.routeToken)throw new Error("入口未允许此设备连接该服务。");const C=new URL(xn(S.url));return C.pathname="/api/federation/relay",C.searchParams.set("routeToken",L.routeToken),_=await Sn({url:C.href,targetPeerId:t.targetPeerId,pairingCode:f,identity:o,socketFactory:Yp(t.targetPeerId),signal:AbortSignal.any([v,AbortSignal.timeout(8e3)])}),f=void 0,await I(_,v),{client:_,entry:E,path:"relay"}}catch(L){throw _?.close(),E&&E!==r&&E!==n&&E.close(),L}}});const y=Jp(t.targetPeerId);w.sort((S,v)=>+(v.key===y)-+(S.key===y));const A=await Qp(w,S=>{S.client.close(),S.entry&&S.entry!==n&&S.entry!==r&&S.entry.close()},!!f);if(d=A.value.client,u=A.value.entry,h=A.value.path,e.renewIfCurrent){if(Q!==e.renewIfCurrent||n!==e.renewIfCurrent||n.closed||!n.canSwitchTransport||se()?.targetPeerId!==t.targetPeerId){d.close();for(const S of g)S!==Ue&&S!==Q&&S.close();return Q??n}Q=d,pr=h,Ue=u,hc(t.targetPeerId,A.key),n.retire();for(const S of new Set([r,...g]))S&&S!==n&&S!==d&&S!==u&&S.close();return window.dispatchEvent(new Event(et)),d}if(hc(t.targetPeerId,A.key),Q!==n&&Q&&!Q.closed&&Q.targetPeerId===t.targetPeerId){d.close();for(const S of g)S!==Ue&&S.close();return Q}h==="direct"&&new URL(s).host===location.host&&Jm(t.targetPeerId);const N=(await Ge()).find(S=>S.targetPeerId===t.targetPeerId||!S.targetPeerId&&(S.serviceOrigin||S.url)===s),k=N?.label||t.serviceName||new URL(s).host,T={url:s,targetPeerId:t.targetPeerId,serviceName:k,serviceOrigin:s,routes:a.routes??c};if(await(e.rememberOnly?ew:Lt)({id:N?.id||t.targetPeerId,...T,label:k}),Vn!=="unpaired"&&Vn!==t.targetPeerId&&wt()&&Ks({id:N?.id||t.targetPeerId,...T,label:k})){d.close();for(const S of g)S!==n&&S!==r&&S.close();return n||d}Hf(T),Q=d,pr=h,Ue=u;for(const S of new Set([n,r,...g]))S&&S!==d&&S!==u&&S.close();return Vn!==t.targetPeerId?(location.reload(),new Promise(()=>{})):(window.dispatchEvent(new Event(et)),d)}catch(w){d?.close();for(const I of g)I!==r&&I.close();throw w}}async function LE(){const t=Q,e=se();if(!(ls||cs||qn||!t?.renewalDue||!t.canSwitchTransport||!e||performance.now()-xu<3e4)){xu=performance.now(),ls=!0;try{await ct(e,{renewIfCurrent:t})}catch(n){console.debug("[connection] renewal deferred",{reason:n instanceof Error?n.message:"unknown"})}finally{ls=!1}}}async function BE(){const t=Q,e=se();if(Date.now()-Su<6e4||ls||cs||pr!=="relay"||!t||t.closed||!t.canSwitchTransport||!e?.serviceOrigin)return;cs=!0,Su=Date.now();let n;try{for(const o of Sr(e))try{n=await Sn({url:xn(o),targetPeerId:e.targetPeerId,identity:await nt(),signal:AbortSignal.timeout(3e3)}),await vr(n);break}catch(s){if(n?.close(),n=void 0,s instanceof tt)throw s}if(!n||Q!==t||!t.canSwitchTransport)return;const r=Ue;Q=n,n=void 0,Ue=void 0,pr="direct",t.close(),r?.close(),window.dispatchEvent(new Event(et))}catch(r){r instanceof tt&&Q===t&&(og(),window.dispatchEvent(new Event("auth:unauthorized")))}finally{n?.close(),cs=!1}}function _E(){return pr}async function OE(t){return t?(t.throwIfAborted(),new Promise((e,n)=>{const r=()=>n(t.reason);t.addEventListener("abort",r,{once:!0}),it().then(o=>{t.removeEventListener("abort",r),t.aborted?n(t.reason):e(o)},o=>{t.removeEventListener("abort",r),n(o)})})):it()}async function it(){if(Q&&!Q.closed){const e=Q;return LE(),e}if(Q=void 0,qn)return qn;const t=se();if(!t)throw new Error("DEVICE_PAIRING_REQUIRED");return qn=ct(t,{rememberOnly:!0}).catch(e=>{if(Q&&!Q.closed&&Q.targetPeerId===t.targetPeerId)return Q;throw e}).finally(()=>{qn=void 0}),qn}function ig(t){const e=new URL(t,location.href);if(Q&&!Q.closed)return Q.openSocket(e.pathname+e.search);let n;const r=new Xp(t,o=>n?.send(o),()=>n?.close());return it().then(o=>{r.readyState!==3&&(n=o.openSocket(e.pathname+e.search),r.getConnectionDiagnostics=()=>{const s=n?.getConnectionDiagnostics?.();return s?{...s,socketOpenMs:r.openedAfterMs}:void 0},n.onopen=()=>r.accept({type:"ws-ready",id:""}),n.onmessage=s=>r.accept({type:"ws-data",id:"",data:s.data}),n.onclose=s=>r.accept({type:"ws-close",id:"",code:s.code,reason:s.reason}),n.onerror=()=>r.fail(new Error("Encrypted connection unavailable")))}).catch(o=>r.fail(o)),r}function DE(){gE(it),window.fetch=async(t,e)=>{const n=new URL(t instanceof Request?t.url:String(t),location.href);if(!n.pathname.startsWith("/api/"))return gr(t,e);if(n.origin!==location.origin)throw new Error("Remote business API requires a paired encrypted service");if(n.pathname==="/api/meta")return gr(t,e);if(n.pathname==="/api/auth/status"){if(!se()){const s=await sg();return Response.json({enabled:s.enabled,authenticated:!1})}try{const s=await vr(await it());return Response.json({enabled:s.grants.length>0,authenticated:!0})}catch(s){if(s instanceof tt)return Response.json({enabled:!0,authenticated:!1});throw s}}if(n.pathname==="/api/auth/login"){const i=await new Request(t instanceof Request?t:n.href,e).json();return TE(typeof i.password=="string"?i.password:"")}if(n.pathname==="/api/csrf-token")return Response.json({csrfToken:"encrypted-device-channel"});if(n.pathname==="/api/auth/logout")return Q&&!Q.closed&&await Q.request({type:"logout"}),Q?.close(),Ue?.close(),Q=void 0,Ue=void 0,Zm(),location.reload(),Response.json({ok:!0});const r=e?.signal!==void 0?e.signal:t instanceof Request?t.signal:void 0,o=await OE(r);return t instanceof Request?o.fetch(t,e):o.fetch(n.pathname+n.search,e)}}async function FE(t){if(!t.targetPeerId)throw new Error("请先连接这台服务,再查看可中转的服务。");for(const e of Sr({...t,targetPeerId:t.targetPeerId})){let n;const r={url:e,targetPeerId:t.targetPeerId};try{n=await nn(r)}catch{continue}try{const o=await n.request({type:"route-targets"},{timeoutMs:5e3});if(!Array.isArray(o.items))throw new Error("入口服务需要更新后才能查看中转列表。");return{route:r,canManage:o.canManage===!0,items:o.items}}catch(o){throw o instanceof Error&&/UNKNOWN|UNSUPPORTED/i.test(o.message)?new Error("入口服务需要更新后才能查看中转列表。"):o}finally{n.close()}}throw new Error("暂时连不上中转入口,请检查地址和网络后重试。")}async function ME(t,e){const n=await nn(t);try{const r=await n.request({type:"route-targets"},{timeoutMs:5e3}),o=(Array.isArray(r.items)?r.items:[]).find(c=>c.serviceId===e);if(!o)throw new Error("该服务已不可见,请刷新列表或请入口管理员授权。");if(!o.available)throw new Error("入口暂时无法中转到这台服务,请稍后重试。");const s=(await Ge()).find(c=>c.targetPeerId===o.serviceId),i=[t,...(s?.routes||[]).filter(c=>c.targetPeerId!==t.targetPeerId)];if(i.length>4)throw new Error("这台服务已保存 4 个备用连接,请先移除一个后重试。");if(!o.authorized){if(!r.canManage)throw new Error("请先让入口管理员授权此设备。");await n.request({type:"route-grant",serviceId:o.serviceId,subjectId:(await nt()).peerId})}const a=s?.serviceOrigin||s?.url||o.url||t.url;return{url:a,serviceOrigin:a,targetPeerId:o.serviceId,serviceName:s?.label||o.label||(o.url?new URL(o.url).host:`中转服务 ${o.serviceId.slice(0,8)}`),routes:i}}finally{n.close()}}async function jE(t,e){const n=await nn(t);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),o=(await nt()).peerId;return{canManage:r.canManage===!0,grants:(Array.isArray(r.grants)?r.grants:[]).filter(s=>s.subjectId===o&&s.targetServiceId===e)}}finally{n.close()}}async function HE(t,e,n){if(n!==void 0&&(await Al(Me(e.url),n)).targetPeerId!==e.targetPeerId)throw new Error("入口服务的身份已改变,请重新连接并确认。");const r=await nn(e);try{await r.request({type:"route-grant",serviceId:t.targetPeerId,subjectId:(await nt()).peerId,url:Me(t.serviceOrigin||t.url)})}finally{r.close()}}async function UE(t,e){const n=await nn(e);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),o=(await nt()).peerId,s=(Array.isArray(r.grants)?r.grants:[]).filter(i=>i.subjectId===o&&i.targetServiceId===t&&i.active);for(const i of s)await n.request({type:"route-revoke",grantId:i.id})}finally{n.close()}}async function ag(t,e){const n=await nn(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 ds(t,e){const n=(await Ge()).find(o=>o.id===t.id||t.targetPeerId&&o.targetPeerId===t.targetPeerId)||t;await Lt({...n,url:n.serviceOrigin||n.url,entryServiceId:void 0,routes:e});const r=se();r&&r.targetPeerId===t.targetPeerId&&Hf({...r,url:r.serviceOrigin||r.url,entryServiceId:void 0,routes:e})}async function $E(t,e){const n=t.targetPeerId;if(!n)throw new Error("请先连接这台服务,再添加备用地址。");let r;try{r=Me(e)}catch{throw new Error("请输入有效的 HTTPS 地址,例如 https://电脑地址:9834。")}const o=async()=>(await Ge()).find(a=>a.targetPeerId===n)||t,s=a=>{const c=a.routes??en({...a,targetPeerId:n});if(Me(a.serviceOrigin||a.url)===r||c.some(l=>Me(l.url)===r))throw new Error("这个地址已经在连接列表中。");if(c.length>=4)throw new Error("最多保存 4 个备用地址或入口,请先移除不再使用的连接。");return[...c,{url:r,targetPeerId:n}]};s(await o());let i;try{try{i=await Sn({url:xn(r),targetPeerId:n,identity:await nt(),signal:AbortSignal.timeout(5e3)}),await vr(i)}catch(l){throw l instanceof tt?new Error("这台服务尚未授权当前设备,请先恢复设备授权。"):new Error("无法验证这个地址。请确认能访问该地址、HTTPS 证书受信任,且运行的是同一台 Termdock 服务。")}const a=await o(),c=s(a);if(await ds(a,c),se()?.targetPeerId===n&&Vn===n&&(!Q||Q.closed)){const l=Q,d=Ue;Q=i,i=void 0,Ue=void 0,pr="direct",l?.close(),d?.close(),window.dispatchEvent(new Event(et))}return c}finally{i?.close()}}async function Au(t,e){await mc(t,e),await ct({...t,pairingCode:void 0,routeCode:void 0})}function qE(){let t=!1,e=!1,n=!1,r;const o=new Map,s=new Set,i=new Map,a=async(f,h,g)=>{const m=JSON.stringify(g);if(o.get(h.serviceId)===m)return;const b=AbortSignal.timeout(1e4),w=await f.fetch("/api/csrf-token",{signal:b});if(!w.ok)throw new Error("CONNECTION_AUTHORIZATION_REQUIRED");const I=await w.json();if(typeof I.csrfToken!="string")throw new Error("INVALID_CSRF_TOKEN");const y=await f.fetch("/api/terminal/operations/collaboration-connections",{method:"POST",signal:b,headers:{"Content-Type":"application/json","X-XSRF-TOKEN":I.csrfToken},body:JSON.stringify({origin:h.origin,nodes:g})});if(!y.ok){const A=await y.json().catch(()=>({}));throw new Error(A.error||`HTTP_${y.status}`)}o.set(h.serviceId,m)},c=async()=>{if(t){n=!0;return}const f=se(),h=Vt();if(!(e||!f||!h||h.closed)){t=!0,n=!1;try{let g;const m=await Promise.race([Ge(),new Promise((N,k)=>{g=setTimeout(()=>k(new Error("SERVICE_DIRECTORY_TIMEOUT")),8e3)})]).finally(()=>clearTimeout(g));m.some(N=>N.targetPeerId===f.targetPeerId)||m.push({...f,id:f.targetPeerId,label:f.serviceName||f.url});const b=[...new Map(m.filter(N=>!!N.targetPeerId).map(N=>[N.targetPeerId,N])).values()].slice(0,64);if(b.length<2)return;const w=[];for(const N of b)try{const k=`${N.targetPeerId}:${N.serviceOrigin||N.url}`;let T=i.get(k);if(!T){const S=N.targetPeerId===f.targetPeerId?(await h.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node:await PE({...N,targetPeerId:N.targetPeerId},AbortSignal.timeout(8e3));if(S?.serviceId!==N.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");const v=S.origin||N.serviceOrigin||N.url,E=new URL(v);if(E.protocol!=="https:"||E.origin!==v)throw new Error("INVALID_SERVICE_ORIGIN");T={serviceId:S.serviceId,origin:v,...S.caFingerprint256?{caFingerprint256:S.caFingerprint256}:{}},i.set(k,T)}w.push({service:N,node:T})}catch{}if(e||Vt()!==h||se()?.targetPeerId!==f.targetPeerId)return;const I=w.find(N=>N.node.serviceId===f.targetPeerId);if(!I||w.length<2){l(3e4);return}const y=w.map(N=>N.node).sort((N,k)=>N.serviceId.localeCompare(k.serviceId));await a(h,I.node,y);let A=w.length<b.length;for(const N of w){if(N===I||o.get(N.node.serviceId)===JSON.stringify(y))continue;let k;try{k=await NE({...N.service,targetPeerId:N.node.serviceId},AbortSignal.timeout(8e3)),await a(k,N.node,y)}catch{let T=s.has(N.node.serviceId);if(!T&&k)try{(await k.request({type:"collaboration-scoped-peer",origin:N.node.origin,node:I.node},{timeoutMs:8e3})).type==="result"&&(s.add(N.node.serviceId),T=!0)}catch{}T||(A=!0)}finally{k?.close()}}window.dispatchEvent(new CustomEvent("termdock:collaboration-enrollment",{detail:{ok:!0}})),A&&l(3e4)}catch(g){window.dispatchEvent(new CustomEvent("termdock:collaboration-enrollment",{detail:{ok:!1,error:g instanceof Error?g.message:"CONNECTION_ENROLLMENT_FAILED"}})),l(3e4)}finally{t=!1,n&&l(100)}}};function l(f=100){e||(clearTimeout(r),r=setTimeout(()=>{c()},f))}const d=()=>{l()},u=ni(d);window.addEventListener(et,d),window.addEventListener("termdock:collaboration-enroll",d),window.addEventListener("online",d),window.addEventListener("pageshow",d),window.addEventListener("pagehide",f=>{f.persisted||(e=!0,clearTimeout(r),u(),window.removeEventListener("termdock:collaboration-enroll",d),window.removeEventListener(et,d),window.removeEventListener("online",d),window.removeEventListener("pageshow",d))}),l()}var Yo={},ku;function KE(){if(ku)return Yo;ku=1;var t=$m();return Yo.createRoot=t.createRoot,Yo.hydrateRoot=t.hydrateRoot,Yo}var zE=KE();const GE=jf(zE);function $e({size:t=16,className:e="",...n}){const r=!!(n["aria-label"]||n["aria-labelledby"]);return p.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none","aria-hidden":r?void 0:!0,role:r?"img":void 0,focusable:"false",...n,className:`td-loading-spinner animate-spin ${e.replace(/\b(?:animate-spin|service-spinning)\b/g,"")}`,children:p.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2.5",strokeDasharray:"18 44.8",strokeLinecap:"round"})})}function WE(){return p.jsx("span",{className:"td-loading-dots","aria-hidden":"true",children:[0,1,2].map(t=>p.jsx("span",{style:{animationDelay:`${(t-3)*400}ms`}},t))})}function MR({label:t,className:e="",dots:n=!1}){return p.jsxs("div",{role:"status","aria-live":"polite","aria-atomic":"true",className:`flex items-center justify-center gap-2 text-sm text-muted-foreground ${e}`,children:[n?p.jsx(WE,{}):p.jsx($e,{size:18}),p.jsx("span",{children:t})]})}const cg=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim();const VE=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const XE=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,r)=>r?r.toUpperCase():n.toLowerCase());const Cu=t=>{const e=XE(t);return e.charAt(0).toUpperCase()+e.slice(1)};var ea={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 YE=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1},ZE=O.createContext({}),JE=()=>O.useContext(ZE),QE=O.forwardRef(({color:t,size:e,strokeWidth:n,absoluteStrokeWidth:r,className:o="",children:s,iconNode:i,...a},c)=>{const{size:l=24,strokeWidth:d=2,absoluteStrokeWidth:u=!1,color:f="currentColor",className:h=""}=JE()??{},g=r??u?Number(n??d)*24/Number(e??l):n??d;return O.createElement("svg",{ref:c,...ea,width:e??l??ea.width,height:e??l??ea.height,stroke:t??f,strokeWidth:g,className:cg("lucide",h,o),...!s&&!YE(a)&&{"aria-hidden":"true"},...a},[...i.map(([m,b])=>O.createElement(m,b)),...Array.isArray(s)?s:[s]])});const Le=(t,e)=>{const n=O.forwardRef(({className:r,...o},s)=>O.createElement(QE,{ref:s,iconNode:e,className:cg(`lucide-${VE(Cu(t))}`,`lucide-${t}`,r),...o}));return n.displayName=Cu(t),n};const e1=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],lg=Le("arrow-left",e1);const t1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],n1=Le("arrow-right",t1);const r1=[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]],o1=Le("arrow-up-right",r1);const s1=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M11.68 2.009A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673c-.824-.85-1.678-1.731-2.21-3.348",key:"xaq59h"}],["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}]],dg=Le("bell-dot",s1);const i1=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],zs=Le("check",i1);const a1=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],ug=Le("chevron-down",a1);const c1=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],En=Le("chevron-right",c1);const l1=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],d1=Le("chevron-up",l1);const u1=[["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"}]],fg=Le("copy",u1);const f1=[["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"}]],hg=Le("ellipsis",f1);const h1=[["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"}]],p1=Le("monitor",h1);const g1=[["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"}]],m1=Le("pencil",g1);const w1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],pg=Le("plus",w1);const y1=[["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"}]],wi=Le("server",y1);const b1=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],gg=Le("smartphone",b1);const v1=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],S1=Le("terminal",v1);const x1=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],mg=Le("x",x1),E1={},Iu=t=>{let e;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(e):d;if(!Object.is(f,e)){const h=e;e=u??(typeof f!="object"||f===null)?f:Object.assign({},e,f),n.forEach(g=>g(e,h))}},o=()=>e,c={setState:r,getState:o,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(E1?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},l=e=t(r,o,c);return c},A1=t=>t?Iu(t):Iu;var ta={exports:{}},na={},ra={exports:{}},oa={};var Ru;function k1(){if(Ru)return oa;Ru=1;var t=zc();function e(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var n=typeof Object.is=="function"?Object.is:e,r=t.useState,o=t.useEffect,s=t.useLayoutEffect,i=t.useDebugValue;function a(u,f){var h=f(),g=r({inst:{value:h,getSnapshot:f}}),m=g[0].inst,b=g[1];return s(function(){m.value=h,m.getSnapshot=f,c(m)&&b({inst:m})},[u,h,f]),o(function(){return c(m)&&b({inst:m}),u(function(){c(m)&&b({inst:m})})},[u]),i(h),h}function c(u){var f=u.getSnapshot;u=u.value;try{var h=f();return!n(u,h)}catch{return!0}}function l(u,f){return f()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?l:a;return oa.useSyncExternalStore=t.useSyncExternalStore!==void 0?t.useSyncExternalStore:d,oa}var Tu;function C1(){return Tu||(Tu=1,ra.exports=k1()),ra.exports}var Pu;function I1(){if(Pu)return na;Pu=1;var t=zc(),e=C1();function n(l,d){return l===d&&(l!==0||1/l===1/d)||l!==l&&d!==d}var r=typeof Object.is=="function"?Object.is:n,o=e.useSyncExternalStore,s=t.useRef,i=t.useEffect,a=t.useMemo,c=t.useDebugValue;return na.useSyncExternalStoreWithSelector=function(l,d,u,f,h){var g=s(null);if(g.current===null){var m={hasValue:!1,value:null};g.current=m}else m=g.current;g=a(function(){function w(k){if(!I){if(I=!0,y=k,k=f(k),h!==void 0&&m.hasValue){var T=m.value;if(h(T,k))return A=T}return A=k}if(T=A,r(y,k))return T;var S=f(k);return h!==void 0&&h(T,S)?(y=k,T):(y=k,A=S)}var I=!1,y,A,N=u===void 0?null:u;return[function(){return w(d())},N===null?void 0:function(){return w(N())}]},[d,u,f,h]);var b=o(l,g[0],g[1]);return i(function(){m.hasValue=!0,m.value=b},[b]),c(b),b},na}var Nu;function R1(){return Nu||(Nu=1,ta.exports=I1()),ta.exports}var T1=R1();const P1=jf(T1),wg={},{useDebugValue:N1}=Ye,{useSyncExternalStoreWithSelector:L1}=P1;let Lu=!1;const B1=t=>t;function _1(t,e=B1,n){(wg?"production":void 0)!=="production"&&n&&!Lu&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),Lu=!0);const r=L1(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,n);return N1(r),r}const Bu=t=>{(wg?"production":void 0)!=="production"&&typeof t!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof t=="function"?A1(t):t,n=(r,o)=>_1(e,r,o);return Object.assign(n,e),n},yi=t=>t?Bu(t):Bu,Cl=t=>`@collaboration:${t}`,yg=yi(t=>({activePaneId:null,setActivePane:e=>t({activePaneId:e}),docks:{},hosts:{},setDock:(e,n)=>t(r=>{const o={...r.docks};return n?o[e]=n:delete o[e],{docks:o,...!n&&r.activePaneId===Cl(e)?{activePaneId:r.docks[e]?.sessionId??null}:{}}}),setHost:(e,n)=>t(r=>{const o={...r.hosts};return n?o[e]=n:delete o[e],{hosts:o}})})),fn=new Map;let io;function bg(){const t=yg.getState().activePaneId;for(const[n,r]of fn)if(r.requiresFocus&&t===Cl(n))return r.receive;const e=fn.get(io??"");return e&&!e.requiresFocus?e.receive:void 0}function jR(t){const e=fn.get(t);e&&(e.requiresFocus?yg.getState().setActivePane(Cl(t)):io=t)}function O1(t){const e=bg();return!e||!t?!1:(e(t),!0)}function HR(t,e="default",n=!1){fn.set(e,{receive:t,requiresFocus:n}),n||(io=e);const r=o=>{const{text:s,nonce:i}=o.detail??{};!s||bg()!==t||(t(s),o.stopImmediatePropagation(),i&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:i,ok:!0}})))};return window.addEventListener("termdock-insert-reference",r,!0),()=>{fn.get(e)?.receive===t&&(fn.delete(e),io===e&&(io=[...fn.keys()].at(-1))),window.removeEventListener("termdock-insert-reference",r,!0)}}const D1=/^[A-Za-z0-9_@%+=:,./-]$/;function F1(t){return Array.from(t,e=>(e.codePointAt(0)??0)>127||D1.test(e)?e:`\\${e}`).join("")}function M1(t,e){if(!e)return!1;try{const n=new URL(e.serviceOrigin||e.url);return n.origin===t&&/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})$/.test(n.hostname)&&!(e.routes??[]).some(r=>r.targetPeerId!==e.targetPeerId)}catch{return!1}}function j1(t){const e=s=>s.target instanceof Element?s.target.closest("[data-termdock-terminal-dropzone]"):null,n=()=>!M1(location.origin,fo()),r=s=>{const i=e(s);!i||!n()||!s.dataTransfer?.types.includes("Files")||(s.preventDefault(),s.stopImmediatePropagation(),s.dataTransfer.dropEffect="copy",i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="remote")},o=s=>{const i=e(s),a=Array.from(s.dataTransfer?.files??[]);if(!i||!a.length||!n())return;s.preventDefault(),s.stopImmediatePropagation();const c=i.dataset.termdockTerminalDropzone??"";i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="uploading",tn(async()=>{const{uploadFiles:l}=await Promise.resolve().then(()=>aI);return{uploadFiles:l}},void 0).then(({uploadFiles:l})=>l("/tmp",a)).then(l=>{if(l.files.length!==a.length||l.files.some(d=>!d.path))throw new Error("Upload did not return every file path");delete i.dataset.nativeFileDrag,delete i.dataset.nativeFileDropState,t({sessionKey:c,paths:l.files.map(d=>d.path)})}).catch(l=>{i.dataset.nativeFileDropState="error",i.dispatchEvent(new CustomEvent("termdock:file-drop-error",{bubbles:!0,detail:l instanceof Error?l.message:"File upload failed"})),window.setTimeout(()=>{i.dataset.nativeFileDropState==="error"&&(delete i.dataset.nativeFileDrag,delete i.dataset.nativeFileDropState)},3e3)})};return window.addEventListener("dragover",r,!0),window.addEventListener("drop",o,!0),()=>{window.removeEventListener("dragover",r,!0),window.removeEventListener("drop",o,!0)}}function rt(){return typeof window>"u"?null:window.termdockDesktop??null}const sa=new Set;let _u=!1;function UR(t){const e=rt();if(!e)return()=>{};if(sa.add(t),!_u){const n=r=>{if(!O1(r.paths.map(F1).join(" ")+" "))for(const o of sa)o(r)};j1(n),e.onNativeFileDrop(n),_u=!0}return()=>{sa.delete(t)}}function vg(t=navigator.userAgent,e=navigator.maxTouchPoints){const n=/iPad/.test(t)||/Macintosh/.test(t)&&e>1?"iPad":/iPhone/.test(t)?"iPhone":/Android/.test(t)?"Android":/Windows/.test(t)?"Windows":/Macintosh|Mac OS X/.test(t)?"Mac":/Linux/.test(t)?"Linux":"设备",r=/Electron/.test(t)?"Termdock":/Edg\//.test(t)?"Edge":/Firefox|FxiOS/.test(t)?"Firefox":/Chrome|CriOS/.test(t)?"Chrome":/Safari/.test(t)?"Safari":"浏览器";return`${n} · ${r}`}let H1;function U1(){return H1??=(async()=>{const t=navigator.userAgent,[e,n]=vg().split(" · "),r=/(?:Edg|Firefox|FxiOS|Chrome|CriOS|Version)\/([\d.]+)/g,o=[...t.matchAll(r)],s=/(?:CPU (?:iPhone )?OS |Mac OS X |Android )([\d._]+)/.exec(t)?.[1]?.replaceAll("_","."),i={system:`${e}${s?` ${s}`:""}`,client:`${n}${o.length?` ${o.at(-1)[1]}`:""}`,mode:matchMedia("(display-mode: standalone)").matches||navigator.standalone?"已安装的网页应用":"网页"},a=rt();if(a){i.mode="桌面客户端";const l=/Electron\/([\d.]+)/.exec(t)?.[1];i.client=l?`Termdock(Electron ${l})`:"Termdock";try{Object.assign(i,await a.deviceInfo?.())}catch{}return i}const c=navigator.userAgentData;try{const l=await c?.getHighEntropyValues(["model","architecture","bitness","platformVersion"]);typeof l?.model=="string"&&l.model&&(i.model=l.model),typeof l?.architecture=="string"&&l.architecture&&(i.arch=`${l.architecture}${l.bitness?` ${l.bitness} 位`:""}`)}catch{}return i})()}function $1({service:t,onBusyChange:e,onConnect:n,onConnectWithPassword:r}){const[o,s]=O.useState(),[i,a]=O.useState(!0),[c,l]=O.useState(!1),[d,u]=O.useState(""),[f,h]=O.useState(0),[g,m]=O.useState(),[b,w]=O.useState("");O.useEffect(()=>{let A=!1,N=!1,k;a(!0),u(""),s(void 0);const T=async S=>{try{const v=await FE(t);if(A)return;N=!0,s(v),u("")}catch(v){!A&&(!N||S)&&u(v instanceof Error?v.message:"暂时无法读取中转列表,请重试。")}finally{A||(a(!1),k=setTimeout(()=>{T(!1)},2e3))}};return T(!0),()=>{A=!0,clearTimeout(k)}},[t.id,t.url,f]);const I=async A=>{if(!c){l(!0),e(!0),u("");try{await A()}catch(N){u(N instanceof Error?N.message:"暂时无法连接,请重试。")}finally{l(!1),e(!1)}}},y=async A=>{const N=await ME(o.route,A.serviceId);try{await n(N)}catch(k){if(!(k instanceof tt))throw k;m(N)}};return p.jsxs("div",{className:"service-form",children:[g?p.jsxs("form",{className:"service-form",onSubmit:A=>{A.preventDefault(),I(async()=>{try{await r?.(g,b)}finally{w("")}})},children:[p.jsxs("p",{className:"service-help",children:["已通过“",t.label,"”连接到“",g.serviceName,"”。请登录目标服务,完成此设备的访问授权。"]}),r?p.jsxs(p.Fragment,{children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"目标服务密码"}),p.jsx("input",{type:"password",autoFocus:!0,required:!0,autoComplete:"current-password",value:b,disabled:c,onChange:A=>w(A.target.value)})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:c||!b,children:c?"正在登录…":"登录并连接"})]}):p.jsx("p",{className:"service-help",children:"请让目标服务管理员邀请此设备后再连接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>{m(void 0),w(""),u(""),h(A=>A+1)},children:"返回中转列表"})]}):p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["通过“",t.label,"”连接下方服务。",o?.canManage?"选择未授权的服务会授权此设备使用该中转。":"这里只显示已授权给此设备的中转。","目标服务会单独验证访问权限。"]}),i?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx($e,{size:16,className:"service-spinning"}),"正在读取可中转的服务…"]}):o&&p.jsxs("div",{className:"service-list",children:[o.items.map(A=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:c||!A.available,onClick:()=>{I(()=>y(A))},children:[p.jsx("span",{className:"service-icon",children:p.jsx(wi,{size:19})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:A.label||(A.url?new URL(A.url).host:`中转服务 ${A.serviceId.slice(0,8)}`)}),p.jsx("span",{className:"service-description",children:A.available?A.authorized?"已获中转授权 · 连接":"授权此设备并连接":"中转暂不可用"})]}),p.jsx(En,{size:16})]},A.serviceId)),o.items.length===0&&p.jsx("p",{className:"service-empty",children:o.canManage?"暂无可中转的服务。可在本机 Mac 客户端连接目标服务,或在目标服务的“备用连接”中启用本入口。":"暂无已授权的中转服务,请让入口管理员分享备用连接邀请。"})]}),c&&p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx($e,{size:16,className:"service-spinning"}),"正在授权并连接目标服务…"]}),!i&&p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>h(A=>A+1),children:"刷新列表"})]}),d&&p.jsx("p",{className:"service-error",role:"alert",children:d})]})}const wc="#termdock-invite=";function Sg(t){const e=new URL(t.entryUrl);e.hash="",e.search="",e.pathname="/";const n=new TextEncoder().encode(JSON.stringify(t));return e.hash=wc.slice(1)+btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.href}function Gs(t){const e=new URL(t);if(!["https:","http:"].includes(e.protocol)||!e.hash.startsWith(wc))throw new Error("这不是有效的 Termdock 邀请链接");const n=e.hash.slice(wc.length);if(n.length>8192)throw new Error("邀请链接过长");let r;try{const i=n.replace(/-/g,"+").replace(/_/g,"/");r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(atob(i),a=>a.charCodeAt(0))))}catch{throw new Error("邀请链接不完整,请重新复制")}if(r.v!==1||typeof r.serviceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(r.serviceId)||r.routeOnly!==!0&&(typeof r.code!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(r.code)))throw new Error("邀请信息无效或版本不兼容");const o=new URL(r.entryUrl);if(o.origin!==e.origin||o.username||o.password||!["https:","http:"].includes(o.protocol))throw new Error("邀请地址与服务不一致");if(o.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(o.hostname))throw new Error("远程邀请需要 HTTPS");if(r.entryServiceId!==void 0&&(typeof r.entryServiceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(r.entryServiceId)))throw new Error("邀请入口身份无效");if(r.routeCode!==void 0&&(typeof r.routeCode!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(r.routeCode)||!r.entryServiceId))throw new Error("邀请入口权限无效");if(r.routeOnly===!0&&(!r.entryServiceId||!r.routeCode||r.code!==void 0))throw new Error("备用连接邀请不完整");let s=o.origin;if(r.serviceUrl!==void 0){const i=new URL(r.serviceUrl);if(!["https:","http:"].includes(i.protocol)||i.username||i.password)throw new Error("目标服务地址无效");s=r.entryServiceId&&r.entryServiceId!==r.serviceId?i.origin:o.origin}return{url:o.origin,targetPeerId:r.serviceId,pairingCode:r.code,...r.routeOnly===!0?{routeOnly:!0}:{},serviceOrigin:s,serviceName:typeof r.name=="string"?r.name.slice(0,120):void 0,entryServiceId:r.entryServiceId,routeCode:r.routeCode}}function q1({service:t,onBusyChange:e}){const n={...t,targetPeerId:t.targetPeerId,serviceName:t.label},[r,o]=O.useState(()=>t.routes??en(n)),[s,i]=O.useState([]),[a,c]=O.useState(!0),[l,d]=O.useState(!1),[u,f]=O.useState(""),h=B=>{d(B),e(B)},[g,m]=O.useState(),[b,w]=O.useState(""),[I,y]=O.useState(""),[A,N]=O.useState(""),[k,T]=O.useState(!1),[S,v]=O.useState(),[E,_]=O.useState(),[L,C]=O.useState(!1);O.useEffect(()=>{let B=!1;return Ge().then(H=>{B||i(H.filter($=>$.targetPeerId&&$.targetPeerId!==t.targetPeerId))}).catch(()=>{B||f("暂时无法读取可用服务。")}).finally(()=>{B||c(!1)}),()=>{B=!0}},[t.targetPeerId]);const x=B=>s.find(H=>H.targetPeerId===B.targetPeerId)?.label||new URL(B.url).host,P=async B=>{h(!0),f(""),N("");try{await B()}catch(H){const $=H instanceof Error?H.message:"";f(/AUTHORIZATION|DENIED/.test($)?"当前设备没有入口管理权限。请让管理员分享备用连接邀请,或使用入口密码授权。":"暂时无法完成。请确认入口能连接目标服务,且目标地址、证书和授权有效。")}finally{h(!1)}},R=async(B,H)=>{const $={url:B.serviceOrigin||B.url,targetPeerId:B.targetPeerId};await P(async()=>{const X=await jE($,n.targetPeerId);if(!X.grants.some(U=>U.active)){if(!X.canManage&&H===void 0){m(B);return}await HE(n,$,H)}const Y=[...r.filter(U=>U.targetPeerId!==$.targetPeerId),$];await ds(t,Y),o(Y),m(void 0),w("")})};if(E)return p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["把链接发给需要使用此备用连接的人。它只允许通过入口连接“",t.label,"”,对方仍需获得目标服务的访问权限。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用连接邀请"}),p.jsx("input",{readOnly:!0,value:E,onFocus:B=>B.target.select()})]}),p.jsxs("button",{type:"button",className:"service-button service-primary",onClick:()=>{navigator.clipboard.writeText(E).then(()=>C(!0)).catch(()=>f("无法自动复制,请长按链接复制。"))},children:[p.jsx(fg,{size:16}),L?"已复制":"复制邀请链接"]}),p.jsx("button",{type:"button",className:"service-button service-secondary",onClick:()=>{_(void 0),C(!1)},children:"返回备用连接"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});if(g)return p.jsxs("form",{className:"service-form",onSubmit:B=>{B.preventDefault(),R(g,b).finally(()=>w(""))},children:[p.jsxs("p",{className:"service-help",children:["需要“",g.label,"”的管理员授权。若这是你的服务,可以使用它的密码;否则请管理员分享备用连接邀请。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"入口服务密码"}),p.jsx("input",{type:"password",required:!0,value:b,onChange:B=>w(B.target.value),autoComplete:"current-password",disabled:l,autoFocus:!0})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||!b,children:l?"正在授权…":"授权并启用"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{m(void 0),w("")},children:"取消"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});const D=r.filter(B=>B.targetPeerId===n.targetPeerId),M=r.filter(B=>B.targetPeerId!==n.targetPeerId),F=async()=>{if(!l){h(!0),T(!0),f(""),N("");try{o(await $E({...t,routes:r},I)),y(""),N("备用地址已验证并保存。")}catch(B){f(B instanceof Error?B.message:"暂时无法添加地址,请重试。")}finally{h(!1),T(!1)}}};return p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"电脑换了网络?添加它在新网络下的地址,原地址连不上时会自动尝试。只接受同一台服务。"}),p.jsxs("form",{className:"service-form",onSubmit:B=>{B.preventDefault(),F()},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用地址"}),p.jsx("input",{value:I,onChange:B=>{y(B.target.value),f(""),N("")},required:!0,disabled:l||r.length>=4,inputMode:"url",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:192.168.10.20:9834"})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||r.length>=4||!I.trim(),children:k?p.jsxs(p.Fragment,{children:[p.jsx($e,{size:16,className:"service-spinning"}),"正在验证…"]}):"验证并添加"})]}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u}),A&&p.jsx("p",{role:"status",className:"service-help",children:A}),r.length>=4&&p.jsx("p",{className:"service-help",children:"已保存 4 个备用连接。移除不再使用的地址或入口后,可以继续添加。"}),p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"首选地址"}),p.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url})]}),D.length>0&&p.jsx("div",{className:"service-list",children:D.map(B=>p.jsxs("div",{className:"service-route-item",children:[p.jsxs("div",{className:"service-route-line",children:[p.jsx("span",{className:"service-address service-route-address",children:B.url}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`移除地址 ${B.url}`,disabled:l,onClick:()=>v(B),children:"移除"})]}),S?.targetPeerId===B.targetPeerId&&S.url===B.url&&p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"从备用连接中移除此地址?不会停止正在运行的终端。"}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>v(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{P(async()=>{const H=r.filter($=>$.targetPeerId!==B.targetPeerId||$.url!==B.url);await ds(t,H),o(H),v(void 0)})},children:"确认移除"})]})]})]},B.url))}),p.jsxs("details",{className:"service-relay-options",children:[p.jsxs("summary",{children:["通过其他服务中转",M.length?`(${M.length})`:""]}),p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"所有直连地址都不可用时,尝试下方已授权入口;直连恢复后自动切回。"}),M.length>0&&p.jsx("div",{className:"service-list",children:M.map(B=>p.jsxs("div",{className:"service-route-item",children:[p.jsxs("div",{className:"service-route-line",children:[p.jsx("span",{className:"service-icon",children:p.jsx(wi,{size:18})}),p.jsx("span",{className:"service-name",children:x(B)}),p.jsx(zs,{size:16,className:"service-selected"})]}),S?.targetPeerId===B.targetPeerId?p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["撤销此设备经“",x(B),"”连接目标的权限?如当前无法直连,目标服务将断开。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>v(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{P(async()=>{await UE(n.targetPeerId,B);const H=r.filter($=>$.targetPeerId!==B.targetPeerId);await ds(t,H),o(H),v(void 0)})},children:"确认撤销"})]})]}):p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>{P(async()=>{const H=await ag(n,B);_(Sg({v:1,routeOnly:!0,serviceId:n.targetPeerId,name:t.label,serviceUrl:t.serviceOrigin||t.url,entryUrl:B.url,entryServiceId:B.targetPeerId,routeCode:H.routeCode}))})},children:"分享备用连接"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>v(B),children:"撤销授权"})]})]},B.targetPeerId))}),a?p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx($e,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"添加中转入口"}),s.filter(B=>!r.some(H=>H.targetPeerId===B.targetPeerId)).map(B=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:l||r.length>=4,onClick:()=>{R(B)},children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:B.label}),p.jsx("span",{className:"service-description",children:"验证并授权后启用"})]}),p.jsx(En,{size:16})]},B.id)),s.length===0&&p.jsx("p",{className:"service-empty",children:"添加并登录另一台服务后,可以将它设为中转入口。"})]})]})]}),l&&!k&&p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx($e,{size:16,className:"service-spinning"}),"正在验证连接与授权…"]})]})}function K1({current:t,renderRoutes:e,renderRelayServices:n,onOpen:r,onAdd:o,onInvite:s,hideHeader:i,onNavigation:a,onBusyChange:c,initiallyAdding:l=!1}){const[d,u]=O.useState([]),[f,h]=O.useState(!0),[g,m]=O.useState(l?{kind:"add"}:{kind:"list"}),[b,w]=O.useState(!1),I=O.useCallback(C=>{w(C),c?.(C)},[c]),[y,A]=O.useState(""),N=O.useCallback(()=>{m(C=>C.kind==="routes"||C.kind==="relay-services"?{kind:"edit",service:C.service}:{kind:"list"}),A("")},[]),k=g.kind==="add"?"添加服务":g.kind==="edit"?"服务设置":g.kind==="routes"?"备用连接":g.kind==="relay-services"?"可中转的服务":void 0;O.useEffect(()=>{a?.({title:k,...k?{back:N}:{}})},[k,N,a]),O.useEffect(()=>{let C=!1,x=0;const P=async()=>{const D=++x;try{const M=await Ge();!C&&x===D&&(u(M),A(""))}catch{!C&&x===D&&A("暂时无法读取服务列表,请重试。")}finally{!C&&x===D&&h(!1)}};P();const R=ni(()=>{P()});return()=>{C=!0,R()}},[]);const T=async C=>{if(!b){I(!0),A("");try{await C()}catch(x){A(x instanceof Error?x.message:"暂时无法完成,请重试。")}finally{I(!1)}}},S=g.kind==="edit"||g.kind==="routes"||g.kind==="relay-services"?d.find(C=>Ct(C,g.service))||g.service:void 0,v=t?d.find(C=>Ct(C,t))||t:void 0,E=d.filter(C=>!t||!Ct(C,t)),_=v?[v,...E]:E,L=p.jsxs(p.Fragment,{children:[f?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx($e,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{className:"service-list",children:[_.map(C=>{const x=!!t&&Ct(C,t);return p.jsxs("div",{className:"service-row",children:[p.jsxs("button",{type:"button",className:"service-row-open",disabled:b||x,onClick:()=>{T(async()=>{(await r(C))?.passwordRequired&&m({kind:"add",input:C.serviceOrigin||C.url,passwordRequired:!0})})},"aria-label":x?`当前服务 ${C.label}`:`打开 ${C.label}`,children:[p.jsx("span",{className:"service-icon",children:p.jsx(wi,{size:20})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:C.label}),p.jsx("span",{className:"service-description",children:x?"当前服务":new URL(C.serviceOrigin||C.url).host})]}),x?p.jsx(zs,{size:17,className:"service-selected"}):p.jsx(En,{size:16,className:"service-muted"})]}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`管理 ${C.label}`,disabled:b,onClick:()=>{m({kind:"edit",service:C}),A("")},children:p.jsx(hg,{size:19})})]},C.id)}),_.length===0&&p.jsx("p",{className:"service-empty",children:"还没有添加服务。连接你的电脑,或粘贴收到的邀请链接。"})]}),p.jsxs("div",{className:`service-actions${s?" service-actions-pair":""}`,children:[p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:b,onClick:()=>{m({kind:"add"}),A("")},children:[p.jsx(pg,{size:16}),"添加服务"]}),s&&p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:b,onClick:s,children:[p.jsx(gg,{size:16}),"邀请设备"]})]})]});return p.jsxs("div",{className:"service-manager",children:[!i&&p.jsxs("div",{className:"service-heading",children:[k&&p.jsx("button",{type:"button",className:"service-icon-button","aria-label":"返回服务",disabled:b,onClick:N,children:p.jsx(lg,{size:20})}),p.jsx("h2",{children:k||"服务"})]}),g.kind==="relay-services"?n?.(S,I):g.kind==="routes"?e?.(S,I):g.kind==="list"?L:g.kind==="add"?p.jsx(z1,{onSave:C=>T(async()=>{const x=Me(C);u(await Lt({id:x,url:x,label:new URL(x).host})),N()}),initialInput:g.input,passwordRequired:g.passwordRequired,busy:b,onSubmit:async(C,x)=>{let P;return await T(async()=>{P=await o(C,x),P?.passwordRequired||N()}),P}}):p.jsx(G1,{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:S,busy:b,canRemove:!t||!Ct(g.service,t),onSave:C=>{T(async()=>{u(await Lt({...S,label:C})),N()})},onRemove:()=>{T(async()=>{u(await tw(g.service.id)),N()})}}),y&&p.jsx("p",{className:"service-error",role:"alert",children:y})]})}function z1({busy:t,onSubmit:e,onSave:n,initialInput:r="",passwordRequired:o=!1}){const[s,i]=O.useState(r),[a,c]=O.useState(""),[l,d]=O.useState(o);return p.jsxs("form",{className:"service-form",onSubmit:async u=>{u.preventDefault(),(await e(s.trim(),l?a:void 0))?.passwordRequired&&d(!0),c("")},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务地址或邀请链接"}),p.jsx("input",{value:s,onChange:u=>{i(u.target.value),d(!1),c("")},disabled:t,required:!0,autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:电脑地址:9834 或 https://…"})]}),l?p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务密码"}),p.jsx("input",{type:"password",value:a,onChange:u=>c(u.target.value),disabled:t,required:!0,autoFocus:!0,autoComplete:"current-password",placeholder:"输入这台服务的密码"})]}):p.jsx("p",{className:"service-help",children:"连接自己的服务,输入地址即可;收到邀请时,粘贴完整链接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:t||!s.trim()||s.includes("#termdock-invite="),onClick:()=>{n(s.trim())},children:"仅保存,不连接"}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:t||!s.trim()||l&&!a,children:t?p.jsxs(p.Fragment,{children:[p.jsx($e,{size:16,className:"service-spinning"}),"正在连接…"]}):l?"登录并连接":"继续"})]})}function G1({service:t,busy:e,canRemove:n,onSave:r,onRemove:o,onRoutes:s,onRelayServices:i}){const[a,c]=O.useState(t.label),[l,d]=O.useState(!1);return p.jsxs("form",{className:"service-form",onSubmit:u=>{u.preventDefault(),r(a.trim())},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"服务名称"}),p.jsx("input",{value:a,onChange:u=>c(u.target.value),disabled:e,required:!0,maxLength:120,placeholder:"例如:办公室电脑"})]}),p.jsx("p",{className:"service-address",children:t.serviceOrigin||t.url}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:e||!a.trim(),children:"保存名称"}),i&&p.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:i,children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:"可中转的服务"}),p.jsx("span",{className:"service-description",children:"通过这台服务连接其他电脑"})]}),p.jsx(En,{size:16})]}),s&&p.jsxs("button",{type:"button",className:"service-row-open",disabled:e,onClick:s,children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:"备用连接"}),p.jsx("span",{className:"service-description",children:"添加其他网络地址或授权入口"})]}),p.jsx(En,{size:16})]}),n&&p.jsx("div",{className:"service-remove",children:l?p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["从列表移除“",t.label,"”?不会停止服务或删除终端。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:e,onClick:()=>d(!1),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:o,children:"确认移除"})]})]}):p.jsx("button",{type:"button",className:"service-button service-danger",disabled:e,onClick:()=>d(!0),children:"移除服务"})})]})}var Mn={},ia,Ou;function W1(){return Ou||(Ou=1,ia=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),ia}var aa={},Kt={},Du;function In(){if(Du)return Kt;Du=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 Kt.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},Kt.getSymbolTotalCodewords=function(r){return e[r]},Kt.getBCHDigit=function(n){let r=0;for(;n!==0;)r++,n>>>=1;return r},Kt.setToSJISFunction=function(r){if(typeof r!="function")throw new Error('"toSJISFunc" is not a valid function.');t=r},Kt.isKanjiModeEnabled=function(){return typeof t<"u"},Kt.toSJIS=function(r){return t(r)},Kt}var ca={},Fu;function Il(){return Fu||(Fu=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+n)}}t.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},t.from=function(r,o){if(t.isValid(r))return r;try{return e(r)}catch{return o}}})(ca)),ca}var la,Mu;function V1(){if(Mu)return la;Mu=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++}},la=t,la}var da,ju;function X1(){if(ju)return da;ju=1;function t(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return t.prototype.set=function(e,n,r,o){const s=e*this.size+n;this.data[s]=r,o&&(this.reservedBit[s]=!0)},t.prototype.get=function(e,n){return this.data[e*this.size+n]},t.prototype.xor=function(e,n,r){this.data[e*this.size+n]^=r},t.prototype.isReserved=function(e,n){return this.reservedBit[e*this.size+n]},da=t,da}var ua={},Hu;function Y1(){return Hu||(Hu=1,(function(t){const e=In().getSymbolSize;t.getRowColCoords=function(r){if(r===1)return[];const o=Math.floor(r/7)+2,s=e(r),i=s===145?26:Math.ceil((s-13)/(2*o-2))*2,a=[s-7];for(let c=1;c<o-1;c++)a[c]=a[c-1]-i;return a.push(6),a.reverse()},t.getPositions=function(r){const o=[],s=t.getRowColCoords(r),i=s.length;for(let a=0;a<i;a++)for(let c=0;c<i;c++)a===0&&c===0||a===0&&c===i-1||a===i-1&&c===0||o.push([s[a],s[c]]);return o}})(ua)),ua}var fa={},Uu;function Z1(){if(Uu)return fa;Uu=1;const t=In().getSymbolSize,e=7;return fa.getPositions=function(r){const o=t(r);return[[0,0],[o-e,0],[0,o-e]]},fa}var ha={},$u;function J1(){return $u||($u=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},t.from=function(o){return t.isValid(o)?parseInt(o,10):void 0},t.getPenaltyN1=function(o){const s=o.size;let i=0,a=0,c=0,l=null,d=null;for(let u=0;u<s;u++){a=c=0,l=d=null;for(let f=0;f<s;f++){let h=o.get(u,f);h===l?a++:(a>=5&&(i+=e.N1+(a-5)),l=h,a=1),h=o.get(f,u),h===d?c++:(c>=5&&(i+=e.N1+(c-5)),d=h,c=1)}a>=5&&(i+=e.N1+(a-5)),c>=5&&(i+=e.N1+(c-5))}return i},t.getPenaltyN2=function(o){const s=o.size;let i=0;for(let a=0;a<s-1;a++)for(let c=0;c<s-1;c++){const l=o.get(a,c)+o.get(a,c+1)+o.get(a+1,c)+o.get(a+1,c+1);(l===4||l===0)&&i++}return i*e.N2},t.getPenaltyN3=function(o){const s=o.size;let i=0,a=0,c=0;for(let l=0;l<s;l++){a=c=0;for(let d=0;d<s;d++)a=a<<1&2047|o.get(l,d),d>=10&&(a===1488||a===93)&&i++,c=c<<1&2047|o.get(d,l),d>=10&&(c===1488||c===93)&&i++}return i*e.N3},t.getPenaltyN4=function(o){let s=0;const i=o.data.length;for(let c=0;c<i;c++)s+=o.data[c];return Math.abs(Math.ceil(s*100/i/5)-10)*e.N4};function n(r,o,s){switch(r){case t.Patterns.PATTERN000:return(o+s)%2===0;case t.Patterns.PATTERN001:return o%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(o+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return o*s%2+o*s%3===0;case t.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case t.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}t.applyMask=function(o,s){const i=s.size;for(let a=0;a<i;a++)for(let c=0;c<i;c++)s.isReserved(c,a)||s.xor(c,a,n(o,c,a))},t.getBestMask=function(o,s){const i=Object.keys(t.Patterns).length;let a=0,c=1/0;for(let l=0;l<i;l++){s(l),t.applyMask(l,o);const d=t.getPenaltyN1(o)+t.getPenaltyN2(o)+t.getPenaltyN3(o)+t.getPenaltyN4(o);t.applyMask(l,o),d<c&&(c=d,a=l)}return a}})(ha)),ha}var Zo={},qu;function xg(){if(qu)return Zo;qu=1;const t=Il(),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 Zo.getBlocksCount=function(o,s){switch(s){case t.L:return e[(o-1)*4+0];case t.M:return e[(o-1)*4+1];case t.Q:return e[(o-1)*4+2];case t.H:return e[(o-1)*4+3];default:return}},Zo.getTotalCodewordsCount=function(o,s){switch(s){case t.L:return n[(o-1)*4+0];case t.M:return n[(o-1)*4+1];case t.Q:return n[(o-1)*4+2];case t.H:return n[(o-1)*4+3];default:return}},Zo}var pa={},Dr={},Ku;function Q1(){if(Ku)return Dr;Ku=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let r=1;for(let o=0;o<255;o++)t[o]=r,e[r]=o,r<<=1,r&256&&(r^=285);for(let o=255;o<512;o++)t[o]=t[o-255]})(),Dr.log=function(r){if(r<1)throw new Error("log("+r+")");return e[r]},Dr.exp=function(r){return t[r]},Dr.mul=function(r,o){return r===0||o===0?0:t[e[r]+e[o]]},Dr}var zu;function eA(){return zu||(zu=1,(function(t){const e=Q1();t.mul=function(r,o){const s=new Uint8Array(r.length+o.length-1);for(let i=0;i<r.length;i++)for(let a=0;a<o.length;a++)s[i+a]^=e.mul(r[i],o[a]);return s},t.mod=function(r,o){let s=new Uint8Array(r);for(;s.length-o.length>=0;){const i=s[0];for(let c=0;c<o.length;c++)s[c]^=e.mul(o[c],i);let a=0;for(;a<s.length&&s[a]===0;)a++;s=s.slice(a)}return s},t.generateECPolynomial=function(r){let o=new Uint8Array([1]);for(let s=0;s<r;s++)o=t.mul(o,new Uint8Array([1,e.exp(s)]));return o}})(pa)),pa}var ga,Gu;function tA(){if(Gu)return ga;Gu=1;const t=eA();function e(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(r){this.degree=r,this.genPoly=t.generateECPolynomial(this.degree)},e.prototype.encode=function(r){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(r.length+this.degree);o.set(r);const s=t.mod(o,this.genPoly),i=this.degree-s.length;if(i>0){const a=new Uint8Array(this.degree);return a.set(s,i),a}return s},ga=e,ga}var ma={},wa={},ya={},Wu;function Eg(){return Wu||(Wu=1,ya.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),ya}var pt={},Vu;function Ag(){if(Vu)return pt;Vu=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
  ]))+`;pt.KANJI=new RegExp(n,"g"),pt.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),pt.BYTE=new RegExp(r,"g"),pt.NUMERIC=new RegExp(t,"g"),pt.ALPHANUMERIC=new RegExp(e,"g");const o=new RegExp("^"+n+"$"),s=new RegExp("^"+t+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return pt.testKanji=function(c){return o.test(c)},pt.testNumeric=function(c){return s.test(c)},pt.testAlphanumeric=function(c){return i.test(c)},pt}var Xu;function Rn(){return Xu||(Xu=1,(function(t){const e=Eg(),n=Ag();t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(s,i){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!e.isValid(i))throw new Error("Invalid version: "+i);return i>=1&&i<10?s.ccBits[0]:i<27?s.ccBits[1]:s.ccBits[2]},t.getBestModeForData=function(s){return n.testNumeric(s)?t.NUMERIC:n.testAlphanumeric(s)?t.ALPHANUMERIC:n.testKanji(s)?t.KANJI:t.BYTE},t.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},t.isValid=function(s){return s&&s.bit&&s.ccBits};function r(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+o)}}t.from=function(s,i){if(t.isValid(s))return s;try{return r(s)}catch{return i}}})(wa)),wa}var Yu;function nA(){return Yu||(Yu=1,(function(t){const e=In(),n=xg(),r=Il(),o=Rn(),s=Eg(),i=7973,a=e.getBCHDigit(i);function c(f,h,g){for(let m=1;m<=40;m++)if(h<=t.getCapacity(m,g,f))return m}function l(f,h){return o.getCharCountIndicator(f,h)+4}function d(f,h){let g=0;return f.forEach(function(m){const b=l(m.mode,h);g+=b+m.getBitsLength()}),g}function u(f,h){for(let g=1;g<=40;g++)if(d(f,g)<=t.getCapacity(g,h,o.MIXED))return g}t.from=function(h,g){return s.isValid(h)?parseInt(h,10):g},t.getCapacity=function(h,g,m){if(!s.isValid(h))throw new Error("Invalid QR Code version");typeof m>"u"&&(m=o.BYTE);const b=e.getSymbolTotalCodewords(h),w=n.getTotalCodewordsCount(h,g),I=(b-w)*8;if(m===o.MIXED)return I;const y=I-l(m,h);switch(m){case o.NUMERIC:return Math.floor(y/10*3);case o.ALPHANUMERIC:return Math.floor(y/11*2);case o.KANJI:return Math.floor(y/13);case o.BYTE:default:return Math.floor(y/8)}},t.getBestVersionForData=function(h,g){let m;const b=r.from(g,r.M);if(Array.isArray(h)){if(h.length>1)return u(h,b);if(h.length===0)return 1;m=h[0]}else m=h;return c(m.mode,m.getLength(),b)},t.getEncodedBits=function(h){if(!s.isValid(h)||h<7)throw new Error("Invalid QR Code version");let g=h<<12;for(;e.getBCHDigit(g)-a>=0;)g^=i<<e.getBCHDigit(g)-a;return h<<12|g}})(ma)),ma}var ba={},Zu;function rA(){if(Zu)return ba;Zu=1;const t=In(),e=1335,n=21522,r=t.getBCHDigit(e);return ba.getEncodedBits=function(s,i){const a=s.bit<<3|i;let c=a<<10;for(;t.getBCHDigit(c)-r>=0;)c^=e<<t.getBCHDigit(c)-r;return(a<<10|c)^n},ba}var va={},Sa,Ju;function oA(){if(Ju)return Sa;Ju=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 o,s,i;for(o=0;o+3<=this.data.length;o+=3)s=this.data.substr(o,3),i=parseInt(s,10),r.put(i,10);const a=this.data.length-o;a>0&&(s=this.data.substr(o),i=parseInt(s,10),r.put(i,a*3+1))},Sa=e,Sa}var xa,Qu;function sA(){if(Qu)return xa;Qu=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(o){return 11*Math.floor(o/2)+6*(o%2)},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(o){let s;for(s=0;s+2<=this.data.length;s+=2){let i=e.indexOf(this.data[s])*45;i+=e.indexOf(this.data[s+1]),o.put(i,11)}this.data.length%2&&o.put(e.indexOf(this.data[s]),6)},xa=n,xa}var Ea,ef;function iA(){if(ef)return Ea;ef=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,o=this.data.length;r<o;r++)n.put(this.data[r],8)},Ea=e,Ea}var Aa,tf;function aA(){if(tf)return Aa;tf=1;const t=Rn(),e=In();function n(r){this.mode=t.KANJI,this.data=r}return n.getBitsLength=function(o){return o*13},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(r){let o;for(o=0;o<this.data.length;o++){let s=e.toSJIS(this.data[o]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
4
4
  Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),r.put(s,13)}},Aa=n,Aa}var ka={exports:{}},nf;function cA(){return nf||(nf=1,(function(t){var e={single_source_shortest_paths:function(n,r,o){var s={},i={};i[r]=0;var a=e.PriorityQueue.make();a.push(r,0);for(var c,l,d,u,f,h,g,m,b;!a.empty();){c=a.pop(),l=c.value,u=c.cost,f=n[l]||{};for(d in f)f.hasOwnProperty(d)&&(h=f[d],g=u+h,m=i[d],b=typeof i[d]>"u",(b||m>g)&&(i[d]=g,a.push(d,g),s[d]=l))}if(typeof o<"u"&&typeof i[o]>"u"){var w=["Could not find a path from ",r," to ",o,"."].join("");throw new Error(w)}return s},extract_shortest_path_from_predecessor_list:function(n,r){for(var o=[],s=r;s;)o.push(s),n[s],s=n[s];return o.reverse(),o},find_path:function(n,r,o){var s=e.single_source_shortest_paths(n,r,o);return e.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(n){var r=e.PriorityQueue,o={},s;n=n||{};for(s in r)r.hasOwnProperty(s)&&(o[s]=r[s]);return o.queue=[],o.sorter=n.sorter||r.default_sorter,o},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var o={value:n,cost:r};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=e})(ka)),ka.exports}var rf;function lA(){return rf||(rf=1,(function(t){const e=Rn(),n=oA(),r=sA(),o=iA(),s=aA(),i=Ag(),a=In(),c=cA();function l(w){return unescape(encodeURIComponent(w)).length}function d(w,I,y){const A=[];let N;for(;(N=w.exec(y))!==null;)A.push({data:N[0],index:N.index,mode:I,length:N[0].length});return A}function u(w){const I=d(i.NUMERIC,e.NUMERIC,w),y=d(i.ALPHANUMERIC,e.ALPHANUMERIC,w);let A,N;return a.isKanjiModeEnabled()?(A=d(i.BYTE,e.BYTE,w),N=d(i.KANJI,e.KANJI,w)):(A=d(i.BYTE_KANJI,e.BYTE,w),N=[]),I.concat(y,A,N).sort(function(T,S){return T.index-S.index}).map(function(T){return{data:T.data,mode:T.mode,length:T.length}})}function f(w,I){switch(I){case e.NUMERIC:return n.getBitsLength(w);case e.ALPHANUMERIC:return r.getBitsLength(w);case e.KANJI:return s.getBitsLength(w);case e.BYTE:return o.getBitsLength(w)}}function h(w){return w.reduce(function(I,y){const A=I.length-1>=0?I[I.length-1]:null;return A&&A.mode===y.mode?(I[I.length-1].data+=y.data,I):(I.push(y),I)},[])}function g(w){const I=[];for(let y=0;y<w.length;y++){const A=w[y];switch(A.mode){case e.NUMERIC:I.push([A,{data:A.data,mode:e.ALPHANUMERIC,length:A.length},{data:A.data,mode:e.BYTE,length:A.length}]);break;case e.ALPHANUMERIC:I.push([A,{data:A.data,mode:e.BYTE,length:A.length}]);break;case e.KANJI:I.push([A,{data:A.data,mode:e.BYTE,length:l(A.data)}]);break;case e.BYTE:I.push([{data:A.data,mode:e.BYTE,length:l(A.data)}])}}return I}function m(w,I){const y={},A={start:{}};let N=["start"];for(let k=0;k<w.length;k++){const T=w[k],S=[];for(let v=0;v<T.length;v++){const E=T[v],_=""+k+v;S.push(_),y[_]={node:E,lastCount:0},A[_]={};for(let L=0;L<N.length;L++){const C=N[L];y[C]&&y[C].node.mode===E.mode?(A[C][_]=f(y[C].lastCount+E.length,E.mode)-f(y[C].lastCount,E.mode),y[C].lastCount+=E.length):(y[C]&&(y[C].lastCount=E.length),A[C][_]=f(E.length,E.mode)+4+e.getCharCountIndicator(E.mode,I))}}N=S}for(let k=0;k<N.length;k++)A[N[k]].end=0;return{map:A,table:y}}function b(w,I){let y;const A=e.getBestModeForData(w);if(y=e.from(I,A),y!==e.BYTE&&y.bit<A.bit)throw new Error('"'+w+'" cannot be encoded with mode '+e.toString(y)+`.
5
5
  Suggested mode is: `+e.toString(A));switch(y===e.KANJI&&!a.isKanjiModeEnabled()&&(y=e.BYTE),y){case e.NUMERIC:return new n(w);case e.ALPHANUMERIC:return new r(w);case e.KANJI:return new s(w);case e.BYTE:return new o(w)}}t.fromArray=function(I){return I.reduce(function(y,A){return typeof A=="string"?y.push(b(A,null)):A.data&&y.push(b(A.data,A.mode)),y},[])},t.fromString=function(I,y){const A=u(I,a.isKanjiModeEnabled()),N=g(A),k=m(N,y),T=c.find_path(k.map,"start","end"),S=[];for(let v=1;v<T.length-1;v++)S.push(k.table[T[v]].node);return t.fromArray(h(S))},t.rawSplit=function(I){return t.fromArray(u(I,a.isKanjiModeEnabled()))}})(va)),va}var of;function dA(){if(of)return aa;of=1;const t=In(),e=Il(),n=V1(),r=X1(),o=Y1(),s=Z1(),i=J1(),a=xg(),c=tA(),l=nA(),d=rA(),u=Rn(),f=lA();function h(k,T){const S=k.size,v=s.getPositions(T);for(let E=0;E<v.length;E++){const _=v[E][0],L=v[E][1];for(let C=-1;C<=7;C++)if(!(_+C<=-1||S<=_+C))for(let x=-1;x<=7;x++)L+x<=-1||S<=L+x||(C>=0&&C<=6&&(x===0||x===6)||x>=0&&x<=6&&(C===0||C===6)||C>=2&&C<=4&&x>=2&&x<=4?k.set(_+C,L+x,!0,!0):k.set(_+C,L+x,!1,!0))}}function g(k){const T=k.size;for(let S=8;S<T-8;S++){const v=S%2===0;k.set(S,6,v,!0),k.set(6,S,v,!0)}}function m(k,T){const S=o.getPositions(T);for(let v=0;v<S.length;v++){const E=S[v][0],_=S[v][1];for(let L=-2;L<=2;L++)for(let C=-2;C<=2;C++)L===-2||L===2||C===-2||C===2||L===0&&C===0?k.set(E+L,_+C,!0,!0):k.set(E+L,_+C,!1,!0)}}function b(k,T){const S=k.size,v=l.getEncodedBits(T);let E,_,L;for(let C=0;C<18;C++)E=Math.floor(C/3),_=C%3+S-8-3,L=(v>>C&1)===1,k.set(E,_,L,!0),k.set(_,E,L,!0)}function w(k,T,S){const v=k.size,E=d.getEncodedBits(T,S);let _,L;for(_=0;_<15;_++)L=(E>>_&1)===1,_<6?k.set(_,8,L,!0):_<8?k.set(_+1,8,L,!0):k.set(v-15+_,8,L,!0),_<8?k.set(8,v-_-1,L,!0):_<9?k.set(8,15-_-1+1,L,!0):k.set(8,15-_-1,L,!0);k.set(v-8,8,1,!0)}function I(k,T){const S=k.size;let v=-1,E=S-1,_=7,L=0;for(let C=S-1;C>0;C-=2)for(C===6&&C--;;){for(let x=0;x<2;x++)if(!k.isReserved(E,C-x)){let P=!1;L<T.length&&(P=(T[L]>>>_&1)===1),k.set(E,C-x,P),_--,_===-1&&(L++,_=7)}if(E+=v,E<0||S<=E){E-=v,v=-v;break}}}function y(k,T,S){const v=new n;S.forEach(function(x){v.put(x.mode.bit,4),v.put(x.getLength(),u.getCharCountIndicator(x.mode,k)),x.write(v)});const E=t.getSymbolTotalCodewords(k),_=a.getTotalCodewordsCount(k,T),L=(E-_)*8;for(v.getLengthInBits()+4<=L&&v.put(0,4);v.getLengthInBits()%8!==0;)v.putBit(0);const C=(L-v.getLengthInBits())/8;for(let x=0;x<C;x++)v.put(x%2?17:236,8);return A(v,k,T)}function A(k,T,S){const v=t.getSymbolTotalCodewords(T),E=a.getTotalCodewordsCount(T,S),_=v-E,L=a.getBlocksCount(T,S),C=v%L,x=L-C,P=Math.floor(v/L),R=Math.floor(_/L),D=R+1,M=P-R,F=new c(M);let B=0;const H=new Array(L),$=new Array(L);let X=0;const Y=new Uint8Array(k.buffer);for(let z=0;z<L;z++){const V=z<x?R:D;H[z]=Y.slice(B,B+V),$[z]=F.encode(H[z]),B+=V,X=Math.max(X,V)}const U=new Uint8Array(v);let K=0,q,G;for(q=0;q<X;q++)for(G=0;G<L;G++)q<H[G].length&&(U[K++]=H[G][q]);for(q=0;q<M;q++)for(G=0;G<L;G++)U[K++]=$[G][q];return U}function N(k,T,S,v){let E;if(Array.isArray(k))E=f.fromArray(k);else if(typeof k=="string"){let P=T;if(!P){const R=f.rawSplit(k);P=l.getBestVersionForData(R,S)}E=f.fromString(k,P||40)}else throw new Error("Invalid data");const _=l.getBestVersionForData(E,S);if(!_)throw new Error("The amount of data is too big to be stored in a QR Code");if(!T)T=_;else if(T<_)throw new Error(`
@@ -32,4 +32,4 @@ ${t.stack}`:"",e?`
32
32
  React component stack:
33
33
  ${e.trim()}`:""].filter(Boolean).join(`
34
34
  `)}async function i2(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 a2({error:t,componentStack:e}){const{t:n}=vi(),[r,o]=Ye.useState("idle"),s=async()=>{const i=s2(t,e,{url:window.location.href,userAgent:navigator.userAgent,capturedAt:new Date().toISOString()});o(await i2(i)?"copied":"failed")};return p.jsx("div",{className:"flex h-full items-center justify-center p-4",children:p.jsxs("div",{className:"flex flex-col items-center gap-3 text-center max-w-md",children:[p.jsx("div",{className:"w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center",children:p.jsx("svg",{className:"w-6 h-6 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:p.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),p.jsxs("div",{className:"space-y-1",children:[p.jsx("h3",{className:"font-medium text-foreground",children:n("errorBoundary.title")}),p.jsx("p",{className:"text-sm text-muted-foreground",children:t?.message||n("errorBoundary.unexpected")})]}),p.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-center gap-2",children:[p.jsx("button",{type:"button",onClick:()=>{s()},className:"rounded-full bg-surface-2 px-5 py-2.5 text-sm font-medium text-foreground ring-1 ring-border/15 transition hover:bg-surface-elevated active:scale-[0.97]",children:n(r==="copied"?"errorBoundary.copied":r==="failed"?"errorBoundary.copyFailed":"errorBoundary.copyDetails")}),p.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"rounded-full bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground shadow-sm transition-all hover:bg-primary/90 active:scale-[0.97]",children:n("errorBoundary.retry")})]})]})})}class c2 extends Ye.Component{state={hasError:!1,error:null,componentStack:""};static getDerivedStateFromError(e){return{hasError:!0,error:e,componentStack:""}}componentDidCatch(e,n){console.error("Terminal error caught by boundary:",e,n),this.setState({componentStack:n.componentStack??""})}render(){return this.state.hasError?this.props.fallback?this.props.fallback:p.jsx(a2,{error:this.state.error,componentStack:this.state.componentStack}):this.props.children}}function ve(){try{if(window.parent!==window&&location.pathname==="/workspace.html"&&window.parent.location.origin===location.origin&&window.parent.__termdockWorkspaceHost)return window.parent}catch{}return window}const l2="debug",d2="termdock:debug";function Ef(t){return t?new Set(t.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean)):new Set}function u2(){if(typeof window>"u")return new Set;const t=Ef(new URLSearchParams(window.location.search).get(l2));let e=new Set;try{e=Ef(window.localStorage.getItem(d2))}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 f2(t){const e=u2();return e.has("*")||e.has(t)}function h2(t){const e=f2(t);return(...n)=>{e&&console.log(`[debug:${t}]`,...n)}}const Af=80,p2=60,g2="termdock:viewport-keyboard-change",m2="termdock:viewport-layout-change",Tt=240,kf=640,Cf=360,w2=1500;function y2({measuredHeight:t,documentVisible:e,editableFocused:n}){return e&&n&&t>0}function Da(){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 Ys=t=>{const e=typeof t=="number"?t:Number.parseFloat(typeof t=="string"?t:"0");return Number.isFinite(e)&&e>0?Math.round(e):0},fm=(t,e)=>{const n=t.map(Ys).filter(r=>r>0);return n.find(r=>r>=Tt)??n[0]??e},lo=()=>typeof window>"u"?kf:fm([ve().innerHeight,document.documentElement?.clientHeight,document.body?.clientHeight,ve().visualViewport?.height,window.screen?.availHeight,window.screen?.height],kf),hm=()=>typeof window>"u"?Cf:fm([ve().innerWidth,document.documentElement?.clientWidth,document.body?.clientWidth,ve().visualViewport?.width,window.screen?.availWidth,window.screen?.width],Cf),zt=t=>{const e=Number.parseFloat(t||"0");return Number.isFinite(e)?Math.max(0,Math.round(e)):0},pm=()=>typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,b2=()=>typeof window>"u"?!1:ve().navigator.standalone===!0||ve().matchMedia?.("(display-mode: standalone)").matches===!0,gm=()=>{if(typeof window>"u"||!pm()||!b2())return{top:0,right:0,bottom:0,left:0};if(!(lo()>=hm()))return{top:0,right:0,bottom:0,left:0};const e=window.screen?.width||window.innerWidth,n=window.screen?.height||window.innerHeight,r=Math.min(e,n),o=Math.max(e,n);return r>=700?{top:20,right:0,bottom:20,left:0}:o<780?{top:20,right:0,bottom:0,left:0}:{top:o>=852?59:o>=844?47:44,right:0,bottom:34,left:0}};function v2(t="--app-vh"){if(typeof window>"u"||typeof document>"u")return;const e=Ys(ve().visualViewport?.height),n=Math.max(0,Math.round(ve().visualViewport?.offsetTop??0)),r=lo(),s=e>=Tt?Math.min(r,e+n):r,i=Math.max(r,s),a=document.documentElement.style;a.setProperty(t,`${Math.max(s,Tt)}px`),a.setProperty("--app-base-vh",`${Math.max(i,Tt)}px`),a.setProperty("--app-visible-vh",`${Math.max(s,Tt)}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=gm();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 ZR(t={}){const{cssVarName:e="--app-vh"}=t,n=Ye.useMemo(()=>h2("viewport"),[]),r=Ye.useCallback(()=>{if(typeof window>"u")return 0;const d=ve().visualViewport,u=lo();if(!d)return u;const f=Ys(d.height);if(f<Tt&&u>=Tt)return u;const h=d.offsetTop,m=f<u-1&&h>0&&h<=96?f+h:f,b=Math.max(0,Math.min(u,m));return b>0?Math.round(b):u},[]),[o,s]=Ye.useState(r),i=Ye.useRef(0),a=Ye.useRef(0),c=Ye.useRef(0),l=Ye.useRef(!1);return Ye.useEffect(()=>{if(typeof window>"u")return;let d=null,u=0,f=null,h="",g=null;const m=()=>{if(g?.isConnected)return g;try{return g=document.createElement("div"),g.setAttribute("aria-hidden","true"),g.style.cssText=["position:fixed","top:0","left:0","width:0","height:0","visibility:hidden","pointer-events:none","padding-top:constant(safe-area-inset-top)","padding-top:env(safe-area-inset-top,0px)","padding-right:constant(safe-area-inset-right)","padding-right:env(safe-area-inset-right,0px)","padding-bottom:constant(safe-area-inset-bottom)","padding-bottom:env(safe-area-inset-bottom,0px)","padding-left:constant(safe-area-inset-left)","padding-left:env(safe-area-inset-left,0px)"].join(";"),(document.body||document.documentElement).appendChild(g),g}catch{}return null},b=()=>{let R={top:0,right:0,bottom:0,left:0};try{const B=m();if(B){const H=getComputedStyle(B);R={top:zt(H.paddingTop),right:zt(H.paddingRight),bottom:zt(H.paddingBottom),left:zt(H.paddingLeft)}}}catch{}const D=ve();if(D!==window){const B=D.getComputedStyle(D.document.documentElement);R={top:Math.max(R.top,zt(B.getPropertyValue("--safe-top-inset"))),right:Math.max(R.right,zt(B.getPropertyValue("--safe-right-inset"))),bottom:Math.max(R.bottom,zt(B.getPropertyValue("--safe-bottom-inset"))),left:Math.max(R.left,zt(B.getPropertyValue("--safe-left-inset")))}}const M=gm(),F={top:Math.max(R.top,M.top),right:Math.max(R.right,M.right),bottom:Math.max(R.bottom,M.bottom),left:Math.max(R.left,M.left)};return document.documentElement.style.setProperty("--safe-top-inset",`${F.top}px`),document.documentElement.style.setProperty("--safe-right-inset",`${F.right}px`),document.documentElement.style.setProperty("--safe-bottom-inset",`${F.bottom}px`),document.documentElement.style.setProperty("--safe-left-inset",`${F.left}px`),F},w=(R,D,M,F)=>{const B=Math.max(D,M);if(i.current===0){i.current=B,a.current=R,document.documentElement.style.setProperty("--app-base-vh",`${B}px`);return}const H=Math.abs(R-a.current),$=F<=Af;(H>p2||$)&&(i.current=B,a.current=R,document.documentElement.style.setProperty("--app-base-vh",`${B}px`))},I=(R="event")=>{d=null;const D=r(),M=Math.round(ve().visualViewport?.offsetTop??0),F=Ys(ve().visualViewport?.height),B=F>=Tt?F:D,H=lo(),$=hm(),X=Math.max(0,B+M),Y=b(),U=Y.bottom,K=Math.max(0,i.current-X-U);w($,H,X,K),s(xr=>xr===D?xr:D);const q=Number.parseInt(document.documentElement.style.getPropertyValue(e)||"0",10);document.documentElement.style.setProperty(e,`${D}px`),document.documentElement.style.setProperty("--app-vv-offset-top",`${M}px`);const G=i.current,z=Math.min(D,B),V=Math.max(0,Math.min(G,X)),J=Math.max(0,Math.round(G-z-U)),oe=Da(),ne=y2({measuredHeight:J,documentVisible:document.visibilityState==="visible",editableFocused:oe}),ae=ne?J:0,he=ae>=Af,Be=-ae,We=ae;document.documentElement.style.setProperty("--kb-translate-y",`${Be}px`),document.documentElement.style.setProperty("--kb-margin-top",`${We}px`),document.documentElement.style.setProperty("--kb-height",`${ae}px`),document.documentElement.style.setProperty("--app-visible-vh",`${V}px`);const ke=Math.abs(ae-c.current)>1,je=he!==l.current;(ke||je)&&(c.current=ae,l.current=he,document.dispatchEvent(new CustomEvent(g2,{detail:{baseHeight:G,visibleHeight:V,visualViewportHeight:B,offsetTop:M,keyboardHeight:ae,isOpen:he,source:R}}))),(q!==D||M>0||ke||je)&&n("sync",{cssVarName:e,innerHeight:H,baseHeight:G,rawViewportHeight:B,offsetTop:M,visibleHeight:V,rawHeight:D,appliedHeight:D,keyboardViewportHeight:z,measuredKeyboardHeight:J,editableFocused:oe,applyKeyboardInset:ne,keyboardHeight:ae,isKeyboardOpen:he,safeAreaInsets:Y,source:R}),document.dispatchEvent(new CustomEvent(m2,{detail:{height:D,baseHeight:G,visibleHeight:V,offsetTop:M,source:R}}))},y=()=>{d===null&&(d=window.requestAnimationFrame(()=>{d=null;const R=ve(),D=R.visualViewport,M=[R.innerWidth,R.innerHeight,D?.width,D?.height,D?.offsetTop,D?.offsetLeft,document.visibilityState,Da()].join(":"),F=f;f=null,(F||M!==h)&&(h=M,I(F||"viewport.settle")),performance.now()<u&&y()}))},A=(R="event")=>{(R.includes("visibilitychange")||R.includes("pageshow"))&&n("schedule",{source:R}),f=R,pm()&&document.visibilityState==="visible"&&(u=performance.now()+w2),y()};A("mount");const N=()=>A("resize"),k=()=>A("orientationchange"),T=()=>A("visualViewport.resize"),S=()=>A("visualViewport.scroll"),v=()=>A("focusin"),E=()=>A("focusout"),_=R=>{u=0;const D=document.activeElement;D instanceof HTMLElement&&Da()&&D.blur(),c.current=0,l.current=!1;const M=Math.max(i.current,lo(),Tt),F=document.documentElement.style;F.setProperty(e,`${M}px`),F.setProperty("--app-visible-vh",`${M}px`),F.setProperty("--app-vv-offset-top","0px"),F.setProperty("--kb-translate-y","0px"),F.setProperty("--kb-margin-top","0px"),F.setProperty("--kb-height","0px"),s(B=>B===M?B:M),n("keyboard session reset",{source:R,baseHeight:M})};window.addEventListener("resize",N),window.addEventListener("orientationchange",k),ve().visualViewport?.addEventListener("resize",T),ve().visualViewport?.addEventListener("scroll",S),document.addEventListener("focusin",v),document.addEventListener("focusout",E);const L=R=>{n("resume",{source:R,innerHeight:Math.round(window.innerHeight),visualViewport:ve().visualViewport?{width:Math.round(ve().visualViewport.width),height:Math.round(ve().visualViewport.height),offsetTop:Math.round(ve().visualViewport.offsetTop)}:null,hidden:document.hidden}),A(R)},C=()=>{document.hidden?_("visibilitychange:hidden"):L("visibilitychange")},x=()=>L("pageshow"),P=()=>_("pagehide");return document.addEventListener("visibilitychange",C),window.addEventListener("pageshow",x),window.addEventListener("pagehide",P),()=>{window.removeEventListener("resize",N),window.removeEventListener("orientationchange",k),ve().visualViewport?.removeEventListener("resize",T),ve().visualViewport?.removeEventListener("scroll",S),document.removeEventListener("focusin",v),document.removeEventListener("focusout",E),document.removeEventListener("visibilitychange",C),window.removeEventListener("pageshow",x),window.removeEventListener("pagehide",P),d!==null&&window.cancelAnimationFrame(d),g?.remove()}},[e,n,r]),o}const S2=1e3,x2=2e4,E2=9e4,A2=5e3,ee={ws:null,listeners:new Set,reconnectAttempt:0,reconnectTimer:null,idleCloseTimer:null,closing:!1};let rs=0,lr=null;function k2(){return typeof window>"u"?null:`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/control/ws`}function mm(){ee.idleCloseTimer&&(clearTimeout(ee.idleCloseTimer),ee.idleCloseTimer=null)}function C2(){mm(),!(ee.ws&&ee.ws.readyState===WebSocket.OPEN)&&(ee.idleCloseTimer=setTimeout(()=>{ee.idleCloseTimer=null,ee.listeners.size===0&&I2()},A2))}function I2(){if(ee.ws){try{ee.ws.close()}catch{}ee.ws=null}lr&&(clearInterval(lr),lr=null)}function If(){if(ee.reconnectTimer)return;const t=Math.min(S2*Math.pow(2,ee.reconnectAttempt),x2);ee.reconnectAttempt+=1,ee.reconnectTimer=setTimeout(()=>{ee.reconnectTimer=null,wm()},t)}function wm(){const t=k2();if(!t||ee.ws&&ee.ws.readyState===WebSocket.OPEN)return;let e;try{e=ig(t)}catch{If();return}ee.ws=e,e.onopen=()=>{ee.reconnectAttempt=0,rs=Date.now(),lr||(lr=setInterval(()=>{if(!(!ee.ws||ee.ws.readyState!==WebSocket.OPEN)&&rs>0&&Date.now()-rs>E2)try{ee.ws.close()}catch{}},3e4),lr.unref?.())},e.onmessage=n=>{rs=Date.now();let r=null;try{r=JSON.parse(n.data)}catch{return}if(!r)return;if(r.type==="session-notice"){if(typeof r.id!="string"||typeof r.sessionId!="string"||typeof r.sessionName!="string"||typeof r.message!="string"||!r.message.trim()||r.message.length>4e3||r.title!==void 0&&(typeof r.title!="string"||r.title.length>120)||typeof r.createdAt!="number")return;const i=r;for(const a of ee.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type==="update-state"){const i=r.state;if(!i||typeof i.status!="string"||typeof i.currentVersion!="string")return;const a={type:"update-state",state:i};for(const c of ee.listeners)try{c(a)}catch(l){console.error("[clientStateSync] listener threw:",l)}return}if(r.type==="server-health"){const i=r.state;if(!i||typeof i.attention!="boolean"||typeof i.supervised!="boolean")return;const a={type:"server-health",state:i};for(const c of ee.listeners)try{c(a)}catch(l){console.error("[clientStateSync] listener threw:",l)}return}if(r.type==="context-draft"){if(typeof r.text!="string")return;const i={type:"context-draft",text:r.text,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const a of ee.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type==="pinned-explorer-roots"){if(!r.pinnedExplorerRoots||typeof r.pinnedExplorerRoots!="object"||Array.isArray(r.pinnedExplorerRoots))return;const i={type:"pinned-explorer-roots",pinnedExplorerRoots:r.pinnedExplorerRoots,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const a of ee.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type==="config-updated"){if(r.key!=="toolbar-presets"&&r.key!=="agent-rules"&&r.key!=="program-detection")return;const i={type:"config-updated",key:r.key,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0};for(const a of ee.listeners)try{a(i)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type!=="client-state"||!r.state)return;const o=r.state,s={type:"client-state",clientState:{sessions:Array.isArray(o.sessions)?o.sessions:[],updatedAt:typeof o.updatedAt=="number"?o.updatedAt:Date.now()},inventory:r.inventory,seq:typeof r.seq=="number"?r.seq:void 0};for(const i of ee.listeners)try{i(s)}catch(a){console.error("[clientStateSync] listener threw:",a)}},e.onclose=()=>{ee.ws===e&&(ee.ws=null),ee.listeners.size>0&&If()},e.onerror=()=>{}}function ym(t){return ee.listeners.add(t),mm(),ee.ws||wm(),()=>{ee.listeners.delete(t),ee.listeners.size===0&&C2()}}const Fa=yi(t=>({unread:{},viewing:null,receive:(e,n)=>t(r=>{const o=r.unread[e]??[];return r.viewing===e||o.includes(n)?r:{unread:{...r.unread,[e]:[...o,n]}}}),view:e=>t(n=>{if(!e||!n.unread[e])return n.viewing===e?n:{viewing:e};const r={...n.unread};return delete r[e],{viewing:e,unread:r}})})),bm=new Set(["bash","zsh","fish","sh","dash","ksh","tcsh","csh","nu"]);function Wn(t){if(!t)return null;if(t==="/")return"/";const e=t.replace(/\/+$/,"").split("/");return e[e.length-1]||t}function R2(t,e,n,r=bm,o=null,s=null){if(t.customName)return{primary:t.name,secondary:Wn(n)};if(o){const a=Wn(n),c=o===n||o===a;if(s!=="idle"&&!r.has(o)&&!c)return{primary:o,secondary:a}}if(e&&!r.has(e))return{primary:e,secondary:Wn(n)};const i=Wn(n);return i?{primary:i,secondary:null}:{primary:t.name,secondary:null}}function T2(t,e,n,r=bm,o=null,s=null){return R2(t,e,n,r,o,s).primary}function P2(t,e,n){const r=[],o=new Map;for(const s of t){const i=e(s),a=i&&i.trim().length>0?i:"";let c=o.get(a);c||(c={key:a,label:a?Wn(a)??a:n,sessions:[]},o.set(a,c),r.push(c)),c.sessions.push(s)}return r.sort((s,i)=>(s.key===""?1:0)-(i.key===""?1:0))}function JR(t){return t&&t.trim().length>0?t:""}function QR(t,e,n){const r=[...t],[o]=r.splice(e,1);return o?(r.splice(n,0,o),r.flatMap(s=>s.sessions.map(i=>i.id))):t.flatMap(s=>s.sessions.map(i=>i.id))}function N2(t,e){const n=new Set;return t.flatMap(r=>{const o=[...new Set(r.sessionIds)].filter(s=>e.has(s)&&!n.has(s));return o.length<(r.federated?1:2)?[]:(o.forEach(s=>n.add(s)),[{...r,sessionIds:o}])})}function eT(t,e,n,r,o=[],s=[]){const i=new Map(t.map(g=>[g.id,g])),a=N2(s,new Set(i.keys())),c=new Map,l=new Map,d=o.filter(g=>g.sessionIds.length>=2&&g.sessionIds.every(m=>i.has(m))),u=(g,m)=>{const b=i.get(m);g.forEach(w=>{c.set(w,g),l.set(w,b)})};for(const g of a){const m=new Set(g.sessionIds),b=new Map;for(const y of d)y.sessionIds.every(A=>m.has(A))&&y.sessionIds.forEach(A=>b.set(A,y.sessionIds));const w=new Set,I=g.sessionIds.flatMap(y=>{if(w.has(y))return[];const A=b.get(y)??[y];return A.forEach(N=>w.add(N)),A});u(I,g.sessionIds[0])}for(const g of d)g.sessionIds.some(m=>c.has(m))||u(g.sessionIds,g.sessionIds[0]);const f=g=>{const m=new Set;return g.flatMap(b=>{if(m.has(b.id))return[];const w=c.get(b.id)??[b.id];return w.forEach(I=>m.add(I)),w.map(I=>i.get(I))})};if(!n)return{arranged:f(t),groups:[]};const h=P2(t,g=>e(l.get(g.id)??g),r).map(g=>({...g,sessions:f(g.sessions)}));return{arranged:h.flatMap(g=>g.sessions),groups:h}}function L2(t,e,n){const r=t.findIndex(o=>n(o)===e);return r<0?null:t[r+1]?n(t[r+1]):r>0?n(t[r-1]):null}const vm="termdock-session-fonts-v1",Rf=8,B2=32;function Sm(t){return Number.isFinite(t)?Math.max(Rf,Math.min(B2,Math.round(t))):Rf}function Kl(){if(typeof window>"u")return{};try{const t=window.localStorage.getItem(vm);if(!t)return{};const e=JSON.parse(t);if(typeof e!="object"||e===null)return{};const n={};for(const[r,o]of Object.entries(e))typeof o=="number"&&Number.isFinite(o)&&(n[r]=Sm(o));return n}catch{return{}}}function xm(t){if(!(typeof window>"u"))try{window.localStorage.setItem(vm,JSON.stringify(t))}catch{}}function tT(t){return Kl()[t]??null}function nT(t,e){if(typeof window>"u")return;const n=Kl(),r=e===null?null:Sm(e);r===null?delete n[t]:n[t]=r,xm(n),window.dispatchEvent(new CustomEvent("termfontchange",{detail:{sessionId:t,fontSize:r}}))}function _2(t){if(typeof window>"u")return;const e=Kl();t in e&&(delete e[t],xm(e))}const Ma="termdock-sessions",Dc="termdock-active-session",zl="termdock-sessions-cache";function Fc(){try{const t=localStorage.getItem(Dc);return t&&t.trim().length>0?t:null}catch{return null}}function Un(t){try{t?localStorage.setItem(Dc,t):localStorage.removeItem(Dc)}catch{}}function Em(){if(typeof window>"u")return null;try{const t=localStorage.getItem(zl);if(!t)return null;const e=JSON.parse(t);return Array.isArray(e)?e.filter(n=>typeof n=="object"&&n!==null&&typeof n.sessionId=="string"&&typeof n.name=="string"):null}catch{return null}}function sn(t){if(!(typeof window>"u"))try{localStorage.setItem(zl,JSON.stringify(t))}catch{}}function Tf(){if(!(typeof window>"u"))try{localStorage.removeItem(zl)}catch{}}function Am(t){return t.map(e=>({...e,mode:e.mode==="tmux"?"tmux":"shell",tmuxSessionName:e.tmuxSessionName??null,customName:e.customName===!0}))}function Pf(t){return Am(t.map(e=>({sessionId:e.sessionId,name:e.name,customName:e.customName===!0,backendSessionId:e.backendSessionId,mode:e.mode,tmuxSessionName:e.tmuxSessionName,createdAt:e.createdAt,lastActivity:e.lastActivity}))).map((e,n)=>({...e,activeProgram:t[n]?.activeProgram??null,cwd:t[n]?.cwd??null,shellTitle:t[n]?.shellTitle??null,agent:t[n]?.agent}))}function Nf(t){return t.map(e=>`${e.sessionId}:${e.name}:${e.customName}:${e.backendSessionId}:${e.mode}:${e.tmuxSessionName}:${e.lastActivity}:${e.activeProgram??""}:${e.cwd??""}:${e.shellTitle??""}:${JSON.stringify(e.agent)??""}`).join("|")}function Mc(t,e){return t.length===0?null:e&&t.some(n=>n.sessionId===e)?e:t[0]?.sessionId??null}function O2(){const t=Em()??[];return{sessions:t,activeSessionId:Mc(t,Fc())}}function rT(){const t=O.useRef(Em()).current,e=O.useRef(Fc()).current,[n,r]=O.useState(t??[]),[o,s]=O.useState(null),[i,a]=O.useState(t&&t.length>0?Mc(t,e):e),[c,l]=O.useState(t===null),d=O.useRef(!1),u=O.useRef(null),f=O.useRef(t===null),h=O.useRef(0),g=O.useRef(new Set),m=O.useRef(0);O.useEffect(()=>{f.current=c},[c]),O.useEffect(()=>{u.current=i},[i]);const b=O.useCallback(x=>{const P=Mc(x,u.current??Fc());return a(R=>R===P?R:P),Un(P),u.current=P,P},[]),w=O.useCallback((x,P)=>{const R=x.filter(D=>!g.current.has(D.sessionId));r(D=>Nf(D)===Nf(R)?D:R),sn(R),P?.reconcileActive&&b(R)},[b]),I=O.useCallback((x,P)=>{const R=g.current.size===0?x:{...x,clientSessions:x.clientSessions.filter(D=>!g.current.has(D.sessionId))};s(R),w(Pf(R.clientSessions),P)},[w]),y=O.useCallback(()=>typeof window>"u"?[]:localStorage.getItem(Ma)?(localStorage.removeItem(Ma),Tf(),Un(null),r([]),a(null),console.info("[session-persist] discarded legacy local session cache"),[]):[],[]),A=O.useCallback(async()=>{if(typeof window>"u")return[];const x=m.current;try{const P=await jg(),R=Pf(P.clientSessions);return x!==m.current?(console.info("[session-inventory] ignored restore snapshot superseded by a local mutation"),R.filter(D=>!g.current.has(D.sessionId))):(I(P,{reconcileActive:!0}),R.length>0?R:y())}catch(P){console.error("Failed to restore sessions from server:",P);try{return y()}catch(R){console.error("Failed to discard legacy local sessions:",R)}}finally{l(!1)}return[]},[I,y]),N=O.useCallback(async x=>{const P=++m.current,R=await Hg(x);return P===m.current&&(I(R.inventory),a(R.session.sessionId),Un(R.session.sessionId)),R},[I]),k=O.useCallback(async(x,P)=>{++m.current,g.current.add(x),_2(x),r(R=>{const D=R.filter(B=>B.sessionId!==x),M=P!=null&&D.some(B=>B.sessionId===P),F=u.current===x?M?P:L2(R,x,B=>B.sessionId):u.current;return a(F),Un(F),sn(D),D});try{await $g(x)}catch(R){console.error("Failed to remove session from inventory:",R)}},[]),T=O.useCallback(x=>{const P=Date.now();r(R=>{const D=R.map(M=>M.sessionId===x?{...M,lastActivity:P}:M);return sn(D),D})},[]),S=O.useCallback(x=>{a(x),Un(x)},[]),v=O.useCallback(async(x,P)=>{const R=P.trim();if(!R)return;const D=++m.current;r(M=>{const F=M.map(B=>B.sessionId===x?{...B,name:R,customName:!0}:B);return sn(F),F});try{const M=await fs(x,{name:R,customName:!0});D===m.current&&I(M)}catch(M){console.error("Failed to rename session in inventory:",M)}},[I]),E=O.useCallback(async x=>{const P=++m.current;r(R=>{const D=R.map(M=>M.sessionId===x?{...M,customName:!1}:M);return sn(D),D});try{const R=await fs(x,{customName:!1});P===m.current&&I(R)}catch(R){console.error("Failed to reset session name in inventory:",R)}},[I]),_=O.useCallback(async x=>{const P=++m.current;r(R=>{const D=new Map(R.map($=>[$.sessionId,$])),M=x.map($=>D.get($)).filter($=>$!==void 0),F=new Set(x),B=R.filter($=>!F.has($.sessionId)),H=[...M,...B];return sn(H),H});try{const R=await Ug(x);P===m.current&&I(R)}catch(R){console.error("Failed to reorder sessions in inventory:",R)}},[I]),L=O.useCallback(async()=>{++m.current;for(const x of n)g.current.add(x.sessionId);r([]),s(null),a(null),Un(null),Tf(),typeof window<"u"&&localStorage.removeItem(Ma);try{await qg()}catch(x){console.error("Failed to clear session inventory:",x)}},[n]),C=O.useCallback(async(x,P)=>{const R=++m.current;r(D=>{const M=D.map(F=>F.sessionId===x?{...F,backendSessionId:P}:F);return sn(M),M});try{const D=await fs(x,{backendSessionId:P});R===m.current&&I(D)}catch(D){console.error("Failed to update session backend in inventory:",D)}},[I]);return O.useEffect(()=>{d.current||(d.current=!0,A())},[A]),O.useEffect(()=>ym(P=>{if(P.type!=="client-state"||f.current)return;const R=typeof P.seq=="number"?P.seq:null;if(R!==null){if(R<h.current){console.warn("[session-inventory] ignored stale control snapshot",{seq:R,latestSeq:h.current});return}h.current=R}if(P.inventory){I(P.inventory,{reconcileActive:!0});return}const D=Am(P.clientState.sessions||[]);w(D,{reconcileActive:!0})}),[I,w]),{sessions:n,inventory:o,activeSessionId:i,isLoading:c,openSession:N,removeSession:k,updateSessionActivity:T,setActiveSession:S,updateSessionBackendId:C,renameSession:v,resetSessionCustomName:E,reorderSessions:_,clearAllSessions:L,restoreSessions:A}}const D2=256*1024,F2=256*1024,M2=128;function Lf(t,e=D2){if(!t)return[];if(t.length<=e)return[t];const n=[];let r=0;for(;r<t.length;){let o=Math.min(r+e,t.length);if(o<t.length){const s=t.lastIndexOf(`
35
- `,o);s>r&&(o=s+1)}n.push(t.slice(r,o)),r=o}return n}function j2(t,e=F2,n=M2){const r=new Map;let o=0,s=0;for(const i of[...t.keys()]){const a=t.get(i);if(!a||a.length===0){t.delete(i);continue}const c=[];for(;a.length>0;){const l=a[0];if(s>0&&(s>=n||o+l.length>e))break;a.shift(),c.push(l),o+=l.length,s+=1}if(c.length>0&&r.set(i,c),t.delete(i),a.length>0&&t.set(i,a),s>=n||o>=e)break}return r}async function km(t,e=!1,n="termdock-encrypted-background"){const r=await new Promise((o,s)=>{const i=indexedDB.open(n,1);i.onupgradeneeded=()=>i.result.createObjectStore("state"),i.onsuccess=()=>o(i.result),i.onerror=()=>s(i.error)});try{return await new Promise((o,s)=>{const i=r.transaction("state",e?"readwrite":"readonly"),a=t(i.objectStore("state"));i.oncomplete=()=>o(a.result),i.onabort=i.onerror=()=>s(i.error)})}finally{r.close()}}const H2=t=>km(e=>e.put(t,t.targetPeerId),!0),U2=t=>km(e=>e.delete(t),!0),Cm="termdock-pwa-notifications-enabled",Im="termdock-pwa-ai-notifications-enabled",Rm="termdock-pwa-exit-notifications-enabled",Tm="termdock-pwa-notification-alert-style",$2="termdock-notification-claim:",jc=5e3,q2=1500,Hc="termdock-push-last-sync",Bf=360*60*1e3,K2=10080*60*1e3,uo=new Map;function Gl(){return rt()?!0:typeof window<"u"&&typeof Notification<"u"&&"serviceWorker"in navigator&&window.isSecureContext}function z2(){if(typeof navigator>"u")return!1;const t=navigator.userAgent;return/iPad|iPhone|iPod/.test(t)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}function G2(){return typeof window>"u"?!1:!!(window.matchMedia("(display-mode: standalone)").matches||"standalone"in navigator&&navigator.standalone===!0)}function W2(){return rt()?!0:!(!Gl()||z2()&&!G2())}function oT(){return rt()?"granted":typeof Notification>"u"?"unsupported":Notification.permission}function Wl(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Cm)==="true"}catch{return!1}}function sT(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Cm,String(t))}catch{}}function Zs(){if(typeof window>"u")return!0;try{const t=window.localStorage.getItem(Im);return t===null?!0:t==="true"}catch{return!0}}function iT(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Im,String(t))}catch{}}function Uc(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Rm)==="true"}catch{return!1}}function aT(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Rm,String(t))}catch{}}function So(){if(typeof window>"u")return"normal";try{const t=window.localStorage.getItem(Tm);if(t==="quiet"||t==="persistent")return t}catch{}return"normal"}function cT(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Tm,t)}catch{}}async function lT(){return rt()?"granted":Gl()?Notification.permission==="default"?Notification.requestPermission():Notification.permission:"unsupported"}function V2(){return typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus()}function X2(t){for(const[e,n]of uo)t-n>jc&&uo.delete(e)}function Y2(t){return t.dedupKey?.trim()?t.dedupKey.trim():t.tag?.trim()?t.tag.trim():[t.data?.sessionId,t.title,t.body].filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()).join("|")}function Z2(t){const e=Y2(t);if(!e)return!0;const n=Date.now();X2(n);const r=uo.get(e)??0;if(n-r<jc)return!1;try{if(typeof window<"u"&&window.localStorage){const o=`${$2}${e}`,s=Number(window.localStorage.getItem(o)??"0");if(Number.isFinite(s)&&n-s<jc)return uo.set(e,s),!1;Number.isFinite(s)&&s>0&&window.localStorage.removeItem(o),window.localStorage.setItem(o,String(n))}}catch{}return uo.set(e,n),!0}async function Si(){if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;try{const t=await navigator.serviceWorker.getRegistration()??null;return t?.active?t:await Promise.race([navigator.serviceWorker.ready,new Promise(n=>{window.setTimeout(()=>n(null),q2)})])??t}catch{return null}}function J2(t){const e="=".repeat((4-t.length%4)%4),n=(t+e).replace(/-/g,"+").replace(/_/g,"/"),r=window.atob(n),o=new Uint8Array(new ArrayBuffer(r.length));for(let s=0;s<r.length;s+=1)o[s]=r.charCodeAt(s);return o}async function Vl(t,e){const n=await fetch("/api/csrf-token");if(!n.ok)throw new Error("Unable to get notification security token");const{csrfToken:r}=await n.json();return fetch(`/api/notifications/${t}`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(e)})}async function Q2(t=!1,e=!1){if(rt())return!0;if(!Wl()||!W2()||Notification.permission!=="granted")return!1;const n=await Si();if(!n?.pushManager)return!1;try{const r=await fetch("/api/notifications/status");if(!r.ok)return!1;const o=await r.json();let s=await n.pushManager.getSubscription();const i=!!(s?.expirationTime&&s.expirationTime-Date.now()<K2);if(!s)try{s=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:J2(o.publicKey)})}catch(d){return console.warn(`[PWA notifications] Push subscription missing; re-subscribe failed${e?" (user gesture)":""}:`,d),!1}const a=Number(window.localStorage.getItem(Hc)??"0"),c=!o.subscription||o.subscription.endpoint!==s.endpoint||Date.now()-(o.subscription.updatedAt??0)>=Bf;if(t||c||Date.now()-a>=Bf||i){if(!(await Vl("subscribe",{subscription:s.toJSON(),aiEnabled:Zs(),exitEnabled:Uc(),alertStyle:So(),locale:navigator.language})).ok)return!1;window.localStorage.setItem(Hc,String(Date.now()))}const l=se();return l&&await H2({targetPeerId:l.targetPeerId,addresses:Sr(l),routes:en(l),publicKey:o.publicKey,preferences:{aiEnabled:Zs(),exitEnabled:Uc(),alertStyle:So(),locale:navigator.language}}),!0}catch(r){return console.warn("[PWA notifications] Push subscription sync failed:",r),!1}}async function dT(){if(rt())return;const e=await(await Si())?.pushManager?.getSubscription();try{await Vl("unsubscribe",{endpoint:e?.endpoint})}finally{const n=se();n&&await U2(n.targetPeerId),await e?.unsubscribe();try{window.localStorage.removeItem(Hc)}catch{}}}async function uT(){if(rt()||!Wl())return;(await Vl("preferences",{aiEnabled:Zs(),exitEnabled:Uc(),alertStyle:So(),locale:navigator.language})).status===404&&await Q2(!0)}async function fT(){if(!rt())try{const t=navigator;typeof t.clearAppBadge=="function"&&await t.clearAppBadge()}catch{}}async function hT(t){if(!rt())try{const e=await Si();if(!e||typeof e.getNotifications!="function")return;const n=`agent:${t}`,r=await e.getNotifications({tag:n});for(const s of r)s.close();const o=navigator;if(typeof o.setAppBadge=="function"){const s=await e.getNotifications();await o.setAppBadge(s.length)}}catch{}}async function ja(t){if(!Wl()||!Gl())return!1;if(t.requireHidden!==!1&&V2())return!0;const e=rt();if(e){const s=t.alertStyle??So(),i=await e.showNotification({title:t.title,body:t.body,tag:t.tag,sessionId:t.data?.sessionId,silent:s==="quiet",persistent:s==="persistent"});return e.notificationDeliveryConfirmation===!0&&i}if(Notification.permission!=="granted")return!1;const n=await Si();if(t.deferToPush&&await n?.pushManager?.getSubscription())return!0;if(t.requireHidden!==!1){if(await n?.pushManager?.getSubscription())return!0}if(!Z2(t))return!0;const r=t.alertStyle??So(),o={body:t.body,tag:t.tag,icon:"/pwa-192x192.png",badge:"/maskable-icon-512x512.png",requireInteraction:r==="persistent",renotify:r==="persistent"?!!t.tag:!1,silent:r==="quiet",vibrate:r==="quiet"?[]:[80,40,80],data:{url:t.data?.url??"/",sessionId:t.data?.sessionId}};try{if(n&&typeof n.showNotification=="function")return await n.showNotification(t.title,o),!0;const s=new Notification(t.title,o);return s.onclick=()=>{window.focus(),t.data?.url&&window.location.href!==t.data.url&&window.location.assign(t.data.url),s.close()},!0}catch(s){if(s instanceof DOMException&&s.name==="NotSupportedError"&&o.renotify)try{const i={...o,renotify:!1};return n&&typeof n.showNotification=="function"?await n.showNotification(t.title,i):new Notification(t.title,i),!0}catch(i){return console.warn("[PWA notifications] Failed to show notification (renotify fallback):",i),!1}return console.warn("[PWA notifications] Failed to show notification:",s),!1}}function eR(){try{return localStorage.getItem("termdock:locale")||"en"}catch{return"en"}}function tR(t,e){return t==="zh"?{waitingTitle:`${e} 需要你的处理`,waitingBody:`${e} 需要你的处理。`,doneTitle:`${e} 已完成`,doneBody:`${e} 已完成,点按查看结果。`,exitedTitle:`${e} 已退出`,exitedBody:`${e} 已退出,点按查看结果。`}:{waitingTitle:`${e} needs your input`,waitingBody:`${e} is waiting for your input.`,doneTitle:`${e} finished`,doneBody:"Tap to see the result.",exitedTitle:`${e} exited`,exitedBody:"Tap to see the result."}}const _f=1e6;function gt(t){return{sessionId:t,directory:"",terminalSessionId:null,mode:"shell",tmuxSessionName:null,activeProgram:null,activeProgramRaw:null,activeProgramSource:null,cwd:null,inCopyMode:!1,isConnecting:!1,agentStatus:null,agentIndicator:null,agentStatusDetail:null,agent:null,agentMessage:null,agentNativeSessionId:null,agentResumeRecovered:!1,agentRich:!1,agentActivity:0,agentCwd:null,agentNeedsReview:!1,shellTitle:null,promptState:null,shellExitCode:null,tuiProgress:null,gitStatus:null,bufferChunks:[],bufferLength:0,lastOutputAt:null,updatedAt:Date.now()}}const xi="termdock-shell-titles-v1";function Ei(){if(typeof window>"u")return{};try{const t=localStorage.getItem(xi);if(!t)return{};const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:{}}catch{return{}}}function nR(t){return Ei()[t]??null}function rR(t,e){if(!(typeof window>"u"))try{const n=Ei();e?n[t]=e:delete n[t],localStorage.setItem(xi,JSON.stringify(n))}catch{}}function oR(t){if(!(typeof window>"u"))try{const e=Ei();delete e[t],localStorage.setItem(xi,JSON.stringify(e))}catch{}}const Ai="termdock-agent-cache-v1";function Xl(){if(typeof window>"u")return{};try{const t=localStorage.getItem(Ai);if(!t)return{};const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:{}}catch{return{}}}function Of(t,e){if(!(typeof window>"u"))try{const n=Xl();e?n[t]=e:delete n[t],localStorage.setItem(Ai,JSON.stringify(n))}catch{}}function sR(t){if(!(typeof window>"u"))try{const e=Xl();delete e[t],localStorage.setItem(Ai,JSON.stringify(e))}catch{}}function iR(){if(!(typeof window>"u"))try{localStorage.removeItem(Ai)}catch{}}function aR(t){return Xl()[t]??null}function cR(){if(!(typeof window>"u"))try{localStorage.removeItem(xi)}catch{}}const Ha=yi((t,e)=>{const n={pendingChunksBySession:new Map,activitySessionIds:new Set,batchFlushRafRef:null},r=(i,a)=>{const c=new Map;return t(l=>{const d=new Map(l.sessions);let u=l.nextChunkId;const f=Date.now();for(const[h,g]of i){const m=d.get(h)??gt(h);let b=m.bufferChunks.length>0?[...m.bufferChunks]:[],w=m.bufferLength;for(const I of g){const y=u++;b.push({id:y,data:I}),c.set(h,y),w+=I.length}for(;w>_f&&b.length>1;){const I=b.shift();if(!I)break;w-=I.data.length}d.set(h,{...m,bufferChunks:b,bufferLength:w,lastOutputAt:a.has(h)?f:m.lastOutputAt,updatedAt:f})}return{sessions:d,nextChunkId:u}}),c},o=()=>{if(n.batchFlushRafRef===null){if(typeof window>"u"){s();return}n.batchFlushRafRef=window.requestAnimationFrame(()=>{n.batchFlushRafRef=null,s()})}},s=()=>{if(n.pendingChunksBySession.size===0)return;const i=j2(n.pendingChunksBySession),a=new Set([...i.keys()].filter(c=>n.activitySessionIds.has(c)));for(const c of i.keys())n.pendingChunksBySession.has(c)||n.activitySessionIds.delete(c);r(i,a),n.pendingChunksBySession.size>0&&o()};return{sessions:new Map,nextChunkId:1,activeSessionId:null,getTerminalSession:i=>e().sessions.get(i),setActiveSessionId:i=>{if(t({activeSessionId:i}),i){const a=e().sessions.get(i);if(a?.agentNeedsReview){const c=new Map(e().sessions);c.set(i,{...a,agentNeedsReview:!1,updatedAt:Date.now()}),t({sessions:c}),a.terminalSessionId&&kc(a.terminalSessionId)}}},setTerminalSession:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i),f=!d||d.terminalSessionId!==a.sessionId?gt(i):d??gt(i),h=a.history??d?.history??[];return l.set(i,{...f,terminalSessionId:a.sessionId,mode:a.mode??f.mode,tmuxSessionName:a.tmuxSessionName??f.tmuxSessionName,activeProgram:a.activeProgram??d?.activeProgram??f.activeProgram,activeProgramRaw:a.activeProgramRaw??d?.activeProgramRaw??f.activeProgramRaw,activeProgramSource:a.activeProgramSource??d?.activeProgramSource??f.activeProgramSource,cwd:a.cwd??d?.cwd??f.cwd,agent:d?.agent??aR(i)??f.agent,agentResumeRecovered:d?.agentResumeRecovered??f.agentResumeRecovered,shellTitle:d?.shellTitle??Ei()[i]??f.shellTitle,sessionId:i,isConnecting:!1,history:h,updatedAt:Date.now()}),{sessions:l}})},setSessionHistory:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??gt(i);return l.set(i,{...d,history:a,updatedAt:Date.now()}),{sessions:l}})},setSessionActiveProgram:(i,a,c=null,l=null)=>{t(d=>{const u=new Map(d.sessions),f=u.get(i)??gt(i);return u.set(i,{...f,activeProgram:a,activeProgramRaw:l,activeProgramSource:c,updatedAt:Date.now()}),{sessions:u}})},setSessionCwd:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??gt(i);return l.set(i,{...d,cwd:a,updatedAt:Date.now()}),{sessions:l}})},setSessionShellTitle:(i,a)=>{t(c=>{const l=c.sessions.get(i)??gt(i);if(l.shellTitle===a)return c;const d=new Map(c.sessions);return d.set(i,{...l,shellTitle:a,updatedAt:Date.now()}),{sessions:d}}),rR(i,a)},setSessionPromptState:(i,a,c)=>{t(l=>{const d=l.sessions.get(i);if(!d||d.promptState===a)return l;const u=new Map(l.sessions);return u.set(i,{...d,promptState:a,shellExitCode:c??d.shellExitCode,updatedAt:Date.now()}),{sessions:u}})},setSessionTuiProgress:(i,a)=>{t(c=>{const l=c.sessions.get(i);if(!l)return c;const d=a?.state==="remove"?null:a;if(l.tuiProgress?.state===d?.state&&l.tuiProgress?.progress===d?.progress)return c;const u=new Map(c.sessions);return u.set(i,{...l,tuiProgress:d,updatedAt:Date.now()}),{sessions:u}})},setSessionGitStatus:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i);return!d||JSON.stringify(d.gitStatus)===JSON.stringify(a)?c:(l.set(i,{...d,gitStatus:a,updatedAt:Date.now()}),{sessions:l})})},setSessionCopyMode:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i);return!d||d.inCopyMode===a?c:(l.set(i,{...d,inCopyMode:a,updatedAt:Date.now()}),{sessions:l})})},setSessionAgentIdentity:(i,a)=>{Of(i,a),t(c=>{const l=c.sessions.get(i)??gt(i);if(JSON.stringify(l.agent)===JSON.stringify(a))return c;const d=new Map(c.sessions);return d.set(i,{...l,agent:a,updatedAt:Date.now()}),{sessions:d}})},setSessionAgentStatus:(i,a)=>{const c=e(),l=c.sessions.get(i);if(!l)return;const d=a.agentStatus??null,u=d&&d!=="idle"?a.agentIndicator??l.agentIndicator??null:null,f=d&&d!=="idle"?a.agentStatusDetail??null:null,h=a.agent!==void 0?a.agent:l.agent,g=a.agentMessage!==void 0?a.agentMessage:d?l.agentMessage:null,m=a.agentNativeSessionId!==void 0?a.agentNativeSessionId:l.agentNativeSessionId,b=a.agentResumeRecovered!==void 0?a.agentResumeRecovered:l.agentResumeRecovered,w=a.agentRich??l.agentRich,I=a.agentActivity??l.agentActivity,y=a.agentCwd!==void 0?a.agentCwd:l.agentCwd,A=c.activeSessionId!==i,N=l.agentStatus==="working"||l.agentStatus==="waiting"||l.agentStatus==="done",k=a.reviewed===!1||a.reviewed===null&&d===null&&N&&A;if(l.agentStatus===d&&l.agentIndicator===u&&l.agentStatusDetail===f&&l.agent===h&&l.agentMessage===g&&l.agentNativeSessionId===m&&l.agentResumeRecovered===b&&l.agentRich===w&&l.agentActivity===I&&l.agentCwd===y&&l.agentNeedsReview===k)return;const T=new Map(c.sessions);if(T.set(i,{...l,agentStatus:d,agentIndicator:u,agentStatusDetail:f,agent:h,agentMessage:g,agentNativeSessionId:m,agentResumeRecovered:b,agentRich:w,agentActivity:I,agentCwd:y,agentNeedsReview:k,updatedAt:Date.now()}),t({sessions:T}),h&&Of(i,h),!Zs())return;const S=h?.displayName??l.agent?.displayName??"Agent",v=eR(),E=tR(v,S);if(d==="waiting"&&l.agentStatus!=="waiting"&&A){ja({title:E.waitingTitle,body:g??E.waitingBody,tag:`agent:${i}`,dedupKey:`agent:${i}:waiting:${I}`,data:{url:"/",sessionId:i},deferToPush:!0});return}if(d==="done"&&l.agentStatus!=="done"&&A){ja({title:E.doneTitle,body:E.doneBody,tag:`agent:${i}`,dedupKey:`agent:${i}:done:${I}`,data:{url:"/",sessionId:i},deferToPush:!0});return}d===null&&(l.agentStatus==="working"||l.agentStatus==="waiting")&&A&&ja({title:E.exitedTitle,body:E.exitedBody,tag:`agent:${i}`,dedupKey:`agent:${i}:exited:${I}`,data:{url:"/",sessionId:i},deferToPush:!0})},setAgentResumeRecovered:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??gt(i);return d.agentResumeRecovered===a?c:(l.set(i,{...d,agentResumeRecovered:a,updatedAt:Date.now()}),{sessions:l})})},clearAgentNeedsReview:i=>{const a=e().sessions.get(i);a?.agentNeedsReview&&(t(c=>{const l=new Map(c.sessions),d=l.get(i);return!d||!d.agentNeedsReview?c:(l.set(i,{...d,agentNeedsReview:!1,updatedAt:Date.now()}),{sessions:l})}),a.terminalSessionId&&kc(a.terminalSessionId))},setConnecting:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??gt(i);return l.set(i,{...d,isConnecting:a,updatedAt:Date.now()}),{sessions:l}})},appendToBuffer:(i,a,c)=>{if(!a)return;let l=n.pendingChunksBySession.get(i);l||(l=[],n.pendingChunksBySession.set(i,l)),l.push(...Lf(a)),c?.markActivity!==!1&&n.activitySessionIds.add(i),o()},hasPendingBufferWrites:i=>(n.pendingChunksBySession.get(i)?.length??0)>0,flushPendingBufferWrites:i=>{const a=n.pendingChunksBySession.get(i);if(!a?.length)return e().sessions.get(i)?.bufferChunks.at(-1)?.id??null;n.pendingChunksBySession.delete(i);const c=n.activitySessionIds.delete(i);return n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),r(new Map([[i,a]]),c?new Set([i]):new Set).get(i)??null},replaceBuffer:(i,a)=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null);let c=null;return t(l=>{const d=new Map(l.sessions),u=d.get(i);if(!u)return l;if(!a||a.length===0)return d.set(i,{...u,bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:d};let f=l.nextChunkId;const h=[];let g=0;for(const m of a)if(m)for(const b of Lf(m)){const w=f++;h.push({id:w,data:b}),c=w,g+=b.length}for(;g>_f&&h.length>1;){const m=h.shift();if(!m)break;g-=m.data.length}return d.set(i,{...u,bufferChunks:h,bufferLength:g,updatedAt:Date.now()}),{sessions:d,nextChunkId:f}}),c},clearTerminalSession:i=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),t(a=>{const c=new Map(a.sessions),l=c.get(i);return l&&c.set(i,{...l,terminalSessionId:null,isConnecting:!1,agentStatus:null,agentIndicator:null,agentStatusDetail:null,agent:null,agentMessage:null,agentNeedsReview:!1,updatedAt:Date.now()}),{sessions:c}})},clearBuffer:i=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),t(a=>{const c=new Map(a.sessions),l=c.get(i);return l?(c.set(i,{...l,bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:c}):a})},removeTerminalSession:i=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),t(a=>{const c=new Map(a.sessions);return c.delete(i),{sessions:c}}),oR(i),sR(i)},clearAllTerminalSessions:()=>{n.pendingChunksBySession.clear(),n.activitySessionIds.clear(),n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),t({sessions:new Map,nextChunkId:1}),cR(),iR()}}}),$c="termdock:session-notice";function lR(){return O.useEffect(()=>{const t=()=>Fa.getState().view(!document.hidden&&as()?Ha.getState().activeSessionId:null);t();const e=Ha.subscribe((n,r)=>{n.activeSessionId!==r.activeSessionId&&t()});return document.addEventListener("visibilitychange",t),window.addEventListener(bo,t),()=>{e(),document.removeEventListener("visibilitychange",t),window.removeEventListener(bo,t),Fa.getState().view(null)}},[]),O.useEffect(()=>ym(t=>{if(t.type!=="session-notice")return;Fa.getState().receive(t.sessionId,t.id);const e=se()?.targetPeerId,n=wt(),r=window.parent,o=O2().sessions.find(u=>u.sessionId===t.sessionId),s=Ha.getState().sessions.get(t.sessionId),i=s?.shellTitle??nR(t.sessionId),a=i===s?.cwd||i===Wn(s?.cwd??null)?null:i,c=T2(o??{name:t.sessionName},s?.activeProgram??null,null,void 0,a,s?.promptState??null),l={...t,sessionName:c,key:`${e??"local"}:${t.id}`,open:()=>e&&n?n.focusSession(e,t.sessionId):(window.dispatchEvent(new CustomEvent("termdock:focus-session",{detail:t.sessionId})),!0)},d=r.document.createEvent("CustomEvent");d.initCustomEvent($c,!1,!1,l),r.dispatchEvent(d)}),[]),null}function dR(){const{locale:t}=vi(),e=t==="zh",[n,r]=O.useState([]);O.useEffect(()=>{const i=a=>{const c=a.detail;r(l=>l.some(d=>d.key===c.key)?l:[...l,c])};return window.addEventListener($c,i),()=>window.removeEventListener($c,i)},[]);const o=O.useCallback(i=>{r(a=>a.filter(c=>c.key!==i))},[]),s=n[0];return s?Gc.createPortal(p.jsx(uR,{notice:s,remaining:n.length-1,chinese:e,onDismiss:o},s.key),document.body):null}function uR({notice:t,remaining:e,chinese:n,onDismiss:r}){const[o,s]=O.useState(!1);return p.jsxs("section",{"aria-label":n?"关键进展提醒":"Progress reminder",className:"fixed left-3 right-3 top-[calc(var(--safe-top-inset,0px)+0.75rem)] z-toast overflow-hidden rounded-xl bg-surface text-foreground shadow-lg ring-1 ring-inset ring-border/15 animate-fade-in md:left-auto md:right-4 md:w-[360px]",children:[p.jsxs("button",{type:"button","aria-label":n?"查看 Session":"Open session",className:"group flex w-full items-start gap-2.5 p-3.5 pr-11 text-left transition-colors hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",onClick:()=>{t.open()?r(t.key):s(!0)},children:[p.jsx(dg,{size:16,className:"mt-0.5 shrink-0 text-primary","aria-hidden":"true"}),p.jsxs("span",{className:"min-w-0 flex-1",role:"status","aria-live":"polite","aria-atomic":"true",children:[p.jsxs("span",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium",title:t.sessionName,children:t.sessionName}),p.jsx(o1,{size:13,className:"shrink-0 text-muted-foreground/60 transition-colors group-hover:text-primary","aria-hidden":"true"})]}),t.title&&p.jsx("span",{className:"mt-1 block truncate text-[11px] text-muted-foreground",children:t.title}),p.jsx("span",{className:"mt-1.5 line-clamp-3 whitespace-pre-wrap break-words text-[13px] leading-relaxed text-foreground/85",title:t.message,children:t.message}),e>0&&p.jsx("span",{className:"mt-2 block text-[10px] text-muted-foreground",children:n?`还有 ${e} 条`:`${e} more`}),o&&p.jsx("span",{role:"alert",className:"mt-2 block text-xs text-warning",children:n?"暂时无法打开该服务,请重试。":"Unable to open the service. Please retry."})]})]}),p.jsx("button",{type:"button","aria-label":n?"关闭提醒":"Dismiss reminder",className:"absolute right-0 top-0 flex h-11 w-11 items-center justify-center rounded-tr-xl text-muted-foreground/60 transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",onClick:()=>r(t.key),children:p.jsx(mg,{size:14})})]})}const Df=5*6e4;let qc,Pm=!1,Nm=!1,Ff=!1;const Kc=new Set;function Mf(){Pm=!0,Kc.forEach(t=>t())}function fR(){return O.useSyncExternalStore(t=>(Kc.add(t),()=>{Kc.delete(t)}),()=>Pm,()=>!1)}function hR(){window.dispatchEvent(new Event("termdock:before-update")),Nm=!0,qc?.waiting?qc.waiting.postMessage({type:"SKIP_WAITING"}):window.location.reload()}function pR(t,e){let n=t;return()=>{if(!n){n=!0;return}e()}}function gR(){if(Ff||typeof window>"u"||!("serviceWorker"in navigator))return;Ff=!0,navigator.serviceWorker.addEventListener("controllerchange",pR(!!navigator.serviceWorker.controller,()=>{Nm?window.location.reload():Mf()}));const t=()=>{navigator.serviceWorker.register("/sw.js",{scope:"/",updateViaCache:"none"}).then(e=>{qc=e;const n=()=>{e.waiting&&Mf()},r=()=>{const i=e.installing;i?.addEventListener("statechange",()=>{i.state==="installed"&&navigator.serviceWorker.controller&&n()})};e.addEventListener("updatefound",r),r(),n();let o=0;const s=()=>{document.visibilityState!=="visible"||Date.now()-o<Df||(o=Date.now(),e.update().then(n).catch(()=>{}))};s(),window.setInterval(s,Df),document.addEventListener("visibilitychange",s)}).catch(()=>{})};document.readyState==="complete"?t():window.addEventListener("load",t,{once:!0})}function mR(){const t=fR(),[e,n]=O.useState(!1),{locale:r}=vi();if(!t||e)return null;const o=r==="zh";return p.jsxs("div",{role:"status",className:"fixed bottom-16 left-1/2 z-toast flex max-w-[calc(100%-2rem)] -translate-x-1/2 items-center gap-3 rounded-lg border border-border bg-background px-4 py-3 text-sm text-foreground shadow-lg",children:[p.jsx("span",{children:o?"新版本已就绪":"An update is ready"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-primary",onClick:hR,children:o?"重新加载":"Reload"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-muted-foreground",onClick:()=>n(!0),children:o?"稍后":"Later"})]})}function Lm(t){const e=document.querySelector('meta[name="theme-color"]');e&&e.setAttribute("content",t==="light"?"#FFFCF0":"#1C1B1A")}const Bm=O.createContext(void 0);function pT({children:t}){const e=O.useContext(Bm),n=e===void 0?typeof document>"u"?null:document.body:e;return n?Gc.createPortal(t,n):null}const wR={activeKey:"root",items:[]},yR=()=>()=>{},bR=()=>wR;function vR({host:t,item:e,visible:n,active:r}){const o=O.useRef(null);return O.useEffect(()=>{o.current?.toggleAttribute("inert",!r)},[r]),O.useLayoutEffect(()=>{const s=o.current;return()=>{try{const i=s?.contentWindow,a=i?.document.createEvent("Event");a&&(a.initEvent("termdock:before-update",!1,!1),i?.dispatchEvent(a))}catch{}t.attach(e.key,null)}},[t,e.key]),p.jsx("iframe",{ref:o,title:e.service?.label||"服务工作区","data-workspace-key":e.key,src:`/workspace.html?${ng}=${encodeURIComponent(e.key)}`,className:"fixed inset-0 w-full border-0 bg-[var(--chrome-bg)]",style:{height:"var(--app-base-vh, 100%)",visibility:n?"visible":"hidden",pointerEvents:r?"auto":"none"},"aria-hidden":!r,tabIndex:r?0:-1,allow:"clipboard-read; clipboard-write; fullscreen"})}function SR({children:t}){const e=window.parent===window?wt():void 0,n=O.useSyncExternalStore(e?.subscribe||yR,e?.snapshot||bR),[r,o]=O.useState(null),[s,i]=O.useState(()=>n.activeKey==="root"?"root":null),[a,c]=O.useState(),[l,d]=O.useState(!1),[u,f]=O.useState(),h=n.items.find(y=>y.key===n.activeKey),g=h?.rendered||a===n.activeKey?n.activeKey:s,m=g!==n.activeKey,b=m&&s===null;O.useLayoutEffect(()=>{if(!m||b){f(void 0);return}const y=()=>{const A=Array.from(document.querySelectorAll("iframe[data-workspace-key]")).find(_=>_.dataset.workspaceKey===s),S=(s==="root"?r:A?.contentDocument)?.querySelector('nav[aria-label="切换服务"]')?.closest("[data-sidebar-gesture-ignore]")?.getBoundingClientRect();if(!S||S.width===0||S.right<=0){f(void 0);return}const v=A?.getBoundingClientRect(),E=S.top+(v?.top??0)>=160;f({left:S.left+(v?.left??0)+12,top:(E?S.top-8:S.bottom+8)+(v?.top??0),width:Math.max(0,S.width-24),transform:E?"translateY(-100%)":"none"})};return y(),window.addEventListener("resize",y),()=>window.removeEventListener("resize",y)},[m,b,s,r]),O.useLayoutEffect(()=>{e?.present(g),m||i(g),r?.toggleAttribute("inert",g!=="root"||m)},[e,r,g,m]),O.useEffect(()=>{if(d(!1),!m)return;const y=setTimeout(()=>d(!0),8e3);return()=>clearTimeout(y)},[n.activeKey,m]),O.useEffect(()=>{c(void 0)},[n.activeKey]);const w=n.items.find(y=>y.key===s),I=h?.phase==="offline"?"网络已断开,等待恢复…":h?.phase==="reconnecting"?"连接暂未恢复,正在重试…":l?"连接时间较长,仍在等待服务…":b?"正在恢复服务…":"正在切换服务…";return O.useEffect(()=>{if(!e)return;const y=()=>{try{const A=JSON.parse(localStorage.getItem("termdock-color-theme")||"null");(A==="dark"||A==="light")&&(document.documentElement.dataset.theme=A,Lm(A))}catch{}};return window.addEventListener("storage",y),()=>window.removeEventListener("storage",y)},[e]),O.useEffect(()=>{if(!e||!("serviceWorker"in navigator))return;const y=k=>{if(k.source!==navigator.serviceWorker.controller)return;const T=k.data;T?.type==="termdock:focus-session"&&typeof T.targetPeerId=="string"&&typeof T.sessionId=="string"&&e.focusSession(T.targetPeerId,T.sessionId)&&(k.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),k.stopImmediatePropagation())},A=async()=>{if("caches"in window)try{const k=await caches.open("termdock-notification-target-v1"),T=await k.match("/__termdock-notification-target");if(!T)return;const S=await T.json();typeof S.targetPeerId=="string"&&typeof S.sessionId=="string"&&Date.now()-S.clickedAt<3e4&&e.focusSession(S.targetPeerId,S.sessionId)&&await k.delete("/__termdock-notification-target")}catch{}},N=()=>{document.hidden||A()};return navigator.serviceWorker.addEventListener("message",y),document.addEventListener("visibilitychange",N),A(),()=>{navigator.serviceWorker.removeEventListener("message",y),document.removeEventListener("visibilitychange",N)}},[e]),e?p.jsxs("div",{className:"relative h-full w-full overflow-hidden bg-[var(--chrome-bg)]",children:[p.jsx("div",{ref:o,className:"isolate h-full w-full","aria-hidden":g!=="root"||m,style:{visibility:g==="root"?"visible":"hidden"},children:p.jsx(Bm.Provider,{value:r,children:t})}),n.items.filter(y=>y.key!=="root").map(y=>p.jsx(vR,{host:e,item:y,visible:g===y.key,active:!m&&g===y.key},y.key)),b&&p.jsx(ql,{className:"z-modal-panel",status:I,detail:l||h?.phase==="offline"||h?.phase==="reconnecting"?h?.service?.label:void 0,actionLabel:l||h?.phase==="offline"||h?.phase==="reconnecting"?"查看连接页面":void 0,onAction:()=>c(n.activeKey)}),m&&!b&&p.jsx("div",{className:"fixed inset-0 z-modal-panel flex items-end justify-center px-3 pb-[calc(env(safe-area-inset-bottom)+96px)]",role:"dialog","aria-modal":"true","aria-label":"切换服务",onKeyDown:y=>{if(y.key==="Escape"&&w?.service&&(y.preventDefault(),e.activate(w.service)),y.key==="Tab"){const A=Array.from(y.currentTarget.querySelectorAll("button")),N=A[0],k=A[A.length-1];y.shiftKey&&document.activeElement===N?(y.preventDefault(),k?.focus()):!y.shiftKey&&document.activeElement===k&&(y.preventDefault(),N?.focus())}},children:p.jsxs("div",{style:u?{position:"absolute",...u}:void 0,className:"flex w-full max-w-sm flex-wrap items-center gap-x-2 gap-y-1 rounded-xl border border-border bg-surface-elevated px-3 py-1.5 text-foreground shadow-lg",children:[p.jsxs("div",{role:"status","aria-live":"polite",className:"flex min-w-0 flex-1 items-center gap-2",children:[p.jsx($e,{size:16,className:"shrink-0 animate-spin text-primary motion-reduce:animate-none","aria-hidden":"true"}),p.jsxs("div",{className:"min-w-0",children:[p.jsx("div",{className:"truncate text-sm font-medium",children:h?.service?.label||"服务工作区"}),p.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:I})]})]}),p.jsxs("div",{className:"flex items-center justify-end gap-1",children:[l&&p.jsx("button",{type:"button",className:"min-h-11 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2",onClick:()=>c(n.activeKey),children:"查看连接页面"}),w?.service&&p.jsx("button",{type:"button",autoFocus:!0,"aria-label":"取消切换",className:"min-h-11 shrink-0 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>e.activate(w.service),children:"取消"})]})]})})]}):t}const xR=O.lazy(()=>tn(()=>import("./App-ecgsYB-4.js").then(t=>t.b),__vite__mapDeps([4,2,1,5,6,3,7,8]))),ER=O.lazy(()=>tn(()=>import("./DagPlayground-BCp8dP9Q.js"),__vite__mapDeps([9,10,2,1,11,7,3])).then(t=>({default:t.DagPlayground}))),AR=O.lazy(()=>tn(()=>import("./DiffLab-CoflQdbG.js"),__vite__mapDeps([12,2,1,13,8,14,3])).then(t=>({default:t.DiffLab}))),kR=O.lazy(()=>tn(()=>import("./DiffReviewLab-cxdwBbrY.js"),__vite__mapDeps([15,2,1,16,5,6,11,13,8,14,3])).then(t=>({default:t.DiffReviewLab})));v2();DE();qE();window.parent===window&&gR();const eo=se();eo&&tn(()=>import("./App-ecgsYB-4.js").then(t=>t.b),__vite__mapDeps([4,2,1,5,6,3,7,8])).catch(()=>{});!new URLSearchParams(location.search).has("dag-playground")&&!new URLSearchParams(location.search).has("diff-lab")&&!new URLSearchParams(location.search).has("diff-review-lab")&&kE(eo?{...eo,id:eo.targetPeerId,label:eo.serviceName||location.host}:void 0);try{const t=JSON.parse(window.localStorage.getItem("termdock-color-theme")||"null");(t==="dark"||t==="light")&&(document.documentElement.dataset.theme=t,Lm(t))}catch{}GE.createRoot(document.getElementById("root")).render(p.jsxs(Ye.StrictMode,{children:[p.jsx(n2,{}),p.jsxs(hI,{children:[window.parent===window&&p.jsxs(p.Fragment,{children:[p.jsx(mR,{}),p.jsx(dR,{})]}),p.jsx(c2,{children:p.jsx(O.Suspense,{fallback:p.jsx(ql,{}),children:(()=>{const t=new URLSearchParams(window.location.search);return t.get("dag-playground")==="1"?p.jsx(ER,{}):t.get("diff-review-lab")==="1"?p.jsx(kR,{}):t.get("diff-lab")==="1"?p.jsx(AR,{}):p.jsx(SR,{children:p.jsxs(o2,{children:[p.jsx(lR,{}),p.jsx(xR,{})]})})})()})})]})]}));export{Cl as $,_l as A,dg as B,zs as C,bm as D,Pg as E,gl as F,pC as G,pE as H,Uk as I,Hv as J,FA as K,$e as L,vE as M,vk as N,WR as O,kI as P,gn as Q,DC as R,wi as S,S1 as T,OC as U,m2 as V,bo as W,mg as X,fT as Y,yk as Z,tn as _,lg as a,Pk as a$,CA as a0,MA as a1,ak as a2,FR as a3,yi as a4,jk as a5,h2 as a6,Le as a7,ik as a8,Gi as a9,LC as aA,Nk as aB,Wn as aC,aC as aD,IC as aE,HC as aF,mC as aG,MC as aH,TC as aI,AC as aJ,Zk as aK,oT as aL,BC as aM,Xs as aN,HA as aO,R2 as aP,T2 as aQ,tT as aR,Xt as aS,Zs as aT,Uc as aU,So as aV,Wl as aW,rt as aX,DA as aY,ZA as aZ,SA as a_,Kk as aa,xC as ab,eT as ac,hT as ad,UA as ae,Ck as af,qk as ag,SC as ah,jA as ai,F1 as aj,Rg as ak,$A as al,xI as am,jR as an,JR as ao,Sk as ap,it as aq,Ok as ar,_k as as,Mk as at,sk as au,_C as av,NC as aw,aR as ax,nR as ay,PC as az,n1 as b,Yk as b$,Ek as b0,Rk as b1,FC as b2,Wg as b3,wt as b4,Da as b5,ap as b6,Ip as b7,bC as b8,Dk as b9,Wk as bA,iI as bB,lk as bC,ut as bD,O2 as bE,yC as bF,gC as bG,wC as bH,vC as bI,YR as bJ,XR as bK,$R as bL,dk as bM,qA as bN,HR as bO,vc as bP,GC as bQ,Vk as bR,XC as bS,nI as bT,QR as bU,Jk as bV,Xk as bW,Tk as bX,$n as bY,lT as bZ,Qk as b_,Hk as ba,Gg as bb,iC as bc,cC as bd,tC as be,sC as bf,rC as bg,W2 as bh,Gl as bi,as as bj,p as bk,DR as bl,Ak as bm,$C as bn,Gk as bo,jl as bp,rI as bq,uC as br,xk as bs,Bk as bt,QC as bu,N2 as bv,kC as bw,Cg as bx,Hg as by,L2 as bz,ug as c,mi as c$,mk as c0,VR as c1,bk as c2,kk as c3,YC as c4,zk as c5,VC as c6,BR as c7,O1 as c8,KC as c9,eI as cA,ym as cB,WC as cC,UR as cD,uk as cE,_R as cF,uT as cG,Q2 as cH,Lm as cI,LR as cJ,Fk as cK,dT as cL,$k as cM,Lk as cN,fs as cO,Ve as cP,EC as cQ,yg as cR,vi as cS,KR as cT,Fa as cU,rT as cV,Ee as cW,Ha as cX,ZR as cY,ve as cZ,hC as c_,jC as ca,qC as cb,JC as cc,se as cd,fC as ce,sI as cf,ig as cg,oI as ch,gk as ci,fk as cj,ck,pk as cl,wk as cm,zC as cn,ZC as co,tI as cp,nT as cq,iT as cr,aT as cs,cT as ct,sT as cu,Mg as cv,ok as cw,Wi as cx,GR as cy,ja as cz,En as d,ze as d0,zR as d1,qR as d2,d1 as e,fg as f,hg as g,c2 as h,MR as i,Tg as j,m1 as k,pg as l,vI as m,gg as n,ql as o,me as p,pT as q,hk as r,pl as s,Ot as t,UC as u,OR as v,pA as w,P2 as x,lC as y,oC as z};
35
+ `,o);s>r&&(o=s+1)}n.push(t.slice(r,o)),r=o}return n}function j2(t,e=F2,n=M2){const r=new Map;let o=0,s=0;for(const i of[...t.keys()]){const a=t.get(i);if(!a||a.length===0){t.delete(i);continue}const c=[];for(;a.length>0;){const l=a[0];if(s>0&&(s>=n||o+l.length>e))break;a.shift(),c.push(l),o+=l.length,s+=1}if(c.length>0&&r.set(i,c),t.delete(i),a.length>0&&t.set(i,a),s>=n||o>=e)break}return r}async function km(t,e=!1,n="termdock-encrypted-background"){const r=await new Promise((o,s)=>{const i=indexedDB.open(n,1);i.onupgradeneeded=()=>i.result.createObjectStore("state"),i.onsuccess=()=>o(i.result),i.onerror=()=>s(i.error)});try{return await new Promise((o,s)=>{const i=r.transaction("state",e?"readwrite":"readonly"),a=t(i.objectStore("state"));i.oncomplete=()=>o(a.result),i.onabort=i.onerror=()=>s(i.error)})}finally{r.close()}}const H2=t=>km(e=>e.put(t,t.targetPeerId),!0),U2=t=>km(e=>e.delete(t),!0),Cm="termdock-pwa-notifications-enabled",Im="termdock-pwa-ai-notifications-enabled",Rm="termdock-pwa-exit-notifications-enabled",Tm="termdock-pwa-notification-alert-style",$2="termdock-notification-claim:",jc=5e3,q2=1500,Hc="termdock-push-last-sync",Bf=360*60*1e3,K2=10080*60*1e3,uo=new Map;function Gl(){return rt()?!0:typeof window<"u"&&typeof Notification<"u"&&"serviceWorker"in navigator&&window.isSecureContext}function z2(){if(typeof navigator>"u")return!1;const t=navigator.userAgent;return/iPad|iPhone|iPod/.test(t)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}function G2(){return typeof window>"u"?!1:!!(window.matchMedia("(display-mode: standalone)").matches||"standalone"in navigator&&navigator.standalone===!0)}function W2(){return rt()?!0:!(!Gl()||z2()&&!G2())}function oT(){return rt()?"granted":typeof Notification>"u"?"unsupported":Notification.permission}function Wl(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Cm)==="true"}catch{return!1}}function sT(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Cm,String(t))}catch{}}function Zs(){if(typeof window>"u")return!0;try{const t=window.localStorage.getItem(Im);return t===null?!0:t==="true"}catch{return!0}}function iT(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Im,String(t))}catch{}}function Uc(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Rm)==="true"}catch{return!1}}function aT(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Rm,String(t))}catch{}}function So(){if(typeof window>"u")return"normal";try{const t=window.localStorage.getItem(Tm);if(t==="quiet"||t==="persistent")return t}catch{}return"normal"}function cT(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Tm,t)}catch{}}async function lT(){return rt()?"granted":Gl()?Notification.permission==="default"?Notification.requestPermission():Notification.permission:"unsupported"}function V2(){return typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus()}function X2(t){for(const[e,n]of uo)t-n>jc&&uo.delete(e)}function Y2(t){return t.dedupKey?.trim()?t.dedupKey.trim():t.tag?.trim()?t.tag.trim():[t.data?.sessionId,t.title,t.body].filter(e=>typeof e=="string"&&e.trim().length>0).map(e=>e.trim()).join("|")}function Z2(t){const e=Y2(t);if(!e)return!0;const n=Date.now();X2(n);const r=uo.get(e)??0;if(n-r<jc)return!1;try{if(typeof window<"u"&&window.localStorage){const o=`${$2}${e}`,s=Number(window.localStorage.getItem(o)??"0");if(Number.isFinite(s)&&n-s<jc)return uo.set(e,s),!1;Number.isFinite(s)&&s>0&&window.localStorage.removeItem(o),window.localStorage.setItem(o,String(n))}}catch{}return uo.set(e,n),!0}async function Si(){if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;try{const t=await navigator.serviceWorker.getRegistration()??null;return t?.active?t:await Promise.race([navigator.serviceWorker.ready,new Promise(n=>{window.setTimeout(()=>n(null),q2)})])??t}catch{return null}}function J2(t){const e="=".repeat((4-t.length%4)%4),n=(t+e).replace(/-/g,"+").replace(/_/g,"/"),r=window.atob(n),o=new Uint8Array(new ArrayBuffer(r.length));for(let s=0;s<r.length;s+=1)o[s]=r.charCodeAt(s);return o}async function Vl(t,e){const n=await fetch("/api/csrf-token");if(!n.ok)throw new Error("Unable to get notification security token");const{csrfToken:r}=await n.json();return fetch(`/api/notifications/${t}`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(e)})}async function Q2(t=!1,e=!1){if(rt())return!0;if(!Wl()||!W2()||Notification.permission!=="granted")return!1;const n=await Si();if(!n?.pushManager)return!1;try{const r=await fetch("/api/notifications/status");if(!r.ok)return!1;const o=await r.json();let s=await n.pushManager.getSubscription();const i=!!(s?.expirationTime&&s.expirationTime-Date.now()<K2);if(!s)try{s=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:J2(o.publicKey)})}catch(d){return console.warn(`[PWA notifications] Push subscription missing; re-subscribe failed${e?" (user gesture)":""}:`,d),!1}const a=Number(window.localStorage.getItem(Hc)??"0"),c=!o.subscription||o.subscription.endpoint!==s.endpoint||Date.now()-(o.subscription.updatedAt??0)>=Bf;if(t||c||Date.now()-a>=Bf||i){if(!(await Vl("subscribe",{subscription:s.toJSON(),aiEnabled:Zs(),exitEnabled:Uc(),alertStyle:So(),locale:navigator.language})).ok)return!1;window.localStorage.setItem(Hc,String(Date.now()))}const l=se();return l&&await H2({targetPeerId:l.targetPeerId,addresses:Sr(l),routes:en(l),publicKey:o.publicKey,preferences:{aiEnabled:Zs(),exitEnabled:Uc(),alertStyle:So(),locale:navigator.language}}),!0}catch(r){return console.warn("[PWA notifications] Push subscription sync failed:",r),!1}}async function dT(){if(rt())return;const e=await(await Si())?.pushManager?.getSubscription();try{await Vl("unsubscribe",{endpoint:e?.endpoint})}finally{const n=se();n&&await U2(n.targetPeerId),await e?.unsubscribe();try{window.localStorage.removeItem(Hc)}catch{}}}async function uT(){if(rt()||!Wl())return;(await Vl("preferences",{aiEnabled:Zs(),exitEnabled:Uc(),alertStyle:So(),locale:navigator.language})).status===404&&await Q2(!0)}async function fT(){if(!rt())try{const t=navigator;typeof t.clearAppBadge=="function"&&await t.clearAppBadge()}catch{}}async function hT(t){if(!rt())try{const e=await Si();if(!e||typeof e.getNotifications!="function")return;const n=`agent:${t}`,r=await e.getNotifications({tag:n});for(const s of r)s.close();const o=navigator;if(typeof o.setAppBadge=="function"){const s=await e.getNotifications();await o.setAppBadge(s.length)}}catch{}}async function ja(t){if(!Wl()||!Gl())return!1;if(t.requireHidden!==!1&&V2())return!0;const e=rt();if(e){const s=t.alertStyle??So(),i=await e.showNotification({title:t.title,body:t.body,tag:t.tag,sessionId:t.data?.sessionId,silent:s==="quiet",persistent:s==="persistent"});return e.notificationDeliveryConfirmation===!0&&i}if(Notification.permission!=="granted")return!1;const n=await Si();if(t.deferToPush&&await n?.pushManager?.getSubscription())return!0;if(t.requireHidden!==!1){if(await n?.pushManager?.getSubscription())return!0}if(!Z2(t))return!0;const r=t.alertStyle??So(),o={body:t.body,tag:t.tag,icon:"/pwa-192x192.png",badge:"/maskable-icon-512x512.png",requireInteraction:r==="persistent",renotify:r==="persistent"?!!t.tag:!1,silent:r==="quiet",vibrate:r==="quiet"?[]:[80,40,80],data:{url:t.data?.url??"/",sessionId:t.data?.sessionId}};try{if(n&&typeof n.showNotification=="function")return await n.showNotification(t.title,o),!0;const s=new Notification(t.title,o);return s.onclick=()=>{window.focus(),t.data?.url&&window.location.href!==t.data.url&&window.location.assign(t.data.url),s.close()},!0}catch(s){if(s instanceof DOMException&&s.name==="NotSupportedError"&&o.renotify)try{const i={...o,renotify:!1};return n&&typeof n.showNotification=="function"?await n.showNotification(t.title,i):new Notification(t.title,i),!0}catch(i){return console.warn("[PWA notifications] Failed to show notification (renotify fallback):",i),!1}return console.warn("[PWA notifications] Failed to show notification:",s),!1}}function eR(){try{return localStorage.getItem("termdock:locale")||"en"}catch{return"en"}}function tR(t,e){return t==="zh"?{waitingTitle:`${e} 需要你的处理`,waitingBody:`${e} 需要你的处理。`,doneTitle:`${e} 已完成`,doneBody:`${e} 已完成,点按查看结果。`,exitedTitle:`${e} 已退出`,exitedBody:`${e} 已退出,点按查看结果。`}:{waitingTitle:`${e} needs your input`,waitingBody:`${e} is waiting for your input.`,doneTitle:`${e} finished`,doneBody:"Tap to see the result.",exitedTitle:`${e} exited`,exitedBody:"Tap to see the result."}}const _f=1e6;function gt(t){return{sessionId:t,directory:"",terminalSessionId:null,mode:"shell",tmuxSessionName:null,activeProgram:null,activeProgramRaw:null,activeProgramSource:null,cwd:null,inCopyMode:!1,isConnecting:!1,agentStatus:null,agentIndicator:null,agentStatusDetail:null,agent:null,agentMessage:null,agentNativeSessionId:null,agentResumeRecovered:!1,agentRich:!1,agentActivity:0,agentCwd:null,agentNeedsReview:!1,shellTitle:null,promptState:null,shellExitCode:null,tuiProgress:null,gitStatus:null,bufferChunks:[],bufferLength:0,lastOutputAt:null,updatedAt:Date.now()}}const xi="termdock-shell-titles-v1";function Ei(){if(typeof window>"u")return{};try{const t=localStorage.getItem(xi);if(!t)return{};const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:{}}catch{return{}}}function nR(t){return Ei()[t]??null}function rR(t,e){if(!(typeof window>"u"))try{const n=Ei();e?n[t]=e:delete n[t],localStorage.setItem(xi,JSON.stringify(n))}catch{}}function oR(t){if(!(typeof window>"u"))try{const e=Ei();delete e[t],localStorage.setItem(xi,JSON.stringify(e))}catch{}}const Ai="termdock-agent-cache-v1";function Xl(){if(typeof window>"u")return{};try{const t=localStorage.getItem(Ai);if(!t)return{};const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:{}}catch{return{}}}function Of(t,e){if(!(typeof window>"u"))try{const n=Xl();e?n[t]=e:delete n[t],localStorage.setItem(Ai,JSON.stringify(n))}catch{}}function sR(t){if(!(typeof window>"u"))try{const e=Xl();delete e[t],localStorage.setItem(Ai,JSON.stringify(e))}catch{}}function iR(){if(!(typeof window>"u"))try{localStorage.removeItem(Ai)}catch{}}function aR(t){return Xl()[t]??null}function cR(){if(!(typeof window>"u"))try{localStorage.removeItem(xi)}catch{}}const Ha=yi((t,e)=>{const n={pendingChunksBySession:new Map,activitySessionIds:new Set,batchFlushRafRef:null},r=(i,a)=>{const c=new Map;return t(l=>{const d=new Map(l.sessions);let u=l.nextChunkId;const f=Date.now();for(const[h,g]of i){const m=d.get(h)??gt(h);let b=m.bufferChunks.length>0?[...m.bufferChunks]:[],w=m.bufferLength;for(const I of g){const y=u++;b.push({id:y,data:I}),c.set(h,y),w+=I.length}for(;w>_f&&b.length>1;){const I=b.shift();if(!I)break;w-=I.data.length}d.set(h,{...m,bufferChunks:b,bufferLength:w,lastOutputAt:a.has(h)?f:m.lastOutputAt,updatedAt:f})}return{sessions:d,nextChunkId:u}}),c},o=()=>{if(n.batchFlushRafRef===null){if(typeof window>"u"){s();return}n.batchFlushRafRef=window.requestAnimationFrame(()=>{n.batchFlushRafRef=null,s()})}},s=()=>{if(n.pendingChunksBySession.size===0)return;const i=j2(n.pendingChunksBySession),a=new Set([...i.keys()].filter(c=>n.activitySessionIds.has(c)));for(const c of i.keys())n.pendingChunksBySession.has(c)||n.activitySessionIds.delete(c);r(i,a),n.pendingChunksBySession.size>0&&o()};return{sessions:new Map,nextChunkId:1,activeSessionId:null,getTerminalSession:i=>e().sessions.get(i),setActiveSessionId:i=>{if(t({activeSessionId:i}),i){const a=e().sessions.get(i);if(a?.agentNeedsReview){const c=new Map(e().sessions);c.set(i,{...a,agentNeedsReview:!1,updatedAt:Date.now()}),t({sessions:c}),a.terminalSessionId&&kc(a.terminalSessionId)}}},setTerminalSession:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i),f=!d||d.terminalSessionId!==a.sessionId?gt(i):d??gt(i),h=a.history??d?.history??[];return l.set(i,{...f,terminalSessionId:a.sessionId,mode:a.mode??f.mode,tmuxSessionName:a.tmuxSessionName??f.tmuxSessionName,activeProgram:a.activeProgram??d?.activeProgram??f.activeProgram,activeProgramRaw:a.activeProgramRaw??d?.activeProgramRaw??f.activeProgramRaw,activeProgramSource:a.activeProgramSource??d?.activeProgramSource??f.activeProgramSource,cwd:a.cwd??d?.cwd??f.cwd,agent:d?.agent??aR(i)??f.agent,agentResumeRecovered:d?.agentResumeRecovered??f.agentResumeRecovered,shellTitle:d?.shellTitle??Ei()[i]??f.shellTitle,sessionId:i,isConnecting:!1,history:h,updatedAt:Date.now()}),{sessions:l}})},setSessionHistory:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??gt(i);return l.set(i,{...d,history:a,updatedAt:Date.now()}),{sessions:l}})},setSessionActiveProgram:(i,a,c=null,l=null)=>{t(d=>{const u=new Map(d.sessions),f=u.get(i)??gt(i);return u.set(i,{...f,activeProgram:a,activeProgramRaw:l,activeProgramSource:c,updatedAt:Date.now()}),{sessions:u}})},setSessionCwd:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??gt(i);return l.set(i,{...d,cwd:a,updatedAt:Date.now()}),{sessions:l}})},setSessionShellTitle:(i,a)=>{t(c=>{const l=c.sessions.get(i)??gt(i);if(l.shellTitle===a)return c;const d=new Map(c.sessions);return d.set(i,{...l,shellTitle:a,updatedAt:Date.now()}),{sessions:d}}),rR(i,a)},setSessionPromptState:(i,a,c)=>{t(l=>{const d=l.sessions.get(i);if(!d||d.promptState===a)return l;const u=new Map(l.sessions);return u.set(i,{...d,promptState:a,shellExitCode:c??d.shellExitCode,updatedAt:Date.now()}),{sessions:u}})},setSessionTuiProgress:(i,a)=>{t(c=>{const l=c.sessions.get(i);if(!l)return c;const d=a?.state==="remove"?null:a;if(l.tuiProgress?.state===d?.state&&l.tuiProgress?.progress===d?.progress)return c;const u=new Map(c.sessions);return u.set(i,{...l,tuiProgress:d,updatedAt:Date.now()}),{sessions:u}})},setSessionGitStatus:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i);return!d||JSON.stringify(d.gitStatus)===JSON.stringify(a)?c:(l.set(i,{...d,gitStatus:a,updatedAt:Date.now()}),{sessions:l})})},setSessionCopyMode:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i);return!d||d.inCopyMode===a?c:(l.set(i,{...d,inCopyMode:a,updatedAt:Date.now()}),{sessions:l})})},setSessionAgentIdentity:(i,a)=>{Of(i,a),t(c=>{const l=c.sessions.get(i)??gt(i);if(JSON.stringify(l.agent)===JSON.stringify(a))return c;const d=new Map(c.sessions);return d.set(i,{...l,agent:a,updatedAt:Date.now()}),{sessions:d}})},setSessionAgentStatus:(i,a)=>{const c=e(),l=c.sessions.get(i);if(!l)return;const d=a.agentStatus??null,u=d&&d!=="idle"?a.agentIndicator??l.agentIndicator??null:null,f=d&&d!=="idle"?a.agentStatusDetail??null:null,h=a.agent!==void 0?a.agent:l.agent,g=a.agentMessage!==void 0?a.agentMessage:d?l.agentMessage:null,m=a.agentNativeSessionId!==void 0?a.agentNativeSessionId:l.agentNativeSessionId,b=a.agentResumeRecovered!==void 0?a.agentResumeRecovered:l.agentResumeRecovered,w=a.agentRich??l.agentRich,I=a.agentActivity??l.agentActivity,y=a.agentCwd!==void 0?a.agentCwd:l.agentCwd,A=c.activeSessionId!==i,N=l.agentStatus==="working"||l.agentStatus==="waiting"||l.agentStatus==="done",k=a.reviewed===!1||a.reviewed===null&&d===null&&N&&A;if(l.agentStatus===d&&l.agentIndicator===u&&l.agentStatusDetail===f&&l.agent===h&&l.agentMessage===g&&l.agentNativeSessionId===m&&l.agentResumeRecovered===b&&l.agentRich===w&&l.agentActivity===I&&l.agentCwd===y&&l.agentNeedsReview===k)return;const T=new Map(c.sessions);if(T.set(i,{...l,agentStatus:d,agentIndicator:u,agentStatusDetail:f,agent:h,agentMessage:g,agentNativeSessionId:m,agentResumeRecovered:b,agentRich:w,agentActivity:I,agentCwd:y,agentNeedsReview:k,updatedAt:Date.now()}),t({sessions:T}),h&&Of(i,h),!Zs())return;const S=h?.displayName??l.agent?.displayName??"Agent",v=eR(),E=tR(v,S);if(d==="waiting"&&l.agentStatus!=="waiting"&&A){ja({title:E.waitingTitle,body:g??E.waitingBody,tag:`agent:${i}`,dedupKey:`agent:${i}:waiting:${I}`,data:{url:"/",sessionId:i},deferToPush:!0});return}if(d==="done"&&l.agentStatus!=="done"&&A){ja({title:E.doneTitle,body:E.doneBody,tag:`agent:${i}`,dedupKey:`agent:${i}:done:${I}`,data:{url:"/",sessionId:i},deferToPush:!0});return}d===null&&(l.agentStatus==="working"||l.agentStatus==="waiting")&&A&&ja({title:E.exitedTitle,body:E.exitedBody,tag:`agent:${i}`,dedupKey:`agent:${i}:exited:${I}`,data:{url:"/",sessionId:i},deferToPush:!0})},setAgentResumeRecovered:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??gt(i);return d.agentResumeRecovered===a?c:(l.set(i,{...d,agentResumeRecovered:a,updatedAt:Date.now()}),{sessions:l})})},clearAgentNeedsReview:i=>{const a=e().sessions.get(i);a?.agentNeedsReview&&(t(c=>{const l=new Map(c.sessions),d=l.get(i);return!d||!d.agentNeedsReview?c:(l.set(i,{...d,agentNeedsReview:!1,updatedAt:Date.now()}),{sessions:l})}),a.terminalSessionId&&kc(a.terminalSessionId))},setConnecting:(i,a)=>{t(c=>{const l=new Map(c.sessions),d=l.get(i)??gt(i);return l.set(i,{...d,isConnecting:a,updatedAt:Date.now()}),{sessions:l}})},appendToBuffer:(i,a,c)=>{if(!a)return;let l=n.pendingChunksBySession.get(i);l||(l=[],n.pendingChunksBySession.set(i,l)),l.push(...Lf(a)),c?.markActivity!==!1&&n.activitySessionIds.add(i),o()},hasPendingBufferWrites:i=>(n.pendingChunksBySession.get(i)?.length??0)>0,flushPendingBufferWrites:i=>{const a=n.pendingChunksBySession.get(i);if(!a?.length)return e().sessions.get(i)?.bufferChunks.at(-1)?.id??null;n.pendingChunksBySession.delete(i);const c=n.activitySessionIds.delete(i);return n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),r(new Map([[i,a]]),c?new Set([i]):new Set).get(i)??null},replaceBuffer:(i,a)=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null);let c=null;return t(l=>{const d=new Map(l.sessions),u=d.get(i);if(!u)return l;if(!a||a.length===0)return d.set(i,{...u,bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:d};let f=l.nextChunkId;const h=[];let g=0;for(const m of a)if(m)for(const b of Lf(m)){const w=f++;h.push({id:w,data:b}),c=w,g+=b.length}for(;g>_f&&h.length>1;){const m=h.shift();if(!m)break;g-=m.data.length}return d.set(i,{...u,bufferChunks:h,bufferLength:g,updatedAt:Date.now()}),{sessions:d,nextChunkId:f}}),c},clearTerminalSession:i=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),t(a=>{const c=new Map(a.sessions),l=c.get(i);return l&&c.set(i,{...l,terminalSessionId:null,isConnecting:!1,agentStatus:null,agentIndicator:null,agentStatusDetail:null,agent:null,agentMessage:null,agentNeedsReview:!1,updatedAt:Date.now()}),{sessions:c}})},clearBuffer:i=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),t(a=>{const c=new Map(a.sessions),l=c.get(i);return l?(c.set(i,{...l,bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:c}):a})},removeTerminalSession:i=>{n.pendingChunksBySession.delete(i),n.activitySessionIds.delete(i),t(a=>{const c=new Map(a.sessions);return c.delete(i),{sessions:c}}),oR(i),sR(i)},clearAllTerminalSessions:()=>{n.pendingChunksBySession.clear(),n.activitySessionIds.clear(),n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),t({sessions:new Map,nextChunkId:1}),cR(),iR()}}}),$c="termdock:session-notice";function lR(){return O.useEffect(()=>{const t=()=>Fa.getState().view(!document.hidden&&as()?Ha.getState().activeSessionId:null);t();const e=Ha.subscribe((n,r)=>{n.activeSessionId!==r.activeSessionId&&t()});return document.addEventListener("visibilitychange",t),window.addEventListener(bo,t),()=>{e(),document.removeEventListener("visibilitychange",t),window.removeEventListener(bo,t),Fa.getState().view(null)}},[]),O.useEffect(()=>ym(t=>{if(t.type!=="session-notice")return;Fa.getState().receive(t.sessionId,t.id);const e=se()?.targetPeerId,n=wt(),r=window.parent,o=O2().sessions.find(u=>u.sessionId===t.sessionId),s=Ha.getState().sessions.get(t.sessionId),i=s?.shellTitle??nR(t.sessionId),a=i===s?.cwd||i===Wn(s?.cwd??null)?null:i,c=T2(o??{name:t.sessionName},s?.activeProgram??null,null,void 0,a,s?.promptState??null),l={...t,sessionName:c,key:`${e??"local"}:${t.id}`,open:()=>e&&n?n.focusSession(e,t.sessionId):(window.dispatchEvent(new CustomEvent("termdock:focus-session",{detail:t.sessionId})),!0)},d=r.document.createEvent("CustomEvent");d.initCustomEvent($c,!1,!1,l),r.dispatchEvent(d)}),[]),null}function dR(){const{locale:t}=vi(),e=t==="zh",[n,r]=O.useState([]);O.useEffect(()=>{const i=a=>{const c=a.detail;r(l=>l.some(d=>d.key===c.key)?l:[...l,c])};return window.addEventListener($c,i),()=>window.removeEventListener($c,i)},[]);const o=O.useCallback(i=>{r(a=>a.filter(c=>c.key!==i))},[]),s=n[0];return s?Gc.createPortal(p.jsx(uR,{notice:s,remaining:n.length-1,chinese:e,onDismiss:o},s.key),document.body):null}function uR({notice:t,remaining:e,chinese:n,onDismiss:r}){const[o,s]=O.useState(!1);return p.jsxs("section",{"aria-label":n?"关键进展提醒":"Progress reminder",className:"fixed left-3 right-3 top-[calc(var(--safe-top-inset,0px)+0.75rem)] z-toast overflow-hidden rounded-xl bg-surface text-foreground shadow-lg ring-1 ring-inset ring-border/15 animate-fade-in md:left-auto md:right-4 md:w-[360px]",children:[p.jsxs("button",{type:"button","aria-label":n?"查看 Session":"Open session",className:"group flex w-full items-start gap-2.5 p-3.5 pr-11 text-left transition-colors hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",onClick:()=>{t.open()?r(t.key):s(!0)},children:[p.jsx(dg,{size:16,className:"mt-0.5 shrink-0 text-primary","aria-hidden":"true"}),p.jsxs("span",{className:"min-w-0 flex-1",role:"status","aria-live":"polite","aria-atomic":"true",children:[p.jsxs("span",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium",title:t.sessionName,children:t.sessionName}),p.jsx(o1,{size:13,className:"shrink-0 text-muted-foreground/60 transition-colors group-hover:text-primary","aria-hidden":"true"})]}),t.title&&p.jsx("span",{className:"mt-1 block truncate text-[11px] text-muted-foreground",children:t.title}),p.jsx("span",{className:"mt-1.5 line-clamp-3 whitespace-pre-wrap break-words text-[13px] leading-relaxed text-foreground/85",title:t.message,children:t.message}),e>0&&p.jsx("span",{className:"mt-2 block text-[10px] text-muted-foreground",children:n?`还有 ${e} 条`:`${e} more`}),o&&p.jsx("span",{role:"alert",className:"mt-2 block text-xs text-warning",children:n?"暂时无法打开该服务,请重试。":"Unable to open the service. Please retry."})]})]}),p.jsx("button",{type:"button","aria-label":n?"关闭提醒":"Dismiss reminder",className:"absolute right-0 top-0 flex h-11 w-11 items-center justify-center rounded-tr-xl text-muted-foreground/60 transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",onClick:()=>r(t.key),children:p.jsx(mg,{size:14})})]})}const Df=5*6e4;let qc,Pm=!1,Nm=!1,Ff=!1;const Kc=new Set;function Mf(){Pm=!0,Kc.forEach(t=>t())}function fR(){return O.useSyncExternalStore(t=>(Kc.add(t),()=>{Kc.delete(t)}),()=>Pm,()=>!1)}function hR(){window.dispatchEvent(new Event("termdock:before-update")),Nm=!0,qc?.waiting?qc.waiting.postMessage({type:"SKIP_WAITING"}):window.location.reload()}function pR(t,e){let n=t;return()=>{if(!n){n=!0;return}e()}}function gR(){if(Ff||typeof window>"u"||!("serviceWorker"in navigator))return;Ff=!0,navigator.serviceWorker.addEventListener("controllerchange",pR(!!navigator.serviceWorker.controller,()=>{Nm?window.location.reload():Mf()}));const t=()=>{navigator.serviceWorker.register("/sw.js",{scope:"/",updateViaCache:"none"}).then(e=>{qc=e;const n=()=>{e.waiting&&Mf()},r=()=>{const i=e.installing;i?.addEventListener("statechange",()=>{i.state==="installed"&&navigator.serviceWorker.controller&&n()})};e.addEventListener("updatefound",r),r(),n();let o=0;const s=()=>{document.visibilityState!=="visible"||Date.now()-o<Df||(o=Date.now(),e.update().then(n).catch(()=>{}))};s(),window.setInterval(s,Df),document.addEventListener("visibilitychange",s)}).catch(()=>{})};document.readyState==="complete"?t():window.addEventListener("load",t,{once:!0})}function mR(){const t=fR(),[e,n]=O.useState(!1),{locale:r}=vi();if(!t||e)return null;const o=r==="zh";return p.jsxs("div",{role:"status",className:"fixed bottom-16 left-1/2 z-toast flex max-w-[calc(100%-2rem)] -translate-x-1/2 items-center gap-3 rounded-lg border border-border bg-background px-4 py-3 text-sm text-foreground shadow-lg",children:[p.jsx("span",{children:o?"新版本已就绪":"An update is ready"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-primary",onClick:hR,children:o?"重新加载":"Reload"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-muted-foreground",onClick:()=>n(!0),children:o?"稍后":"Later"})]})}function Lm(t){const e=document.querySelector('meta[name="theme-color"]');e&&e.setAttribute("content",t==="light"?"#FFFCF0":"#1C1B1A")}const Bm=O.createContext(void 0);function pT({children:t}){const e=O.useContext(Bm),n=e===void 0?typeof document>"u"?null:document.body:e;return n?Gc.createPortal(t,n):null}const wR={activeKey:"root",items:[]},yR=()=>()=>{},bR=()=>wR;function vR({host:t,item:e,visible:n,active:r}){const o=O.useRef(null);return O.useEffect(()=>{o.current?.toggleAttribute("inert",!r)},[r]),O.useLayoutEffect(()=>{const s=o.current;return()=>{try{const i=s?.contentWindow,a=i?.document.createEvent("Event");a&&(a.initEvent("termdock:before-update",!1,!1),i?.dispatchEvent(a))}catch{}t.attach(e.key,null)}},[t,e.key]),p.jsx("iframe",{ref:o,title:e.service?.label||"服务工作区","data-workspace-key":e.key,src:`/workspace.html?${ng}=${encodeURIComponent(e.key)}`,className:"fixed inset-0 w-full border-0 bg-[var(--chrome-bg)]",style:{height:"var(--app-base-vh, 100%)",visibility:n?"visible":"hidden",pointerEvents:r?"auto":"none"},"aria-hidden":!r,tabIndex:r?0:-1,allow:"clipboard-read; clipboard-write; fullscreen"})}function SR({children:t}){const e=window.parent===window?wt():void 0,n=O.useSyncExternalStore(e?.subscribe||yR,e?.snapshot||bR),[r,o]=O.useState(null),[s,i]=O.useState(()=>n.activeKey==="root"?"root":null),[a,c]=O.useState(),[l,d]=O.useState(!1),[u,f]=O.useState(),h=n.items.find(y=>y.key===n.activeKey),g=h?.rendered||a===n.activeKey?n.activeKey:s,m=g!==n.activeKey,b=m&&s===null;O.useLayoutEffect(()=>{if(!m||b){f(void 0);return}const y=()=>{const A=Array.from(document.querySelectorAll("iframe[data-workspace-key]")).find(_=>_.dataset.workspaceKey===s),S=(s==="root"?r:A?.contentDocument)?.querySelector('nav[aria-label="切换服务"]')?.closest("[data-sidebar-gesture-ignore]")?.getBoundingClientRect();if(!S||S.width===0||S.right<=0){f(void 0);return}const v=A?.getBoundingClientRect(),E=S.top+(v?.top??0)>=160;f({left:S.left+(v?.left??0)+12,top:(E?S.top-8:S.bottom+8)+(v?.top??0),width:Math.max(0,S.width-24),transform:E?"translateY(-100%)":"none"})};return y(),window.addEventListener("resize",y),()=>window.removeEventListener("resize",y)},[m,b,s,r]),O.useLayoutEffect(()=>{e?.present(g),m||i(g),r?.toggleAttribute("inert",g!=="root"||m)},[e,r,g,m]),O.useEffect(()=>{if(d(!1),!m)return;const y=setTimeout(()=>d(!0),8e3);return()=>clearTimeout(y)},[n.activeKey,m]),O.useEffect(()=>{c(void 0)},[n.activeKey]);const w=n.items.find(y=>y.key===s),I=h?.phase==="offline"?"网络已断开,等待恢复…":h?.phase==="reconnecting"?"连接暂未恢复,正在重试…":l?"连接时间较长,仍在等待服务…":b?"正在恢复服务…":"正在切换服务…";return O.useEffect(()=>{if(!e)return;const y=()=>{try{const A=JSON.parse(localStorage.getItem("termdock-color-theme")||"null");(A==="dark"||A==="light")&&(document.documentElement.dataset.theme=A,Lm(A))}catch{}};return window.addEventListener("storage",y),()=>window.removeEventListener("storage",y)},[e]),O.useEffect(()=>{if(!e||!("serviceWorker"in navigator))return;const y=k=>{if(k.source!==navigator.serviceWorker.controller)return;const T=k.data;T?.type==="termdock:focus-session"&&typeof T.targetPeerId=="string"&&typeof T.sessionId=="string"&&e.focusSession(T.targetPeerId,T.sessionId)&&(k.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),k.stopImmediatePropagation())},A=async()=>{if("caches"in window)try{const k=await caches.open("termdock-notification-target-v1"),T=await k.match("/__termdock-notification-target");if(!T)return;const S=await T.json();typeof S.targetPeerId=="string"&&typeof S.sessionId=="string"&&Date.now()-S.clickedAt<3e4&&e.focusSession(S.targetPeerId,S.sessionId)&&await k.delete("/__termdock-notification-target")}catch{}},N=()=>{document.hidden||A()};return navigator.serviceWorker.addEventListener("message",y),document.addEventListener("visibilitychange",N),A(),()=>{navigator.serviceWorker.removeEventListener("message",y),document.removeEventListener("visibilitychange",N)}},[e]),e?p.jsxs("div",{className:"relative h-full w-full overflow-hidden bg-[var(--chrome-bg)]",children:[p.jsx("div",{ref:o,className:"isolate h-full w-full","aria-hidden":g!=="root"||m,style:{visibility:g==="root"?"visible":"hidden"},children:p.jsx(Bm.Provider,{value:r,children:t})}),n.items.filter(y=>y.key!=="root").map(y=>p.jsx(vR,{host:e,item:y,visible:g===y.key,active:!m&&g===y.key},y.key)),b&&p.jsx(ql,{className:"z-modal-panel",status:I,detail:l||h?.phase==="offline"||h?.phase==="reconnecting"?h?.service?.label:void 0,actionLabel:l||h?.phase==="offline"||h?.phase==="reconnecting"?"查看连接页面":void 0,onAction:()=>c(n.activeKey)}),m&&!b&&p.jsx("div",{className:"fixed inset-0 z-modal-panel flex items-end justify-center px-3 pb-[calc(env(safe-area-inset-bottom)+96px)]",role:"dialog","aria-modal":"true","aria-label":"切换服务",onKeyDown:y=>{if(y.key==="Escape"&&w?.service&&(y.preventDefault(),e.activate(w.service)),y.key==="Tab"){const A=Array.from(y.currentTarget.querySelectorAll("button")),N=A[0],k=A[A.length-1];y.shiftKey&&document.activeElement===N?(y.preventDefault(),k?.focus()):!y.shiftKey&&document.activeElement===k&&(y.preventDefault(),N?.focus())}},children:p.jsxs("div",{style:u?{position:"absolute",...u}:void 0,className:"flex w-full max-w-sm flex-wrap items-center gap-x-2 gap-y-1 rounded-xl border border-border bg-surface-elevated px-3 py-1.5 text-foreground shadow-lg",children:[p.jsxs("div",{role:"status","aria-live":"polite",className:"flex min-w-0 flex-1 items-center gap-2",children:[p.jsx($e,{size:16,className:"shrink-0 animate-spin text-primary motion-reduce:animate-none","aria-hidden":"true"}),p.jsxs("div",{className:"min-w-0",children:[p.jsx("div",{className:"truncate text-sm font-medium",children:h?.service?.label||"服务工作区"}),p.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:I})]})]}),p.jsxs("div",{className:"flex items-center justify-end gap-1",children:[l&&p.jsx("button",{type:"button",className:"min-h-11 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2",onClick:()=>c(n.activeKey),children:"查看连接页面"}),w?.service&&p.jsx("button",{type:"button",autoFocus:!0,"aria-label":"取消切换",className:"min-h-11 shrink-0 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>e.activate(w.service),children:"取消"})]})]})})]}):t}const xR=O.lazy(()=>tn(()=>import("./App-B6IcjDoE.js").then(t=>t.b),__vite__mapDeps([4,2,1,5,6,3,7,8]))),ER=O.lazy(()=>tn(()=>import("./DagPlayground-B0RDj7Hc.js"),__vite__mapDeps([9,10,2,1,11,7,3])).then(t=>({default:t.DagPlayground}))),AR=O.lazy(()=>tn(()=>import("./DiffLab-CPYmWsZm.js"),__vite__mapDeps([12,2,1,13,8,14,3])).then(t=>({default:t.DiffLab}))),kR=O.lazy(()=>tn(()=>import("./DiffReviewLab-COARnMyi.js"),__vite__mapDeps([15,2,1,16,5,6,11,13,8,14,3])).then(t=>({default:t.DiffReviewLab})));v2();DE();qE();window.parent===window&&gR();const eo=se();eo&&tn(()=>import("./App-B6IcjDoE.js").then(t=>t.b),__vite__mapDeps([4,2,1,5,6,3,7,8])).catch(()=>{});!new URLSearchParams(location.search).has("dag-playground")&&!new URLSearchParams(location.search).has("diff-lab")&&!new URLSearchParams(location.search).has("diff-review-lab")&&kE(eo?{...eo,id:eo.targetPeerId,label:eo.serviceName||location.host}:void 0);try{const t=JSON.parse(window.localStorage.getItem("termdock-color-theme")||"null");(t==="dark"||t==="light")&&(document.documentElement.dataset.theme=t,Lm(t))}catch{}GE.createRoot(document.getElementById("root")).render(p.jsxs(Ye.StrictMode,{children:[p.jsx(n2,{}),p.jsxs(hI,{children:[window.parent===window&&p.jsxs(p.Fragment,{children:[p.jsx(mR,{}),p.jsx(dR,{})]}),p.jsx(c2,{children:p.jsx(O.Suspense,{fallback:p.jsx(ql,{}),children:(()=>{const t=new URLSearchParams(window.location.search);return t.get("dag-playground")==="1"?p.jsx(ER,{}):t.get("diff-review-lab")==="1"?p.jsx(kR,{}):t.get("diff-lab")==="1"?p.jsx(AR,{}):p.jsx(SR,{children:p.jsxs(o2,{children:[p.jsx(lR,{}),p.jsx(xR,{})]})})})()})})]})]}));export{Cl as $,_l as A,dg as B,zs as C,bm as D,Pg as E,gl as F,pC as G,pE as H,Uk as I,Hv as J,FA as K,$e as L,vE as M,vk as N,WR as O,kI as P,gn as Q,DC as R,wi as S,S1 as T,OC as U,m2 as V,bo as W,mg as X,fT as Y,yk as Z,tn as _,lg as a,Pk as a$,CA as a0,MA as a1,ak as a2,FR as a3,yi as a4,jk as a5,h2 as a6,Le as a7,ik as a8,Gi as a9,LC as aA,Nk as aB,Wn as aC,aC as aD,IC as aE,HC as aF,mC as aG,MC as aH,TC as aI,AC as aJ,Zk as aK,oT as aL,BC as aM,Xs as aN,HA as aO,R2 as aP,T2 as aQ,tT as aR,Xt as aS,Zs as aT,Uc as aU,So as aV,Wl as aW,rt as aX,DA as aY,ZA as aZ,SA as a_,Kk as aa,xC as ab,eT as ac,hT as ad,UA as ae,Ck as af,qk as ag,SC as ah,jA as ai,F1 as aj,Rg as ak,$A as al,xI as am,jR as an,JR as ao,Sk as ap,it as aq,Ok as ar,_k as as,Mk as at,sk as au,_C as av,NC as aw,aR as ax,nR as ay,PC as az,n1 as b,Yk as b$,Ek as b0,Rk as b1,FC as b2,Wg as b3,wt as b4,Da as b5,ap as b6,Ip as b7,bC as b8,Dk as b9,Wk as bA,iI as bB,lk as bC,ut as bD,O2 as bE,yC as bF,gC as bG,wC as bH,vC as bI,YR as bJ,XR as bK,$R as bL,dk as bM,qA as bN,HR as bO,vc as bP,GC as bQ,Vk as bR,XC as bS,nI as bT,QR as bU,Jk as bV,Xk as bW,Tk as bX,$n as bY,lT as bZ,Qk as b_,Hk as ba,Gg as bb,iC as bc,cC as bd,tC as be,sC as bf,rC as bg,W2 as bh,Gl as bi,as as bj,p as bk,DR as bl,Ak as bm,$C as bn,Gk as bo,jl as bp,rI as bq,uC as br,xk as bs,Bk as bt,QC as bu,N2 as bv,kC as bw,Cg as bx,Hg as by,L2 as bz,ug as c,hC as c$,mk as c0,VR as c1,bk as c2,kk as c3,YC as c4,zk as c5,VC as c6,BR as c7,O1 as c8,KC as c9,ja as cA,eI as cB,ym as cC,WC as cD,UR as cE,uk as cF,_R as cG,uT as cH,Q2 as cI,Lm as cJ,LR as cK,Fk as cL,dT as cM,$k as cN,Lk as cO,fs as cP,Ve as cQ,EC as cR,yg as cS,vi as cT,KR as cU,Fa as cV,rT as cW,Ee as cX,Ha as cY,ZR as cZ,ve as c_,jC as ca,qC as cb,JC as cc,se as cd,fC as ce,sI as cf,ig as cg,fo as ch,oI as ci,gk as cj,fk as ck,ck as cl,pk as cm,wk as cn,zC as co,ZC as cp,tI as cq,nT as cr,iT as cs,aT as ct,cT as cu,sT as cv,Mg as cw,ok as cx,Wi as cy,GR as cz,En as d,mi as d0,ze as d1,zR as d2,qR as d3,d1 as e,fg as f,hg as g,c2 as h,MR as i,Tg as j,m1 as k,pg as l,vI as m,gg as n,ql as o,me as p,pT as q,hk as r,pl as s,Ot as t,UC as u,OR as v,pA as w,P2 as x,lC as y,oC as z};