termdock 1.4.210 → 1.4.211

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (308) hide show
  1. package/dist/client/assets/{App-CsLpah-H.js → App-ecJnsxAe.js} +26 -26
  2. package/dist/client/assets/App-ecJnsxAe.js.br +0 -0
  3. package/dist/client/assets/App-ecJnsxAe.js.gz +0 -0
  4. package/dist/client/assets/{ChangeWalkthroughPanel-9pjAhzmc.js → ChangeWalkthroughPanel-cwW3KamQ.js} +1 -1
  5. package/dist/client/assets/ChangeWalkthroughPanel-cwW3KamQ.js.br +0 -0
  6. package/dist/client/assets/ChangeWalkthroughPanel-cwW3KamQ.js.gz +0 -0
  7. package/dist/client/assets/{DagPlayground-DrW4_0hZ.js → DagPlayground-CVDZjmaY.js} +1 -1
  8. package/dist/client/assets/DagPlayground-CVDZjmaY.js.br +0 -0
  9. package/dist/client/assets/DagPlayground-CVDZjmaY.js.gz +0 -0
  10. package/dist/client/assets/{DiffLab-Dj9e4Fc7.js → DiffLab-DhGouK9C.js} +1 -1
  11. package/dist/client/assets/DiffLab-DhGouK9C.js.br +0 -0
  12. package/dist/client/assets/DiffLab-DhGouK9C.js.gz +0 -0
  13. package/dist/client/assets/{DiffReview-B96r7R72.js → DiffReview-BkQ5C7W4.js} +1 -1
  14. package/dist/client/assets/DiffReview-BkQ5C7W4.js.br +0 -0
  15. package/dist/client/assets/DiffReview-BkQ5C7W4.js.gz +0 -0
  16. package/dist/client/assets/{DiffReviewLab-D4w5pPtn.js → DiffReviewLab-DOV2Vv34.js} +1 -1
  17. package/dist/client/assets/DiffReviewLab-DOV2Vv34.js.br +0 -0
  18. package/dist/client/assets/DiffReviewLab-DOV2Vv34.js.gz +0 -0
  19. package/dist/client/assets/{DiffViewer-BnuC5XJ-.js → DiffViewer-8g1tSLXq.js} +1 -1
  20. package/dist/client/assets/DiffViewer-8g1tSLXq.js.br +0 -0
  21. package/dist/client/assets/DiffViewer-8g1tSLXq.js.gz +0 -0
  22. package/dist/client/assets/{ModelPreview-DzF4OoFj.js → ModelPreview-DekXqs8K.js} +1 -1
  23. package/dist/client/assets/ModelPreview-DekXqs8K.js.br +0 -0
  24. package/dist/client/assets/ModelPreview-DekXqs8K.js.gz +0 -0
  25. package/dist/client/assets/{RightSidebar-BA-cc-Qe.js → RightSidebar-B_3lv40T.js} +4 -4
  26. package/dist/client/assets/RightSidebar-B_3lv40T.js.br +0 -0
  27. package/dist/client/assets/RightSidebar-B_3lv40T.js.gz +0 -0
  28. package/dist/client/assets/{abnfDiagram-VCTEODGH-BZLdU_yA.js → abnfDiagram-VCTEODGH-CIp_5R8n.js} +1 -1
  29. package/dist/client/assets/abnfDiagram-VCTEODGH-CIp_5R8n.js.br +0 -0
  30. package/dist/client/assets/abnfDiagram-VCTEODGH-CIp_5R8n.js.gz +0 -0
  31. package/dist/client/assets/{app-C3lkifM6.js → app-BEAAs6m_.js} +3 -3
  32. package/dist/client/assets/app-BEAAs6m_.js.br +0 -0
  33. package/dist/client/assets/app-BEAAs6m_.js.gz +0 -0
  34. package/dist/client/assets/{arc-DDQgfuy6.js → arc-wIOpTWeE.js} +1 -1
  35. package/dist/client/assets/arc-wIOpTWeE.js.br +0 -0
  36. package/dist/client/assets/arc-wIOpTWeE.js.gz +0 -0
  37. package/dist/client/assets/{architectureDiagram-5GKGNRK7-D3JZQS6A.js → architectureDiagram-5GKGNRK7-Cv3dzTcv.js} +1 -1
  38. package/dist/client/assets/architectureDiagram-5GKGNRK7-Cv3dzTcv.js.br +0 -0
  39. package/dist/client/assets/architectureDiagram-5GKGNRK7-Cv3dzTcv.js.gz +0 -0
  40. package/dist/client/assets/{blockDiagram-I7D4REHJ-DHBgrQry.js → blockDiagram-I7D4REHJ-CZJTT8FZ.js} +1 -1
  41. package/dist/client/assets/blockDiagram-I7D4REHJ-CZJTT8FZ.js.br +0 -0
  42. package/dist/client/assets/blockDiagram-I7D4REHJ-CZJTT8FZ.js.gz +0 -0
  43. package/dist/client/assets/{c4Diagram-7LVT6UL2-DwrzYgDu.js → c4Diagram-7LVT6UL2-CdA3FM1q.js} +1 -1
  44. package/dist/client/assets/c4Diagram-7LVT6UL2-CdA3FM1q.js.br +0 -0
  45. package/dist/client/assets/c4Diagram-7LVT6UL2-CdA3FM1q.js.gz +0 -0
  46. package/dist/client/assets/channel-pwMMGiD7.js +1 -0
  47. package/dist/client/assets/{chunk-2Q5K7J3B-C5S4S5e5.js → chunk-2Q5K7J3B-D5lqbcyP.js} +1 -1
  48. package/dist/client/assets/{chunk-5VM5RSS4-DKcwKBrq.js → chunk-5VM5RSS4-BjG7Ys03.js} +1 -1
  49. package/dist/client/assets/{chunk-F27PBJKO-CtWaFdw2.js → chunk-F27PBJKO-S41rEiP9.js} +1 -1
  50. package/dist/client/assets/chunk-F27PBJKO-S41rEiP9.js.br +0 -0
  51. package/dist/client/assets/chunk-F27PBJKO-S41rEiP9.js.gz +0 -0
  52. package/dist/client/assets/{chunk-IMKFNOWR-eWFqTGPw.js → chunk-IMKFNOWR-DSEeshkw.js} +1 -1
  53. package/dist/client/assets/chunk-IMKFNOWR-DSEeshkw.js.br +0 -0
  54. package/dist/client/assets/chunk-IMKFNOWR-DSEeshkw.js.gz +0 -0
  55. package/dist/client/assets/{chunk-JWPE2WC7-B1CYKvn5.js → chunk-JWPE2WC7-CT5afAmF.js} +1 -1
  56. package/dist/client/assets/{chunk-POPQ4Y6H-RzVsVya9.js → chunk-POPQ4Y6H-C-T-em3X.js} +1 -1
  57. package/dist/client/assets/{chunk-SVP7TREG-Bw3h4rUk.js → chunk-SVP7TREG-Dzp-gHQt.js} +1 -1
  58. package/dist/client/assets/chunk-SVP7TREG-Dzp-gHQt.js.br +0 -0
  59. package/dist/client/assets/chunk-SVP7TREG-Dzp-gHQt.js.gz +0 -0
  60. package/dist/client/assets/{chunk-TICWLB2K-C3Z8kS1S.js → chunk-TICWLB2K-DwC01FNO.js} +1 -1
  61. package/dist/client/assets/chunk-TICWLB2K-DwC01FNO.js.br +0 -0
  62. package/dist/client/assets/chunk-TICWLB2K-DwC01FNO.js.gz +0 -0
  63. package/dist/client/assets/{chunk-XXDRQBXY-C6X3ae-5.js → chunk-XXDRQBXY-DEfygzxz.js} +1 -1
  64. package/dist/client/assets/classDiagram-ZZMXUADV-DDh5UaIb.js +1 -0
  65. package/dist/client/assets/classDiagram-v2-VYDZK3BY-DDh5UaIb.js +1 -0
  66. package/dist/client/assets/{cose-bilkent-JH36ORCC-Bj0dE671.js → cose-bilkent-JH36ORCC-DY7dbsjz.js} +1 -1
  67. package/dist/client/assets/cose-bilkent-JH36ORCC-DY7dbsjz.js.br +0 -0
  68. package/dist/client/assets/cose-bilkent-JH36ORCC-DY7dbsjz.js.gz +0 -0
  69. package/dist/client/assets/{cynefin-OW5HDTMX-BZqIm0V4.js → cynefin-OW5HDTMX-Dj1B8ZI6.js} +1 -1
  70. package/dist/client/assets/cynefin-OW5HDTMX-Dj1B8ZI6.js.br +0 -0
  71. package/dist/client/assets/cynefin-OW5HDTMX-Dj1B8ZI6.js.gz +0 -0
  72. package/dist/client/assets/{cynefinDiagram-5FMLGOSQ-BtSDof2E.js → cynefinDiagram-5FMLGOSQ-vk-Vyacp.js} +1 -1
  73. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-vk-Vyacp.js.br +0 -0
  74. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-vk-Vyacp.js.gz +0 -0
  75. package/dist/client/assets/{dagre-GXQ25YYZ-D_fwVisa.js → dagre-GXQ25YYZ-vSKvgUeI.js} +1 -1
  76. package/dist/client/assets/dagre-GXQ25YYZ-vSKvgUeI.js.br +0 -0
  77. package/dist/client/assets/dagre-GXQ25YYZ-vSKvgUeI.js.gz +0 -0
  78. package/dist/client/assets/{diagram-S7CK7UJ4-DruZ3tNp.js → diagram-S7CK7UJ4-0EkSMckg.js} +1 -1
  79. package/dist/client/assets/diagram-S7CK7UJ4-0EkSMckg.js.br +0 -0
  80. package/dist/client/assets/diagram-S7CK7UJ4-0EkSMckg.js.gz +0 -0
  81. package/dist/client/assets/{diagram-UQ7AKVKN-Bv87b5ES.js → diagram-UQ7AKVKN-xNGWO2Ti.js} +1 -1
  82. package/dist/client/assets/diagram-UQ7AKVKN-xNGWO2Ti.js.br +0 -0
  83. package/dist/client/assets/diagram-UQ7AKVKN-xNGWO2Ti.js.gz +0 -0
  84. package/dist/client/assets/{diagram-VSXAHHWV-By4eKfnp.js → diagram-VSXAHHWV-tVMqtVqu.js} +1 -1
  85. package/dist/client/assets/diagram-VSXAHHWV-tVMqtVqu.js.br +0 -0
  86. package/dist/client/assets/diagram-VSXAHHWV-tVMqtVqu.js.gz +0 -0
  87. package/dist/client/assets/{diagram-VX7I27RA-C3sFs7EN.js → diagram-VX7I27RA-CrCMXe5l.js} +1 -1
  88. package/dist/client/assets/diagram-VX7I27RA-CrCMXe5l.js.br +0 -0
  89. package/dist/client/assets/{diagram-VX7I27RA-C3sFs7EN.js.gz → diagram-VX7I27RA-CrCMXe5l.js.gz} +0 -0
  90. package/dist/client/assets/{diagram-Z3DM3KII-BsWhXp08.js → diagram-Z3DM3KII-zXI-djjI.js} +1 -1
  91. package/dist/client/assets/diagram-Z3DM3KII-zXI-djjI.js.br +0 -0
  92. package/dist/client/assets/diagram-Z3DM3KII-zXI-djjI.js.gz +0 -0
  93. package/dist/client/assets/{ebnfDiagram-PWID7BFC-DoQKVXP-.js → ebnfDiagram-PWID7BFC-DTxivi4e.js} +1 -1
  94. package/dist/client/assets/ebnfDiagram-PWID7BFC-DTxivi4e.js.br +0 -0
  95. package/dist/client/assets/ebnfDiagram-PWID7BFC-DTxivi4e.js.gz +0 -0
  96. package/dist/client/assets/{erDiagram-RLTQ6QDP-BFWWJ5Ou.js → erDiagram-RLTQ6QDP-CBmpxQmS.js} +1 -1
  97. package/dist/client/assets/erDiagram-RLTQ6QDP-CBmpxQmS.js.br +0 -0
  98. package/dist/client/assets/erDiagram-RLTQ6QDP-CBmpxQmS.js.gz +0 -0
  99. package/dist/client/assets/{flowDiagram-HODETNUW-DCjkLTmk.js → flowDiagram-HODETNUW-BHAg8JtG.js} +1 -1
  100. package/dist/client/assets/flowDiagram-HODETNUW-BHAg8JtG.js.br +0 -0
  101. package/dist/client/assets/flowDiagram-HODETNUW-BHAg8JtG.js.gz +0 -0
  102. package/dist/client/assets/{ganttDiagram-EL5Y4UJY-Uc4efO5H.js → ganttDiagram-EL5Y4UJY-DOPnjy7J.js} +1 -1
  103. package/dist/client/assets/ganttDiagram-EL5Y4UJY-DOPnjy7J.js.br +0 -0
  104. package/dist/client/assets/ganttDiagram-EL5Y4UJY-DOPnjy7J.js.gz +0 -0
  105. package/dist/client/assets/{gestureArbiter-CvlW1We6.js → gestureArbiter-DWSSfkze.js} +1 -1
  106. package/dist/client/assets/gestureArbiter-DWSSfkze.js.br +0 -0
  107. package/dist/client/assets/gestureArbiter-DWSSfkze.js.gz +0 -0
  108. package/dist/client/assets/{gitGraphDiagram-WWUBYQGX-00YUDgON.js → gitGraphDiagram-WWUBYQGX-BUzhUkX1.js} +1 -1
  109. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-BUzhUkX1.js.br +0 -0
  110. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-BUzhUkX1.js.gz +0 -0
  111. package/dist/client/assets/{infoDiagram-27XIBGKW-DuQms3YY.js → infoDiagram-27XIBGKW-5FjW29QK.js} +1 -1
  112. package/dist/client/assets/{ishikawaDiagram-5VMMS53U-Cf0OgBhG.js → ishikawaDiagram-5VMMS53U-BgP7kErX.js} +1 -1
  113. package/dist/client/assets/ishikawaDiagram-5VMMS53U-BgP7kErX.js.br +0 -0
  114. package/dist/client/assets/ishikawaDiagram-5VMMS53U-BgP7kErX.js.gz +0 -0
  115. package/dist/client/assets/{journeyDiagram-3NMN7TZE-Gp4r3rCF.js → journeyDiagram-3NMN7TZE-DqRWqkIL.js} +1 -1
  116. package/dist/client/assets/journeyDiagram-3NMN7TZE-DqRWqkIL.js.br +0 -0
  117. package/dist/client/assets/journeyDiagram-3NMN7TZE-DqRWqkIL.js.gz +0 -0
  118. package/dist/client/assets/{kanban-definition-UXKFOSKX-C-AKurN1.js → kanban-definition-UXKFOSKX-CKAABxM8.js} +1 -1
  119. package/dist/client/assets/kanban-definition-UXKFOSKX-CKAABxM8.js.br +0 -0
  120. package/dist/client/assets/kanban-definition-UXKFOSKX-CKAABxM8.js.gz +0 -0
  121. package/dist/client/assets/{layout-D-QOmsMi.js → layout-l_MO7E1g.js} +1 -1
  122. package/dist/client/assets/layout-l_MO7E1g.js.br +0 -0
  123. package/dist/client/assets/layout-l_MO7E1g.js.gz +0 -0
  124. package/dist/client/assets/{linear-BeqO_tof.js → linear-CVPWLJmO.js} +1 -1
  125. package/dist/client/assets/linear-CVPWLJmO.js.br +0 -0
  126. package/dist/client/assets/linear-CVPWLJmO.js.gz +0 -0
  127. package/dist/client/assets/{mermaid.core-BLtEkDK8.js → mermaid.core-gkwZYRk7.js} +5 -5
  128. package/dist/client/assets/mermaid.core-gkwZYRk7.js.br +0 -0
  129. package/dist/client/assets/mermaid.core-gkwZYRk7.js.gz +0 -0
  130. package/dist/client/assets/{mindmap-definition-YA3MSWOX-vk40s7Xp.js → mindmap-definition-YA3MSWOX-Bn9KwkQs.js} +1 -1
  131. package/dist/client/assets/mindmap-definition-YA3MSWOX-Bn9KwkQs.js.br +0 -0
  132. package/dist/client/assets/mindmap-definition-YA3MSWOX-Bn9KwkQs.js.gz +0 -0
  133. package/dist/client/assets/{passwordBootstrap-Di4aP0lT.js → passwordBootstrap-ftNAkf2B.js} +1 -1
  134. package/dist/client/assets/passwordBootstrap-ftNAkf2B.js.br +0 -0
  135. package/dist/client/assets/passwordBootstrap-ftNAkf2B.js.gz +0 -0
  136. package/dist/client/assets/{pegDiagram-XKGWAZYB-CkDTWBkF.js → pegDiagram-XKGWAZYB-BNXQSQ36.js} +1 -1
  137. package/dist/client/assets/pegDiagram-XKGWAZYB-BNXQSQ36.js.br +0 -0
  138. package/dist/client/assets/pegDiagram-XKGWAZYB-BNXQSQ36.js.gz +0 -0
  139. package/dist/client/assets/{pieDiagram-E7YTZNPT-QSUx2yJ-.js → pieDiagram-E7YTZNPT-C1eWcUzQ.js} +1 -1
  140. package/dist/client/assets/pieDiagram-E7YTZNPT-C1eWcUzQ.js.br +0 -0
  141. package/dist/client/assets/pieDiagram-E7YTZNPT-C1eWcUzQ.js.gz +0 -0
  142. package/dist/client/assets/{quadrantDiagram-AXDQQJYC-D8wrrCn2.js → quadrantDiagram-AXDQQJYC-BEKOOvf8.js} +1 -1
  143. package/dist/client/assets/quadrantDiagram-AXDQQJYC-BEKOOvf8.js.br +0 -0
  144. package/dist/client/assets/quadrantDiagram-AXDQQJYC-BEKOOvf8.js.gz +0 -0
  145. package/dist/client/assets/{railroadDiagram-O6MQD6OU-COf3jWKM.js → railroadDiagram-O6MQD6OU-DTFfytnV.js} +1 -1
  146. package/dist/client/assets/railroadDiagram-O6MQD6OU-DTFfytnV.js.br +0 -0
  147. package/dist/client/assets/railroadDiagram-O6MQD6OU-DTFfytnV.js.gz +0 -0
  148. package/dist/client/assets/{referenceLongPress-CL-_oV1W.js → referenceLongPress-CFKfzfAt.js} +1 -1
  149. package/dist/client/assets/referenceLongPress-CFKfzfAt.js.br +0 -0
  150. package/dist/client/assets/referenceLongPress-CFKfzfAt.js.gz +0 -0
  151. package/dist/client/assets/{requirementDiagram-BXWQKSXE-BBLWeRi-.js → requirementDiagram-BXWQKSXE-BapDsjqm.js} +1 -1
  152. package/dist/client/assets/requirementDiagram-BXWQKSXE-BapDsjqm.js.br +0 -0
  153. package/dist/client/assets/{requirementDiagram-BXWQKSXE-BBLWeRi-.js.gz → requirementDiagram-BXWQKSXE-BapDsjqm.js.gz} +0 -0
  154. package/dist/client/assets/{sankeyDiagram-P5KCCOFB-DEmGIxkm.js → sankeyDiagram-P5KCCOFB-DJ1XpW2-.js} +1 -1
  155. package/dist/client/assets/sankeyDiagram-P5KCCOFB-DJ1XpW2-.js.br +0 -0
  156. package/dist/client/assets/sankeyDiagram-P5KCCOFB-DJ1XpW2-.js.gz +0 -0
  157. package/dist/client/assets/{sequenceDiagram-WJ2MYXX4-B4SUb8S0.js → sequenceDiagram-WJ2MYXX4-Cs1DRPSi.js} +1 -1
  158. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-Cs1DRPSi.js.br +0 -0
  159. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-Cs1DRPSi.js.gz +0 -0
  160. package/dist/client/assets/{sizeCapture-INFHLROL-2a4ZeWnN.js → sizeCapture-INFHLROL-CzT_i8Ho.js} +1 -1
  161. package/dist/client/assets/sizeCapture-INFHLROL-CzT_i8Ho.js.br +0 -0
  162. package/dist/client/assets/sizeCapture-INFHLROL-CzT_i8Ho.js.gz +0 -0
  163. package/dist/client/assets/{sparkles-DBi87wGw.js → sparkles-iNhURufY.js} +1 -1
  164. package/dist/client/assets/{stateDiagram-D77RDMKH-DVqqTfxD.js → stateDiagram-D77RDMKH-BeG1-0oF.js} +1 -1
  165. package/dist/client/assets/stateDiagram-D77RDMKH-BeG1-0oF.js.br +0 -0
  166. package/dist/client/assets/stateDiagram-D77RDMKH-BeG1-0oF.js.gz +0 -0
  167. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-Cj36KoCn.js +1 -0
  168. package/dist/client/assets/{swimlanes-42K2YHIH-C9GqpQYJ.js → swimlanes-42K2YHIH-C_qsOmvw.js} +1 -1
  169. package/dist/client/assets/swimlanes-42K2YHIH-C_qsOmvw.js.br +0 -0
  170. package/dist/client/assets/{swimlanes-42K2YHIH-C9GqpQYJ.js.gz → swimlanes-42K2YHIH-C_qsOmvw.js.gz} +0 -0
  171. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-BUlADEyz.js +8 -0
  172. package/dist/client/assets/{timeline-definition-24CTP7MA-CXGCbcAJ.js → timeline-definition-24CTP7MA-ByKMwWWK.js} +1 -1
  173. package/dist/client/assets/timeline-definition-24CTP7MA-ByKMwWWK.js.br +0 -0
  174. package/dist/client/assets/timeline-definition-24CTP7MA-ByKMwWWK.js.gz +0 -0
  175. package/dist/client/assets/{triangle-alert-e2w8-tp7.js → triangle-alert-B3n8oGh0.js} +1 -1
  176. package/dist/client/assets/{vennDiagram-4TSXK5OY-Bn8n3YMo.js → vennDiagram-4TSXK5OY-e1UJjIa6.js} +1 -1
  177. package/dist/client/assets/vennDiagram-4TSXK5OY-e1UJjIa6.js.br +0 -0
  178. package/dist/client/assets/vennDiagram-4TSXK5OY-e1UJjIa6.js.gz +0 -0
  179. package/dist/client/assets/{wardleyDiagram-VM6X3IG4-BDBTLgbT.js → wardleyDiagram-VM6X3IG4-B7HQI7JC.js} +1 -1
  180. package/dist/client/assets/wardleyDiagram-VM6X3IG4-B7HQI7JC.js.br +0 -0
  181. package/dist/client/assets/wardleyDiagram-VM6X3IG4-B7HQI7JC.js.gz +0 -0
  182. package/dist/client/assets/{xychartDiagram-S5SC5T6Z-B_h_NFjr.js → xychartDiagram-S5SC5T6Z-Dc_FexEL.js} +1 -1
  183. package/dist/client/assets/xychartDiagram-S5SC5T6Z-Dc_FexEL.js.br +0 -0
  184. package/dist/client/assets/xychartDiagram-S5SC5T6Z-Dc_FexEL.js.gz +0 -0
  185. package/dist/client/index.html +1 -1
  186. package/dist/client/index.html.br +0 -0
  187. package/dist/client/index.html.gz +0 -0
  188. package/dist/client/sw.js +1 -1
  189. package/dist/client/sw.js.br +0 -0
  190. package/dist/client/sw.js.gz +0 -0
  191. package/package.json +1 -1
  192. package/runtime-manifest.json +2 -2
  193. package/dist/client/assets/App-CsLpah-H.js.br +0 -0
  194. package/dist/client/assets/App-CsLpah-H.js.gz +0 -0
  195. package/dist/client/assets/ChangeWalkthroughPanel-9pjAhzmc.js.br +0 -0
  196. package/dist/client/assets/ChangeWalkthroughPanel-9pjAhzmc.js.gz +0 -0
  197. package/dist/client/assets/DagPlayground-DrW4_0hZ.js.br +0 -0
  198. package/dist/client/assets/DagPlayground-DrW4_0hZ.js.gz +0 -0
  199. package/dist/client/assets/DiffLab-Dj9e4Fc7.js.br +0 -0
  200. package/dist/client/assets/DiffLab-Dj9e4Fc7.js.gz +0 -0
  201. package/dist/client/assets/DiffReview-B96r7R72.js.br +0 -0
  202. package/dist/client/assets/DiffReview-B96r7R72.js.gz +0 -0
  203. package/dist/client/assets/DiffReviewLab-D4w5pPtn.js.br +0 -0
  204. package/dist/client/assets/DiffReviewLab-D4w5pPtn.js.gz +0 -0
  205. package/dist/client/assets/DiffViewer-BnuC5XJ-.js.br +0 -0
  206. package/dist/client/assets/DiffViewer-BnuC5XJ-.js.gz +0 -0
  207. package/dist/client/assets/ModelPreview-DzF4OoFj.js.br +0 -0
  208. package/dist/client/assets/ModelPreview-DzF4OoFj.js.gz +0 -0
  209. package/dist/client/assets/RightSidebar-BA-cc-Qe.js.br +0 -0
  210. package/dist/client/assets/RightSidebar-BA-cc-Qe.js.gz +0 -0
  211. package/dist/client/assets/abnfDiagram-VCTEODGH-BZLdU_yA.js.br +0 -0
  212. package/dist/client/assets/abnfDiagram-VCTEODGH-BZLdU_yA.js.gz +0 -0
  213. package/dist/client/assets/app-C3lkifM6.js.br +0 -0
  214. package/dist/client/assets/app-C3lkifM6.js.gz +0 -0
  215. package/dist/client/assets/arc-DDQgfuy6.js.br +0 -0
  216. package/dist/client/assets/arc-DDQgfuy6.js.gz +0 -0
  217. package/dist/client/assets/architectureDiagram-5GKGNRK7-D3JZQS6A.js.br +0 -0
  218. package/dist/client/assets/architectureDiagram-5GKGNRK7-D3JZQS6A.js.gz +0 -0
  219. package/dist/client/assets/blockDiagram-I7D4REHJ-DHBgrQry.js.br +0 -0
  220. package/dist/client/assets/blockDiagram-I7D4REHJ-DHBgrQry.js.gz +0 -0
  221. package/dist/client/assets/c4Diagram-7LVT6UL2-DwrzYgDu.js.br +0 -0
  222. package/dist/client/assets/c4Diagram-7LVT6UL2-DwrzYgDu.js.gz +0 -0
  223. package/dist/client/assets/channel-CLgKEJq0.js +0 -1
  224. package/dist/client/assets/chunk-F27PBJKO-CtWaFdw2.js.br +0 -0
  225. package/dist/client/assets/chunk-F27PBJKO-CtWaFdw2.js.gz +0 -0
  226. package/dist/client/assets/chunk-IMKFNOWR-eWFqTGPw.js.br +0 -0
  227. package/dist/client/assets/chunk-IMKFNOWR-eWFqTGPw.js.gz +0 -0
  228. package/dist/client/assets/chunk-SVP7TREG-Bw3h4rUk.js.br +0 -0
  229. package/dist/client/assets/chunk-SVP7TREG-Bw3h4rUk.js.gz +0 -0
  230. package/dist/client/assets/chunk-TICWLB2K-C3Z8kS1S.js.br +0 -0
  231. package/dist/client/assets/chunk-TICWLB2K-C3Z8kS1S.js.gz +0 -0
  232. package/dist/client/assets/classDiagram-ZZMXUADV-Iy1giMMH.js +0 -1
  233. package/dist/client/assets/classDiagram-v2-VYDZK3BY-Iy1giMMH.js +0 -1
  234. package/dist/client/assets/cose-bilkent-JH36ORCC-Bj0dE671.js.br +0 -0
  235. package/dist/client/assets/cose-bilkent-JH36ORCC-Bj0dE671.js.gz +0 -0
  236. package/dist/client/assets/cynefin-OW5HDTMX-BZqIm0V4.js.br +0 -0
  237. package/dist/client/assets/cynefin-OW5HDTMX-BZqIm0V4.js.gz +0 -0
  238. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-BtSDof2E.js.br +0 -0
  239. package/dist/client/assets/cynefinDiagram-5FMLGOSQ-BtSDof2E.js.gz +0 -0
  240. package/dist/client/assets/dagre-GXQ25YYZ-D_fwVisa.js.br +0 -0
  241. package/dist/client/assets/dagre-GXQ25YYZ-D_fwVisa.js.gz +0 -0
  242. package/dist/client/assets/diagram-S7CK7UJ4-DruZ3tNp.js.br +0 -0
  243. package/dist/client/assets/diagram-S7CK7UJ4-DruZ3tNp.js.gz +0 -0
  244. package/dist/client/assets/diagram-UQ7AKVKN-Bv87b5ES.js.br +0 -0
  245. package/dist/client/assets/diagram-UQ7AKVKN-Bv87b5ES.js.gz +0 -0
  246. package/dist/client/assets/diagram-VSXAHHWV-By4eKfnp.js.br +0 -0
  247. package/dist/client/assets/diagram-VSXAHHWV-By4eKfnp.js.gz +0 -0
  248. package/dist/client/assets/diagram-VX7I27RA-C3sFs7EN.js.br +0 -0
  249. package/dist/client/assets/diagram-Z3DM3KII-BsWhXp08.js.br +0 -0
  250. package/dist/client/assets/diagram-Z3DM3KII-BsWhXp08.js.gz +0 -0
  251. package/dist/client/assets/ebnfDiagram-PWID7BFC-DoQKVXP-.js.br +0 -0
  252. package/dist/client/assets/ebnfDiagram-PWID7BFC-DoQKVXP-.js.gz +0 -0
  253. package/dist/client/assets/erDiagram-RLTQ6QDP-BFWWJ5Ou.js.br +0 -0
  254. package/dist/client/assets/erDiagram-RLTQ6QDP-BFWWJ5Ou.js.gz +0 -0
  255. package/dist/client/assets/flowDiagram-HODETNUW-DCjkLTmk.js.br +0 -0
  256. package/dist/client/assets/flowDiagram-HODETNUW-DCjkLTmk.js.gz +0 -0
  257. package/dist/client/assets/ganttDiagram-EL5Y4UJY-Uc4efO5H.js.br +0 -0
  258. package/dist/client/assets/ganttDiagram-EL5Y4UJY-Uc4efO5H.js.gz +0 -0
  259. package/dist/client/assets/gestureArbiter-CvlW1We6.js.br +0 -0
  260. package/dist/client/assets/gestureArbiter-CvlW1We6.js.gz +0 -0
  261. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-00YUDgON.js.br +0 -0
  262. package/dist/client/assets/gitGraphDiagram-WWUBYQGX-00YUDgON.js.gz +0 -0
  263. package/dist/client/assets/ishikawaDiagram-5VMMS53U-Cf0OgBhG.js.br +0 -0
  264. package/dist/client/assets/ishikawaDiagram-5VMMS53U-Cf0OgBhG.js.gz +0 -0
  265. package/dist/client/assets/journeyDiagram-3NMN7TZE-Gp4r3rCF.js.br +0 -0
  266. package/dist/client/assets/journeyDiagram-3NMN7TZE-Gp4r3rCF.js.gz +0 -0
  267. package/dist/client/assets/kanban-definition-UXKFOSKX-C-AKurN1.js.br +0 -0
  268. package/dist/client/assets/kanban-definition-UXKFOSKX-C-AKurN1.js.gz +0 -0
  269. package/dist/client/assets/layout-D-QOmsMi.js.br +0 -0
  270. package/dist/client/assets/layout-D-QOmsMi.js.gz +0 -0
  271. package/dist/client/assets/linear-BeqO_tof.js.br +0 -0
  272. package/dist/client/assets/linear-BeqO_tof.js.gz +0 -0
  273. package/dist/client/assets/mermaid.core-BLtEkDK8.js.br +0 -0
  274. package/dist/client/assets/mermaid.core-BLtEkDK8.js.gz +0 -0
  275. package/dist/client/assets/mindmap-definition-YA3MSWOX-vk40s7Xp.js.br +0 -0
  276. package/dist/client/assets/mindmap-definition-YA3MSWOX-vk40s7Xp.js.gz +0 -0
  277. package/dist/client/assets/passwordBootstrap-Di4aP0lT.js.br +0 -0
  278. package/dist/client/assets/passwordBootstrap-Di4aP0lT.js.gz +0 -0
  279. package/dist/client/assets/pegDiagram-XKGWAZYB-CkDTWBkF.js.br +0 -0
  280. package/dist/client/assets/pegDiagram-XKGWAZYB-CkDTWBkF.js.gz +0 -0
  281. package/dist/client/assets/pieDiagram-E7YTZNPT-QSUx2yJ-.js.br +0 -0
  282. package/dist/client/assets/pieDiagram-E7YTZNPT-QSUx2yJ-.js.gz +0 -0
  283. package/dist/client/assets/quadrantDiagram-AXDQQJYC-D8wrrCn2.js.br +0 -0
  284. package/dist/client/assets/quadrantDiagram-AXDQQJYC-D8wrrCn2.js.gz +0 -0
  285. package/dist/client/assets/railroadDiagram-O6MQD6OU-COf3jWKM.js.br +0 -0
  286. package/dist/client/assets/railroadDiagram-O6MQD6OU-COf3jWKM.js.gz +0 -0
  287. package/dist/client/assets/referenceLongPress-CL-_oV1W.js.br +0 -0
  288. package/dist/client/assets/referenceLongPress-CL-_oV1W.js.gz +0 -0
  289. package/dist/client/assets/requirementDiagram-BXWQKSXE-BBLWeRi-.js.br +0 -0
  290. package/dist/client/assets/sankeyDiagram-P5KCCOFB-DEmGIxkm.js.br +0 -0
  291. package/dist/client/assets/sankeyDiagram-P5KCCOFB-DEmGIxkm.js.gz +0 -0
  292. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-B4SUb8S0.js.br +0 -0
  293. package/dist/client/assets/sequenceDiagram-WJ2MYXX4-B4SUb8S0.js.gz +0 -0
  294. package/dist/client/assets/sizeCapture-INFHLROL-2a4ZeWnN.js.br +0 -0
  295. package/dist/client/assets/sizeCapture-INFHLROL-2a4ZeWnN.js.gz +0 -0
  296. package/dist/client/assets/stateDiagram-D77RDMKH-DVqqTfxD.js.br +0 -0
  297. package/dist/client/assets/stateDiagram-D77RDMKH-DVqqTfxD.js.gz +0 -0
  298. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-nVIOT-VV.js +0 -1
  299. package/dist/client/assets/swimlanes-42K2YHIH-C9GqpQYJ.js.br +0 -0
  300. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-36hPxjFY.js +0 -8
  301. package/dist/client/assets/timeline-definition-24CTP7MA-CXGCbcAJ.js.br +0 -0
  302. package/dist/client/assets/timeline-definition-24CTP7MA-CXGCbcAJ.js.gz +0 -0
  303. package/dist/client/assets/vennDiagram-4TSXK5OY-Bn8n3YMo.js.br +0 -0
  304. package/dist/client/assets/vennDiagram-4TSXK5OY-Bn8n3YMo.js.gz +0 -0
  305. package/dist/client/assets/wardleyDiagram-VM6X3IG4-BDBTLgbT.js.br +0 -0
  306. package/dist/client/assets/wardleyDiagram-VM6X3IG4-BDBTLgbT.js.gz +0 -0
  307. package/dist/client/assets/xychartDiagram-S5SC5T6Z-B_h_NFjr.js.br +0 -0
  308. package/dist/client/assets/xychartDiagram-S5SC5T6Z-B_h_NFjr.js.gz +0 -0
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/passwordBootstrap-Di4aP0lT.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/App-CsLpah-H.js","assets/gestureArbiter-CvlW1We6.js","assets/gestureArbiter-C2J0D0kV.css","assets/referenceLongPress-CL-_oV1W.js","assets/triangle-alert-e2w8-tp7.js","assets/DagPlayground-DrW4_0hZ.js","assets/ChangeWalkthroughPanel-9pjAhzmc.js","assets/sparkles-DBi87wGw.js","assets/DiffLab-Dj9e4Fc7.js","assets/DiffViewer-BnuC5XJ-.js","assets/DiffViewer-T3uj2-aP.css","assets/DiffReviewLab-D4w5pPtn.js","assets/DiffReview-B96r7R72.js"])))=>i.map(i=>d[i]);
2
- import{r as rc,a as lg,g as Du}from"./react-XDCjal2T.js";import{b as F,r as dg,R as $e}from"./dnd-BCFAPC0L.js";import{L as ug,l as fg}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"]'))n(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"&&n(i)}).observe(document,{childList:!0,subtree:!0});function r(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 n(o){if(o.ep)return;o.ep=!0;const s=r(o);fetch(o.href,s)}})();const hg="modulepreload",pg=function(t){return"/"+t},il={},Vt=function(e,r,n){let o=Promise.resolve();if(r&&r.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(r.map(l=>{if(l=pg(l),l in il)return;il[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":hg,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 Qs={exports:{}},fn={};var al;function gg(){if(al)return fn;al=1;var t=rc(),e=Symbol.for("react.element"),r=Symbol.for("react.fragment"),n=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)n.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 fn.Fragment=r,fn.jsx=i,fn.jsxs=i,fn}var cl;function mg(){return cl||(cl=1,Qs.exports=gg()),Qs.exports}var p=mg();const ir="termdock-secure-target-v1",nc="termdock-secure-entry-v1",wg=new Set([ir,nc,"termdock-color-theme","termdock:locale","termdock.federation.connections.v1"]),po=typeof Storage>"u"?void 0:Storage.prototype.getItem,ei=typeof Storage>"u"?void 0:Storage.prototype.setItem,ll="termdock-secure-legacy-owner",Wn=typeof window<"u"&&window.parent!==window&&location.pathname==="/workspace.html";function yg(){if(typeof window>"u")return null;try{if(Wn){const e=new URLSearchParams(location.search).get("termdock-workspace"),r=JSON.parse(localStorage.getItem("termdock.federation.connections.v1")||"[]"),n=Array.isArray(r)?r.find(o=>o?.targetPeerId===e):void 0;return n&&typeof n.url=="string"&&typeof n.targetPeerId=="string"?{...n,serviceName:n.label||n.serviceName}:null}const t=JSON.parse(sessionStorage.getItem(ir)??localStorage.getItem(ir)??"null");return t&&typeof t.url=="string"&&typeof t.targetPeerId=="string"?t:null}catch{return null}}let Rs=yg();const Dr=Rs?.targetPeerId??"unpaired";function Or(){return Rs}function Ou(t){if(Rs=t,Wn)return;const e=JSON.stringify(t);sessionStorage.setItem(ir,e),localStorage.setItem(ir,e)}function bg(){Rs=null,!Wn&&(localStorage.removeItem(ir),sessionStorage.removeItem(ir),localStorage.removeItem(nc))}function Fn(t,e=Dr){return wg.has(t)||t.startsWith("termdock-secure-")?t:`termdock-service:${e}:${t}`}function vg(t){if(!(!po||!ei))try{if(po.call(localStorage,ll))return;ei.call(localStorage,ll,t);for(const r of[localStorage,sessionStorage]){const n=Array.from({length:r.length},(o,s)=>r.key(s)).filter(o=>!!o);for(const o of n){if(o.startsWith("termdock-service:")||Fn(o,t)===o)continue;const s=Fn(o,t),i=po.call(r,o);i!==null&&po.call(r,s)===null&&ei.call(r,s,i)}}}catch{}}let dl=!1;function xg(){if(dl||typeof Storage>"u")return;dl=!0;const t=Storage.prototype.getItem,e=Storage.prototype.setItem,r=Storage.prototype.removeItem;Storage.prototype.getItem=function(n){return t.call(this,Fn(String(n)))},Storage.prototype.setItem=function(n,o){e.call(this,Fn(String(n)),o)},Storage.prototype.removeItem=function(n){r.call(this,Fn(String(n)))}}xg();const ul={pending:0,failed:1,expired:1,delivered:2,read:3},go=32768,Yo="remote:";function Je(t,e){return e.startsWith(Yo)?e:`${Yo}${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function Ke(t){if(!t.startsWith(Yo))return null;const e=t.slice(Yo.length).split(":");if(e.length!==2)return null;try{return{origin:decodeURIComponent(e[0]),id:decodeURIComponent(e[1])}}catch{return null}}function ti(t,e){const r=Ke(e);return r?.origin===t?r.id:e}function mo(t,e){return{...t,fromSessionId:t.fromSessionId?e(t.fromSessionId):null,toSessionId:e(t.toSessionId)}}function ri(t,e){if(!t)return;const r=Object.fromEntries(Object.entries(t).map(([n,o])=>[e(n),o]));return Object.keys(r).length?r:void 0}class Sg{constructor(e){this.services=e}services;snapshots=new Map;reachable=new Set;groups=new Map;messages=new Map;sessions=new Map;diagnostics=new Map;serviceErrors=new Map;inFlight=null;catalogInFlight=null;async refresh(){return this.inFlight?this.inFlight:(this.inFlight=this.synchronize().finally(()=>{this.inFlight=null}),this.inFlight)}async refreshCatalog(){return this.catalogInFlight?this.catalogInFlight:(this.catalogInFlight=this.discover().finally(()=>{this.catalogInFlight=null}),this.catalogInFlight)}async discover(){const e=this.services();this.serviceErrors.clear();const r=await Promise.all(e.map(async n=>{try{const o=await n.request("/collaboration-federation");if(!Array.isArray(o.groups)||!Array.isArray(o.sessions)||!Array.isArray(o.messages))throw new Error("协作目录响应无效,请更新服务");return{service:n,data:o}}catch(o){return this.serviceErrors.set(n.origin,o instanceof Error?o.message.slice(0,300):"协作目录请求失败"),null}}));this.reachable.clear();for(const n of r){if(!n)continue;const{service:o,data:s}=n;for(const[i,a]of Object.entries(s.transportDiagnostics??{}))(!this.diagnostics.has(i)||a.checked_at>this.diagnostics.get(i).checked_at)&&this.diagnostics.set(i,a);this.reachable.add(o.origin),this.snapshots.set(o.origin,s);for(const i of s.groups){const a={...i,sessionIds:i.sessionIds.map(l=>Je(o.origin,l)),roles:ri(i.roles,l=>Je(o.origin,l))},c=this.groups.get(i.id);(!c||a.updatedAt>c.updatedAt)&&this.groups.set(i.id,a)}for(const i of s.messages)this.mergeMessage(mo(i,a=>Je(o.origin,a)))}this.sessions.clear();for(const n of this.groups.values())for(const o of n.remoteSessions??[])this.sessions.set(o.sessionId,{...o,serviceConnected:!1,status:"offline",serviceCheckedAt:Date.now()});for(const[n,o]of this.snapshots){const s=this.reachable.has(n);for(const i of o.sessions){const a=Je(n,i.sessionId);this.sessions.set(a,{...i,sessionId:a,serviceOrigin:n,serviceLabel:e.find(c=>c.origin===n)?.label??n,serviceConnected:s,serviceCheckedAt:Date.now(),status:s?i.status:"offline"})}}}async synchronize(){await this.refreshCatalog();const e=this.services();for(const r of this.messages.values()){const n=Ke(r.toSessionId)?.origin;if(r.status==="pending"&&n&&!this.reachable.has(n)){const o=this.diagnostics.get(r.id);this.diagnostics.set(r.id,{...o,relay_online:!0,peer_reachable:!1,attempt_count:o?.attempt_count??0,next_retry_at:Date.now()+2e3,last_error:"PEER_UNREACHABLE",checked_at:Date.now()})}}await Promise.all(e.filter(r=>this.reachable.has(r.origin)).map(async r=>{for(const n of this.groups.values())if(!(!this.snapshots.get(r.origin)?.groups.some(s=>s.id===n.id)&&!n.sessionIds.some(s=>Ke(s)?.origin===r.origin)))try{await this.push(r,n)}catch{this.reachable.delete(r.origin)}})),await Promise.all(e.filter(r=>this.reachable.has(r.origin)).map(async r=>{if(!((this.snapshots.get(r.origin)?.protocolVersion??1)<2))for(const n of this.groups.values()){if(n.deleted||!n.sessionIds.some(s=>Ke(s)?.origin===r.origin))continue;const o=[...this.diagnostics].filter(([s])=>this.messages.get(s)?.groupId===n.id).map(([s,i])=>({message_id:s,diagnostic:i,...this.messages.get(s)?.status==="failed"?{failure_reason:this.messages.get(s)?.failureReason}:{}}));if(o.length)try{await r.request("/collaboration-federation","POST",{group:this.groupForService(n,r.origin),messages:[],transport:o})}catch{}}}))}mergeMessage(e){const r=this.messages.get(e.id),n=ul;(!r||n[e.status]>n[r.status])&&this.messages.set(e.id,e);const o=this.messages.get(e.id);if(o&&(r?.shellConfirmed===!0||e.shellConfirmed===!0)&&(o.shellConfirmed=!0),this.messages.size>2e3){const s=[...this.messages.values()].find(i=>i.status!=="pending"&&i.status!=="failed");s&&this.messages.delete(s.id)}}groupForService(e,r){const n=e.sessionIds.filter(o=>Ke(o)?.origin!==r).map(o=>{const s=Ke(o),i=this.sessions.get(o);return{sessionId:o,name:i?.name??s.id,cwd:i?.cwd??"",status:i?.status??"offline",capability:i?.capability??"",currentTask:i?.currentTask??"",updatedAt:i?.updatedAt??0,agent:i?.agent??null,backendSessionId:null,agentNativeSessionId:null,serviceOrigin:s.origin,serviceLabel:i?.serviceLabel??s.origin,serviceConnected:this.reachable.has(s.origin),serviceCheckedAt:Date.now()}});return{...e,sessionIds:e.sessionIds.map(o=>ti(r,o)),remoteSessions:n,roles:ri(e.roles,o=>ti(r,o))}}async push(e,r){const n=ul,o=new Map((this.snapshots.get(e.origin)?.messages??[]).map(i=>[i.id,i])),s=[...this.messages.values()].filter(i=>i.groupId===r.id&&(!o.has(i.id)||n[i.status]>n[o.get(i.id).status]||i.shellConfirmed===!0&&o.get(i.id)?.shellConfirmed!==!0)).map(i=>mo(i,a=>ti(e.origin,a)));if(!s.length){await e.request("/collaboration-federation","POST",{group:this.groupForService(r,e.origin),messages:[]});return}for(const i of s){const a=this.messages.get(i.id),c=Ke(a.toSessionId)?.origin===e.origin,l=this.diagnostics.get(i.id);if(c&&l?.next_retry_at&&l.next_retry_at>Date.now()&&l.last_error!=="PEER_UNREACHABLE")continue;const d={relay_online:!0,peer_reachable:!0,attempt_count:(l?.attempt_count??0)+(c?1:0),next_retry_at:null,last_error:null,checked_at:Date.now(),fragments_sent:0,fragments_total:0},u=this.snapshots.get(e.origin)?.protocolVersion??1;if(u<2&&(String(i.content??"").length>2e4||i.responseKind||i.task||i.metadata||i.expiresAt||i.status==="failed"||i.status==="expired")){c&&(this.messages.set(i.id,{...a,status:"failed",failureReason:"PEER_UPGRADE_REQUIRED"}),this.diagnostics.set(i.id,{...d,last_error:"PEER_UPGRADE_REQUIRED"}));continue}try{const f=new TextEncoder().encode(JSON.stringify(i));if(u>=2&&f.length>go&&!o.has(i.id)){const h=Math.ceil(f.length/go),g=Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",f)),m=>m.toString(16).padStart(2,"0")).join("");d.fragments_total=h;for(let m=0;m<h;m++){const y=await e.request("/collaboration-federation","POST",{group:this.groupForService(r,e.origin),messages:[],fragments:[{message_id:i.id,group_id:r.id,index:m,total:h,sha256:g,data:btoa(String.fromCharCode(...f.subarray(m*go,(m+1)*go)))}]}),w=y.fragmentReceipts?.find(I=>I.message_id===i.id);if(!w||m===h-1&&!w.complete)throw new Error("FRAGMENT_ACK_MISSING");d.fragments_sent=w.received;for(const I of y.messages??[])this.mergeMessage(mo(I,v=>Je(e.origin,v)));if(c){this.diagnostics.set(i.id,{...d,checked_at:Date.now()});const I=this.services().find(v=>v.origin===Ke(a.fromSessionId??"")?.origin);I&&I.origin!==e.origin&&(this.snapshots.get(I.origin)?.protocolVersion??1)>=2&&await I.request("/collaboration-federation","POST",{group:this.groupForService(r,I.origin),messages:[],transport:[{message_id:i.id,diagnostic:d}]}).catch(()=>{})}}}else{const h=await e.request("/collaboration-federation","POST",{group:this.groupForService(r,e.origin),messages:[i]});if(!(h.messages??[]).some(g=>g.id===i.id))throw new Error("PEER_REJECTED_MESSAGE");for(const g of h.messages??[])this.mergeMessage(mo(g,m=>Je(e.origin,m)))}c&&this.diagnostics.set(i.id,{...d,checked_at:Date.now()})}catch(f){c&&this.diagnostics.set(i.id,{...d,checked_at:Date.now(),peer_reachable:null,last_error:f instanceof Error?f.message.slice(0,300):"RELAY_REQUEST_FAILED",next_retry_at:Date.now()+Math.min(3e4,1e3*2**Math.min(d.attempt_count,5))})}}}async peers(e){if(!this.services().some(r=>r.origin===e))throw new Error("当前服务未连接");return await this.refreshCatalog(),{protocolVersion:2,origin:e,sessions:[...this.sessions.values()].filter(r=>Ke(r.sessionId)?.origin!==e),services:[...this.snapshots.keys(),...this.services().map(r=>r.origin)].filter((r,n,o)=>o.indexOf(r)===n).map(r=>({origin:r,label:this.services().find(n=>n.origin===r)?.label??r,connected:this.reachable.has(r),error:this.serviceErrors.get(r)}))}}async list(e){const r=this.services().find(s=>s.origin===e);if(!r)throw new Error("当前服务未连接");const[n,o]=await Promise.all([this.peers(e),r.request("/collaboration-groups")]);return{groups:o.groups,sessions:[...n.sessions,...o.sessions]}}async save(e,r){await this.refreshCatalog();const n=this.services().find(u=>u.origin===e);if(!n)throw new Error("当前服务未连接");const o=await n.request("/collaboration-groups"),s=r.id?o.groups.find(u=>u.id===r.id):void 0;if(r.id&&!s)throw new Error("协作组已删除,请刷新列表");if(s&&r.expectedUpdatedAt!==void 0&&r.expectedUpdatedAt!==s.updatedAt)throw new Error("协作组已被修改,请重新打开成员管理后再保存");for(const u of this.sessions.keys())Ke(u)?.origin===e&&this.sessions.delete(u);for(const u of o.sessions){const f=Je(e,u.sessionId);this.sessions.set(f,{...u,sessionId:f,serviceOrigin:e,serviceLabel:n.label,serviceConnected:!0})}if(!r.id?.startsWith("cross-")&&!r.sessionIds.some(u=>Ke(u)))return n.request("/collaboration-groups","POST",r);if(!this.reachable.has(e))throw new Error("当前服务需要升级 Termdock 后才能跨服务组队");const i=[...new Set(r.sessionIds.map(u=>Je(e,u)))],a=new Set(s?.sessionIds.map(u=>Je(e,u))??[]);if(!r.name?.trim()||i.length<2||i.some(u=>!a.has(u)&&(!this.sessions.has(u)||!this.reachable.has(Ke(u).origin))))throw new Error("所选成员已变化或服务不可达,请刷新后重新选择;尚未保存任何修改");const c=s?.federated?{...s,sessionIds:s.sessionIds.map(u=>Je(e,u))}:void 0,l=ri(s?.roles,u=>Je(e,u)),d={id:c?.id??`cross-${crypto.randomUUID()}`,name:r.name.trim(),sessionIds:i,...l?{roles:Object.fromEntries(Object.entries(l).filter(([u])=>i.includes(u)))}:{},createdAt:c?.createdAt??Date.now(),updatedAt:Math.max(Date.now(),(c?.updatedAt??0)+1),federated:!0};if(s&&!s.federated){if(o.capabilities?.groupPromotion!==1)throw new Error("当前服务需要升级后才能将已有组转换为跨服务组;原组和记录均未修改");const u=await n.request(`/collaboration-groups/${encodeURIComponent(s.id)}/promote`,"POST",{group:this.groupForService(d,e),expectedUpdatedAt:r.expectedUpdatedAt??s.updatedAt});d.updatedAt=u.group.updatedAt,d.createdAt=u.group.createdAt}else await n.request("/collaboration-federation","POST",{group:this.groupForService(d,e),messages:[],...c?{expectedUpdatedAt:r.expectedUpdatedAt??c.updatedAt}:{}});return this.groups.set(d.id,d),{group:this.groupForService(d,e)}}async remove(e,r){const n=this.services().find(o=>o.origin===e);if(!n)throw new Error("当前服务未连接");await n.request(`/collaboration-groups/${encodeURIComponent(r)}`,"DELETE")}}const Ts="termdock.federation.connections.v1",ia="termdock:services-changed",oc="termdock-secure-removed-services",Zo=t=>[t.id,t.targetPeerId,t.serviceOrigin||t.url].filter(e=>!!e);function sc(){try{const t=JSON.parse(localStorage.getItem(oc)||"[]");return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}catch{return[]}}function _e(t){const e=t.trim();if(!e)throw new Error("请输入服务地址。");const r=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(e)?e:`https://${e}`);r.protocol==="wss:"&&(r.protocol="https:"),r.protocol==="ws:"&&(r.protocol="http:");const n=["localhost","127.0.0.1","[::1]"].includes(r.hostname);if(!["https:","http:"].includes(r.protocol)||r.protocol==="http:"&&!n)throw new Error("请使用 HTTPS 服务地址。");if(r.username||r.password||r.search||r.hash||!["/","/api/federation/secure"].includes(r.pathname))throw new Error("请输入服务首页地址,不要包含账号或额外参数。");return r.origin}function Ps(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.url=="string")try{const r=_e(e.url),n=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(r).host;return{id:typeof e.id=="string"&&e.id?e.id:n||r,url:r,label:o,...n?{targetPeerId:n}:{},...typeof e.serviceOrigin=="string"?{serviceOrigin:_e(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:_e(s.url),targetPeerId:s.targetPeerId}]:[]}catch{return[]}})}:{}}}catch{return}}function yt(t,e){return t.targetPeerId&&e.targetPeerId?t.targetPeerId===e.targetPeerId:(t.serviceOrigin||t.url)===(e.serviceOrigin||e.url)}function Fu(t){const e=[];for(const r of t){const n=e.findIndex(o=>yt(o,r));n<0?e.push(r):e[n]={...e[n],...r,id:e[n].id}}return e}function to(){return typeof window>"u"?void 0:window.termdockDesktop}function Kt(){try{const t=JSON.parse(localStorage.getItem(Ts)||"[]");return Array.isArray(t)?Fu(t.map(Ps).filter(e=>!!e)):[]}catch{return[]}}function Mu(t){localStorage.setItem(Ts,JSON.stringify(t.map(e=>({...e,serviceName:e.label})))),window.dispatchEvent(new Event(ia))}let hn;async function Xe(){const t=to();if(!t?.serviceConnections||!t.saveServiceConnection)return Kt();if(hn)return hn;hn=(async()=>{let e=await t.serviceConnections();const r=Kt();for(const n of r)e.some(o=>yt(o,n))||(e=await(t.importServiceConnection||t.saveServiceConnection)(n));return r.length&&localStorage.removeItem(Ts),e})();try{return await hn}finally{hn=void 0}}async function At(t){const e=Ps(t);if(!e)throw new Error("服务地址无效。");const r=to();if(r?.saveServiceConnection)return r.saveServiceConnection(e);const n=Kt(),o=n.find(a=>a.id===e.id||yt(a,e)),s=new Set([...Zo(e),...o?Zo(o):[]]);localStorage.setItem(oc,JSON.stringify(sc().filter(a=>!s.has(a))));const i=Fu([...n.filter(a=>a!==o),{...o,...e,id:o?.id||e.id}]);return Mu(i),i}async function Eg(t){const e=Ps(t);if(!e)throw new Error("服务地址无效。");const r=to();if(r?.importServiceConnection)return r.importServiceConnection(e);if(r?.serviceConnections){const n=await r.serviceConnections();return n.some(o=>yt(o,e))?At(e):n}return Zo(e).some(n=>sc().includes(n))?Kt():At(e)}async function Ag(t){const e=to();if(e?.removeServiceConnection)return e.removeServiceConnection(t);const r=Kt(),n=r.find(s=>s.id===t);n&&localStorage.setItem(oc,JSON.stringify([...new Set([...sc(),...Zo(n)])].slice(-768)));const o=r.filter(s=>s.id!==t);return Mu(o),o}function ju(t){const e=n=>{(n.key===Ts||n.key===null)&&t()};window.addEventListener(ia,t),window.addEventListener("storage",e);const r=to()?.onServiceConnections?.(t);return()=>{window.removeEventListener(ia,t),window.removeEventListener("storage",e),r?.()}}class kg extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}let Ig=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},rt=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};class Uu extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class $u extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}}class Cg extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class Rg extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class Ns extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}const Hu=Symbol.for("@libp2p/peer-id");function Tg(t){return typeof t?.handleEvent=="function"}function Pg(t){return t===!0||t===!1}function Ng(t){return Pg(t)?t:t?.capture??!1}function aa(t){const e={capture:Ng(t),once:!!t?.once};return t?.passive!=null&&(e.passive=t?.passive),t?.signal!=null&&(e.signal=t?.signal),e}function fl(t,e){return aa(t).capture===aa(e).capture}class Lg extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){const o=aa(n);if(o?.signal?.aborted===!0)return;const s=l=>{o.once&&this.removeEventListener(e,r,o),Tg(r)?r.handleEvent(l):r(l)};let i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(l=>l.callback!==r?!1:fl(l.options,o)))return;super.addEventListener(e,s,o);const c=()=>{this.removeEventListener(e,r,o)};o.signal?.addEventListener("abort",c),i.push({callback:r,wrapper:s,options:o,onAbort:c})}removeEventListener(e,r,n){const o=this.#e.get(e);if(o==null){super.removeEventListener(e,r??null,n);return}this.#e.set(e,o.filter(s=>s.callback===r&&fl(s.options,n)?(super.removeEventListener(e,s.wrapper,n),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}}const Bg=Symbol.for("@libp2p/service-capabilities");function _g(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function Ls(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 Dg(t){return new TextEncoder().encode(t)}function Og(t){return new TextDecoder().decode(t)}function Fg(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[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,y=0,w=0,I=g.length;w!==I&&g[w]===0;)w++,m++;for(var v=(I-w)*d+1>>>0,k=new Uint8Array(v);w!==I;){for(var B=g[w],R=0,N=v-1;(B!==0||R<y)&&N!==-1;N--,R++)B+=256*k[N]>>>0,k[N]=B%a>>>0,B=B/a>>>0;if(B!==0)throw new Error("Non-zero carry");y=R,w++}for(var A=v-y;A!==v&&k[A]===0;)A++;for(var x=c.repeat(m);A<v;++A)x+=t.charAt(k[A]);return x}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 y=0,w=0;g[m]===c;)y++,m++;for(var I=(g.length-m)*l+1>>>0,v=new Uint8Array(I);g[m];){var k=r[g.charCodeAt(m)];if(k===255)return;for(var B=0,R=I-1;(k!==0||B<w)&&R!==-1;R--,B++)k+=a*v[R]>>>0,v[R]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");w=B,m++}if(g[m]!==" "){for(var N=I-w;N!==I&&v[N]===0;)N++;for(var A=new Uint8Array(y+(I-N)),x=y;N!==I;)A[x++]=v[N++];return A}}}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 Mg=Fg,jg=Mg;class Ug{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class $g{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;const o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}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 qu(this,e)}}class Hg{decoders;constructor(e){this.decoders=e}or(e){return qu(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function qu(t,e){return new Hg({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class qg{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Ug(e,r,n),this.decoder=new $g(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function Bs({name:t,prefix:e,encode:r,decode:n}){return new qg(t,e,r,n)}function ro({name:t,prefix:e,alphabet:r}){const{encode:n,decode:o}=jg(r,t);return Bs({prefix:e,name:t,encode:n,decode:s=>Ls(o(s))})}function Kg(t,e,r,n){let o=t.length;for(;t[o-1]==="=";)--o;const s=new Uint8Array(o*r/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-${n} character`);a=a<<r|d,i+=r,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function zg(t,e,r){const n=e[e.length-1]==="=",o=(1<<r)-1;let s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function Wg(t){const e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function Ae({name:t,prefix:e,bitsPerChar:r,alphabet:n}){const o=Wg(n);return Bs({prefix:e,name:t,encode(s){return zg(s,n,r)},decode(s){return Kg(s,o,r,t)}})}const Le=ro({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Vg=ro({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Gg=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Le,base58flickr:Vg},Symbol.toStringTag,{value:"Module"})),Mn=Ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Xg=Ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Yg=Ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Zg=Ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Jg=Ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Qg=Ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),em=Ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),tm=Ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),rm=Ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),nm=Object.freeze(Object.defineProperty({__proto__:null,base32:Mn,base32hex:Jg,base32hexpad:em,base32hexpadupper:tm,base32hexupper:Qg,base32pad:Yg,base32padupper:Zg,base32upper:Xg,base32z:rm},Symbol.toStringTag,{value:"Module"})),jo=ro({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),om=ro({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),sm=Object.freeze(Object.defineProperty({__proto__:null,base36:jo,base36upper:om},Symbol.toStringTag,{value:"Module"}));var im=Ku,hl=128,am=-128,cm=Math.pow(2,31);function Ku(t,e,r){e=e||[],r=r||0;for(var n=r;t>=cm;)e[r++]=t&255|hl,t/=128;for(;t&am;)e[r++]=t&255|hl,t>>>=7;return e[r]=t|0,Ku.bytes=r-n+1,e}var lm=ca,dm=128,pl=127;function ca(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw ca.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&pl)<<o:(i&pl)*Math.pow(2,o),o+=7}while(i>=dm);return ca.bytes=s-n,r}var um=Math.pow(2,7),fm=Math.pow(2,14),hm=Math.pow(2,21),pm=Math.pow(2,28),gm=Math.pow(2,35),mm=Math.pow(2,42),wm=Math.pow(2,49),ym=Math.pow(2,56),bm=Math.pow(2,63),vm=function(t){return t<um?1:t<fm?2:t<hm?3:t<pm?4:t<gm?5:t<mm?6:t<wm?7:t<ym?8:t<bm?9:10},xm={encode:im,decode:lm,encodingLength:vm},Jo=xm;function la(t,e=0){return[Jo.decode(t,e),Jo.decode.bytes]}function Qo(t,e,r=0){return Jo.encode(t,e,r),e}function es(t){return Jo.encodingLength(t)}function no(t,e){const r=e.byteLength,n=es(t),o=n+es(r),s=new Uint8Array(o+r);return Qo(t,s,0),Qo(r,s,n),s.set(e,o),new ic(t,r,e,s)}function zu(t){const e=Ls(t),[r,n]=la(e),[o,s]=la(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new ic(r,o,i,e)}function Sm(t,e){if(t===e)return!0;{const r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&_g(t.bytes,r.bytes)}}class ic{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}}function gl(t,e){const{bytes:r,version:n}=t;return n===0?Am(r,da(t),e??Le.encoder):km(r,da(t),e??Mn.encoder)}const ml=new WeakMap;function da(t){const e=ml.get(t);if(e==null){const r=new Map;return ml.set(t,r),r}return e}class ce{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,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:r}=this;if(e!==pn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Im)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ce.createV0(r)}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:r}=this.multihash,n=no(e,r);return ce.createV1(this.code,n)}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 ce.equals(this,e)}static equals(e,r){const n=r;return n!=null&&e.code===n.code&&e.version===n.version&&Sm(e.multihash,n.multihash)}toString(e){return gl(this,e)}toJSON(){return{"/":gl(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 r=e;if(r instanceof ce)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){const{version:n,code:o,multihash:s,bytes:i}=r;return new ce(n,o,s,i??wl(n,o,s.bytes))}else if(r[Cm]===!0){const{version:n,multihash:o,code:s}=r,i=zu(o);return ce.create(n,s,i)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==pn)throw new Error(`Version 0 CID must use dag-pb (code: ${pn}) block encoding`);return new ce(e,r,n,n.bytes)}case 1:{const o=wl(e,r,n.bytes);return new ce(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return ce.create(0,pn,e)}static createV1(e,r){return ce.create(1,e,r)}static decode(e){const[r,n]=ce.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){const r=ce.inspectBytes(e),n=r.size-r.multihashSize,o=Ls(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");const s=o.subarray(r.multihashSize-r.digestSize),i=new ic(r.multihashCode,r.digestSize,s,o);return[r.version===0?ce.createV0(i):ce.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0;const n=()=>{const[u,f]=la(e.subarray(r));return r+=f,u};let o=n(),s=pn;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);const i=r,a=n(),c=n(),l=r+c,d=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:l}}static parse(e,r){const[n,o]=Em(e,r),s=ce.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return da(s).set(n,e),s}}function Em(t,e){switch(t[0]){case"Q":{const r=e??Le;return[Le.prefix,r.decode(`${Le.prefix}${t}`)]}case Le.prefix:{const r=e??Le;return[Le.prefix,r.decode(t)]}case Mn.prefix:{const r=e??Mn;return[Mn.prefix,r.decode(t)]}case jo.prefix:{const r=e??jo;return[jo.prefix,r.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 Am(t,e,r){const{prefix:n}=r;if(n!==Le.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const o=e.get(n);if(o==null){const s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function km(t,e,r){const{prefix:n}=r,o=e.get(n);if(o==null){const s=r.encode(t);return e.set(n,s),s}else return o}const pn=112,Im=18;function wl(t,e,r){const n=es(t),o=n+es(e),s=new Uint8Array(o+r.byteLength);return Qo(t,s,0),Qo(e,s,n),s.set(r,o),s}const Cm=Symbol.for("@ipld/js-cid/CID"),Wu=0,Rm="identity",Vu=Ls;function Tm(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 no(Wu,Vu(t))}const oo={code:Wu,name:Rm,encode:Vu,digest:Tm};function nt(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function De(t=0){return new Uint8Array(t)}function kt(t=0){return new Uint8Array(t)}function ua(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));const r=kt(e);let n=0;for(const o of t)r.set(o,n),n+=o.length;return r}const Gu=Symbol.for("@achingbrain/uint8arraylist");function yl(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(const n of t){const o=r+n.byteLength;if(e<o)return{buf:n,index:e-r};r=o}throw new RangeError("index is out of bounds")}function wo(t){return!!t?.[Gu]}class ne{bufs;length;[Gu]=!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 r=0;for(const n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(wo(n)){r+=n.byteLength;for(const o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...e){this.prependAll(e)}prependAll(e){let r=0;for(const n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(wo(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(e){const r=yl(this.bufs,e);return r.buf[r.index]}set(e,r){const n=yl(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(wo(e))for(let n=0;n<e.length;n++)this.set(r+n,e.get(n));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,r){const{bufs:n,length:o}=this._subList(e,r);return ua(n,o)}subarray(e,r){const{bufs:n,length:o}=this._subList(e,r);return n.length===1?n[0]:ua(n,o)}sublist(e,r){const{bufs:n,length:o}=this._subList(e,r),s=new ne;return s.length=o,s.bufs=n,s}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};const n=[];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=r>a&&r<=c;if(l&&d){if(e===a&&r===c){n.push(i);break}const u=e-a;n.push(i.subarray(u,u+(r-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(d){if(r===c){n.push(i);break}n.push(i.subarray(0,r-a));break}n.push(i)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!wo(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const n=e instanceof Uint8Array?e:e.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;const o=n.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[n[u]]=u;const a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1;let d;for(let u=r;u<=c;u+=d){d=0;for(let f=l;f>=0;f--){const h=this.get(u+f);if(n[f]!==h){d=Math.max(1,f-a[h]);break}}if(d===0)return u}return-1}getInt8(e){const r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){const n=kt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){const n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){const o=De(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,e)}getInt32(e,r){const n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){const o=De(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,e)}getBigInt64(e,r){const n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){const o=De(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,e)}getUint8(e){const r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){const n=kt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){const n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){const o=De(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,e)}getUint32(e,r){const n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){const o=De(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,e)}getBigUint64(e,r){const n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){const o=De(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,e)}getFloat32(e,r){const n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){const o=De(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,e)}getFloat64(e,r){const n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){const o=De(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof ne)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!nt(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){const n=new ne;return n.bufs=e,r==null&&(r=e.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}}const Pm=ro({prefix:"9",name:"base10",alphabet:"0123456789"}),Nm=Object.freeze(Object.defineProperty({__proto__:null,base10:Pm},Symbol.toStringTag,{value:"Module"})),Lm=Ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Bm=Ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),_m=Object.freeze(Object.defineProperty({__proto__:null,base16:Lm,base16upper:Bm},Symbol.toStringTag,{value:"Module"})),Dm=Ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Om=Object.freeze(Object.defineProperty({__proto__:null,base2:Dm},Symbol.toStringTag,{value:"Module"})),Xu=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Fm=Xu.reduce((t,e,r)=>(t[r]=e,t),[]),Mm=Xu.reduce((t,e,r)=>{const n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function jm(t){return t.reduce((e,r)=>(e+=Fm[r],e),"")}function Um(t){const e=[];for(const r of t){const n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);const o=Mm[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}const $m=Bs({prefix:"🚀",name:"base256emoji",encode:jm,decode:Um}),Hm=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:$m},Symbol.toStringTag,{value:"Module"})),qm=Ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Km=Ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),zm=Ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Wm=Ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Vm=Object.freeze(Object.defineProperty({__proto__:null,base64:qm,base64pad:Km,base64url:zm,base64urlpad:Wm},Symbol.toStringTag,{value:"Module"})),Gm=Ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Xm=Object.freeze(Object.defineProperty({__proto__:null,base8:Gm},Symbol.toStringTag,{value:"Module"})),Ym=Bs({prefix:"\0",name:"identity",encode:t=>Og(t),decode:t=>Dg(t)}),Zm=Object.freeze(Object.defineProperty({__proto__:null,identity:Ym},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const Jm=20;function Qm({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new ew(t,e,r,n,o)}class ew{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??Jm,this.maxDigestLength=s}digest(e,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?bl(n,this.code,r?.truncate):n.then(o=>bl(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}}function bl(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return no(e,t)}function tw(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}const ac=Qm({name:"sha2-256",code:18,encode:tw("SHA-256")}),vl={...Zm,...Om,...Xm,...Nm,..._m,...nm,...sm,...Gg,...Vm,...Hm};function Yu(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const xl=Yu("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ni=Yu("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=kt(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Zu={utf8:xl,"utf-8":xl,hex:vl.base16,latin1:ni,ascii:ni,binary:ni,...vl};function we(t,e="utf8"){const r=Zu[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function Q(t,e="utf8"){const r=Zu[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}const rw=parseInt("11111",2),fa=parseInt("10000000",2),nw=parseInt("01111111",2),Sl={0:gn,1:gn,2:ow,3:aw,4:cw,5:iw,6:sw,16:gn,22:gn,48:gn};function sn(t,e={offset:0}){const r=t[e.offset]&rw;if(e.offset++,Sl[r]!=null)return Sl[r](t,e);throw new Error("No decoder for tag "+r)}function so(t,e){let r=0;if((t[e.offset]&fa)===fa){const n=t[e.offset]&nw;let o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=t[e.offset].toString(16).padStart(2,"0");r=parseInt(o,16)}else r=t[e.offset],e.offset++;return r}function gn(t,e){so(t,e);const r=[];for(;!(e.offset>=t.byteLength);){const n=sn(t,e);if(n===null)break;r.push(n)}return r}function ow(t,e){const r=so(t,e),n=e.offset,o=e.offset+r,s=[];for(let i=n;i<o;i++)i===n&&t[i]===0||s.push(t[i]);return e.offset+=r,Uint8Array.from(s)}function sw(t,e){const r=so(t,e),n=e.offset+r,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<n;){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 iw(t,e){return e.offset++,null}function aw(t,e){const r=so(t,e),n=t[e.offset];e.offset++;const o=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function cw(t,e){const r=so(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function lw(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);const r=new ne;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function _s(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);const e=lw(t.byteLength);return new ne(Uint8Array.from([e.byteLength|fa]),e)}function Ue(t){const e=new ne,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new ne(Uint8Array.from([2]),_s(e),e)}function cc(t){const e=Uint8Array.from([0]),r=new ne(e,t);return new ne(Uint8Array.from([3]),_s(r),r)}function dw(t){return new ne(Uint8Array.from([4]),_s(t),t)}function St(t,e=48){const r=new ne;for(const n of t)r.append(n);return new ne(Uint8Array.from([e]),_s(r),r)}async function uw(t,e,r){const n=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["sign"]);r?.signal?.throwIfAborted();const o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function fw(t,e,r,n){const o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();const s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,r.subarray());return n?.signal?.throwIfAborted(),s}const hw=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),pw=Uint8Array.from([6,5,43,129,4,0,34]),gw=Uint8Array.from([6,5,43,129,4,0,35]),Ju={ext:!0,kty:"EC",crv:"P-256"},Qu={ext:!0,kty:"EC",crv:"P-384"},ef={ext:!0,kty:"EC",crv:"P-521"},Fr=32,Mr=48,jr=66;function mw(t){const e=sn(t);return ww(e)}function ww(t){const e=t[1],r=Q(e,"base64url"),n=t[2][1][0],o=1;let s,i;if(e.byteLength===Fr)return s=Q(n.subarray(o,o+Fr),"base64url"),i=Q(n.subarray(o+Fr),"base64url"),new oi({...Ju,key_ops:["sign"],d:r,x:s,y:i});if(e.byteLength===Mr)return s=Q(n.subarray(o,o+Mr),"base64url"),i=Q(n.subarray(o+Mr),"base64url"),new oi({...Qu,key_ops:["sign"],d:r,x:s,y:i});if(e.byteLength===jr)return s=Q(n.subarray(o,o+jr),"base64url"),i=Q(n.subarray(o+jr),"base64url"),new oi({...ef,key_ops:["sign"],d:r,x:s,y:i});throw new rt(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function tf(t){const e=sn(t);return yw(e)}function yw(t){const e=t[1][1][0],r=1;let n,o;if(e.byteLength===Fr*2+1)return n=Q(e.subarray(r,r+Fr),"base64url"),o=Q(e.subarray(r+Fr),"base64url"),new Uo({...Ju,key_ops:["verify"],x:n,y:o});if(e.byteLength===Mr*2+1)return n=Q(e.subarray(r,r+Mr),"base64url"),o=Q(e.subarray(r+Mr),"base64url"),new Uo({...Qu,key_ops:["verify"],x:n,y:o});if(e.byteLength===jr*2+1)return n=Q(e.subarray(r,r+jr),"base64url"),o=Q(e.subarray(r+jr),"base64url"),new Uo({...ef,key_ops:["verify"],x:n,y:o});throw new rt(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function bw(t){return St([Ue(Uint8Array.from([1])),dw(we(t.d??"","base64url")),St([rf(t.crv)],160),St([cc(new ne(Uint8Array.from([4]),we(t.x??"","base64url"),we(t.y??"","base64url")))],161)]).subarray()}function vw(t){return St([Ue(Uint8Array.from([1])),St([rf(t.crv)],160),St([cc(new ne(Uint8Array.from([4]),we(t.x??"","base64url"),we(t.y??"","base64url")))],161)]).subarray()}function rf(t){if(t==="P-256")return hw;if(t==="P-384")return pw;if(t==="P-521")return gw;throw new rt(`Invalid curve ${t}`)}class Uo{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=vw(this.jwk)),this._raw}toMultihash(){return oo.digest(Us(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return Le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:nt(this.raw,e.raw)}async verify(e,r,n){return fw(this.jwk,r,e,n)}}class oi{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Uo({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=bw(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:nt(this.raw,e.raw)}async sign(e,r){return uw(this.jwk,e,r)}}const Ar=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 ha(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function hr(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 nf(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ha(t.outputLen),ha(t.blockLen)}function ts(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 xw(t,e){hr(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Yr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function si(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function st(t,e){return t<<32-e|t>>>e}const of=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Sw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function rr(t){if(hr(t),of)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Sw[t[r]];return e}const ht={_0:48,_9:57,A:65,F:70,a:97,f:102};function El(t){if(t>=ht._0&&t<=ht._9)return t-ht._0;if(t>=ht.A&&t<=ht.F)return t-(ht.A-10);if(t>=ht.a&&t<=ht.f)return t-(ht.a-10)}function rs(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(of)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){const i=El(t.charCodeAt(s)),a=El(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)}n[o]=i*16+a}return n}function Ew(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function lc(t){return typeof t=="string"&&(t=Ew(t)),hr(t),t}function ct(...t){let e=0;for(let n=0;n<t.length;n++){const o=t[n];hr(o),e+=o.length}const r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){const s=t[n];r.set(s,o),o+=s.length}return r}class sf{}function af(t){const e=n=>t().update(lc(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function dc(t=32){if(Ar&&typeof Ar.getRandomValues=="function")return Ar.getRandomValues(new Uint8Array(t));if(Ar&&typeof Ar.randomBytes=="function")return Uint8Array.from(Ar.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function Aw(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,l=n?0:4;t.setUint32(e+c,i,n),t.setUint32(e+l,a,n)}function kw(t,e,r){return t&e^~t&r}function Iw(t,e,r){return t&e^t&r^e&r}let cf=class extends sf{constructor(e,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=si(this.buffer)}update(e){ts(this),e=lc(e),hr(e);const{view:r,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(o-this.pos,s-i);if(a===o){const c=si(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ts(this),xw(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:o,isLE:s}=this;let{pos:i}=this;r[i++]=128,Yr(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let u=i;u<o;u++)r[u]=0;Aw(n,o-8,BigInt(this.length*8),s),this.process(n,0);const a=si(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const Pt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ke=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),yo=BigInt(2**32-1),Al=BigInt(32);function Cw(t,e=!1){return e?{h:Number(t&yo),l:Number(t>>Al&yo)}:{h:Number(t>>Al&yo)|0,l:Number(t&yo)|0}}function Rw(t,e=!1){const r=t.length;let n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){const{h:i,l:a}=Cw(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}const kl=(t,e,r)=>t>>>r,Il=(t,e,r)=>t<<32-r|e>>>r,kr=(t,e,r)=>t>>>r|e<<32-r,Ir=(t,e,r)=>t<<32-r|e>>>r,bo=(t,e,r)=>t<<64-r|e>>>r-32,vo=(t,e,r)=>t>>>r-32|e<<64-r;function pt(t,e,r,n){const o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}const Tw=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Pw=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Nw=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Lw=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,Bw=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),_w=(t,e,r,n,o,s)=>e+r+n+o+s+(t/2**32|0)|0,Dw=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]),Nt=new Uint32Array(64);class Ow extends cf{constructor(e=32){super(64,e,8,!1),this.A=Pt[0]|0,this.B=Pt[1]|0,this.C=Pt[2]|0,this.D=Pt[3]|0,this.E=Pt[4]|0,this.F=Pt[5]|0,this.G=Pt[6]|0,this.H=Pt[7]|0}get(){const{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,r){for(let u=0;u<16;u++,r+=4)Nt[u]=e.getUint32(r,!1);for(let u=16;u<64;u++){const f=Nt[u-15],h=Nt[u-2],g=st(f,7)^st(f,18)^f>>>3,m=st(h,17)^st(h,19)^h>>>10;Nt[u]=m+Nt[u-7]+g+Nt[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=st(a,6)^st(a,11)^st(a,25),h=d+f+kw(a,c,l)+Dw[u]+Nt[u]|0,m=(st(n,2)^st(n,13)^st(n,22))+Iw(n,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+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(n,o,s,i,a,c,l,d)}roundClean(){Yr(Nt)}destroy(){this.set(0,0,0,0,0,0,0,0),Yr(this.buffer)}}const lf=Rw(["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))),Fw=lf[0],Mw=lf[1],Lt=new Uint32Array(80),Bt=new Uint32Array(80);class jw extends cf{constructor(e=64){super(128,e,16,!1),this.Ah=ke[0]|0,this.Al=ke[1]|0,this.Bh=ke[2]|0,this.Bl=ke[3]|0,this.Ch=ke[4]|0,this.Cl=ke[5]|0,this.Dh=ke[6]|0,this.Dl=ke[7]|0,this.Eh=ke[8]|0,this.El=ke[9]|0,this.Fh=ke[10]|0,this.Fl=ke[11]|0,this.Gh=ke[12]|0,this.Gl=ke[13]|0,this.Hh=ke[14]|0,this.Hl=ke[15]|0}get(){const{Ah:e,Al:r,Bh:n,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:y}=this;return[e,r,n,o,s,i,a,c,l,d,u,f,h,g,m,y]}set(e,r,n,o,s,i,a,c,l,d,u,f,h,g,m,y){this.Ah=e|0,this.Al=r|0,this.Bh=n|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=y|0}process(e,r){for(let v=0;v<16;v++,r+=4)Lt[v]=e.getUint32(r),Bt[v]=e.getUint32(r+=4);for(let v=16;v<80;v++){const k=Lt[v-15]|0,B=Bt[v-15]|0,R=kr(k,B,1)^kr(k,B,8)^kl(k,B,7),N=Ir(k,B,1)^Ir(k,B,8)^Il(k,B,7),A=Lt[v-2]|0,x=Bt[v-2]|0,S=kr(A,x,19)^bo(A,x,61)^kl(A,x,6),T=Ir(A,x,19)^vo(A,x,61)^Il(A,x,6),P=Nw(N,T,Bt[v-7],Bt[v-16]),b=Lw(P,R,S,Lt[v-7],Lt[v-16]);Lt[v]=b|0,Bt[v]=P|0}let{Ah:n,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:y,Hh:w,Hl:I}=this;for(let v=0;v<80;v++){const k=kr(u,f,14)^kr(u,f,18)^bo(u,f,41),B=Ir(u,f,14)^Ir(u,f,18)^vo(u,f,41),R=u&h^~u&m,N=f&g^~f&y,A=Bw(I,B,N,Mw[v],Bt[v]),x=_w(A,w,k,R,Fw[v],Lt[v]),S=A|0,T=kr(n,o,28)^bo(n,o,34)^bo(n,o,39),P=Ir(n,o,28)^vo(n,o,34)^vo(n,o,39),b=n&s^n&a^s&a,E=o&i^o&c^i&c;w=m|0,I=y|0,m=h|0,y=g|0,h=u|0,g=f|0,{h:u,l:f}=pt(l|0,d|0,x|0,S|0),l=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;const C=Tw(S,P,E);n=Pw(C,x,T,b),o=C|0}({h:n,l:o}=pt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=pt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=pt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=pt(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:f}=pt(this.Eh|0,this.El|0,u|0,f|0),{h,l:g}=pt(this.Fh|0,this.Fl|0,h|0,g|0),{h:m,l:y}=pt(this.Gh|0,this.Gl|0,m|0,y|0),{h:w,l:I}=pt(this.Hh|0,this.Hl|0,w|0,I|0),this.set(n,o,s,i,a,c,l,d,u,f,h,g,m,y,w,I)}roundClean(){Yr(Lt,Bt)}destroy(){Yr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const df=af(()=>new Ow),Uw=af(()=>new jw);const uc=BigInt(0),pa=BigInt(1);function ar(t,e=""){if(typeof t!="boolean"){const r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function tt(t,e,r=""){const n=io(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){const i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function xo(t){const e=t.toString(16);return e.length&1?"0"+e:e}function uf(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?uc:BigInt("0x"+t)}function Ds(t){return uf(rr(t))}function Vn(t){return hr(t),uf(rr(Uint8Array.from(t).reverse()))}function fc(t,e){return rs(t.toString(16).padStart(e*2,"0"))}function ff(t,e){return fc(t,e).reverse()}function fe(t,e,r){let n;if(typeof e=="string")try{n=rs(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(io(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const o=n.length;if(typeof r=="number"&&o!==r)throw new Error(t+" of length "+r+" expected, got "+o);return n}function Cl(t){return Uint8Array.from(t)}const ii=t=>typeof t=="bigint"&&uc<=t;function $w(t,e,r){return ii(t)&&ii(e)&&ii(r)&&e<=t&&t<r}function ga(t,e,r,n){if(!$w(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function hf(t){let e;for(e=0;t>uc;t>>=pa,e+=1);return e}const ao=t=>(pa<<BigInt(t))-pa;function Hw(t,e,r){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 r!="function")throw new Error("hmacFn must be a function");const n=h=>new Uint8Array(h),o=h=>Uint8Array.of(h);let s=n(t),i=n(t),a=0;const c=()=>{s.fill(1),i.fill(0),a=0},l=(...h)=>r(i,s,...h),d=(h=n(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 ct(...g)};return(h,g)=>{c(),d(h);let m;for(;!(m=g(u()));)d();return c(),m}}function co(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(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])=>n(o,s,!1)),Object.entries(r).forEach(([o,s])=>n(o,s,!0))}function ns(t){const e=new WeakMap;return(r,...n)=>{const o=e.get(r);if(o!==void 0)return o;const s=t(r,...n);return e.set(r,s),s}}const Oe=BigInt(0),Ee=BigInt(1),Zt=BigInt(2),pf=BigInt(3),gf=BigInt(4),mf=BigInt(5),qw=BigInt(7),wf=BigInt(8),Kw=BigInt(9),yf=BigInt(16);function ye(t,e){const r=t%e;return r>=Oe?r:e+r}function ue(t,e,r){let n=t;for(;e-- >Oe;)n*=n,n%=r;return n}function Rl(t,e){if(t===Oe)throw new Error("invert: expected non-zero number");if(e<=Oe)throw new Error("invert: expected positive modulus, got "+e);let r=ye(t,e),n=e,o=Oe,s=Ee;for(;r!==Oe;){const a=n/r,c=n%r,l=o-s*a;n=r,r=c,o=s,s=l}if(n!==Ee)throw new Error("invert: does not exist");return ye(o,e)}function hc(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function bf(t,e){const r=(t.ORDER+Ee)/gf,n=t.pow(e,r);return hc(t,n,e),n}function zw(t,e){const r=(t.ORDER-mf)/wf,n=t.mul(e,Zt),o=t.pow(n,r),s=t.mul(e,o),i=t.mul(t.mul(s,Zt),o),a=t.mul(s,t.sub(i,t.ONE));return hc(t,a,e),a}function Ww(t){const e=pr(t),r=vf(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+qw)/yf;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,n);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),y=a.cmov(l,d,m);return hc(a,y,c),y}}function vf(t){if(t<pf)throw new Error("sqrt is not defined for small field");let e=t-Ee,r=0;for(;e%Zt===Oe;)e/=Zt,r++;let n=Zt;const o=pr(t);for(;Tl(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return bf;let s=o.pow(n,e);const i=(e+Ee)/Zt;return function(c,l){if(c.is0(l))return l;if(Tl(c,l)!==1)throw new Error("Cannot find square root");let d=r,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 y=Ee<<BigInt(d-g-1),w=c.pow(u,y);d=g,u=c.sqr(w),f=c.mul(f,u),h=c.mul(h,w)}return h}}function Vw(t){return t%gf===pf?bf:t%wf===mf?zw:t%yf===Kw?Ww(t):vf(t)}const Gw=(t,e)=>(ye(t,e)&Ee)===Ee,Xw=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yw(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=Xw.reduce((n,o)=>(n[o]="function",n),e);return co(t,r),t}function Zw(t,e,r){if(r<Oe)throw new Error("invalid exponent, negatives unsupported");if(r===Oe)return t.ONE;if(r===Ee)return e;let n=t.ONE,o=e;for(;r>Oe;)r&Ee&&(n=t.mul(n,o)),o=t.sqr(o),r>>=Ee;return n}function xf(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),o=e.reduce((i,a,c)=>t.is0(a)?i:(n[c]=i,t.mul(i,a)),t.ONE),s=t.inv(o);return e.reduceRight((i,a,c)=>t.is0(a)?i:(n[c]=t.mul(i,n[c]),t.mul(i,a)),s),n}function Tl(t,e){const r=(t.ORDER-Ee)/Zt,n=t.pow(e,r),o=t.eql(n,t.ONE),s=t.eql(n,t.ZERO),i=t.eql(n,t.neg(t.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function Sf(t,e){e!==void 0&&ha(e);const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function pr(t,e,r=!1,n={}){if(t<=Oe)throw new Error("invalid field: expected ORDER > 0, got "+t);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||r)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"&&(r=f.isLE),typeof f.modFromBytes=="boolean"&&(i=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(o=e),n.sqrt&&(s=n.sqrt);const{nBitLength:c,nByteLength:l}=Sf(t,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:l,MASK:ao(c),ZERO:Oe,ONE:Ee,allowedLengths:a,create:f=>ye(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return Oe<=f&&f<t},is0:f=>f===Oe,isValidNot0:f=>!u.is0(f)&&u.isValid(f),isOdd:f=>(f&Ee)===Ee,neg:f=>ye(-f,t),eql:(f,h)=>f===h,sqr:f=>ye(f*f,t),add:(f,h)=>ye(f+h,t),sub:(f,h)=>ye(f-h,t),mul:(f,h)=>ye(f*h,t),pow:(f,h)=>Zw(u,f,h),div:(f,h)=>ye(f*Rl(h,t),t),sqrN:f=>f*f,addN:(f,h)=>f+h,subN:(f,h)=>f-h,mulN:(f,h)=>f*h,inv:f=>Rl(f,t),sqrt:s||(f=>(d||(d=Vw(t)),d(u,f))),toBytes:f=>r?ff(f,l):fc(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,r?0:m.length-f.length),f=m}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let g=r?Vn(f):Ds(f);if(i&&(g=ye(g,t)),!h&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:f=>xf(u,f),cmov:(f,h,g)=>g?h:f});return Object.freeze(u)}function Ef(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 Af(t){const e=Ef(t);return e+Math.ceil(e/2)}function Jw(t,e,r=!1){const n=t.length,o=Ef(e),s=Af(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const i=r?Vn(t):Ds(t),a=ye(i,e-Ee)+Ee;return r?ff(a,o):fc(a,o)}const Zr=BigInt(0),Jt=BigInt(1);function os(t,e){const r=e.negate();return t?r:e}function Qt(t,e){const r=xf(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function kf(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ai(t,e){kf(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1),o=2**t,s=ao(t),i=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Pl(t,e,r){const{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r;let a=Number(t&o),c=t>>i;a>n&&(a-=s,c+=Jt);const l=e*n,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 Qw(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function ey(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const ci=new WeakMap,If=new WeakMap;function li(t){return If.get(t)||1}function Nl(t){if(t!==Zr)throw new Error("invalid wNAF")}class Cf{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let o=e;for(;r>Zr;)r&Jt&&(n=n.add(o)),o=o.double(),r>>=Jt;return n}precomputeWindow(e,r){const{windows:n,windowSize:o}=ai(r,this.bits),s=[];let i=e,a=i;for(let c=0;c<n;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,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE;const i=ai(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:f,offsetF:h}=Pl(n,a,i);n=c,d?s=s.add(os(f,r[h])):o=o.add(os(u,r[l]))}return Nl(n),{p:o,f:s}}wNAFUnsafe(e,r,n,o=this.ZERO){const s=ai(e,this.bits);for(let i=0;i<s.windows&&n!==Zr;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=Pl(n,i,s);if(n=a,!l){const u=r[c];o=o.add(d?u.negate():u)}}return Nl(n),o}getPrecomputes(e,r,n){let o=ci.get(r);return o||(o=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(o=n(o)),ci.set(r,o))),o}cached(e,r,n){const o=li(e);return this.wNAF(o,this.getPrecomputes(o,e,n),r)}unsafe(e,r,n,o){const s=li(e);return s===1?this._unsafeLadder(e,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),r,o)}createCache(e,r){kf(r,this.bits),If.set(e,r),ci.delete(e)}hasCache(e){return li(e)!==1}}function ty(t,e,r,n){let o=e,s=t.ZERO,i=t.ZERO;for(;r>Zr||n>Zr;)r&Jt&&(s=s.add(o)),n&Jt&&(i=i.add(o)),o=o.double(),r>>=Jt,n>>=Jt;return{p1:s,p2:i}}function Rf(t,e,r,n){Qw(r,t),ey(n,e);const o=r.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,a=hf(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=ao(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 y=n[m],w=Number(y>>BigInt(h)&l);d[w]=d[w].add(r[m])}let g=i;for(let m=d.length-1,y=i;m>0;m--)y=y.add(d[m]),g=g.add(y);if(f=f.add(g),h!==0)for(let m=0;m<c;m++)f=f.double()}return f}function Ll(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Yw(e),e}else return pr(t,{isLE:r})}function Tf(t,e,r={},n){if(n===void 0&&(n=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>Zr))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Ll(e.p,r.Fp,n),s=Ll(e.n,r.Fn,n),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),be=BigInt(1),di=BigInt(2),ry=BigInt(8);function ny(t,e,r,n){const o=t.sqr(r),s=t.sqr(n),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 oy(t,e={}){const r=Tf("edwards",t,e,e.FpFnLE),{Fp:n,Fn:o}=r;let s=r.CURVE;const{h:i}=s;co(e,{},{uvRatio:"function"});const a=di<<BigInt(o.BYTES*8)-be,c=y=>n.create(y),l=e.uvRatio||((y,w)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,w))}}catch{return{isValid:!1,value:_t}}});if(!ny(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(y,w,I=!1){const v=I?be:_t;return ga("coordinate "+y,w,v,a),w}function u(y){if(!(y instanceof g))throw new Error("ExtendedPoint expected")}const f=ns((y,w)=>{const{X:I,Y:v,Z:k}=y,B=y.is0();w==null&&(w=B?ry:n.inv(k));const R=c(I*w),N=c(v*w),A=n.mul(k,w);if(B)return{x:_t,y:be};if(A!==be)throw new Error("invZ was invalid");return{x:R,y:N}}),h=ns(y=>{const{a:w,d:I}=s;if(y.is0())throw new Error("bad point: ZERO");const{X:v,Y:k,Z:B,T:R}=y,N=c(v*v),A=c(k*k),x=c(B*B),S=c(x*x),T=c(N*w),P=c(x*c(T+A)),b=c(S+c(I*c(N*A)));if(P!==b)throw new Error("bad point: equation left != right (1)");const E=c(v*k),C=c(B*R);if(E!==C)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(w,I,v,k){this.X=d("x",w),this.Y=d("y",I),this.Z=d("z",v,!0),this.T=d("t",k),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:v}=w||{};return d("x",I),d("y",v),new g(I,v,be,c(I*v))}static fromBytes(w,I=!1){const v=n.BYTES,{a:k,d:B}=s;w=Cl(tt(w,v,"point")),ar(I,"zip215");const R=Cl(w),N=w[v-1];R[v-1]=N&-129;const A=Vn(R),x=I?a:n.ORDER;ga("point.y",A,_t,x);const S=c(A*A),T=c(S-be),P=c(B*S-k);let{isValid:b,value:E}=l(T,P);if(!b)throw new Error("bad point: invalid y coordinate");const C=(E&be)===be,L=(N&128)!==0;if(!I&&E===_t&&L)throw new Error("bad point: x=0 and x_0=1");return L!==C&&(E=c(-E)),g.fromAffine({x:E,y:A})}static fromHex(w,I=!1){return g.fromBytes(fe("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(di),this}assertValidity(){h(this)}equals(w){u(w);const{X:I,Y:v,Z:k}=this,{X:B,Y:R,Z:N}=w,A=c(I*N),x=c(B*k),S=c(v*N),T=c(R*k);return A===x&&S===T}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:v,Z:k}=this,B=c(I*I),R=c(v*v),N=c(di*c(k*k)),A=c(w*B),x=I+v,S=c(c(x*x)-B-R),T=A+R,P=T-N,b=A-R,E=c(S*P),C=c(T*b),L=c(S*b),M=c(P*T);return new g(E,C,M,L)}add(w){u(w);const{a:I,d:v}=s,{X:k,Y:B,Z:R,T:N}=this,{X:A,Y:x,Z:S,T}=w,P=c(k*A),b=c(B*x),E=c(N*v*T),C=c(R*S),L=c((k+B)*(A+x)-P-b),M=C-E,$=C+E,j=c(b-I*P),D=c(L*M),_=c($*j),O=c(L*j),q=c(M*$);return new g(D,_,q,O)}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:v}=m.cached(this,w,k=>Qt(g,k));return Qt(g,[I,v])[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===be?this:m.unsafe(this,w,v=>Qt(g,v),I)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(w){return f(this,w)}clearCofactor(){return i===be?this:this.multiplyUnsafe(i)}toBytes(){const{x:w,y:I}=this.toAffine(),v=n.toBytes(I);return v[v.length-1]|=w&be?128:0,v}toHex(){return rr(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 Qt(g,w)}static msm(w,I){return Rf(g,o,w,I)}_setWindowSize(w){this.precompute(w)}toRawBytes(){return this.toBytes()}}g.BASE=new g(s.Gx,s.Gy,be,c(s.Gx*s.Gy)),g.ZERO=new g(_t,be,be,_t),g.Fp=n,g.Fn=o;const m=new Cf(g,o.BITS);return g.BASE.precompute(8),g}function sy(t,e,r={}){if(typeof e!="function")throw new Error('"hash" function param is required');co(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:o,Fp:s,Fn:i}=t,a=r.randomBytes||dc,c=r.adjustScalarBytes||(x=>x),l=r.domain||((x,S,T)=>{if(ar(T,"phflag"),S.length||T)throw new Error("Contexts/pre-hash are not supported");return x});function d(x){return i.create(Vn(x))}function u(x){const S=v.secretKey;x=fe("private key",x,S);const T=fe("hashed private key",e(x),2*S),P=c(T.slice(0,S)),b=T.slice(S,2*S),E=d(P);return{head:P,prefix:b,scalar:E}}function f(x){const{head:S,prefix:T,scalar:P}=u(x),b=o.multiply(P),E=b.toBytes();return{head:S,prefix:T,scalar:P,point:b,pointBytes:E}}function h(x){return f(x).pointBytes}function g(x=Uint8Array.of(),...S){const T=ct(...S);return d(e(l(T,fe("context",x),!!n)))}function m(x,S,T={}){x=fe("message",x),n&&(x=n(x));const{prefix:P,scalar:b,pointBytes:E}=f(S),C=g(T.context,P,x),L=o.multiply(C).toBytes(),M=g(T.context,L,E,x),$=i.create(C+M*b);if(!i.isValid($))throw new Error("sign failed: invalid s");const j=ct(L,i.toBytes($));return tt(j,v.signature,"result")}const y={zip215:!0};function w(x,S,T,P=y){const{context:b,zip215:E}=P,C=v.signature;x=fe("signature",x,C),S=fe("message",S),T=fe("publicKey",T,v.publicKey),E!==void 0&&ar(E,"zip215"),n&&(S=n(S));const L=C/2,M=x.subarray(0,L),$=Vn(x.subarray(L,C));let j,D,_;try{j=t.fromBytes(T,E),D=t.fromBytes(M,E),_=o.multiplyUnsafe($)}catch{return!1}if(!E&&j.isSmallOrder())return!1;const O=g(b,D.toBytes(),j.toBytes(),S);return D.add(j.multiplyUnsafe(O)).subtract(_).clearCofactor().is0()}const I=s.BYTES,v={secretKey:I,publicKey:I,signature:2*I,seed:I};function k(x=a(v.seed)){return tt(x,v.seed,"seed")}function B(x){const S=A.randomSecretKey(x);return{secretKey:S,publicKey:h(S)}}function R(x){return io(x)&&x.length===i.BYTES}function N(x,S){try{return!!t.fromBytes(x,S)}catch{return!1}}const A={getExtendedPublicKey:f,randomSecretKey:k,isValidSecretKey:R,isValidPublicKey:N,toMontgomery(x){const{y:S}=t.fromBytes(x),T=v.publicKey,P=T===32;if(!P&&T!==57)throw new Error("only defined for 25519 and 448");const b=P?s.div(be+S,be-S):s.div(S-be,S+be);return s.toBytes(b)},toMontgomerySecret(x){const S=v.secretKey;tt(x,S);const T=e(x.subarray(0,S));return c(T).subarray(0,S)},randomPrivateKey:k,precompute(x=8,S=t.BASE){return S.precompute(x,!1)}};return Object.freeze({keygen:B,getPublicKey:h,sign:m,verify:w,utils:A,Point:t,lengths:v})}function iy(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},r=t.Fp,n=pr(e.n,t.nBitLength,!0),o={Fp:r,Fn:n,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 ay(t,e){const r=e.Point;return Object.assign({},e,{ExtendedPoint:r,CURVE:t,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function cy(t){const{CURVE:e,curveOpts:r,hash:n,eddsaOpts:o}=iy(t),s=oy(e,r),i=sy(s,n,o);return ay(t,i)}const ly=BigInt(1),Bl=BigInt(2);BigInt(3);const dy=BigInt(5),uy=BigInt(8),pc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Pf={p:pc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:uy,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function fy(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=pc,a=t*t%s*t%s,c=ue(a,Bl,s)*a%s,l=ue(c,ly,s)*t%s,d=ue(l,dy,s)*l%s,u=ue(d,e,s)*d%s,f=ue(u,r,s)*u%s,h=ue(f,n,s)*f%s,g=ue(h,o,s)*h%s,m=ue(g,o,s)*h%s,y=ue(m,e,s)*d%s;return{pow_p_5_8:ue(y,Bl,s)*t%s,b2:a}}function hy(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const _l=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function py(t,e){const r=pc,n=ye(e*e*e,r),o=ye(n*n*e,r),s=fy(t*o).pow_p_5_8;let i=ye(t*n*s,r);const a=ye(e*i*i,r),c=i,l=ye(i*_l,r),d=a===t,u=a===ye(-t,r),f=a===ye(-t*_l,r);return d&&(i=c),(u||f)&&(i=l),Gw(i,r)&&(i=ye(-i,r)),{isValid:d||u,value:i}}const gy=pr(Pf.p,{isLE:!0}),my={...Pf,Fp:gy,hash:Uw,adjustScalarBytes:hy,uvRatio:py},ss=cy(my);class Dl extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}}class Ol extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class wy extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}const It={get(t=globalThis){const e=t.crypto;if(e?.subtle==null)throw new wy("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}},is=32,mt=64,ma=32;let Ur;const Nf=(async()=>{try{return await It.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function yy(){const t=ss.utils.randomPrivateKey(),e=ss.getPublicKey(t);return{privateKey:ky(t,e),publicKey:e}}async function by(t,e){let r;t.length===mt?r=t.subarray(0,32):r=t;const n={crv:"Ed25519",kty:"OKP",x:Q(t.subarray(32),"base64url"),d:Q(r,"base64url"),ext:!0,key_ops:["sign"]},o=await It.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await It.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function vy(t,e){const r=t.subarray(0,ma);return ss.sign(e instanceof Uint8Array?e:e.subarray(),r)}async function xy(t,e){return Ur==null&&(Ur=await Nf),Ur?by(t,e):vy(t,e)}async function Sy(t,e,r){if(t.buffer instanceof ArrayBuffer){const n=await It.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await It.get().subtle.verify({name:"Ed25519"},n,e,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Ey(t,e,r){return ss.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function Ay(t,e,r){return Ur==null&&(Ur=await Nf),Ur?Sy(t,e,r):Ey(t,e,r)}function ky(t,e){const r=new Uint8Array(mt);for(let n=0;n<ma;n++)r[n]=t[n],r[ma+n]=e[n];return r}function Os(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}class Lf{type="Ed25519";raw;constructor(e){this.raw=Gn(e,is)}toMultihash(){return oo.digest(Us(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return Le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:nt(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();const o=Ay(this.raw,r,e);return Os(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}}class wa{type="Ed25519";raw;publicKey;constructor(e,r){this.raw=Gn(e,mt),this.publicKey=new Lf(r)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:nt(this.raw,e.raw)}sign(e,r){r?.signal?.throwIfAborted();const n=xy(this.raw,e);return Os(n)?n.then(o=>(r?.signal?.throwIfAborted(),o)):(r?.signal?.throwIfAborted(),n)}}function Iy(t){if(t.length>mt){t=Gn(t,mt+is);const n=t.subarray(0,mt),o=t.subarray(mt,t.length);return new wa(n,o)}t=Gn(t,mt);const e=t.subarray(0,mt),r=t.subarray(is);return new wa(e,r)}function Bf(t){return t=Gn(t,is),new Lf(t)}async function Cy(){const{privateKey:t,publicKey:e}=yy();return new wa(t,e)}function Gn(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new rt(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}const Ry=Math.pow(2,7),Ty=Math.pow(2,14),Py=Math.pow(2,21),gc=Math.pow(2,28),mc=Math.pow(2,35),wc=Math.pow(2,42),yc=Math.pow(2,49),te=128,Ce=127;function gr(t){if(t<Ry)return 1;if(t<Ty)return 2;if(t<Py)return 3;if(t<gc)return 4;if(t<mc)return 5;if(t<wc)return 6;if(t<yc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function _f(t,e,r=0){switch(gr(t)){case 8:e[r++]=t&255|te,t/=128;case 7:e[r++]=t&255|te,t/=128;case 6:e[r++]=t&255|te,t/=128;case 5:e[r++]=t&255|te,t/=128;case 4:e[r++]=t&255|te,t>>>=7;case 3:e[r++]=t&255|te,t>>>=7;case 2:e[r++]=t&255|te,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Ny(t,e,r=0){switch(gr(t)){case 8:e.set(r++,t&255|te),t/=128;case 7:e.set(r++,t&255|te),t/=128;case 6:e.set(r++,t&255|te),t/=128;case 5:e.set(r++,t&255|te),t/=128;case 4:e.set(r++,t&255|te),t>>>=7;case 3:e.set(r++,t&255|te),t>>>=7;case 2:e.set(r++,t&255|te),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function Df(t,e){let r=t[e],n=0;if(n+=r&Ce,r<te||(r=t[e+1],n+=(r&Ce)<<7,r<te)||(r=t[e+2],n+=(r&Ce)<<14,r<te)||(r=t[e+3],n+=(r&Ce)<<21,r<te)||(r=t[e+4],n+=(r&Ce)*gc,r<te)||(r=t[e+5],n+=(r&Ce)*mc,r<te)||(r=t[e+6],n+=(r&Ce)*wc,r<te)||(r=t[e+7],n+=(r&Ce)*yc,r<te))return n;throw new RangeError("Could not decode varint")}function Ly(t,e){let r=t.get(e),n=0;if(n+=r&Ce,r<te||(r=t.get(e+1),n+=(r&Ce)<<7,r<te)||(r=t.get(e+2),n+=(r&Ce)<<14,r<te)||(r=t.get(e+3),n+=(r&Ce)<<21,r<te)||(r=t.get(e+4),n+=(r&Ce)*gc,r<te)||(r=t.get(e+5),n+=(r&Ce)*mc,r<te)||(r=t.get(e+6),n+=(r&Ce)*wc,r<te)||(r=t.get(e+7),n+=(r&Ce)*yc,r<te))return n;throw new RangeError("Could not decode varint")}function By(t,e,r=0){return e==null&&(e=kt(gr(t))),e instanceof Uint8Array?_f(t,e,r):Ny(t,e,r)}function Of(t,e=0){return t instanceof Uint8Array?Df(t,e):Ly(t,e)}const bc=new Float32Array([-0]),Ht=new Uint8Array(bc.buffer);function _y(t,e,r){bc[0]=t,e[r]=Ht[0],e[r+1]=Ht[1],e[r+2]=Ht[2],e[r+3]=Ht[3]}function Dy(t,e){return Ht[0]=t[e],Ht[1]=t[e+1],Ht[2]=t[e+2],Ht[3]=t[e+3],bc[0]}const vc=new Float64Array([-0]),Re=new Uint8Array(vc.buffer);function Oy(t,e,r){vc[0]=t,e[r]=Re[0],e[r+1]=Re[1],e[r+2]=Re[2],e[r+3]=Re[3],e[r+4]=Re[4],e[r+5]=Re[5],e[r+6]=Re[6],e[r+7]=Re[7]}function Fy(t,e){return Re[0]=t[e],Re[1]=t[e+1],Re[2]=t[e+2],Re[3]=t[e+3],Re[4]=t[e+4],Re[5]=t[e+5],Re[6]=t[e+6],Re[7]=t[e+7],vc[0]}const My=BigInt(Number.MAX_SAFE_INTEGER),jy=BigInt(Number.MIN_SAFE_INTEGER);class Te{lo;hi;constructor(e,r){this.lo=e|0,this.hi=r|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){const r=~this.lo+1>>>0;let n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*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 r=~this.lo+1>>>0;let n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<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,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return nr;if(e<My&&e>jy)return this.fromNumber(Number(e));const r=e<0n;r&&(e=-e);let n=e>>32n,o=e-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>Fl&&(o=0n,++n>Fl&&(n=0n))),new Te(Number(o),Number(n))}static fromNumber(e){if(e===0)return nr;const r=e<0;r&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new Te(n,o)}static from(e){return typeof e=="number"?Te.fromNumber(e):typeof e=="bigint"?Te.fromBigInt(e):typeof e=="string"?Te.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new Te(e.low>>>0,e.high>>>0):nr}}const nr=new Te(0,0);nr.toBigInt=function(){return 0n};nr.zzEncode=nr.zzDecode=function(){return this};nr.length=function(){return 1};const Fl=4294967296n;function Uy(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(r&64512)===55296&&(t.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function $y(t,e,r){if(r-e<1)return"";let o;const s=[];let i=0,a;for(;e<r;)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 Ff(t,e,r){const n=r;let o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128);return r-n}function Qe(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function So(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}class Hy{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Qe(this,10);return e}int32(){return this.uint32()|0}sint32(){const e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Qe(this,4);return So(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Qe(this,4);return So(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Qe(this,4);const e=Dy(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Qe(this,4);const e=Fy(this.buf,this.pos);return this.pos+=8,e}bytes(){const e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw Qe(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){const e=this.bytes();return $y(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Qe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Qe(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new Te(0,0);let r=0;if(this.len-this.pos>4){for(;r<4;++r)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*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;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw Qe(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,e}if(this.len-this.pos>4){for(;r<5;++r)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;r<5;++r){if(this.pos>=this.len)throw Qe(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Qe(this,8);const e=So(this.buf,this.pos+=4),r=So(this.buf,this.pos+=4);return new Te(e,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=Df(this.buf,this.pos);return this.pos+=gr(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 qy(t){return new Hy(t instanceof Uint8Array?t:t.subarray())}function Fs(t,e,r){const n=qy(t);return e.decode(n,void 0,r)}function Ky(t){let n,o=8192;return function(i){if(i<1||i>4096)return kt(i);o+i>8192&&(n=kt(8192),o=0);const a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}class Nn{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}}function ui(){}class zy{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const Wy=Ky();function Vy(t){return globalThis.Buffer!=null?kt(t):Wy(t)}class ya{len;head;tail;states;constructor(){this.len=0,this.head=new Nn(ui,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new Nn(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Xy((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(Eo,10,Te.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const r=Te.fromBigInt(e);return this._push(Eo,r.length(),r)}uint64Number(e){return this._push(_f,gr(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 r=Te.fromBigInt(e).zzEncode();return this._push(Eo,r.length(),r)}sint64Number(e){const r=Te.fromNumber(e).zzEncode();return this._push(Eo,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(fi,1,e?1:0)}fixed32(e){return this._push(mn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const r=Te.fromBigInt(e);return this._push(mn,4,r.lo)._push(mn,4,r.hi)}fixed64Number(e){const r=Te.fromNumber(e);return this._push(mn,4,r.lo)._push(mn,4,r.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(_y,4,e)}double(e){return this._push(Oy,8,e)}bytes(e){const r=e.length>>>0;return r===0?this._push(fi,1,0):this.uint32(r)._push(Yy,r,e)}string(e){const r=Uy(e);return r!==0?this.uint32(r)._push(Ff,r,e):this._push(fi,1,0)}fork(){return this.states=new zy(this),this.head=this.tail=new Nn(ui,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 Nn(ui,0,0),this.len=0),this}ldelim(){const e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=r,this.len+=n),this}finish(){let e=this.head.next;const r=Vy(this.len);let n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}}function fi(t,e,r){e[r]=t&255}function Gy(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}class Xy extends Nn{next;constructor(e,r){super(Gy,e,r),this.next=void 0}}function Eo(t,e,r){for(;t.hi!==0;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}function mn(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function Yy(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(ya.prototype.bytes=function(t){const e=t.length>>>0;return this.uint32(e),e>0&&this._push(Zy,e,t),this},ya.prototype.string=function(t){const e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(Jy,e,t),this});function Zy(t,e,r){e.set(t,r)}function Jy(t,e,r){t.length<40?Ff(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(we(t),r)}function Qy(){return new ya}function Ms(t,e){const r=Qy();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var as;(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"})(as||(as={}));function Mf(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function eb(t){function e(o){if(t[o.toString()]==null)throw new Error("Invalid enum value");return t[o]}const r=function(s,i){const a=e(s);i.int32(a)},n=function(s){const i=s.int32();return e(i)};return Mf("enum",as.VARINT,r,n)}function js(t,e){return Mf("message",as.LENGTH_DELIMITED,t,e)}class Ml extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var le;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(le||(le={}));var ba;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(ba||(ba={}));(function(t){t.codec=()=>eb(ba)})(le||(le={}));var cr;(function(t){let e;t.codec=()=>(e==null&&(e=js((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),le.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{const s={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){const a=r.uint32();switch(a>>>3){case 1:{s.Type=le.codec().decode(r);break}case 2:{s.Data=r.bytes();break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ms(r,t.codec()),t.decode=(r,n)=>Fs(r,t.codec(),n)})(cr||(cr={}));var cs;(function(t){let e;t.codec=()=>(e==null&&(e=js((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),le.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{const s={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){const a=r.uint32();switch(a>>>3){case 1:{s.Type=le.codec().decode(r);break}case 2:{s.Data=r.bytes();break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ms(r,t.codec()),t.decode=(r,n)=>Fs(r,t.codec(),n)})(cs||(cs={}));const jf=df;class Uf{type="RSA";jwk;_raw;_multihash;constructor(e,r){this.jwk=e,this._multihash=r}get raw(){return this._raw==null&&(this._raw=Hf(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ce.createV1(114,this._multihash)}toString(){return Le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:nt(this.raw,e.raw)}verify(e,r,n){return gb(this.jwk,r,e,n)}}class tb{type="RSA";jwk;_raw;publicKey;constructor(e,r){this.jwk=e,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=ib(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:nt(this.raw,e.raw)}sign(e,r){return pb(this.jwk,e,r)}}const rb=8192,$f=18,nb=1062,ob=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function sb(t){return{n:Q(t[1],"base64url"),e:Q(t[2],"base64url"),d:Q(t[3],"base64url"),p:Q(t[4],"base64url"),q:Q(t[5],"base64url"),dp:Q(t[6],"base64url"),dq:Q(t[7],"base64url"),qi:Q(t[8],"base64url"),kty:"RSA"}}function ib(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 rt("JWK was missing components");return St([Ue(Uint8Array.from([0])),Ue(we(t.n,"base64url")),Ue(we(t.e,"base64url")),Ue(we(t.d,"base64url")),Ue(we(t.p,"base64url")),Ue(we(t.q,"base64url")),Ue(we(t.dp,"base64url")),Ue(we(t.dq,"base64url")),Ue(we(t.qi,"base64url"))]).subarray()}function ab(t){const e=sn(t[1],{offset:0});return{kty:"RSA",n:Q(e[0],"base64url"),e:Q(e[1],"base64url")}}function Hf(t){if(t.n==null||t.e==null)throw new rt("JWK was missing components");return St([ob,cc(St([Ue(we(t.n,"base64url")),Ue(we(t.e,"base64url"))]))]).subarray()}function cb(t){const e=sn(t);return lb(e)}function lb(t){const e=sb(t);return fb(e)}function db(t,e){if(t.byteLength>=nb)throw new Uu("Key size is too large");const r=sn(t,{offset:0});return ub(r,t,e)}function ub(t,e,r){const n=ab(t);if(r==null){const o=jf(cr.encode({Type:le.RSA,Data:e}));r=no($f,o)}return new Uf(n,r)}function fb(t){if(mb(t)>rb)throw new rt("Key size is too large");const e=hb(t),r=jf(cr.encode({Type:le.RSA,Data:Hf(e.publicKey)})),n=no($f,r);return new tb(e.privateKey,new Uf(e.publicKey,n))}function hb(t){if(t==null)throw new rt("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function pb(t,e,r){const n=await It.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();const o=await It.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function gb(t,e,r,n){const o=await It.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();const s=await It.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),s}function mb(t){if(t.kty!=="RSA")throw new rt("invalid key type");if(t.n==null)throw new rt("invalid key modulus");return we(t.n,"base64url").length*8}class qf extends sf{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,nf(e);const n=lc(r);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(n.length>o?e.create().update(n).digest():n);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),Yr(s)}update(e){return ts(this),this.iHash.update(e),this}digestInto(e){ts(this),hr(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:r,iHash:n,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=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Kf=(t,e,r)=>new qf(t,e).update(r).digest();Kf.create=(t,e)=>new qf(t,e);const jl=(t,e)=>(t+(t>=0?e:-e)/zf)/e;function wb(t,e,r){const[[n,o],[s,i]]=e,a=jl(i*t,r),c=jl(-o*t,r);let l=t-a*n-c*s,d=-a*o-c*i;const u=l<bt,f=d<bt;u&&(l=-l),f&&(d=-d);const h=ao(Math.ceil(hf(r)/2))+$r;if(l<bt||l>=h||d<bt||d>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:f,k2:d}}function va(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function hi(t,e){const r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return ar(r.lowS,"lowS"),ar(r.prehash,"prehash"),r.format!==void 0&&va(r.format),r}class yb extends Error{constructor(e=""){super(e)}}const wt={Err:yb,_tlv:{encode:(t,e)=>{const{Err:r}=wt;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const n=e.length/2,o=xo(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?xo(o.length/2|128):"";return xo(t)+s+o+e},decode(t,e){const{Err:r}=wt;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const o=e[n++],s=!!(o&128);let i=0;if(!s)i=o;else{const c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(n,n+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){const{Err:e}=wt;if(t<bt)throw new e("integer: negative integers are not allowed");let r=xo(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=wt;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 Ds(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=wt,o=fe("signature",t),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,s),{v:l,l:d}=n.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(t){const{_tlv:e,_int:r}=wt,n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}},bt=BigInt(0),$r=BigInt(1),zf=BigInt(2),Ao=BigInt(3),bb=BigInt(4);function Lr(t,e){const{BYTES:r}=t;let n;if(typeof e=="bigint")n=e;else{let o=fe("private key",e);try{n=t.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function vb(t,e={}){const r=Tf("weierstrass",t,e),{Fp:n,Fn:o}=r;let s=r.CURVE;const{h:i,n:a}=s;co(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Vf(n,o);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(P,b,E){const{x:C,y:L}=b.toAffine(),M=n.toBytes(C);if(ar(E,"isCompressed"),E){d();const $=!n.isOdd(L);return ct(Wf($),M)}else return ct(Uint8Array.of(4),M,n.toBytes(L))}function f(P){tt(P,void 0,"Point");const{publicKey:b,publicKeyUncompressed:E}=l,C=P.length,L=P[0],M=P.subarray(1);if(C===b&&(L===2||L===3)){const $=n.fromBytes(M);if(!n.isValid($))throw new Error("bad point: is not on curve, wrong x");const j=m($);let D;try{D=n.sqrt(j)}catch(q){const H=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}d();const _=n.isOdd(D);return(L&1)===1!==_&&(D=n.neg(D)),{x:$,y:D}}else if(C===E&&L===4){const $=n.BYTES,j=n.fromBytes(M.subarray(0,$)),D=n.fromBytes(M.subarray($,$*2));if(!y(j,D))throw new Error("bad point: is not on curve");return{x:j,y:D}}else throw new Error(`bad point: got length ${C}, expected compressed=${b} or uncompressed=${E}`)}const h=e.toBytes||u,g=e.fromBytes||f;function m(P){const b=n.sqr(P),E=n.mul(b,P);return n.add(n.add(E,n.mul(P,s.a)),s.b)}function y(P,b){const E=n.sqr(b),C=m(P);return n.eql(E,C)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const w=n.mul(n.pow(s.a,Ao),bb),I=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(w,I)))throw new Error("bad curve params: a or b");function v(P,b,E=!1){if(!n.isValid(b)||E&&n.is0(b))throw new Error(`bad point coordinate ${P}`);return b}function k(P){if(!(P instanceof x))throw new Error("ProjectivePoint expected")}function B(P){if(!c||!c.basises)throw new Error("no endo");return wb(P,c.basises,o.ORDER)}const R=ns((P,b)=>{const{X:E,Y:C,Z:L}=P;if(n.eql(L,n.ONE))return{x:E,y:C};const M=P.is0();b==null&&(b=M?n.ONE:n.inv(L));const $=n.mul(E,b),j=n.mul(C,b),D=n.mul(L,b);if(M)return{x:n.ZERO,y:n.ZERO};if(!n.eql(D,n.ONE))throw new Error("invZ was invalid");return{x:$,y:j}}),N=ns(P=>{if(P.is0()){if(e.allowInfinityPoint&&!n.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:b,y:E}=P.toAffine();if(!n.isValid(b)||!n.isValid(E))throw new Error("bad point: x or y not field elements");if(!y(b,E))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function A(P,b,E,C,L){return E=new x(n.mul(E.X,P),E.Y,E.Z),b=os(C,b),E=os(L,E),b.add(E)}class x{constructor(b,E,C){this.X=v("x",b),this.Y=v("y",E,!0),this.Z=v("z",C),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){const{x:E,y:C}=b||{};if(!b||!n.isValid(E)||!n.isValid(C))throw new Error("invalid affine point");if(b instanceof x)throw new Error("projective point not allowed");return n.is0(E)&&n.is0(C)?x.ZERO:new x(E,C,n.ONE)}static fromBytes(b){const E=x.fromAffine(g(tt(b,void 0,"point")));return E.assertValidity(),E}static fromHex(b){return x.fromBytes(fe("pointHex",b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,E=!0){return T.createCache(this,b),E||this.multiply(Ao),this}assertValidity(){N(this)}hasEvenY(){const{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){k(b);const{X:E,Y:C,Z:L}=this,{X:M,Y:$,Z:j}=b,D=n.eql(n.mul(E,j),n.mul(M,L)),_=n.eql(n.mul(C,j),n.mul($,L));return D&&_}negate(){return new x(this.X,n.neg(this.Y),this.Z)}double(){const{a:b,b:E}=s,C=n.mul(E,Ao),{X:L,Y:M,Z:$}=this;let j=n.ZERO,D=n.ZERO,_=n.ZERO,O=n.mul(L,L),q=n.mul(M,M),H=n.mul($,$),K=n.mul(L,M);return K=n.add(K,K),_=n.mul(L,$),_=n.add(_,_),j=n.mul(b,_),D=n.mul(C,H),D=n.add(j,D),j=n.sub(q,D),D=n.add(q,D),D=n.mul(j,D),j=n.mul(K,j),_=n.mul(C,_),H=n.mul(b,H),K=n.sub(O,H),K=n.mul(b,K),K=n.add(K,_),_=n.add(O,O),O=n.add(_,O),O=n.add(O,H),O=n.mul(O,K),D=n.add(D,O),H=n.mul(M,$),H=n.add(H,H),O=n.mul(H,K),j=n.sub(j,O),_=n.mul(H,q),_=n.add(_,_),_=n.add(_,_),new x(j,D,_)}add(b){k(b);const{X:E,Y:C,Z:L}=this,{X:M,Y:$,Z:j}=b;let D=n.ZERO,_=n.ZERO,O=n.ZERO;const q=s.a,H=n.mul(s.b,Ao);let K=n.mul(E,M),z=n.mul(C,$),V=n.mul(L,j),X=n.add(E,C),G=n.add(M,$);X=n.mul(X,G),G=n.add(K,z),X=n.sub(X,G),G=n.add(E,L);let Y=n.add(M,j);return G=n.mul(G,Y),Y=n.add(K,V),G=n.sub(G,Y),Y=n.add(C,L),D=n.add($,j),Y=n.mul(Y,D),D=n.add(z,V),Y=n.sub(Y,D),O=n.mul(q,G),D=n.mul(H,V),O=n.add(D,O),D=n.sub(z,O),O=n.add(z,O),_=n.mul(D,O),z=n.add(K,K),z=n.add(z,K),V=n.mul(q,V),G=n.mul(H,G),z=n.add(z,V),V=n.sub(K,V),V=n.mul(q,V),G=n.add(G,V),K=n.mul(z,G),_=n.add(_,K),K=n.mul(Y,G),D=n.mul(X,D),D=n.sub(D,K),K=n.mul(X,z),O=n.mul(Y,O),O=n.add(O,K),new x(D,_,O)}subtract(b){return this.add(b.negate())}is0(){return this.equals(x.ZERO)}multiply(b){const{endo:E}=e;if(!o.isValidNot0(b))throw new Error("invalid scalar: out of range");let C,L;const M=$=>T.cached(this,$,j=>Qt(x,j));if(E){const{k1neg:$,k1:j,k2neg:D,k2:_}=B(b),{p:O,f:q}=M(j),{p:H,f:K}=M(_);L=q.add(K),C=A(E.beta,O,H,$,D)}else{const{p:$,f:j}=M(b);C=$,L=j}return Qt(x,[C,L])[0]}multiplyUnsafe(b){const{endo:E}=e,C=this;if(!o.isValid(b))throw new Error("invalid scalar: out of range");if(b===bt||C.is0())return x.ZERO;if(b===$r)return C;if(T.hasCache(this))return this.multiply(b);if(E){const{k1neg:L,k1:M,k2neg:$,k2:j}=B(b),{p1:D,p2:_}=ty(x,C,M,j);return A(E.beta,D,_,L,$)}else return T.unsafe(C,b)}multiplyAndAddUnsafe(b,E,C){const L=this.multiplyUnsafe(E).add(b.multiplyUnsafe(C));return L.is0()?void 0:L}toAffine(b){return R(this,b)}isTorsionFree(){const{isTorsionFree:b}=e;return i===$r?!0:b?b(x,this):T.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:b}=e;return i===$r?this:b?b(x,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(b=!0){return ar(b,"isCompressed"),this.assertValidity(),h(x,this,b)}toHex(b=!0){return rr(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(b=!0){return this.toBytes(b)}_setWindowSize(b){this.precompute(b)}static normalizeZ(b){return Qt(x,b)}static msm(b,E){return Rf(x,o,b,E)}static fromPrivateKey(b){return x.BASE.multiply(Lr(o,b))}}x.BASE=new x(s.Gx,s.Gy,n.ONE),x.ZERO=new x(n.ZERO,n.ONE,n.ZERO),x.Fp=n,x.Fn=o;const S=o.BITS,T=new Cf(x,e.endo?Math.ceil(S/2):S);return x.BASE.precompute(8),x}function Wf(t){return Uint8Array.of(t?2:3)}function Vf(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function xb(t,e={}){const{Fn:r}=t,n=e.randomBytes||dc,o=Object.assign(Vf(t.Fp,r),{seed:Af(r.ORDER)});function s(h){try{return!!Lr(r,h)}catch{return!1}}function i(h,g){const{publicKey:m,publicKeyUncompressed:y}=o;try{const w=h.length;return g===!0&&w!==m||g===!1&&w!==y?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return Jw(tt(h,o.seed,"seed"),r.ORDER)}function c(h,g=!0){return t.BASE.multiply(Lr(r,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:y}=o;if(r.allowedLengths||g===m)return;const w=fe("key",h).length;return w===m||w===y}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 y=Lr(r,h);return t.fromHex(g).multiply(y).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=>Lr(r,h),precompute(h=8,g=t.BASE){return g.precompute(h,!1)}},lengths:o})}function Sb(t,e,r={}){nf(e),co(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=r.randomBytes||dc,o=r.hmac||((E,...C)=>Kf(e,E,ct(...C))),{Fp:s,Fn:i}=t,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h}=xb(t,r),g={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function y(E){const C=a>>$r;return E>C}function w(E,C){if(!i.isValidNot0(C))throw new Error(`invalid signature ${E}: out of range 1..Point.Fn.ORDER`);return C}function I(E,C){va(C);const L=h.signature,M=C==="compact"?L:C==="recovered"?L+1:void 0;return tt(E,M,`${C} signature`)}class v{constructor(C,L,M){this.r=w("r",C),this.s=w("s",L),M!=null&&(this.recovery=M),Object.freeze(this)}static fromBytes(C,L=m){I(C,L);let M;if(L==="der"){const{r:_,s:O}=wt.toSig(tt(C));return new v(_,O)}L==="recovered"&&(M=C[0],L="compact",C=C.subarray(1));const $=i.BYTES,j=C.subarray(0,$),D=C.subarray($,$*2);return new v(i.fromBytes(j),i.fromBytes(D),M)}static fromHex(C,L){return this.fromBytes(rs(C),L)}addRecoveryBit(C){return new v(this.r,this.s,C)}recoverPublicKey(C){const L=s.ORDER,{r:M,s:$,recovery:j}=this;if(j==null||![0,1,2,3].includes(j))throw new Error("recovery id invalid");if(a*zf<L&&j>1)throw new Error("recovery id is ambiguous for h>1 curve");const _=j===2||j===3?M+a:M;if(!s.isValid(_))throw new Error("recovery id 2 or 3 invalid");const O=s.toBytes(_),q=t.fromBytes(ct(Wf((j&1)===0),O)),H=i.inv(_),K=B(fe("msgHash",C)),z=i.create(-K*H),V=i.create($*H),X=t.BASE.multiplyUnsafe(z).add(q.multiplyUnsafe(V));if(X.is0())throw new Error("point at infinify");return X.assertValidity(),X}hasHighS(){return y(this.s)}toBytes(C=m){if(va(C),C==="der")return rs(wt.hexFromSig(this));const L=i.toBytes(this.r),M=i.toBytes(this.s);if(C==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return ct(Uint8Array.of(this.recovery),L,M)}return ct(L,M)}toHex(C){return rr(this.toBytes(C))}assertValidity(){}static fromCompact(C){return v.fromBytes(fe("sig",C),"compact")}static fromDER(C){return v.fromBytes(fe("sig",C),"der")}normalizeS(){return this.hasHighS()?new v(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return rr(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return rr(this.toBytes("compact"))}}const k=r.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");const L=Ds(C),M=C.length*8-c;return M>0?L>>BigInt(M):L},B=r.bits2int_modN||function(C){return i.create(k(C))},R=ao(c);function N(E){return ga("num < 2^"+c,E,bt,R),i.toBytes(E)}function A(E,C){return tt(E,void 0,"message"),C?tt(e(E),void 0,"prehashed message"):E}function x(E,C,L){if(["recovered","canonical"].some(z=>z in L))throw new Error("sign() legacy options not supported");const{lowS:M,prehash:$,extraEntropy:j}=hi(L,g);E=A(E,$);const D=B(E),_=Lr(i,C),O=[N(_),N(D)];if(j!=null&&j!==!1){const z=j===!0?n(h.secretKey):j;O.push(fe("extraEntropy",z))}const q=ct(...O),H=D;function K(z){const V=k(z);if(!i.isValidNot0(V))return;const X=i.inv(V),G=t.BASE.multiply(V).toAffine(),Y=i.create(G.x);if(Y===bt)return;const se=i.create(X*i.create(H+Y*_));if(se===bt)return;let Ne=(G.x===Y?0:2)|Number(G.y&$r),Me=se;return M&&y(se)&&(Me=i.neg(se),Ne^=1),new v(Y,Me,Ne)}return{seed:q,k2sig:K}}function S(E,C,L={}){E=fe("message",E);const{seed:M,k2sig:$}=x(E,C,L);return Hw(e.outputLen,i.BYTES,o)(M,$)}function T(E){let C;const L=typeof E=="string"||io(E),M=!L&&E!==null&&typeof E=="object"&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!L&&!M)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(M)C=new v(E.r,E.s);else if(L){try{C=v.fromBytes(fe("sig",E),"der")}catch($){if(!($ instanceof wt.Err))throw $}if(!C)try{C=v.fromBytes(fe("sig",E),"compact")}catch{return!1}}return C||!1}function P(E,C,L,M={}){const{lowS:$,prehash:j,format:D}=hi(M,g);if(L=fe("publicKey",L),C=A(fe("message",C),j),"strict"in M)throw new Error("options.strict was renamed to lowS");const _=D===void 0?T(E):v.fromBytes(fe("sig",E),D);if(_===!1)return!1;try{const O=t.fromBytes(L);if($&&_.hasHighS())return!1;const{r:q,s:H}=_,K=B(C),z=i.inv(H),V=i.create(K*z),X=i.create(q*z),G=t.BASE.multiplyUnsafe(V).add(O.multiplyUnsafe(X));return G.is0()?!1:i.create(G.x)===q}catch{return!1}}function b(E,C,L={}){const{prehash:M}=hi(L,g);return C=A(C,M),v.fromBytes(E,"recovered").recoverPublicKey(C).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h,Point:t,sign:S,verify:P,recoverPublicKey:b,Signature:v,hash:e})}function Eb(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},r=t.Fp;let n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0;const o=pr(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),s={Fp:r,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 Ab(t){const{CURVE:e,curveOpts:r}=Eb(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}function kb(t,e){const r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,Sf(r.Fn.ORDER,r.Fn.BITS))})}function Ib(t){const{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:o}=Ab(t),s=vb(e,r),i=Sb(s,n,o);return kb(t,i)}function Cb(t,e){const r=n=>Ib({...t,hash:n});return{...r(e),create:r}}const xc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Rb={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Ul=BigInt(2);function Tb(t){const e=xc.p,r=BigInt(3),n=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=ue(d,r,e)*d%e,f=ue(u,r,e)*d%e,h=ue(f,Ul,e)*l%e,g=ue(h,o,e)*h%e,m=ue(g,s,e)*g%e,y=ue(m,a,e)*m%e,w=ue(y,c,e)*y%e,I=ue(w,a,e)*m%e,v=ue(I,r,e)*d%e,k=ue(v,i,e)*g%e,B=ue(k,n,e)*l%e,R=ue(B,Ul,e);if(!xa.eql(xa.sqr(R),t))throw new Error("Cannot find square root");return R}const xa=pr(xc.p,{sqrt:Tb}),zt=Cb({...xc,Fp:xa,lowS:!0,endo:Rb},df);function Pb(t,e,r){const n=ac.digest(e instanceof Uint8Array?e:e.subarray());if(Os(n))return n.then(({digest:o})=>(r?.signal?.throwIfAborted(),zt.sign(o,t).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new Dl(String(o))});try{return zt.sign(n.digest,t).toDERRawBytes()}catch(o){throw new Dl(String(o))}}function Nb(t,e,r,n){const o=ac.digest(r instanceof Uint8Array?r:r.subarray());if(Os(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),zt.verify(e,s,t))).catch(s=>{throw s.name==="AbortError"?s:new Ol(String(s))});try{return n?.signal?.throwIfAborted(),zt.verify(e,o.digest,t)}catch(s){throw new Ol(String(s))}}class Gf{type="secp256k1";raw;_key;constructor(e){this._key=Ob(e),this.raw=_b(this._key)}toMultihash(){return oo.digest(Us(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return Le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:nt(this.raw,e.raw)}verify(e,r,n){return Nb(this._key,r,e,n)}}class Lb{type="secp256k1";raw;publicKey;constructor(e,r){this.raw=Db(e),this.publicKey=new Gf(r??Fb(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:nt(this.raw,e.raw)}sign(e,r){return Pb(this.raw,e,r)}}function Bb(t){return new Lb(t)}function Xf(t){return new Gf(t)}function _b(t){return zt.ProjectivePoint.fromHex(t).toRawBytes(!0)}function Db(t){try{return zt.getPublicKey(t,!0),t}catch(e){throw new $u(String(e))}}function Ob(t){try{return zt.ProjectivePoint.fromHex(t),t}catch(e){throw new Uu(String(e))}}function Fb(t){try{return zt.getPublicKey(t,!0)}catch(e){throw new $u(String(e))}}async function Mb(t,e){return Cy()}function Sa(t,e){const{Type:r,Data:n}=cr.decode(t),o=n??new Uint8Array;switch(r){case le.RSA:return db(o,e);case le.Ed25519:return Bf(o);case le.secp256k1:return Xf(o);case le.ECDSA:return tf(o);default:throw new Ns}}function jb(t){const{Type:e,Data:r}=cr.decode(t.digest),n=r??new Uint8Array;switch(e){case le.Ed25519:return Bf(n);case le.secp256k1:return Xf(n);case le.ECDSA:return tf(n);default:throw new Ns}}function Us(t){return cr.encode({Type:le[t.type],Data:t.raw})}function Ub(t){const e=cs.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case le.RSA:return cb(r);case le.Ed25519:return Iy(r);case le.secp256k1:return Bb(r);case le.ECDSA:return mw(r);default:throw new Ns}}function $b(t){return cs.encode({Type:le[t.type],Data:t.raw})}const Yf=Symbol.for("nodejs.util.inspect.custom"),Hb=114;class Sc{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()})`}[Hu]=!0;toString(){return this.string==null&&(this.string=Le.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ce.createV1(Hb,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return nt(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return nt(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Yf](){return`PeerId(${this.toString()})`}}class Zf extends Sc{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class Jf extends Sc{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class Qf extends Sc{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}const qb=2336;class eh{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=oo.digest(we(this.url))}[Yf](){return`PeerId(${this.url})`}[Hu]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ce.createV1(qb,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=Q(e)),e.toString()===this.toString())}}const Kb=114,$l=2336;function zb(t,e){let r;if(t.charAt(0)==="1"||t.charAt(0)==="Q")r=zu(Le.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return Wb(ce.parse(t));throw new rt('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return th(r)}function Jr(t){if(t.type==="Ed25519")return new Jf({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new Qf({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new Zf({multihash:t.toCID().multihash,publicKey:t});throw new Ns}function th(t){if(Gb(t))return new Zf({multihash:t});if(Vb(t))try{const e=jb(t);if(e.type==="Ed25519")return new Jf({multihash:t,publicKey:e});if(e.type==="secp256k1")return new Qf({multihash:t,publicKey:e})}catch{const r=Q(t.digest);return new eh(new URL(r))}throw new Rg("Supplied PeerID Multihash is invalid")}function Wb(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==Kb&&t.code!==$l)throw new Cg("Supplied PeerID CID is invalid");if(t.code===$l){const e=Q(t.multihash.digest);return new eh(new URL(e))}return th(t.multihash)}function Vb(t){return t.code===oo.code}function Gb(t){return t.code===ac.code}class rh extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class Xb extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class wn extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class Hl extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}}class Yb extends Event{data;constructor(e,r){super("message",r),this.data=e}}class Ec extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}}class Zb extends Ec{constructor(e,r){super(!0,e,r)}}class Jb extends Ec{constructor(e,r){super(!1,e,r)}}const Qb=t=>t/2**32|0,e0=t=>t>>>0;function t0(t,e,r,n){const o=Qb(r),s=e0(r);t.setUint32(e,n?s:o,n),t.setUint32(e+4,n?o:s,n)}function Ea(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const Aa=t=>t?`"${t}" `:"";function Ct(t,e=""){if(typeof t!="number")throw new TypeError(Aa(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(Aa(e)+"expected integer >= 0, got "+t);return t}function Rt(t,e,r=""){if(Ea(t)&&(e===void 0||t.length===e))return t;e!==void 0&&Ct(e,"length");const n=Ea(t),o=e!==void 0?` of length ${e}`:"",s=n?`length=${t.length}`:`type=${typeof t}`,i=Aa(r)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}function Ac(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Ct(t.outputLen),Ct(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}const r0=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)},ql=(t,e)=>{r0(t,e);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function ls(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function nh(t,e){Rt(t,void 0,"output");const r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function Vk(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function or(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function pi(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function it(t,e){return t<<32-e|t>>>e}function Gk(t,e){return t<<e|t>>>32-e>>>0}const n0=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function o0(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function s0(t){for(let e=0;e<t.length;e++)t[e]=o0(t[e]);return t}const Xk=n0?t=>t:s0,oh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",i0=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function kc(t){if(Rt(t),oh)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=i0[t[r]];return e}function Kl(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function sh(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(oh)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}const e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){const i=Kl(t.charCodeAt(s)),a=Kl(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)}n[o]=i*16+a}return n}function a0(t){const e=globalThis;if(typeof e.scheduler?.yield=="function"){const r=e.scheduler.yield();return t&&r.catch(t),r}return new Promise(r=>e.setTimeout(r,0))}async function Yk(t,e,r,n){if(Ct(t,"iters"),Ct(e,"tick"),typeof r!="function")throw new TypeError("callback must be a function");let o=Date.now();for(let s=0;s<t;s++){r(s);const i=Date.now()-o;i>=0&&i<e||(await a0(n),o=Date.now())}}function c0(t){if(typeof t!="string")throw new TypeError("string expected");const e=new TextEncoder().encode(t);try{return new Uint8Array(e)}finally{or(e)}}function Zk(t,e=""){return typeof t=="string"?c0(t):Rt(t,void 0,e)}function l0(t,e,r="opts"){return ql(t,"defaults"),e!==void 0&&ql(e,r),Object.assign(Object.create(null),t,e)}function d0(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=l0({},e,"info");const r=(o,s)=>t(s).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function u0(t=32){Ct(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 f0=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function h0(t,e,r){return t&e^~t&r}function p0(t,e,r){return t&e^t&r^e&r}class g0{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,o){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=pi(this.buffer)}update(e){ls(this),Rt(e);const{view:r,buffer:n,blockLen:o}=this,s=e.length;let i=!1;for(let a=0;a<s;){const c=Math.min(o-this.pos,s-a);if(c===o){const l=pi(e);for(;o<=s-a;a+=o)this.process(l,a);i=!0;continue}n.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(r,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){ls(this),nh(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:o,isLE:s}=this;let{pos:i}=this;r[i++]=128,r.fill(0,i),this.padOffset>o-i&&(this.process(n,0),r.fill(0)),t0(n,o-8,this.length*8,s),this.process(n,0),this.roundClean();const a=e===r?n:pi(e),c=this.outputLen,l=c/4,d=this.get();if(c%4||l>d.length)throw new Error("invalid outputLen");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneIntoMeta(e){const{buffer:r,length:n,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=n,e.pos=i,i&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const m0=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),w0=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Dt=new Uint32Array(64);class y0 extends g0{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,r){super(64,e,8,!1),this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){const{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|0,this.C=n|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,r){for(let u=0;u<16;u++,r+=4)Dt[u]=e.getUint32(r,!1);for(let u=16;u<64;u++){const f=Dt[u-15],h=Dt[u-2],g=it(f,7)^it(f,18)^f>>>3,m=it(h,17)^it(h,19)^h>>>10;Dt[u]=m+Dt[u-7]+g+Dt[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=it(a,6)^it(a,11)^it(a,25),h=d+f+h0(a,c,l)+w0[u]+Dt[u]|0,m=(it(n,2)^it(n,13)^it(n,22))+p0(n,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+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(n,o,s,i,a,c,l,d)}roundClean(){or(Dt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),or(this.buffer)}}class b0 extends y0{constructor(){super(32,m0)}}const gi=d0(()=>new b0,f0(1));function ih(t,e,r=()=>{}){if(!Array.isArray(t))throw new TypeError(`"${e}" expected array, got type=${typeof t}`);for(let n=0;n<t.length;n++)r(t[n],`${e}[${n}]`);return t}const Hr=(t,e,r)=>Rt(t,e,r),ah=Ct;function qr(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 jn(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}const v0=kc,x0=t=>sh(t),ch=Ea,lh=t=>u0(t),ds=BigInt(0),zl=BigInt(1),S0=t=>t?`"${t}" `:"";function $s(t,e=""){if(typeof t!="boolean")throw new TypeError(S0(e)+"expected boolean, got type="+typeof t);return t}function E0(t){if(typeof t=="bigint"){if(!sr(t))throw new RangeError("positive bigint expected, got "+t)}else ah(t);return t}function ka(t,e=""){if(typeof t!="number"){const r=e&&`"${e}" `;throw new TypeError(r+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){const r=e&&`"${e}" `;throw new RangeError(r+"expected safe integer, got "+t)}}function dh(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?ds:BigInt("0x"+t)}function uh(t){return dh(kc(t))}function us(t){return dh(kc(Xn(Rt(t)).reverse()))}function fh(t,e){if(Ct(e),e===0)throw new Error("zero output length is invalid");t=E0(t);const r=e*2,n=t.toString(16);if(n.length>r)throw new RangeError("number is too large");return sh(n.padStart(r,"0"))}function hh(t,e){return fh(t,e).reverse()}function Xn(t){return Uint8Array.from(Hr(t))}function sr(t){return typeof t=="bigint"&&ds<=t}function ph(t,e,r){return sr(t)&&sr(e)&&sr(r)&&e<=t&&t<r}function Un(t,e,r,n){if(!ph(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function A0(t){if(t<ds)throw new Error("expected non-negative bigint, got "+t);return t===ds?0:t.toString(2).length}const k0=t=>(ka(t,"n"),(zl<<BigInt(t))-zl);function fs(t,e={},r={},n="object"){qr(t,n),qr(e,"fields"),qr(r,"optFields");function o(i,a,c){const l=n==="object"?`param "${String(i)}"`:`"${n}.${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(r,!0)}const xe=BigInt(0),ae=BigInt(1),er=BigInt(2),gh=BigInt(3),Ic=BigInt(4),mh=BigInt(5),I0=BigInt(7),wh=BigInt(8),C0=BigInt(9),R0=BigInt(15),yh=BigInt(16),T0=BigInt("0x10000000000000000");function ie(t,e){if(e<=xe)throw new Error("mod: expected positive modulus, got "+e);const r=t%e;return r>=xe?r:e+r}function P0(t,e,r){if(r<=ae)throw new Error("pow: expected modulus > 1, got "+r);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<xe)throw new Error("invalid exponent, negatives unsupported");if(e===xe)return ae;if(e===ae)return t;let n=t%r;if(n<xe&&(n+=r),e<T0){let a=ae;for(;e>xe;)e&ae&&(a=a*n%r),n=n*n%r,e>>=ae;return a}const o=[];for(;e>xe;)o.push(Number(e&R0)),e>>=Ic;const s=new Array(16);s[0]=ae,s[1]=n;for(let a=2;a<16;a++)s[a]=s[a-1]*n%r;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%r,i=i*i%r,i=i*i%r,i=i*i%r;const c=o[a];c!==0&&(i=i*s[c]%r)}return i}function et(t,e,r){if(r<=ae)throw new Error("pow2: expected modulus > 1, got "+r);if(e<xe)throw new Error("pow2: expected non-negative exponent, got "+e);let n=t;for(;e-- >xe;)n*=n,n%=r;return n}function Wl(t,e){if(t===xe)throw new Error("invert: expected non-zero number");if(e<=ae)throw new Error("invert: expected modulus > 1, got "+e);let r=ie(t,e),n=e,o=xe,s=ae;for(;r!==xe;){const a=n/r,c=n-r*a,l=o-s*a;n=r,r=c,o=s,s=l}if(n!==ae)throw new Error("invert: does not exist");return ie(o,e)}function Cc(t,e,r){const n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function Rc(t,e){if((t&ae)===xe)throw new Error(e+": expected odd modulus, got "+t)}function bh(t,e){const r=t,n=(r.ORDER+ae)/Ic,o=r.pow(e,n);return Cc(r,o,e),o}function N0(t,e){const r=t,n=(r.ORDER-mh)/wh,o=r.mul(e,er),s=r.pow(o,n),i=r.mul(e,s),a=r.mul(r.mul(i,er),s),c=r.mul(i,r.sub(a,r.ONE));return Cc(r,c,e),c}function L0(t){const e=Tc(t),r=vh(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+I0)/yh;return((a,c)=>{const l=a;let d=l.pow(c,i),u=l.mul(d,n);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 y=l.eql(l.sqr(u),c),w=l.cmov(d,u,y);return Cc(l,w,c),w})}function vh(t){if(t<gh)throw new Error("sqrt is not defined for small field");Rc(t,"tonelliShanks");let e=t-ae,r=0;for(;e%er===xe;)e/=er,r++;let n=er;const o=Tc(t);for(;hs(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return bh;let s=o.pow(n,e);const i=(e+ae)/er;return function(c,l){const d=c;if(d.is0(l))return l;if(hs(d,l)!==1)throw new Error("Cannot find square root");let u=r,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,y=d.sqr(h);for(;!d.eql(y,d.ONE);)if(m++,y=d.sqr(y),m===u)throw new Error("Cannot find square root");const w=ae<<BigInt(u-m-1),I=d.pow(f,w);u=m,f=d.sqr(I),h=d.mul(h,f),g=d.mul(g,I)}return g}}function B0(t){return Rc(t,"Fp.sqrt"),t%Ic===gh?bh:t%wh===mh?N0:t%yh===C0?L0(t):vh(t)}const _0=(t,e)=>(ie(t,e)&ae)===ae,D0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yn(t){if(qr(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);ka(t.BYTES,"BYTES"),ka(t.BITS,"BITS");for(const e of D0)jn(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=ae)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function xh(t,e,r=!1){Yn(t),ih(e,"nums"),$s(r,"passZero");const n=t,o=new Array(e.length).fill(r?n.ZERO:void 0),s=e.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),i),o}function hs(t,e){Yn(t);const r=t;Rc(r.ORDER,"FpLegendre");const n=(r.ORDER-ae)/er,o=r.pow(e,n),s=r.eql(o,r.ONE),i=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function O0(t,e){if(e!==void 0&&ah(e),t<=xe)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 r=A0(t);if(e!==void 0&&e<r)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${r})`);const n=e!==void 0?e:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}const Vl=new WeakMap;class Gl{ORDER;BITS;BYTES;isLE;ZERO=xe;ONE=ae;_lengths;_mod;constructor(e,r={}){if(e<=ae)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:o,nByteLength:s}=O0(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return ie(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return xe<=e&&e<this.ORDER}is0(e){return e===xe}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ae)===ae}neg(e){return ie(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return ie(e*e,this.ORDER)}add(e,r){return ie(e+r,this.ORDER)}sub(e,r){return ie(e-r,this.ORDER)}mul(e,r){return ie(e*r,this.ORDER)}pow(e,r){return P0(e,r,this.ORDER)}div(e,r){return ie(e*Wl(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Wl(e,this.ORDER)}sqrt(e){let r=Vl.get(this);return r||Vl.set(this,r=B0(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?hh(e,this.BYTES):fh(e,this.BYTES)}fromBytes(e,r=!1){Hr(e);const{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" 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?us(e):uh(e);if(a&&(c=ie(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return xh(this,e,!0)}cmov(e,r,n){return $s(n,"condition"),n?r:e}}function Tc(t,e={}){return Object.freeze(Gl.prototype),new Gl(t,e)}const Pc=BigInt(0),Zn=BigInt(1),F0=BigInt(4),mi=16,Xl=128,M0=5,Yl=2**31;function Nc(t){const e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);jn(e.fromAffine,"Point.fromAffine"),jn(e.fromBytes,"Point.fromBytes"),jn(e.fromHex,"Point.fromHex"),qr(e.BASE,"Point.BASE"),qr(e.ZERO,"Point.ZERO"),Yn(e.Fp),Yn(e.Fn)}function j0(t,e){Nc(t),Sh(e,t);const r=xh(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function U0(t,e,r=1){if(!Number.isSafeInteger(t)||t<r||t>e)throw new Error("invalid window size, expected ["+r+".."+e+"], got W="+t)}function $0(t,e){const r=t*(4*e+128);if(r>Yl)throw new Error("invalid window size: table would need ~"+Math.ceil(r/2**20)+" MiB, max "+Yl/2**20+" MiB")}function H0(t,e){if(t!==void 0){jn(t,"randomBytes");try{const r=t(e);if(!ch(r)||r.length!==e)return}catch{return}return t}}function Sh(t,e){ih(t,"points"),t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function q0(t,e,r){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,o)=>{if(!(r===void 0?e.isValid(n):sr(n)&&n<r))throw new Error("invalid scalar at index "+o)})}const Eh=new WeakMap;function wi(t){return Eh.get(t)||1}function K0(t,e){const r=t.double(),n=[t];for(let o=1;o<e;o++)n.push(n[o-1].add(r));return n}function z0(t,e){const r=2**e,n=r/2,o=BigInt(r-1),s=[];for(;t>Pc;){let i=0;t&Zn&&(i=Number(t&o),i>=n&&(i-=r),t-=BigInt(i)),s.push(i),t>>=Zn}return s}function W0(t,e,r){const n=2**e,o=n/2,s=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<r;c++){let l=Number(t&s);t>>=i,l>o&&(l-=n,t+=Zn),a.push(l)}if(t!==Pc)throw new Error("invalid wnaf");return a}function V0(t,e,r){let n=0;for(const s of r)n=Math.max(n,s.length);let o=t;for(let s=n-1;s>=0;s--){s!==n-1&&(o=o.double());for(let i=0;i<r.length;i++){const a=r[i][s];if(a){const c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}class G0{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,r){Nc(e),this.randomBytes=H0(r,mi),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,r,n){const o=Math.ceil(n/r)+1,s=2**(r-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:r,bits:n,windows:o,comp:i}}wnafCachedCT(e,r){const{W:n,windows:o,comp:s}=e,i=2**(n-1),a=W0(r,n,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 y=1;y<i;y++)g=y===h?s[f+y]: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,r,n,o){let s=this.wnafPrecomputes.get(r),i=s?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(r,e,n),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(r,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,r){if(this.assertPoint(e),!ph(r,Zn,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,r,n,o){const s=wi(e);return s===1?this.fixedWindowCT(e,r,n):this.wnafCachedCT(this.getWnafPrecomputes(s,e,n,o),r)}mulCT(e,r,n){return this.validateMulInput(e,r),this.runCT(e,r,this.bits,n)}mulCTBlinded(e,r,n){if(this.validateMulInput(e,r),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");const o=this.Point.Fn.BITS+Xl,s=this.randomBytes(mi);if(!ch(s)||s.length!==mi)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;const i=r+uh(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,n)}fixedWindowCT(e,r,n){const o=M0,s=1<<o,i=k0(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(n/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(r>>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,r){return this.randomBytes===void 0?!1:r===Zn?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,r,n,o){return this.shouldBlind(e,n)?this.mulCTBlinded(e,r,o):this.mulCT(e,r,o)}mulUnsafe(e,r,n){if(this.assertPoint(e),!sr(r))throw new Error("invalid scalar");const o=wi(e);if(o===1||r>=this.Point.Fn.ORDER)return X0(this.Point,[e],[r],!0);const s=this.getWnafPrecomputes(o,e,this.bits,n);return this.wnafCachedCT(s,r).p}setWindowSize(e,r){this.assertPoint(e),U0(r,this.bits);const n=Math.ceil((this.bits+Xl)/r)+1;$0(n*2**(r-1),this.Point.Fp.BYTES),Eh.set(e,r),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return wi(e)!==1}}function X0(t,e,r,n=!1){if(Nc(t),Sh(e,t),$s(n,"allowOversized"),q0(r,t.Fn,n?t.Fn.ORDER**F0:void 0),e.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const o=e.map(i=>K0(i,4)),s=r.map(i=>z0(i,4));return V0(t.ZERO,o,s)}function Zl(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Yn(e),e}else return Tc(t,{isLE:r})}function Y0(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);fs(r);for(const c of["p","n","h"]){const l=e[c];if(!(sr(l)&&l!==Pc))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Zl(e.p,r.Fp,n),s=Zl(e.n,r.Fn,n),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 Z0(t,e){return function(n){const o=t(n);return{secretKey:o,publicKey:e(o)}}}const ko=BigInt(0),Io=BigInt(1),Co=BigInt(2),J0=BigInt(4),Jl=BigInt(8);function Q0(t,e,r,n){const o=t.sqr(r),s=t.sqr(n),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 ev(t,e={}){fs(e,{},{},"extraOpts");const r=e,n=Y0("edwards",t,r,r.FpFnLE),{Fp:o,Fn:s}=n;let i=n.CURVE;const{h:a}=i;if(hs(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(hs(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");fs(r,{},{uvRatio:"function",randomBytes:"function"});const c=r.randomBytes===void 0?lh:r.randomBytes,l=Co<<BigInt(o.BYTES*8)-Io;function d(I){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(I)}const u=r.uvRatio===void 0?(I,v)=>{try{return{isValid:!0,value:o.sqrt(o.div(I,v))}}catch{return{isValid:!1,value:ko}}}:r.uvRatio;if(!Q0(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,v,k=!1){const B=k?Io:ko;return Un("coordinate "+I,v,B,l),v}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(v,k,B,R){this.X=h("x",v),this.Y=h("y",k),this.Z=h("z",B,!0),this.T=h("t",R),Object.freeze(this)}static CURVE(){return i}static fromAffine(v){if(v instanceof m)throw new Error("extended point not allowed");const{x:k,y:B}=v||{};return h("x",k),h("y",B),new m(k,B,o.ONE,o.mul(k,B))}static fromBytes(v,k=!1){const B=o.BYTES,{a:R,d:N}=i;v=Xn(Hr(v,B,"point")),$s(k,"zip215");const A=Xn(v),x=v[B-1];A[B-1]=x&-129;const S=us(A),T=k?l:o.ORDER;Un("point.y",S,ko,T);const P=o.sqr(S),b=o.sub(P,o.ONE),E=o.sub(o.mulN(N,P),R);let{isValid:C,value:L}=u(b,E);if(!C)throw new Error("bad point: invalid y coordinate");const M=d(L),$=(x&128)!==0;if(!k&&o.is0(L)&&$)throw new Error("bad point: x=0 and x_0=1");return $!==M&&(L=o.neg(L)),m.fromAffine({x:L,y:S})}static fromHex(v,k=!1){return m.fromBytes(x0(v),k)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=6,k=!0){return w.setWindowSize(this,v),k||this.multiply(Co),this}assertValidity(){const v=this,{a:k,d:B}=i;if(v.is0())throw new Error("bad point: ZERO");const{X:R,Y:N,Z:A,T:x}=v,S=o.sqr(R),T=o.sqr(N),P=o.sqr(A),b=o.sqr(P),E=o.mul(S,k),C=o.mul(o.add(E,T),P),L=o.add(b,o.mul(B,o.mul(S,T)));if(!o.eql(C,L))throw new Error("bad point: equation left != right (1)");const M=o.mul(R,N),$=o.mul(A,x);if(!o.eql(M,$))throw new Error("bad point: equation left != right (2)")}equals(v){g(v);const{X:k,Y:B,Z:R}=this,{X:N,Y:A,Z:x}=v,S=o.mul(k,x),T=o.mul(N,R),P=o.mul(B,x),b=o.mul(A,R);return o.eql(S,T)&&o.eql(P,b)}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:v,Y:k,Z:B}=this,R=o.sqr(v),N=o.sqr(k),A=o.mul(o.sqr(B),Co),x=f(R),S=o.addN(v,k),T=o.sub(o.subN(o.sqr(S),R),N),P=o.addN(x,N),b=o.subN(P,A),E=o.subN(x,N),C=o.mul(T,b),L=o.mul(P,E),M=o.mul(T,E),$=o.mul(b,P);return new m(C,L,$,M)}add(v){g(v);const{d:k}=i,{X:B,Y:R,Z:N,T:A}=this,{X:x,Y:S,Z:T,T:P}=v,b=o.mul(B,x),E=o.mul(R,S),C=o.mul(o.mulN(A,k),P),L=o.mul(N,T),M=o.sub(o.subN(o.mulN(o.addN(B,R),o.addN(x,S)),b),E),$=o.subN(L,C),j=o.addN(L,C),D=o.sub(E,f(b)),_=o.mul(M,$),O=o.mul(j,D),q=o.mul(M,D),H=o.mul($,j);return new m(_,O,H,q)}subtract(v){return g(v),this.add(v.negate())}multiply(v){if(!s.isValidNot0(v))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");const{p:k,f:B}=w.mulSecret(this,v,a,y);return y([k,B])[0]}multiplyUnsafe(v){if(!s.isValid(v))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return v===ko?m.ZERO:this.is0()||v===Io?this:w.mulUnsafe(this,v,y)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.mulUnsafe(this,i.n).is0()}toAffine(v){const k=this;let B=v;if(B!=null&&typeof B!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof B);const{X:R,Y:N,Z:A}=k,x=k.is0();B==null&&(B=x?o.create(Jl):o.inv(A));const S=o.mul(R,B),T=o.mul(N,B),P=o.mul(A,B);if(x)return{x:o.ZERO,y:o.ONE};if(!o.eql(P,o.ONE))throw new Error("invZ was invalid");return{x:S,y:T}}clearCofactor(){return a===Io?this:a===Co?this.double():a===J0?this.double().double():a===Jl?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){const{x:v,y:k}=this.toAffine(),B=o.toBytes(k);return B[B.length-1]|=d(v)?128:0,B}toHex(){return v0(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const y=I=>j0(m,I),w=new G0(m,c);return w.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}const Xt=BigInt(0),We=BigInt(1),Ro=BigInt(2);function Ql(t,e){return t+e-(e>>We<<We)}function tv(t){const e=BigInt(6)*t;return(r,n,o)=>{const s=n+o,a=((e+o-n)*r+n)%t;return{x_2:a,x_3:s-a}}}function rv(t){return fs(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...t})}function nv(t){const e=rv(t),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=e.scalarMultBase,c=n==="x25519";if(!c&&n!=="x448")throw new Error("invalid type");const l=i===void 0?lh:i,d=c?255:448,u=tv(r),f=c?32:56,h=BigInt(c?9:5),g=BigInt(c?121665:39081),m=c?Ro**BigInt(254):Ro**BigInt(447),y=c?BigInt(8)*(Ro**BigInt(251)-We):BigInt(4)*(Ro**BigInt(445)-We),w=m+y+We,I=L=>ie(L,r),v=k(h);function k(L){return hh(I(L),f)}function B(L){const M=Xn(Hr(L,f,"uCoordinate"));return c&&(M[31]&=127),I(us(M))}function R(L){return us(o(Xn(Hr(L,f,"scalar"))))}const N=new Set(c?[Xt,We,r-We,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[Xt,We,r-We]);function A(L,M){const $=B(M);if(N.has($))throw new Error("invalid private or public key received");const j=P($,R(L));if(j===Xt)throw new Error("invalid private or public key received");return k(j)}function x(L){if(a===void 0)return A(L,v);const M=R(L);Un("scalar",M,m,w);const $=I(a(M));if($===Xt)throw new Error("invalid private or public key received");return k($)}const S=x,T=A;function P(L,M){Un("u",L,Xt,r),Un("scalar",M,m,w);const $=M,j=L;let D=We,_=Xt,O=L,q=We;const H=$^$>>We;for(let V=BigInt(d-1);V>=Xt;V--){const X=Ql(r,H>>V);({x_2:D,x_3:O}=u(X,D,O)),{x_2:_,x_3:q}=u(X,_,q);const G=D+_,Y=I(G*G),se=D-_,Ne=I(se*se),Me=Y-Ne,oe=O+q,ot=O-q,vr=I(ot*G),Tt=I(oe*se),Ze=vr+Tt,fo=vr-Tt;O=I(Ze*Ze),q=I(j*I(fo*fo)),D=I(Y*Ne),_=I(Me*(Y+I(g*Me)))}const K=Ql(r,$);({x_2:D,x_3:O}=u(K,D,O)),{x_2:_,x_3:q}=u(K,_,q);const z=s(_);return I(D*z)}const b={secretKey:f,publicKey:f,seed:f},E=L=>(L=L===void 0?l(f):L,Hr(L,b.seed,"seed"),L),C={randomSecretKey:E};return Object.freeze(b),Object.freeze(C),Object.freeze({keygen:Z0(E,S),getSharedSecret:T,getPublicKey:S,scalarMult:A,scalarMultBase:x,utils:C,GuBytes:v.slice(),lengths:b})}const ed=BigInt(0),ov=BigInt(1),td=BigInt(2),sv=BigInt(3),iv=BigInt(5),av=BigInt(8),Hs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),cv={p:Hs,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:av,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ah(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=Hs,a=t*t%s*t%s,c=et(a,td,s)*a%s,l=et(c,ov,s)*t%s,d=et(l,iv,s)*l%s,u=et(d,e,s)*d%s,f=et(u,r,s)*u%s,h=et(f,n,s)*f%s,g=et(h,o,s)*h%s,m=et(g,o,s)*h%s,y=et(m,e,s)*d%s;return{pow_p_5_8:et(y,td,s)*t%s,b2:a}}function lv(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const rd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function dv(t,e){const r=Hs,n=ie(e*e*e,r),o=ie(n*n*e,r),s=Ah(t*o).pow_p_5_8;let i=ie(t*n*s,r);const a=ie(e*i*i,r),c=i,l=ie(i*rd,r),d=a===t,u=a===ie(-t,r),f=a===ie(-t*rd,r);return d&&(i=c),(u||f)&&(i=l),_0(i,r)&&(i=ie(-i,r)),{isValid:d||u,value:i}}const nd=ev(cv,{uvRatio:dv}),To=(()=>{const t=Hs,e=r=>{const{pow_p_5_8:n,b2:o}=Ah(r);return ie(et(n,sv,t)*o,t)};return nv({P:t,type:"x25519",powPminus2:e,adjustScalarBytes:lv,scalarMultBase:r=>{const n=ie(r,nd.Fn.ORDER);if(n===ed)return ed;const o=nd.BASE.multiply(n);return ie((o.Z+o.Y)*e(ie(o.Z-o.Y,t)),t)}})})();class od{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(Ac(e),Rt(r,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 n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);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),or(o)}update(e){return ls(this),this.iHash.update(e),this}digestInto(e){ls(this),nh(e,this),this.finished=!0;const r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),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:r,iHash:n,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=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const kh=(()=>{const t=((e,r,n)=>new od(e,r).update(n).digest());return t.create=(e,r)=>new od(e,r),t})();function sd(){const t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}class id{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 id(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 r=this.head;this.head=r.next=new id(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){const r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}class uv extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}}function fv(t={}){return hv(r=>{const n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function hv(t,e){e=e??{};let r=e.onEnd,n=new yi,o,s,i,a=sd();const c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,w)=>{s=I=>{s=null,n.push(I);try{y(t(n))}catch(v){w(v)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=sd()})}},l=y=>s!=null?s(y):(n.push(y),o),d=y=>(n=new yi,s!=null?s({error:y}):(n.push({error:y}),o)),u=y=>{if(i)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},f=y=>i?o:(i=!0,y!=null?d(y):l({done:!0})),h=()=>(n=new yi,f(),{done:!0}),g=y=>(f(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:g,push:u,end:f,get readableLength(){return n.size},onEmpty:async y=>{const w=y?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let I,v;w!=null&&(I=new Promise((k,B)=>{v=()=>{B(new uv)},w.addEventListener("abort",v)}));try{await Promise.race([a.promise,I])}finally{v!=null&&w!=null&&w?.removeEventListener("abort",v)}}},r==null)return o;const m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:u,end(y){return m.end(y),r!=null&&(r(y),r=void 0),o},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},o}class Lc extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,Lc)}}const ad=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function pv(t,e){const{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e;let a,c;const d=new Promise((u,f)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){f(ad(i));return}if(i&&(c=()=>{f(ad(i))},i.addEventListener("abort",c,{once:!0})),t.then(u,f),r===Number.POSITIVE_INFINITY)return;const h=new Lc;a=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}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 ${r} milliseconds`,f(h))},r)}).finally(()=>{d.clear(),c&&i&&i.removeEventListener("abort",c)});return d.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},d}const gv=t=>{const e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function mv(t,e,r){let n;const o=new Promise((s,i)=>{if(r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();const a=[e].flat(),c=[],{addListener:l,removeListener:d}=gv(t),u=async(...h)=>{const g=r.multiArgs?h:h[0];if(r.filter)try{if(!await r.filter(g))return}catch(m){n(),i(m);return}c.push(g),r.count===c.length&&(n(),s(c))},f=(...h)=>{n(),i(r.rejectionMultiArgs?h:h[0])};n=()=>{for(const h of a)d(h,u);for(const h of r.rejectionEvents)a.includes(h)||d(h,f)};for(const h of a)l(h,u);for(const h of r.rejectionEvents)a.includes(h)||l(h,f);r.signal&&r.signal.addEventListener("abort",()=>{f(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){const s=pv(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function wv(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};const n=mv(t,e,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}class ps extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class yv extends Error{static name="StreamClosedError";name="StreamClosedError"}function bv(t){return t.reason}function Ih(t,e,r){if(e==null||t==null)return t;const n=bv;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let o;return Promise.race([t,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}const vv=Math.pow(2,20)*4;class Ch extends Lg{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??vv,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new ne,this.writeBuffer=new ne,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);const r=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);const n=o=>{this.onDrainPromise?.reject(o.error??new yv)};this.addEventListener("close",n)}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()),Ih(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;const e=fv(),r=s=>{e.push(s.data)};this.addEventListener("message",r);const n=s=>{e.end(s.error)};this.addEventListener("close",n);const o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new wn(`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(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new Zb(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new wn("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 wn("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 wn(`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 wn(`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 Xb;this.dispatchEvent(new Jb(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 Ec))}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 r=this.writeBuffer.byteLength;let n=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 ne(s);this.writeBuffer.consume(s.byteLength);const a=this.sendData(s);if(e=a.canSendMore,n+=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",n,r,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 Yb(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 Hl(`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 Hl(`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 xv=4194304;class cd extends Error{static name="UnwrappedError";name="UnwrappedError"}class Rh extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class Sv extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class Ev extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function Av(t){return typeof t?.closeRead=="function"}function kv(t){return typeof t?.close=="function"}function bi(t){return Av(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:kv(t)?t.status!=="open":!1}function Iv(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function Cv(t,e){const r=e?.maxBufferSize??xv,n=new ne;let o,s=!1;if(!Iv(t))throw new rh("Argument should be a Stream or a Multiaddr");const i=d=>{if(n.append(d.data),n.byteLength>r){const u=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${u} > ${r}`))}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:n,async read(d){if(s===!0)throw new cd("Stream was unwrapped");if(bi(t)){if(d?.bytes==null)return null;if(n.byteLength<d.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,d.bytes),new ps(`Unexpected EOF - stream closed after reading ${n.byteLength}/${d.bytes} bytes`)}const u=d?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=u){o.resolve();break}if(await Ih(o.promise,d?.signal),bi(t)){if(n.byteLength===0&&d?.bytes==null)return null;break}o=Promise.withResolvers()}const f=d?.bytes??n.byteLength;if(n.byteLength<f){if(bi(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,f),new ps(`Unexpected EOF - stream closed while reading ${n.byteLength}/${f} bytes`);return l.read(d)}const h=n.sublist(0,f);return n.consume(f),h},async write(d,u){if(s===!0)throw new cd("Stream was unwrapped");t.send(d)||await wv(t,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",i),t.removeEventListener("close",a),t.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.push(n))),t}};return l}function ld(t,e={}){const r=Cv(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=gr(e.maxDataLength));const n=e?.lengthDecoder??Of,o=e?.lengthEncoder??By;return{async read(i){let a=-1;const c=new ne;for(;;){const d=await r.read({...i,bytes:1});if(d==null)break;c.append(d);try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Rh("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Ev(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Sv(`Message length too long - ${a} > ${e.maxDataLength}`);const l=await r.read({...i,bytes:a});if(l==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new ps(`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 ps(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await r.write(new ne(o(i.byteLength),i),a)},async writeV(i,a){const c=new ne(...i.flatMap(l=>[o(l.byteLength),l]));await r.write(c,a)},unwrap(){return r.unwrap()}}}const Rv=1024*1024*4,Tv=1024*1024*4;class Pv{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new ne,this.maxBufferSize=e.maxBufferSize??Rv,this.maxDataLength=e.maxDataLength??Tv,this.lengthDecoder=e.lengthDecoder??Of,this.encodingLength=e.encodingLength??gr}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new rh(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let r;try{r=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(r<0||r>this.maxDataLength)throw new Rh("Invalid message length");const n=this.encodingLength(r),o=n+r;if(this.buffer.byteLength>=o){const s=this.buffer.sublist(n,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}}var Nv={};const Jn=65535,dd=Jn-16,lo=!!Nv?.DUMP_SESSION_KEYS,ud=16;function Ia(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const gs=t=>t?`"${t}" `:"";function Ca(t,e=""){if(typeof t!="boolean")throw new TypeError(gs(e)+"expected boolean, got type="+typeof t);return t}function Kr(t,e=""){if(typeof t!="number")throw new TypeError(gs(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(gs(e)+"expected integer >= 0, got "+t);return t}function ve(t,e,r=""){if(Ia(t)&&(e===void 0||t.length===e))return t;e!==void 0&&Kr(e,"length");const n=Ia(t),o=e!==void 0?` of length ${e}`:"",s=n?`length=${t.length}`:`type=${typeof t}`,i=gs(r)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}const fd=(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 hd(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function Lv(t,e){ve(t,void 0,"output");const r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function vt(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function qt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Bv(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const zr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function _v(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]=_v(t[e]);return t}const tr=zr?t=>t:Dv;function Ov(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 Fv(t,e){if(Ov(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function Mv(t,e){return fd(t,"defaults"),fd(e,"opts"),Object.assign(t,e)}function jv(t,e){if(t=ve(t),e=ve(e),t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Uv(t,e,r){const n=e,o=(()=>[]),s=(a,c)=>n(c,...o(a)).update(a).digest(),i=n(new Uint8Array(t),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>n(a,...c),s}const $v=(t,e)=>{function r(n,...o){if(ve(n,void 0,"key"),t.nonceLength!==void 0){const u=o[0];ve(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}const s=t.tagLength,i=t.nonceLength!==void 0?1:0;if(!t.withAAD){for(let u=i;u<o.length;u++)if(Ia(o[u]))throw new Error("AAD not supported")}t.withAAD&&o[i]!==void 0&&ve(o[i],void 0,"AAD");const a=e(n,...o),c=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");ve(f,void 0,"output")}};let l=!1;return{encrypt(u,f){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,ve(u,void 0,"data"),c(a.encrypt.length,f),a.encrypt(u,f)},decrypt(u,f){if(ve(u,void 0,"data"),s&&u.length<s)throw new Error('"ciphertext" expected length >= tagLength='+s);return c(a.decrypt.length,f),a.decrypt(u,f)}}}return Object.assign(r,t),r};function Ra(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(ve(e,t,"output"),r&&!ms(e))throw new Error("invalid output, must be aligned");return e}function Hv(t,e,r){Kr(t),Kr(e),Ca(r);const n=new Uint8Array(16),o=Bv(n);return o.setBigUint64(0,BigInt(e),r),o.setBigUint64(8,BigInt(t),r),n}function ms(t){return t.byteOffset%4===0}function ws(t){return Uint8Array.from(ve(t))}const Th=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),qv=tr(vt(Th("expand 16-byte k"))),Kv=tr(vt(Th("expand 32-byte k")));function ee(t,e){return t<<e|t>>>32-e}const yn=64,zv=16,Ta=2**32-1,pd=Uint32Array.of();function Wv(t,e,r,n,o,s,i,a){const c=o.length,l=new Uint8Array(yn),d=vt(l),u=zr&&ms(o)&&ms(s),f=u?vt(o):pd,h=u?vt(s):pd;if(!zr){for(let g=0;g<c;i++){if(t(e,r,n,d,i,a),tr(d),i>=Ta)throw new Error("arx: counter overflow");const m=Math.min(yn,c-g);for(let y=0,w;y<m;y++)w=g+y,s[w]=o[w]^l[y];g+=m}return}for(let g=0;g<c;i++){if(t(e,r,n,d,i,a),i>=Ta)throw new Error("arx: counter overflow");const m=Math.min(yn,c-g);if(u&&m===yn){const y=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,I;w<zv;w++)I=y+w,h[I]=f[I]^d[w];g+=yn;continue}for(let y=0,w;y<m;y++)w=g+y,s[w]=o[w]^l[y];g+=m}}function Vv(t,e){const{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Mv({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Kr(o),Kr(i),Ca(s),Ca(r),(a,c,l,d,u=0)=>{ve(a,void 0,"key"),ve(c,void 0,"nonce"),ve(l,void 0,"data");const f=l.length,h=d!==void 0;if(d=Ra(f,d,!1),h&&Fv(l,d),Kr(u),u<0||u>=Ta)throw new Error("arx: counter overflow");const g=[];let m=a.length,y,w;if(m===32)g.push(y=ws(a)),w=Kv;else if(m===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),w=qv,g.push(y);else throw ve(a,32,"arx key"),new Error("invalid key size");(!zr||!ms(c))&&g.push(c=ws(c));let I=vt(y);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");const B=c.subarray(0,16);if(zr)n(w,I,vt(B),I);else{const R=tr(Uint32Array.from(w));n(R,I,vt(B),I),qt(R),tr(I)}c=c.subarray(16)}else zr||tr(I);const v=16-o;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){const B=new Uint8Array(12);B.set(c,s?0:12-c.length),c=B,g.push(c)}const k=tr(vt(c));try{return Wv(t,w,I,k,l,d,u,i),d}finally{qt(...g)}}}function Se(t,e){return t[e++]&255|(t[e++]&255)<<8}class Gv{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=ws(ve(e,32,"key"));const r=Se(e,0),n=Se(e,2),o=Se(e,4),s=Se(e,6),i=Se(e,8),a=Se(e,10),c=Se(e,12),l=Se(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>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]=Se(e,16+2*d)}process(e,r,n=!1){const o=n?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],y=i[9],w=Se(e,r+0),I=Se(e,r+2),v=Se(e,r+4),k=Se(e,r+6),B=Se(e,r+8),R=Se(e,r+10),N=Se(e,r+12),A=Se(e,r+14);let x=s[0]+(w&8191),S=s[1]+((w>>>13|I<<3)&8191),T=s[2]+((I>>>10|v<<6)&8191),P=s[3]+((v>>>7|k<<9)&8191),b=s[4]+((k>>>4|B<<12)&8191),E=s[5]+(B>>>1&8191),C=s[6]+((B>>>14|R<<2)&8191),L=s[7]+((R>>>11|N<<5)&8191),M=s[8]+((N>>>8|A<<8)&8191),$=s[9]+(A>>>5|o),j=0,D=j+x*a+S*(5*y)+T*(5*m)+P*(5*g)+b*(5*h);j=D>>>13,D&=8191,D+=E*(5*f)+C*(5*u)+L*(5*d)+M*(5*l)+$*(5*c),j+=D>>>13,D&=8191;let _=j+x*c+S*a+T*(5*y)+P*(5*m)+b*(5*g);j=_>>>13,_&=8191,_+=E*(5*h)+C*(5*f)+L*(5*u)+M*(5*d)+$*(5*l),j+=_>>>13,_&=8191;let O=j+x*l+S*c+T*a+P*(5*y)+b*(5*m);j=O>>>13,O&=8191,O+=E*(5*g)+C*(5*h)+L*(5*f)+M*(5*u)+$*(5*d),j+=O>>>13,O&=8191;let q=j+x*d+S*l+T*c+P*a+b*(5*y);j=q>>>13,q&=8191,q+=E*(5*m)+C*(5*g)+L*(5*h)+M*(5*f)+$*(5*u),j+=q>>>13,q&=8191;let H=j+x*u+S*d+T*l+P*c+b*a;j=H>>>13,H&=8191,H+=E*(5*y)+C*(5*m)+L*(5*g)+M*(5*h)+$*(5*f),j+=H>>>13,H&=8191;let K=j+x*f+S*u+T*d+P*l+b*c;j=K>>>13,K&=8191,K+=E*a+C*(5*y)+L*(5*m)+M*(5*g)+$*(5*h),j+=K>>>13,K&=8191;let z=j+x*h+S*f+T*u+P*d+b*l;j=z>>>13,z&=8191,z+=E*c+C*a+L*(5*y)+M*(5*m)+$*(5*g),j+=z>>>13,z&=8191;let V=j+x*g+S*h+T*f+P*u+b*d;j=V>>>13,V&=8191,V+=E*l+C*c+L*a+M*(5*y)+$*(5*m),j+=V>>>13,V&=8191;let X=j+x*m+S*g+T*h+P*f+b*u;j=X>>>13,X&=8191,X+=E*d+C*l+L*c+M*a+$*(5*y),j+=X>>>13,X&=8191;let G=j+x*y+S*m+T*g+P*h+b*f;j=G>>>13,G&=8191,G+=E*u+C*d+L*l+M*c+$*a,j+=G>>>13,G&=8191,j=(j<<2)+j|0,j=j+D|0,D=j&8191,j=j>>>13,_+=j,s[0]=D,s[1]=_,s[2]=O,s[3]=q,s[4]=H,s[5]=K,s[6]=z,s[7]=V,s[8]=X,s[9]=G}finalize(){const{h:e,pad:r}=this,n=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,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[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]+r[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+r[a]|0)+(i>>>16)|0,e[a]=i&65535;qt(n)}update(e){hd(this),ve(e),e=ws(e);const{buffer:r,blockLen:n}=this,o=e.length;for(let s=0;s<o;){const i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,qt(this.h,this.r,this.buffer,this.pad)}digestInto(e){hd(this),Lv(e,this),this.finished=!0;const{buffer:r,h:n}=this;let{pos:o}=this;if(o){for(r[o++]=1;o<16;o++)r[o]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}}const Xv=Uv(32,t=>new Gv(t));function Yv(t,e,r,n,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],y=e[6],w=e[7],I=o,v=r[0],k=r[1],B=r[2],R=i,N=a,A=c,x=l,S=d,T=u,P=f,b=h,E=g,C=m,L=y,M=w,$=I,j=v,D=k,_=B;for(let q=0;q<s;q+=2)R=R+S|0,$=ee($^R,16),E=E+$|0,S=ee(S^E,12),R=R+S|0,$=ee($^R,8),E=E+$|0,S=ee(S^E,7),N=N+T|0,j=ee(j^N,16),C=C+j|0,T=ee(T^C,12),N=N+T|0,j=ee(j^N,8),C=C+j|0,T=ee(T^C,7),A=A+P|0,D=ee(D^A,16),L=L+D|0,P=ee(P^L,12),A=A+P|0,D=ee(D^A,8),L=L+D|0,P=ee(P^L,7),x=x+b|0,_=ee(_^x,16),M=M+_|0,b=ee(b^M,12),x=x+b|0,_=ee(_^x,8),M=M+_|0,b=ee(b^M,7),R=R+T|0,_=ee(_^R,16),L=L+_|0,T=ee(T^L,12),R=R+T|0,_=ee(_^R,8),L=L+_|0,T=ee(T^L,7),N=N+P|0,$=ee($^N,16),M=M+$|0,P=ee(P^M,12),N=N+P|0,$=ee($^N,8),M=M+$|0,P=ee(P^M,7),A=A+b|0,j=ee(j^A,16),E=E+j|0,b=ee(b^E,12),A=A+b|0,j=ee(j^A,8),E=E+j|0,b=ee(b^E,7),x=x+S|0,D=ee(D^x,16),C=C+D|0,S=ee(S^C,12),x=x+S|0,D=ee(D^x,8),C=C+D|0,S=ee(S^C,7);let O=0;n[O++]=i+R|0,n[O++]=a+N|0,n[O++]=c+A|0,n[O++]=l+x|0,n[O++]=d+S|0,n[O++]=u+T|0,n[O++]=f+P|0,n[O++]=h+b|0,n[O++]=g+E|0,n[O++]=m+C|0,n[O++]=y+L|0,n[O++]=w+M|0,n[O++]=I+$|0,n[O++]=v+j|0,n[O++]=k+D|0,n[O++]=B+_|0}const Zv=Vv(Yv,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Jv=new Uint8Array(16),gd=(t,e)=>{t.update(e);const r=e.length%16;r&&t.update(Jv.subarray(r))},Qv=new Uint8Array(32);function md(t,e,r,n,o){o!==void 0&&ve(o,void 0,"AAD");const s=t(e,r,Qv),i=Hv(n.length,o?o.length:0,!0),a=Xv.create(s);o&&gd(a,o),gd(a,n),a.update(i);const c=a.digest();return qt(s,i),c}const ex=t=>(e,r,n)=>({encrypt(s,i){const a=s.length;i=Ra(a+16,i,!1),i.set(s);const c=i.subarray(0,-16);t(e,r,c,c,1);const l=md(t,e,r,c,n);return i.set(l,a),qt(l),i},decrypt(s,i){i=Ra(s.length-16,i,!1);const a=s.subarray(0,-16),c=s.subarray(-16),l=md(t,e,r,a,n);if(!jv(c,l))throw qt(l),new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,r,i,i,1),qt(l),i}}),wd=$v({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},ex(Zv));function tx(t,e,r){return Ac(t),r===void 0&&(r=new Uint8Array(t.outputLen)),kh(t,r,e)}const bn=Uint8Array.of(0),rx=Uint8Array.of();function nx(t,e,r,n=32,o){Ac(t),Ct(n,"length"),Rt(e,void 0,"prk");const s=t.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(n>255*s)throw new Error("Length must be <= 255*HashLen");const i=Math.ceil(n/s);if(r===void 0?r=rx:Rt(r,void 0,"info"),!i)return new Uint8Array;const a=new Uint8Array(i*s),{iHash:c,oHash:l}=kh.create(t,e),d=new Uint8Array(s),u=i>1?t.create():void 0;for(let h=0;h<i-1;h++){bn[0]=h+1;const g=c._cloneInto(u);h&&g.update(d),g.update(r).update(bn).digestInto(d),l._cloneInto(u).update(d).digestInto(d),a.set(d,s*h)}if(bn[0]=i,i>1&&c.update(d),c.update(r).update(bn).digestInto(d),l.update(d).digestInto(d),a.set(d,s*(i-1)),c.destroy(),l.destroy(),u?.destroy(),d!==a&&or(d),or(bn),n===a.length)return a;const f=a.slice(0,n);return or(a),f}const Ph={hashSHA256(t){return gi(t.subarray())},getHKDF(t,e){const r=tx(gi,e,t),o=nx(gi,r,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=To.utils.randomSecretKey();return{publicKey:To.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:To.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return To.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,r,n){return wd(n,e,r).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,r,n,o){return wd(n,e,r).decrypt(t.subarray(),o)}},ox=Ph;function sx(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,r)=>t.generateX25519SharedKey(e.privateKey,r).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}const ys=t=>{const e=kt(2);return e[0]=t>>8,e[1]=t,e};ys.bytes=2;const bs=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)};bs.bytes=2;function ix(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 Nh(t,e){!e.enabled||!lo||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${Q(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${Q(t.privateKey,"hex")}`)):e("Missing local static keys."))}function Lh(t,e){!e.enabled||!lo||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${Q(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${Q(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function ax(t,e){!e.enabled||!lo||e(t?`REMOTE_STATIC_PUBLIC_KEY ${Q(t.subarray(),"hex")}`:"Missing remote static public key.")}function Bh(t,e){!e.enabled||!lo||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${Q(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function _h(t,e,r){!r.enabled||!lo||(r(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&Q(t.k,"hex")}`),r(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&Q(e.k,"hex")}`))}class $n extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=$n.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}const cx=0,lx=4294967295,dx="Cipherstate has reached maximum n, a new handshake must be performed";class ux{n;bytes;view;constructor(e=cx){this.n=e,this.bytes=De(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>lx)throw new Error(dx)}}const Wr=De(0);class Po{k;n;crypto;constructor(e,r=void 0,n=0){this.crypto=e,this.k=r,this.n=new ux(n)}hasKey(){return!!this.k}encryptWithAd(e,r){if(!this.hasKey())return r;this.n.assertValue();const n=this.crypto.encrypt(r,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,r,n){if(!this.hasKey())return r;this.n.assertValue();const o=this.crypto.decrypt(r,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}}class fx{cs;ck;h;crypto;constructor(e,r){this.crypto=e;const n=we(r,"utf-8");this.h=px(e,n),this.ck=this.h,this.cs=new Po(e)}mixKey(e){const[r,n]=this.crypto.hkdf(this.ck,e);this.ck=r,this.cs=new Po(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new ne(this.h,e))}encryptAndHash(e){const r=this.cs.encryptWithAd(this.h,e);return this.mixHash(r),r}decryptAndHash(e){const r=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),r}split(){const[e,r]=this.crypto.hkdf(this.ck,Wr);return[new Po(this.crypto,e),new Po(this.crypto,r)]}}class hx{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:r,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=r,this.ss=new fx(r,n),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,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<r+32)throw new Error("message is not long enough");this.re=e.sublist(r,r+32),this.ss.mixHash(this.re)}readS(e,r=0){if(this.rs)throw new Error("remote static public key is already set");const n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<r+n)throw new Error("message is not long enough");const o=e.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class Dh extends hx{writeMessageA(e){return new ne(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const r=this.writeE();this.writeEE();const n=this.writeS();return this.writeES(),new ne(r,n,this.ss.encryptAndHash(e))}writeMessageC(e){const r=this.writeS();return this.writeSE(),new ne(r,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(r){throw new $n(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();const r=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+r))}catch(r){throw new $n(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(e){try{const r=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(r))}catch(r){throw new $n(`handshake stage 2 validation fail: ${r.message}`)}}}function px(t,e){if(e.length<=32){const r=De(32);return r.set(e),r}else return t.hash(e)}var vs;(function(t){let e;t.codec=()=>(e==null&&(e=js((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.webtransportCerthashes!=null)for(const s of r.webtransportCerthashes)n.uint32(10),n.bytes(s);if(r.streamMuxers!=null)for(const s of r.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{const s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?r.len:r.pos+n;for(;r.pos<i;){const a=r.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new Ml('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(r.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new Ml('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(r.string());break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ms(r,t.codec()),t.decode=(r,n)=>Fs(r,t.codec(),n)})(vs||(vs={}));var xs;(function(t){let e;t.codec=()=>(e==null&&(e=js((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.identityKey!=null&&r.identityKey.byteLength>0&&(n.uint32(10),n.bytes(r.identityKey)),r.identitySig!=null&&r.identitySig.byteLength>0&&(n.uint32(18),n.bytes(r.identitySig)),r.extensions!=null&&(n.uint32(34),vs.codec().encode(r.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{const s={identityKey:De(0),identitySig:De(0)},i=n==null?r.len:r.pos+n;for(;r.pos<i;){const a=r.uint32();switch(a>>>3){case 1:{s.identityKey=r.bytes();break}case 2:{s.identitySig=r.bytes();break}case 4:{s.extensions=vs.codec().decode(r,r.uint32(),{limits:o.limits?.extensions});break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ms(r,t.codec()),t.decode=(r,n)=>Fs(r,t.codec(),n)})(xs||(xs={}));async function Oh(t,e,r){const n=await t.sign(Mh(e));return xs.encode({identityKey:Us(t.publicKey),identitySig:n,extensions:r})}async function Fh(t,e,r){try{const n=xs.decode(t),o=Sa(n.identityKey);if(r?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${r}`);if(!e)throw new Error("Remote static does not exist");const s=Mh(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new kg(n.message)}}function Mh(t){const e=we("noise-libp2p-static-key:");return t instanceof Uint8Array?ua([e,t],e.length+t.length):(t.prepend(e),t)}class gx extends Ch{stream;handshake;metrics;decoder;constructor(e,r,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=r,this.metrics=n,this.decoder=new Pv({lengthDecoder:bs,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 r=new ne;for(let n=0;n<e.byteLength;n+=dd){let o=n+dd;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),r.append(ys(s.byteLength)),r.append(s)}return r}decrypt(e){const r=new ne;for(let n=0;n<e.byteLength;n+=Jn){let o=n+Jn;if(o>e.byteLength&&(o=e.byteLength),o-ud<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);const i=e.subarray(n,o-ud);try{const a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),r.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return r}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}}function yd(t,e,r){return new gx(t,e,r)}async function mx(t,e){const{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Oh(s,a.publicKey,l),u=new Dh({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Nh(u.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(u.writeMessageA(Wr),e),r.trace("Stage 0 - Initiator finished sending first message."),Lh(u.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");const f=u.readMessageB(await n.read(e));r.trace("Stage 1 - Initiator received the message."),Bh(u.re,r),ax(u.rs,r),r.trace("Initiator going to check remote's signature...");const h=await Fh(f,u.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(u.writeMessageC(d),e),r.trace("Stage 2 - Initiator sent message with signed payload.");const[g,m]=u.ss.split();return _h(g,m,r),{payload:h,encrypt:y=>g.encryptWithAd(Wr,y),decrypt:(y,w)=>m.decryptWithAd(Wr,y,w)}}async function wx(t,e){const{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Oh(s,a.publicKey,l),u=new Dh({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Nh(u.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await n.read(e)),r.trace("Stage 0 - Responder received first message."),Bh(u.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(u.writeMessageB(d),e),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Lh(u.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");const f=u.readMessageC(await n.read(e));r.trace("Stage 2 - Responder received the message, finished handshake.");const h=await Fh(f,u.rs,c),[g,m]=u.ss.split();return _h(g,m,r),{payload:h,encrypt:y=>m.encryptWithAd(Wr,y),decrypt:(y,w)=>g.decryptWithAd(Wr,y,w)}}class yx{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,r={}){const{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=r,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");const c=s??ox;this.crypto=sx(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?ix(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??De(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Bg]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,r){const n=e.log?.newScope("noise")??this.log,o=ld(e,{lengthEncoder:ys,lengthDecoder:bs,maxDataLength:Jn}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=Sa(s.payload.identityKey);return{connection:yd(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Jr(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;const r=this.components.upgrader.getStreamMuxers();if(r!=null)for(const n of e){const o=r.get(n);if(o!=null)return o}if(e.length)throw new Ig("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,r){const n=e.log?.newScope("noise")??this.log,o=ld(e,{lengthEncoder:ys,lengthDecoder:bs,maxDataLength:Jn}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=Sa(s.payload.identityKey);return{connection:yd(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Jr(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,r,n,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await mx({connection:e,privateKey:r,remoteIdentityKey:o,log:n.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,r,n,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await wx({connection:e,privateKey:r,remoteIdentityKey:o,log:n.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 bx(t={}){return e=>new yx(e,t)}const vx="termdock-e2ee-v1",Pa=3600*1e3,bd=512*1024*1024,Na=4*1024*1024,$o=()=>{},qs=Object.assign($o,{enabled:!1,error:$o,trace:$o,newScope:()=>qs});Object.freeze(qs);async function jh(){const t=await Mb();return{privateKey:t,peerId:Jr(t.publicKey).toString()}}function xx(t){return btoa(String.fromCharCode(...$b(t.privateKey)))}function vd(t){if(t.length>512||!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Invalid identity encoding");const e=Ub(Uint8Array.from(atob(t),r=>r.charCodeAt(0)));if(e.type!=="Ed25519")throw new Error("Only Ed25519 device identities are supported");return{privateKey:e,peerId:Jr(e.publicKey).toString()}}class Uh{constructor(e=$o){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>Na)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(r=>{this.wake=r})}}}}class Sx extends Ch{constructor(e,r){super({log:qs,direction:r?"outbound":"inbound",maxReadBufferLength:Na,maxWriteBufferLength:Na}),this.duplex=e,this.finished=e.sink(this.outgoing).catch(n=>{this.abort(Qr(n))}),this.readTransport()}duplex;outgoing=new Uh(()=>this.onMuxerDrain());finished;async readTransport(){try{for await(const e of this.duplex.source)this.onData(e.slice());this.onTransportClosed()}catch(e){this.onTransportClosed(Qr(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 Qr(t){return t instanceof Error?t:new Error("Secure transport failed")}class Ex extends Error{code="E2EE_REHANDSHAKE_REQUIRED";constructor(){super("Encrypted connection lifetime reached; establish a new handshake without replaying pending input")}}function Ax(t){const e=t?.maxAgeMs??Pa,r=t?.maxBytesPerDirection??bd;if(!Number.isSafeInteger(e)||e<=0||e>Pa||!Number.isSafeInteger(r)||r<=0||r>bd)throw new Error("Encrypted connection limits cannot exceed the production maximum");return{maxAgeMs:e,maxBytesPerDirection:r}}async function kx(t){const{identity:e,duplex:r,initiator:n,targetPinnedPeerId:o,signal:s}=t,i=Ax(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(n&&!o)throw new Error("A pinned target identity is required");const a=o?zb(o):void 0;if(a&&a.type!=="Ed25519")throw new Error("Only Ed25519 target identities are supported");if(e.peerId!==Jr(e.privateKey.publicKey).toString())throw new Error("Local identity mismatch");if(s?.aborted)throw s.reason??new Error("Connection aborted");const c=new Sx(r,n),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(Qr(s?.reason))};s?.addEventListener("abort",u,{once:!0}),c.addEventListener("close",()=>s?.removeEventListener("abort",u),{once:!0});const f=bx({crypto:Ph,prologueBytes:new TextEncoder().encode(vx)})({privateKey:e.privateKey,peerId:Jr(e.privateKey.publicKey),logger:{forComponent:()=>qs},upgrader:{getStreamMuxers:()=>new Map}});try{const h=await(n?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:Ix(h.connection,i)}}catch(h){throw c.abort(Qr(h)),h}finally{clearTimeout(d),s?.removeEventListener("abort",u)}}function Ix(t,e){const r=new Uh,n=performance.now(),o=Date.now();let s=0,i=0,a;const c=()=>(a??=new Ex,r.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()-n,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,r.push(f.data.subarray())}catch(h){t.abort(Qr(h))}}),t.addEventListener("close",f=>{clearTimeout(l),r.end(f.error)},{once:!0});let u=!1;return{source:r,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(Qr(h)),h}},close(f){f?t.abort(f):t.close()}}}const $h=1012,Hh="Encrypted transport renewed";class Bc{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(r=>{this.wake=r}),this.wake=void 0}}}const vi=2*1024*1024,Cx=new TextEncoder,Rx=new TextDecoder("utf-8",{fatal:!0});class Tx{constructor(e){this.duplex=e;const r=this;this.done=e.sink((async function*(){for await(const n of r.outgoing)try{yield n}finally{r.outgoingBytes-=n.byteLength}})()),this.done.catch(n=>this.close(n instanceof Error?n:new Error("Transport failed")))}duplex;outgoing=new Bc(256);outgoingBytes=0;get hasPendingWrites(){return this.outgoingBytes>0}done;send(e){const r=Cx.encode(JSON.stringify(e));if(r.length>vi)throw new Error("Record too large");const n=new Uint8Array(r.length+4);if(new DataView(n.buffer).setUint32(0,r.length),n.set(r,4),this.outgoingBytes+n.byteLength>4*1024*1024)throw new Error("Record queue byte budget exceeded");this.outgoingBytes+=n.byteLength;try{this.outgoing.push(n)}catch(o){throw this.outgoingBytes-=n.byteLength,o}}close(e){this.outgoing.end(e),this.duplex.close?.(e)}async*read(){let e=new Uint8Array(0);for await(const r of this.duplex.source){if(e.length+r.length>vi*2+8)throw new Error("Record buffer exceeded");const n=new Uint8Array(e.length+r.length);for(n.set(e),n.set(r,e.length),e=n;e.length>=4;){const o=new DataView(e.buffer,e.byteOffset,4).getUint32(0);if(o>vi||o===0)throw new Error("Invalid record size");if(e.length<o+4)break;const s=JSON.parse(Rx.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 qh(t){let e="";for(let r=0;r<t.length;r+=8192)e+=String.fromCharCode(...t.subarray(r,r+8192));return btoa(e)}function Kh(t){const e=atob(t);return Uint8Array.from(e,r=>r.charCodeAt(0))}function Px(t){const e=new Bc(64);t.binaryType="arraybuffer";const r=n=>{e.end(n),t.close(1e3)};return t.addEventListener("message",n=>{try{if(!(n.data instanceof ArrayBuffer)||n.data.byteLength>1024*1024)throw new Error("Invalid encrypted frame");e.push(new Uint8Array(n.data))}catch{r(new Error("Encrypted transport rejected frame"))}}),t.addEventListener("close",()=>e.end()),t.addEventListener("error",()=>e.end(new Error("Encrypted transport disconnected"))),{source:e,close:r,async sink(n){try{for await(const o of n)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 r(o instanceof Error?o:new Error("Encrypted transport failed")),o}}}}const zh=8,Wh=128,Nx=5*1024*1024,Lx=Wh+zh+8,Bx=256,No=3e4,vn=64*1024;function jt(t){return t instanceof Error?t:new Error(String(t??"Secure connection closed"))}function xd(t){if(!t.startsWith("/")||t.startsWith("//")||t.includes("#"))throw new Error("A local API path is required");return t}class Vh extends EventTarget{constructor(e,r,n){super(),this.url=e,this.transmit=r,this.disconnect=n}url;transmit;disconnect;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;binaryType="arraybuffer";bufferedAmount=0;protocol="termdock-e2ee-v1";extensions="";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;send(e){if(this.readyState!==1)throw new Error("Secure socket is not open");if(typeof e!="string"||new TextEncoder().encode(e).length>1024*1024)throw new Error("Unsupported socket payload");this.transmit(e)}close(e=1e3,r=""){this.readyState!==3&&(this.disconnect(),this.finish(e,r))}accept(e){if(this.readyState!==3)if(e.type==="ws-ready"){this.readyState=1;const r=new Event("open");this.dispatchEvent(r),this.onopen?.(r)}else if(e.type==="ws-data"&&typeof e.data=="string"){const r=new MessageEvent("message",{data:e.data});this.dispatchEvent(r),this.onmessage?.(r)}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(jt(e.error))}fail(e){if(this.readyState===3)return;const r=new Event("error");this.dispatchEvent(r),this.onerror?.(r),this.finish(1006,e.message)}finish(e,r){if(this.readyState===3)return;this.readyState=3;const n=new CloseEvent("close",{code:e,reason:r,wasClean:e===1e3});this.dispatchEvent(n),this.onclose?.(n)}}class _x{constructor(e,r,n){this.channel=e,this.identity=r,this.targetPeerId=n,this.read().catch(o=>this.close(jt(o))),e.done.catch(o=>this.close(jt(o)))}channel;identity;targetPeerId;establishedAt=performance.now();establishedWallTime=Date.now();lastInputAt=-1/0;pending=new Map;waiting=[];stopped=!1;closeReason;get canSwitchTransport(){return!this.channel.hasPendingWrites&&performance.now()-this.lastInputAt>=2e3&&![...this.pending.values()].some(e=>e.kind!=="socket")&&!this.waiting.some(e=>e.kind!=="socket")}get renewalDue(){return!this.stopped&&Math.max(performance.now()-this.establishedAt,Date.now()-this.establishedWallTime)>=Pa-5*6e4}get closed(){return this.stopped}hasCapacity(e){if(this.pending.size>=Lx)return!1;const r=[...this.pending.values()].filter(n=>n.kind===e).length;return e==="http"?r<zh:e==="socket"?r<Wh:!0}allocate(e){if(this.stopped)throw this.closeReason??new Error("Secure connection closed");const r=crypto.randomUUID(),n=new Bc(4);return this.pending.set(r,{queue:n,kind:e}),{id:r,queue:n}}reserve(e,r){return r?.aborted?Promise.reject(r.reason):this.stopped?Promise.reject(this.closeReason??new Error("Secure connection closed")):this.hasCapacity(e)?Promise.resolve(this.allocate(e)):this.waiting.length>=Bx?Promise.reject(new Error("连接繁忙,请稍后重试。")):new Promise((n,o)=>{const s=l=>{this.waiting=this.waiting.filter(d=>d!==c),c.cleanup(),o(l)},i=()=>s(r?.reason??new Error("Request aborted")),a=setTimeout(()=>s(new Error("连接等待超时,请重试。")),No),c={kind:e,resolve:n,reject:o,cleanup:()=>{clearTimeout(a),r?.removeEventListener("abort",i)}};this.waiting.push(c),r?.addEventListener("abort",i,{once:!0})})}dispatchWaiting(){if(!this.stopped)for(let e=0;e<this.waiting.length;){const r=this.waiting[e];if(!this.hasCapacity(r.kind)){e++;continue}this.waiting.splice(e,1),r.cleanup(),r.resolve(this.allocate(r.kind))}}async read(){try{for await(const e of this.channel.read()){const r=this.pending.get(e.id);r&&(r.socket?(r.socket.accept(e),(e.type==="ws-close"||e.type==="error")&&this.release(e.id)):(r.queue.push(e),(e.type==="end"||e.type==="error")&&(r.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,r){const{id:n,queue:o}=await this.reserve("request"),s=setTimeout(()=>this.close(new Error("Secure connection timed out")),Math.max(1e3,Math.min(No,r?.timeoutMs??No)));try{if(this.stopped)throw this.closeReason;this.channel.send({...e,id:n});const i=(await o[Symbol.asyncIterator]().next()).value;if(!i)throw new Error("Secure request closed");if(i.type==="error")throw jt(i.error);return i}finally{clearTimeout(s),this.release(n)}}openSocket(e){xd(e);let r;const n=new AbortController,o=new Vh(e,s=>{if(r){try{JSON.parse(s)?.type==="input"&&(this.lastInputAt=performance.now())}catch{}this.channel.send({id:r,type:"ws-data",data:s})}},()=>{if(n.abort(),r)try{this.channel.send({id:r,type:"ws-close"})}finally{this.release(r)}});return this.reserve("socket",n.signal).then(s=>{if(r=s.id,o.readyState===3){this.release(r);return}const i=this.pending.get(r);if(!i)throw new Error("Secure connection closed");i.socket=o,this.channel.send({id:r,type:"ws-open",path:e})}).catch(s=>{r&&this.release(r),o.fail(jt(s))}),o}async fetch(e,r){const n=typeof location>"u"?"https://termdock.invalid":location.origin,o=e instanceof Request?e:null,s=new URL(o?.url??String(e),n);if(s.origin!==n)throw new Error("Only current-service API requests are supported");const i=new Request(s,o?new Request(o,r):r),a=i.method.toUpperCase(),c=xd(s.pathname+s.search),l=s.pathname==="/api/terminal/fs/upload"?110*1024*1024:Nx;if(i.signal.aborted)throw i.signal.reason;const d={};i.headers.forEach((k,B)=>{["cookie","authorization","host","connection","content-length"].includes(B)||(d[B]=k)});const{id:u,queue:f}=await this.reserve("http",i.signal),h=f[Symbol.asyncIterator]();let g;const m=()=>{g?.cancel().catch(()=>{})},y=this.pending.get(u);if(!y)throw new Error("Secure connection closed");y.cancelUpload=m;const w=()=>{m();try{this.channel.send({id:u,type:"cancel"})}catch{}f.end(jt(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)},v=async()=>{let k;try{const B=(await Promise.race([h.next(),new Promise((R,N)=>{k=setTimeout(()=>N(new Error("服务响应超时,请重试。")),No)})])).value;if(!B)throw new Error("Secure response ended unexpectedly");if(B.type==="error")throw jt(B.error);return B}finally{clearTimeout(k)}};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 A=i.body.getReader();g=A;let x=0,S=0;try{for(;;){const{done:T,value:P}=await A.read();if(T)break;if(x+=P.byteLength,x>l)throw new Error("Request body exceeds upload limit");for(let b=0;b<P.byteLength;b+=vn){if(this.channel.send({id:u,type:"upload",data:qh(P.subarray(b,b+vn))}),(await v()).type!=="upload-ack")throw new Error("Invalid upload acknowledgement");S+=Math.min(vn,P.byteLength-b),r?.onUploadProgress?.(S)}}}catch(T){throw await A.cancel(T).catch(()=>{}),T}finally{g=void 0,A.releaseLock()}}if(i.signal.aborted||this.stopped)throw new Error("Request aborted");this.channel.send({id:u,type:"upload-end"});const k=await v();if(k.type!=="head"||typeof k.status!="number")throw new Error("Invalid response header");const B=new Headers(k.headers);if(a==="HEAD"||[204,205,304].includes(k.status)){if((await v()).type!=="end")throw new Error("Unexpected response body");return I(),new Response(null,{status:k.status,headers:B})}let R=!1;const N=new ReadableStream({pull:async A=>{try{R&&(this.channel.send({id:u,type:"ack"}),R=!1);const x=await v();if(x.type==="end"){A.close(),I();return}if(x.type!=="chunk"||typeof x.data!="string")throw new Error("Invalid response chunk");const S=Kh(x.data);if(S.length>vn)throw new Error("Response chunk exceeds budget");A.enqueue(S),R=!0}catch(x){A.error(x),w(),I()}},cancel:()=>{w(),I()}},{highWaterMark:vn,size:A=>A.byteLength});return new Response(N,{status:k.status,headers:B})}catch(k){throw w(),I(),k}}retire(){for(const e of this.pending.values())e.socket?.accept({id:"",type:"ws-close",code:$h,reason:Hh});this.close()}close(e=new Error("Secure connection closed")){if(!this.stopped){this.stopped=!0,this.closeReason=e;for(const r of this.waiting.splice(0))r.cleanup(),r.reject(e);for(const r of this.pending.values())r.queue.end(e),r.cancelUpload?.(),r.socket?.fail(e);this.pending.clear(),this.channel.close(e)}}}async function lr(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 r=t.identity??await jh(),n=(t.socketFactory??(c=>new WebSocket(c)))(e.href),o=Px(n),s=new AbortController,i=setTimeout(()=>s.abort(new Error("Secure handshake timed out")),2e4),a=t.signal?AbortSignal.any([t.signal,s.signal]):s.signal;try{await new Promise((d,u)=>{if(a.aborted){u(a.reason);return}const f=()=>{a.removeEventListener("abort",m),n.removeEventListener("open",h),n.removeEventListener("error",g),n.removeEventListener("close",g)},h=()=>{f(),d()},g=()=>{f(),u(new Error("Secure transport unavailable"))},m=()=>{f(),u(a.reason)};a.addEventListener("abort",m,{once:!0}),n.addEventListener("open",h),n.addEventListener("error",g),n.addEventListener("close",g),n.readyState===1&&h()});const c=await kx({identity:r,duplex:o,initiator:!0,targetPinnedPeerId:t.targetPeerId,signal:a}),l=new _x(new Tx(c.duplex),r,c.authenticatedPeerId);if(t.pairingCode)try{await l.request({type:"pair",code:t.pairingCode})}catch(d){throw l.close(jt(d)),d}return l}catch(c){throw n.close(),c}finally{clearTimeout(i)}}const Sd=256*1024,Dx=1024*1024;class Ox extends EventTarget{constructor(e,r,n=o=>new WebSocket(o)){if(super(),this.url=e,!/^[a-zA-Z0-9_.:-]{1,160}$/.test(r))throw new Error("Invalid target identity");this.upstream=n(e),this.deadline=setTimeout(()=>this.fail("Relay connection timed out"),2e4),this.upstream.addEventListener("message",o=>{if(this.readyState!==3)try{if(typeof o.data!="string"||new TextEncoder().encode(o.data).length>Sd)throw new Error("Invalid relay envelope");const s=JSON.parse(o.data);if(s.type==="ready"&&!this.requested){this.requested=!0,this.transmit({type:"open",streamId:this.streamId,serviceId:r});return}if(s.streamId!==this.streamId)return;if(s.type==="opened"&&this.readyState===0){clearTimeout(this.deadline),this.readyState=1;const l=new Event("open");this.dispatchEvent(l),this.onopen?.(l);return}if(s.type==="close"){this.finish(1001,"Relay route closed"),this.upstream.close();return}if(s.type!=="data"||this.readyState!==1||s.encoding!=="base64"||typeof s.payload!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(s.payload))throw new Error("Invalid ciphertext relay frame");const i=Kh(s.payload),a=this.binaryType==="blob"?new Blob([i]):i.buffer,c=new MessageEvent("message",{data:a});this.dispatchEvent(c),this.onmessage?.(c)}catch{this.fail("Relay protocol rejected frame")}}),this.upstream.addEventListener("close",o=>this.finish(o.code||1006,"Relay disconnected")),this.upstream.addEventListener("error",()=>this.fail("Relay transport unavailable"))}url;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;protocol="";extensions="";binaryType="arraybuffer";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;upstream;streamId=crypto.randomUUID();requested=!1;deadline;get bufferedAmount(){return this.upstream.bufferedAmount}transmit(e){const r=JSON.stringify(e);if(this.upstream.readyState!==1||this.upstream.bufferedAmount+r.length>Dx||r.length>Sd)throw new Error("Relay unavailable or congested");this.upstream.send(r)}send(e){if(this.readyState!==1)throw new Error("Relay socket is not open");let r;if(ArrayBuffer.isView(e))r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof ArrayBuffer)r=new Uint8Array(e);else throw new Error("Relay secure transport requires binary bytes");try{this.transmit({type:"data",streamId:this.streamId,encoding:"base64",payload:qh(r)})}catch(n){throw this.fail("Relay transport congested"),n}}close(e=1e3,r=""){if(this.readyState!==3){try{this.requested&&this.transmit({type:"close",streamId:this.streamId})}catch{}this.finish(e,r),this.upstream.close()}}fail(e){if(this.readyState===3)return;const r=new Event("error");this.dispatchEvent(r),this.onerror?.(r),this.finish(1006,e),this.upstream.close()}finish(e,r){if(this.readyState===3)return;clearTimeout(this.deadline),this.readyState=3;const n=new CloseEvent("close",{code:e,reason:r,wasClean:e===1e3});this.dispatchEvent(n),this.onclose?.(n)}}function Gh(t){return e=>new Ox(e,t)}function Fx(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 n=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 n.endsWith("/")&&!n.startsWith("/api/terminal/fs/preview/")?null:n}catch{return null}}function Mx(t){if(!("serviceWorker"in navigator))return()=>{};const e=new Set,r=n=>{if(n.source!==navigator.serviceWorker.controller||n.data?.type!=="termdock-secure-fetch"||n.ports.length!==1)return;const o=n.ports[0],{path:s,method:i,headers:a,body:c,expectedTargetPeerId:l,previewPrefix:d}=n.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)||!Fx(u.pathname)?.startsWith(d))){o.postMessage({type:"error"}),o.close();return}const f=new AbortController;let h,g,m=!1,y=!1;const w=()=>{y||(y=!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||y||(m=!0,(async()=>{if(!h){o.postMessage({type:"end"}),w();return}if(!g?.length){const k=await h.read();if(k.done){o.postMessage({type:"end"}),w();return}g=k.value}const v=g.slice(0,64*1024);g=g.subarray(v.length),o.postMessage({type:"chunk",data:v.buffer},[v.buffer])})().catch(()=>{o.postMessage({type:"error"}),w()}).finally(()=>{m=!1}))},o.onmessageerror=w,o.start(),(async()=>{const I=await t();if(y)return;if(l&&l!==I.targetPeerId)throw new Error("Preview target changed");const v=await I.fetch(u.pathname+u.search,{method:i,headers:a,body:["GET","HEAD"].includes(i)?void 0:c,signal:f.signal});if(y){await v.body?.cancel();return}h=v.body?.getReader();const k={};v.headers.forEach((B,R)=>{k[R]=B}),o.postMessage({type:"head",status:v.status,headers:k,bodyless:!h,targetPeerId:I.targetPeerId})})().catch(()=>{y||(o.postMessage({type:"error"}),w())})};return navigator.serviceWorker.addEventListener("message",r),()=>{navigator.serviceWorker.removeEventListener("message",r);for(const n of[...e])n()}}class Ge extends Error{constructor(){super("Device authorization expired or revoked")}}const Lo=new WeakMap;function an(t,e={}){const r=Lo.get(t);if(!t.closed&&r&&(!r.settled||Date.now()-r.at<(e.maxAgeMs??1e3)))return r.pending;const n={at:Date.now(),settled:!1,pending:void 0},o=jx(t,e.timeoutMs??5e3).then(s=>(n.at=Date.now(),n.settled=!0,s),s=>{throw Lo.get(t)===n&&Lo.delete(t),s});return n.pending=o,Lo.set(t,n),o}async function jx(t,e){const r=await t.request({type:"permissions"},{timeoutMs:e});if(r.type!=="result"||typeof r.fullService!="boolean"||!Array.isArray(r.grants))throw new Error("Invalid permission response");const n=r.grants,o=r.fullService===!0;if(!o&&n.length===0)throw new Ge;return{fullService:o,grants:n,canManage:o&&n.length>0||n.some(s=>s.actions.includes("authorization.manage"))}}const Xh="termdock-secure-last-path:",Ux=10*6e4;function Yh(t){try{const e=JSON.parse(sessionStorage.getItem(Xh+t)||"null");return e&&typeof e.key=="string"&&Date.now()-e.at<Ux?e.key:void 0}catch{return}}function La(t,e){try{sessionStorage.setItem(Xh+t,JSON.stringify({key:e,at:Date.now()}))}catch{}}function Zh(t,e,r=!1){return new Promise((n,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>=(r?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}})},y=new AbortController;d.add(y),i++,h.run(y.signal).then(w=>{if(m(!0),d.delete(y),a){e(w);return}a=!0,u(),n({value:w,key:h.key})},w=>{if(m(!1),d.delete(y),i--,!a){if(c=w,w instanceof Ge){a=!0,u(),o(w);return}f()}}),clearTimeout(l),!r&&s<t.length&&(l=setTimeout(f,400))};f()})}const Jh="termdock-workspace",Ba="termdock:workspace-visibility",_a="termdock:workspace-activate";function _c(){return window.parent!==window&&location.pathname==="/workspace.html"&&new URLSearchParams(location.search).get(Jh)||"root"}let Ed,Ad;function Et(){try{if(window.parent===window)return window.__termdockWorkspaceHost;const t=window.parent.__termdockWorkspaceHost;return t&&t!==Ed&&(Ed=t,Ad={...t,subscribe(e){const r=t.subscribe(e),n=o=>{o.persisted||r()};return window.addEventListener("pagehide",n),()=>{r(),window.removeEventListener("pagehide",n)}}}),t?Ad:void 0}catch{return}}function xi(){const t=Et();return!t||t.snapshot().activeKey===_c()}function Ss(t,e=!0){return Et()?.activate(t,e)??!1}function Ln(t){Et()?.report(_c(),t)}const Da="termdock-secure-workspace-session:";function Jk(t){if(t)try{const e=JSON.parse(localStorage.getItem(Da+t)||"null");return localStorage.removeItem(Da+t),e&&typeof e.sessionId=="string"&&Date.now()-e.at<6e4?e.sessionId:void 0}catch{return}}function $x(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 c=sessionStorage.getItem("termdock-secure-last-workspace"),l=t&&c!==t.targetPeerId?Kt().find(d=>d.targetPeerId===c):void 0;l?.targetPeerId&&(e={activeKey:l.targetPeerId,items:[...e.items,{key:l.targetPeerId,service:l,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]})}catch{}const r=new Set,n=new Map([["root",window]]),o=new Set,s=()=>{for(const c of[...r])c()},i=(c,l)=>{try{const d=l.document.createEvent("CustomEvent");if(d.initCustomEvent(Ba,!1,!1,{active:e.activeKey===c}),l.dispatchEvent(d),e.activeKey===c){const u=l.document.createEvent("Event");if(u.initEvent("resize",!1,!1),l.dispatchEvent(u),o.delete(c)){const f=l.document.createEvent("Event");f.initEvent(_a,!1,!1),l.dispatchEvent(f)}}else l.document.activeElement?.blur?.()}catch{}},a={snapshot:()=>e,subscribe:c=>(r.add(c),()=>{r.delete(c)}),activate(c,l=!0){const d=Ps(c);if(!d?.targetPeerId)return!1;const u=e.items.find(g=>g.service?.targetPeerId===d.targetPeerId),f=u?.key||d.targetPeerId,h=u?{...u,service:d,touchedAt:Date.now()}:{key:f,service:d,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()};e={activeKey:f,items:u?e.items.map(g=>g===u?h:g):[...e.items,h]};try{sessionStorage.setItem("termdock-secure-last-workspace",d.targetPeerId)}catch{}l&&o.add(f),s();for(const[g,m]of n)i(g,m);return!0},report(c,l){const d=e.items.find(f=>f.key===c);if(!d||l.service&&d.service?.targetPeerId&&l.service.targetPeerId!==d.service.targetPeerId)return;const u={...d,...l};JSON.stringify(u)!==JSON.stringify(d)&&(e={...e,items:e.items.map(f=>f===d?u:f)},s())},attach(c,l){l?(n.set(c,l),i(c,l)):n.delete(c)},focusSession(c,l){const d=Kt().find(f=>f.targetPeerId===c);if(!d)return!1;try{localStorage.setItem(Da+c,JSON.stringify({sessionId:l,at:Date.now()}))}catch{return!1}a.activate(d,!1);const u=n.get(e.activeKey);if(u){const f=u.document.createEvent("CustomEvent");f.initCustomEvent("termdock:workspace-session",!1,!1,null),u.dispatchEvent(f)}return!0}};return window.__termdockWorkspaceHost=a,a}let Si;async function Ye(){return Si||(Si=(async()=>{const t=await new Promise((e,r)=>{const n=indexedDB.open("termdock-device-identity",1);n.onupgradeneeded=()=>n.result.createObjectStore("keys"),n.onsuccess=()=>e(n.result),n.onerror=()=>r(n.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 vd(e);const r=await jh();let n=r;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"?n=vd(c.result):a.put(xx(r),"identity")},i.oncomplete=()=>o(),i.onerror=()=>s(i.error)}),n}finally{t.close()}})()),Si}const Wt="termdock:secure-state";let J,Pr,Be,en="direct",Ho=!1,kd=0,qo=!1,Id=-1/0;const tn=globalThis.fetch.bind(globalThis);function re(){return Or()}function xn(){return J}function Hx(){return Be}function Qh(){J?.close(),Be?.close(),J=void 0,Be=void 0}async function ep(){const t=await tn("/api/auth/status",{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error("Failed to query auth status");return t.json()}async function qx(){if(re()){await lt();return}if((await ep()).enabled)return;const t=await tn("/api/auth/open/parameters",{cache:"no-store"});if(!t.ok)throw new Error("Open service unavailable");const{serviceIdentity:e}=await t.json();if(typeof e!="string"||!e)throw new Error("Invalid service identity");await Ve({url:location.origin,targetPeerId:e,serviceName:location.hostname})}async function Kx(t,e){const{startPasswordBootstrap:r,finishPasswordBootstrap:n}=await Vt(async()=>{const{startPasswordBootstrap:l,finishPasswordBootstrap:d}=await import("./passwordBootstrap-Di4aP0lT.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 tn(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 Ye(),c=await r(e,i);try{const l=await s("/api/auth/password/start",{startLoginRequest:c.startLoginRequest,clientIdentity:a.peerId});let d;try{d=await n(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 Dc(t,e){const r=re();if(r&&(r.serviceOrigin||r.url)===t)return await Oa(r,e),r;try{return await Kx(t,e)}catch(n){if(!(n instanceof TypeError)&&!(n instanceof DOMException))throw n;const o=(await Xe()).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 Oa(s,e),s}}async function Oa(t,e){const r=await tp(t),{startPasswordBootstrap:n,finishPasswordBootstrap:o}=await Vt(async()=>{const{startPasswordBootstrap:i,finishPasswordBootstrap:a}=await import("./passwordBootstrap-Di4aP0lT.js");return{startPasswordBootstrap:i,finishPasswordBootstrap:a}},__vite__mapDeps([0,1,2,3]));let s;try{const i=await r.request({type:"password-parameters"},{timeoutMs:5e3});s=await n(e,String(i.saltHex));const a=await r.request({type:"password-start",startLoginRequest:s.startLoginRequest,origin:location.origin}),c=await o(s,a,{clientIdentity:(await Ye()).peerId,origin:location.origin});if(c.serverIdentity!==t.targetPeerId)throw new Error("服务身份发生变化。");await r.request({type:"password-finish",attemptId:c.attemptId,finishLoginRequest:c.finishLoginRequest})}catch{throw new Error("暂时无法登录,请检查目标服务密码与入口授权后重试。")}finally{s&&(s.passwordKey=""),r.close()}}async function zx(t){try{const e=re(),r=e?.serviceOrigin||location.origin,n=await Dc(r,t);return await Ve({...n,routes:e?.routes,serviceName:e?.serviceName||n.serviceName}),Response.json({ok:!0})}catch(e){return Response.json({error:e instanceof Error?e.message:"暂时无法登录,请重试。",code:"INVALID_PASSWORD"},{status:401})}}async function Cd(t,e){const r=_e(t),n=(await Xe()).find(i=>(i.serviceOrigin||i.url)===r&&i.targetPeerId);if(e===void 0&&n?.targetPeerId)try{return await Ve({...n,targetPeerId:n.targetPeerId,serviceName:n.label}),{}}catch(i){if(!(i instanceof Ge))throw i}if(e!==void 0){const i=await Dc(r,e);if(n?.targetPeerId&&n.targetPeerId!==i.targetPeerId)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await Ve({...i,routes:n?.routes,serviceName:n?.label||i.serviceName}),{}}const o=await tn(new URL("/api/auth/open/parameters",r).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(n?.targetPeerId&&n.targetPeerId!==s)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await Ve({url:r,targetPeerId:s,serviceName:n?.label||new URL(r).host,serviceOrigin:r}),{}}function dr(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 r=JSON.parse(localStorage.getItem(nc)||"null");r&&r.targetPeerId!==t.targetPeerId&&new URL(r.url).host===new URL(t.url).host&&e.push(r)}catch{}return e.flatMap((r,n)=>{try{return r.targetPeerId&&r.targetPeerId!==t.targetPeerId&&e.findIndex(o=>o.targetPeerId===r.targetPeerId)===n?[{url:_e(r.url),targetPeerId:r.targetPeerId}]:[]}catch{return[]}}).slice(0,4)}function uo(t){const e=dr(t),r=[t.serviceOrigin||t.url,...(t.routes||[]).slice(0,4).filter(o=>o.targetPeerId===t.targetPeerId).map(o=>o.url)],n=new Set;for(const o of r)try{const s=_e(o);e.some(i=>i.url===s)||n.add(s)}catch{}return[...n]}function ur(t){const e=new URL("/api/federation/secure",_e(t));return e.protocol=e.protocol==="https:"?"wss:":"ws:",e.href}async function Gt(t,e){return lr({url:ur(t.url),targetPeerId:t.targetPeerId,identity:await Ye(),signal:e?AbortSignal.any([e,AbortSignal.timeout(5e3)]):AbortSignal.timeout(5e3)})}async function tp(t,e){const r=await Ye(),n=uo(t).map(i=>({key:`direct:${i}`,run:a=>lr({url:ur(i),targetPeerId:t.targetPeerId,identity:r,signal:AbortSignal.any([a,AbortSignal.timeout(8e3),...e?[e]:[]])})}));for(const i of dr(t))n.push({key:`relay:${i.targetPeerId}:${i.url}`,run:async a=>{e&&(a=AbortSignal.any([a,e]));const c=[J,Be].find(d=>d&&!d.closed&&d.targetPeerId===i.targetPeerId),l=c||await Gt(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(ur(i.url));return u.pathname="/api/federation/relay",u.searchParams.set("routeToken",d.routeToken),await lr({url:u.href,targetPeerId:t.targetPeerId,identity:r,socketFactory:Gh(t.targetPeerId),signal:AbortSignal.any([a,AbortSignal.timeout(8e3)])})}finally{c||l.close()}}});const o=Yh(t.targetPeerId);n.sort((i,a)=>+(a.key===o)-+(i.key===o));const s=await Zh(n,i=>i.close());return La(t.targetPeerId,s.key),s.value}async function Wx(t,e){const r=await tp(t,e),n=()=>r.close();e.addEventListener("abort",n,{once:!0});try{if(e.aborted||(await an(r,{timeoutMs:3e3}),e.aborted))throw e.reason;return r}catch(o){throw r.close(),o}finally{e.removeEventListener("abort",n)}}async function Ve(t,e={}){const r=J,n=Be,o=await Ye(),s=_e(t.serviceOrigin||t.url),i=(await Xe()).find(w=>w.targetPeerId===t.targetPeerId),a={...t,routes:t.routes??i?.routes},c=dr(a),l=uo(a);let d,u,f=t.pairingCode,h="direct";const g=new Set,m=new Map,y=async(w,I)=>{if(r&&!r.closed&&r.targetPeerId===w.targetPeerId)return r;if(n&&!n.closed&&n.targetPeerId===w.targetPeerId)return n;const v=m.get(w.targetPeerId);if(v&&!v.closed)return v;const k=await Gt(w,I);return g.add(k),m.set(w.targetPeerId,k),k};try{if(t.routeCode&&t.entryServiceId){const A=c.find(T=>T.targetPeerId===t.entryServiceId);if(!A)throw new Error("邀请缺少入口信息。");if((await(await y(A)).request({type:"route-pair",code:t.routeCode})).serviceId!==t.targetPeerId)throw new Error("邀请的目标服务不一致。");t.routeOnly&&await At({id:t.targetPeerId,url:s,label:t.serviceName||new URL(s).host,targetPeerId:t.targetPeerId,serviceOrigin:s,routes:c})}const w=[],I=async(A,x)=>{const S=()=>A.close();x.addEventListener("abort",S,{once:!0});try{if(x.aborted||(await an(A),x.aborted))throw x.reason}catch(T){throw A.close(),T}finally{x.removeEventListener("abort",S)}};for(const A of l)w.push({key:`direct:${A}`,run:async x=>{const S=await lr({url:ur(A),targetPeerId:t.targetPeerId,pairingCode:f,identity:o,signal:AbortSignal.any([x,AbortSignal.timeout(8e3)])});return f=void 0,await I(S,x),{client:S,path:"direct"}}});for(const A of c)w.push({key:`relay:${A.targetPeerId}:${A.url}`,run:async x=>{let S,T;try{if(S=await y(A,x),x.aborted)throw x.reason;const P=await S.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(x.aborted)throw x.reason;if(typeof P.routeToken!="string"||!P.routeToken)throw new Error("入口未允许此设备连接该服务。");const b=new URL(ur(A.url));return b.pathname="/api/federation/relay",b.searchParams.set("routeToken",P.routeToken),T=await lr({url:b.href,targetPeerId:t.targetPeerId,pairingCode:f,identity:o,socketFactory:Gh(t.targetPeerId),signal:AbortSignal.any([x,AbortSignal.timeout(8e3)])}),f=void 0,await I(T,x),{client:T,entry:S,path:"relay"}}catch(P){throw T?.close(),S&&S!==n&&S!==r&&S.close(),P}}});const v=Yh(t.targetPeerId);w.sort((A,x)=>+(x.key===v)-+(A.key===v));const k=await Zh(w,A=>{A.client.close(),A.entry&&A.entry!==r&&A.entry!==n&&A.entry.close()},!!f);if(d=k.value.client,u=k.value.entry,h=k.value.path,e.renewIfCurrent){if(J!==e.renewIfCurrent||r!==e.renewIfCurrent||r.closed||!r.canSwitchTransport||re()?.targetPeerId!==t.targetPeerId){d.close();for(const A of g)A!==Be&&A!==J&&A.close();return J??r}J=d,en=h,Be=u,La(t.targetPeerId,k.key),r.retire();for(const A of new Set([n,...g]))A&&A!==r&&A!==d&&A!==u&&A.close();return window.dispatchEvent(new Event(Wt)),d}if(La(t.targetPeerId,k.key),J!==r&&J&&!J.closed&&J.targetPeerId===t.targetPeerId){d.close();for(const A of g)A!==Be&&A.close();return J}h==="direct"&&new URL(s).host===location.host&&vg(t.targetPeerId);const B=(await Xe()).find(A=>A.targetPeerId===t.targetPeerId||!A.targetPeerId&&(A.serviceOrigin||A.url)===s),R=B?.label||t.serviceName||new URL(s).host,N={url:s,targetPeerId:t.targetPeerId,serviceName:R,serviceOrigin:s,routes:a.routes??c};if(await(e.rememberOnly?Eg:At)({id:B?.id||t.targetPeerId,...N,label:R}),Dr!=="unpaired"&&Dr!==t.targetPeerId&&Et()&&Ss({id:B?.id||t.targetPeerId,...N,label:R})){d.close();for(const A of g)A!==r&&A!==n&&A.close();return r||d}Ou(N),J=d,en=h,Be=u;for(const A of new Set([r,n,...g]))A&&A!==d&&A!==u&&A.close();return Dr!==t.targetPeerId?(location.reload(),new Promise(()=>{})):(window.dispatchEvent(new Event(Wt)),d)}catch(w){d?.close();for(const I of g)I!==n&&I.close();throw w}}async function Vx(){const t=J,e=re();if(!(qo||Ho||Pr||!t?.renewalDue||!t.canSwitchTransport||!e||performance.now()-Id<3e4)){Id=performance.now(),qo=!0;try{await Ve(e,{renewIfCurrent:t})}catch(r){console.debug("[connection] renewal deferred",{reason:r instanceof Error?r.message:"unknown"})}finally{qo=!1}}}async function Gx(){const t=J,e=re();if(Date.now()-kd<6e4||qo||Ho||en!=="relay"||!t||t.closed||!t.canSwitchTransport||!e?.serviceOrigin)return;Ho=!0,kd=Date.now();let r;try{for(const o of uo(e))try{r=await lr({url:ur(o),targetPeerId:e.targetPeerId,identity:await Ye(),signal:AbortSignal.timeout(3e3)}),await an(r);break}catch(s){if(r?.close(),r=void 0,s instanceof Ge)throw s}if(!r||J!==t||!t.canSwitchTransport)return;const n=Be;J=r,r=void 0,Be=void 0,en="direct",t.close(),n?.close(),window.dispatchEvent(new Event(Wt))}catch(n){n instanceof Ge&&J===t&&(Qh(),window.dispatchEvent(new Event("auth:unauthorized")))}finally{r?.close(),Ho=!1}}function Xx(){return en}async function lt(){if(J&&!J.closed){const e=J;return Vx(),e}if(J=void 0,Pr)return Pr;const t=re();if(!t)throw new Error("DEVICE_PAIRING_REQUIRED");return Pr=Ve(t,{rememberOnly:!0}).catch(e=>{if(J&&!J.closed&&J.targetPeerId===t.targetPeerId)return J;throw e}).finally(()=>{Pr=void 0}),Pr}function Yx(t){const e=new URL(t,location.href);if(J&&!J.closed)return J.openSocket(e.pathname+e.search);let r;const n=new Vh(t,o=>r?.send(o),()=>r?.close());return lt().then(o=>{n.readyState!==3&&(r=o.openSocket(e.pathname+e.search),r.onopen=()=>n.accept({type:"ws-ready",id:""}),r.onmessage=s=>n.accept({type:"ws-data",id:"",data:s.data}),r.onclose=s=>n.accept({type:"ws-close",id:"",code:s.code,reason:s.reason}),r.onerror=()=>n.fail(new Error("Encrypted connection unavailable")))}).catch(o=>n.fail(o)),n}function Zx(){Mx(lt),window.fetch=async(t,e)=>{const r=new URL(t instanceof Request?t.url:String(t),location.href);if(!r.pathname.startsWith("/api/"))return tn(t,e);if(r.origin!==location.origin)throw new Error("Remote business API requires a paired encrypted service");if(r.pathname==="/api/meta")return tn(t,e);if(r.pathname==="/api/auth/status"){if(!re()){const o=await ep();return Response.json({enabled:o.enabled,authenticated:!1})}try{const o=await an(await lt());return Response.json({enabled:o.grants.length>0,authenticated:!0})}catch(o){if(o instanceof Ge)return Response.json({enabled:!0,authenticated:!1});throw o}}if(r.pathname==="/api/auth/login"){const s=await new Request(t instanceof Request?t:r.href,e).json();return zx(typeof s.password=="string"?s.password:"")}if(r.pathname==="/api/csrf-token")return Response.json({csrfToken:"encrypted-device-channel"});if(r.pathname==="/api/auth/logout")return J&&!J.closed&&await J.request({type:"logout"}),J?.close(),Be?.close(),J=void 0,Be=void 0,bg(),location.reload(),Response.json({ok:!0});const n=await lt();return t instanceof Request?n.fetch(t,e):n.fetch(r.pathname+r.search,e)}}async function Jx(t){if(!t.targetPeerId)throw new Error("请先连接这台服务,再查看可中转的服务。");for(const e of uo({...t,targetPeerId:t.targetPeerId})){let r;const n={url:e,targetPeerId:t.targetPeerId};try{r=await Gt(n)}catch{continue}try{const o=await r.request({type:"route-targets"},{timeoutMs:5e3});if(!Array.isArray(o.items))throw new Error("入口服务需要更新后才能查看中转列表。");return{route:n,canManage:o.canManage===!0,items:o.items}}catch(o){throw o instanceof Error&&/UNKNOWN|UNSUPPORTED/i.test(o.message)?new Error("入口服务需要更新后才能查看中转列表。"):o}finally{r.close()}}throw new Error("暂时连不上中转入口,请检查地址和网络后重试。")}async function Qx(t,e){const r=await Gt(t);try{const n=await r.request({type:"route-targets"},{timeoutMs:5e3}),o=(Array.isArray(n.items)?n.items:[]).find(c=>c.serviceId===e);if(!o)throw new Error("该服务已不可见,请刷新列表或请入口管理员授权。");if(!o.available)throw new Error("入口暂时无法中转到这台服务,请稍后重试。");const s=(await Xe()).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(!n.canManage)throw new Error("请先让入口管理员授权此设备。");await r.request({type:"route-grant",serviceId:o.serviceId,subjectId:(await Ye()).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{r.close()}}async function eS(t,e){const r=await Gt(t);try{const n=await r.request({type:"route-access"},{timeoutMs:5e3}),o=(await Ye()).peerId;return{canManage:n.canManage===!0,grants:(Array.isArray(n.grants)?n.grants:[]).filter(s=>s.subjectId===o&&s.targetServiceId===e)}}finally{r.close()}}async function tS(t,e,r){if(r!==void 0&&(await Dc(_e(e.url),r)).targetPeerId!==e.targetPeerId)throw new Error("入口服务的身份已改变,请重新连接并确认。");const n=await Gt(e);try{await n.request({type:"route-grant",serviceId:t.targetPeerId,subjectId:(await Ye()).peerId,url:_e(t.serviceOrigin||t.url)})}finally{n.close()}}async function rS(t,e){const r=await Gt(e);try{const n=await r.request({type:"route-access"},{timeoutMs:5e3}),o=(await Ye()).peerId,s=(Array.isArray(n.grants)?n.grants:[]).filter(i=>i.subjectId===o&&i.targetServiceId===t&&i.active);for(const i of s)await r.request({type:"route-revoke",grantId:i.id})}finally{r.close()}}async function rp(t,e){const r=await Gt(e);try{const n=await r.request({type:"route-invite-create",serviceId:t.targetPeerId});if(typeof n.routeCode!="string"||typeof n.expiresAt!="number")throw new Error("暂时无法生成备用连接邀请。");return{routeCode:n.routeCode,expiresAt:n.expiresAt}}finally{r.close()}}async function Ko(t,e){const r=(await Xe()).find(o=>o.id===t.id||t.targetPeerId&&o.targetPeerId===t.targetPeerId)||t;await At({...r,url:r.serviceOrigin||r.url,entryServiceId:void 0,routes:e});const n=re();n&&n.targetPeerId===t.targetPeerId&&Ou({...n,url:n.serviceOrigin||n.url,entryServiceId:void 0,routes:e})}async function nS(t,e){const r=t.targetPeerId;if(!r)throw new Error("请先连接这台服务,再添加备用地址。");let n;try{n=_e(e)}catch{throw new Error("请输入有效的 HTTPS 地址,例如 https://电脑地址:9834。")}const o=async()=>(await Xe()).find(a=>a.targetPeerId===r)||t,s=a=>{const c=a.routes??dr({...a,targetPeerId:r});if(_e(a.serviceOrigin||a.url)===n||c.some(l=>_e(l.url)===n))throw new Error("这个地址已经在连接列表中。");if(c.length>=4)throw new Error("最多保存 4 个备用地址或入口,请先移除不再使用的连接。");return[...c,{url:n,targetPeerId:r}]};s(await o());let i;try{try{i=await lr({url:ur(n),targetPeerId:r,identity:await Ye(),signal:AbortSignal.timeout(5e3)}),await an(i)}catch(l){throw l instanceof Ge?new Error("这台服务尚未授权当前设备,请先恢复设备授权。"):new Error("无法验证这个地址。请确认能访问该地址、HTTPS 证书受信任,且运行的是同一台 Termdock 服务。")}const a=await o(),c=s(a);if(await Ko(a,c),re()?.targetPeerId===r&&Dr===r&&(!J||J.closed)){const l=J,d=Be;J=i,i=void 0,Be=void 0,en="direct",l?.close(),d?.close(),window.dispatchEvent(new Event(Wt))}return c}finally{i?.close()}}async function Rd(t,e){await Oa(t,e),await Ve({...t,pairingCode:void 0,routeCode:void 0})}function oS(t,e){return e.aborted?Promise.reject(e.reason):new Promise((r,n)=>{const o=()=>n(e.reason);e.addEventListener("abort",o,{once:!0}),t.then(r,n).finally(()=>e.removeEventListener("abort",o))})}function np(){if(window.termdockDesktop||window.parent!==window)return;if(window.__termdockCollaboration)return window.__termdockCollaboration;const t=new Map;let e=[],r=!1;const n=l=>{const d=l.targetPeerId;if(re()?.targetPeerId===d)return lt();const u=t.get(d);if(u)return u.then(h=>h.closed?(t.get(d)===u&&t.delete(d),n(l)):h);const f=Wx({...l,targetPeerId:d},AbortSignal.timeout(12e3)).then(h=>{if(r||t.get(d)!==f)throw h.close(),new Error("服务连接已移除");return h}).catch(h=>{throw t.get(d)===f&&t.delete(d),h});return t.set(d,f),f},o=()=>{const l=re(),d=Kt();l&&!d.some(f=>f.targetPeerId===l.targetPeerId)&&d.push({...l,id:l.targetPeerId,label:l.serviceName||l.serviceOrigin||l.url});const u=new Set(d.map(f=>f.targetPeerId));for(const[f,h]of t)u.has(f)||(t.delete(f),h.then(g=>g.close()).catch(()=>{}));e=d.filter(f=>!!f.targetPeerId).map(f=>({origin:f.serviceOrigin||f.url,label:f.label,request:async(h,g="GET",m)=>{if(!/^\/collaboration-(?:federation|groups)(?:\/[^?#]*)?$/.test(h))throw new Error("无效的协作请求");const y=AbortSignal.timeout(18e3),w=await oS(n(f),y),I=new Headers({"Content-Type":"application/json"});if(g!=="GET"&&g!=="HEAD"){const B=await w.fetch("/api/csrf-token",{signal:y});if(!B.ok)throw new Error("无法读取目标服务的请求令牌");const R=await B.json();if(typeof R.csrfToken!="string")throw new Error("目标服务的请求令牌无效");I.set("X-XSRF-TOKEN",R.csrfToken)}const v=await w.fetch(`/api/terminal/operations${h}`,{method:g,headers:I,signal:y,...m===void 0?{}:{body:JSON.stringify(m)}}),k=v.status===204?void 0:await v.json();if(!v.ok)throw new Error(k?.error||"服务不可达或未授权协作访问");return k}}))},s=new Sg(()=>e),i={peers:l=>(o(),s.peers(l)),save:async(l,d)=>{o();const u=await s.save(l,d);return a(),u}},a=async()=>{r||document.hidden||!navigator.onLine||!re()||(o(),!(e.length<2)&&await s.refresh().catch(()=>{}))};window.__termdockCollaboration=i;const c=window.setInterval(()=>{a()},2e3);return document.addEventListener("visibilitychange",a),window.addEventListener("online",a),window.addEventListener("pageshow",a),window.addEventListener("pagehide",l=>{if(!l.persisted){r=!0,clearInterval(c);for(const d of t.values())d.then(u=>u.close()).catch(()=>{});t.clear()}}),a(),i}function op(){if(!window.termdockDesktop)try{if(window.parent===window)return np();if(location.pathname==="/workspace.html"&&window.parent.location.origin===location.origin)return window.parent.__termdockCollaboration}catch{}}var Bo={},Td;function sS(){if(Td)return Bo;Td=1;var t=lg();return Bo.createRoot=t.createRoot,Bo.hydrateRoot=t.hydrateRoot,Bo}var iS=sS();const aS=Du(iS);const sp=(...t)=>t.filter((e,r,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===r).join(" ").trim();const cS=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const lS=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,r,n)=>n?n.toUpperCase():r.toLowerCase());const Pd=t=>{const e=lS(t);return e.charAt(0).toUpperCase()+e.slice(1)};var Ei={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 dS=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1},uS=F.createContext({}),fS=()=>F.useContext(uS),hS=F.forwardRef(({color:t,size:e,strokeWidth:r,absoluteStrokeWidth:n,className:o="",children:s,iconNode:i,...a},c)=>{const{size:l=24,strokeWidth:d=2,absoluteStrokeWidth:u=!1,color:f="currentColor",className:h=""}=fS()??{},g=n??u?Number(r??d)*24/Number(e??l):r??d;return F.createElement("svg",{ref:c,...Ei,width:e??l??Ei.width,height:e??l??Ei.height,stroke:t??f,strokeWidth:g,className:sp("lucide",h,o),...!s&&!dS(a)&&{"aria-hidden":"true"},...a},[...i.map(([m,y])=>F.createElement(m,y)),...Array.isArray(s)?s:[s]])});const Pe=(t,e)=>{const r=F.forwardRef(({className:n,...o},s)=>F.createElement(hS,{ref:s,iconNode:e,className:sp(`lucide-${cS(Pd(t))}`,`lucide-${t}`,n),...o}));return r.displayName=Pd(t),r};const pS=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],ip=Pe("arrow-left",pS);const gS=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],mS=Pe("arrow-right",gS);const wS=[["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"}]],yS=Pe("bell-dot",wS);const bS=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Oc=Pe("check",bS);const vS=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],xS=Pe("chevron-down",vS);const SS=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],fr=Pe("chevron-right",SS);const ES=[["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"}]],ap=Pe("copy",ES);const AS=[["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"}]],kS=Pe("ellipsis",AS);const IS=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],He=Pe("loader-circle",IS);const CS=[["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"}]],RS=Pe("monitor",CS);const TS=[["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"}]],PS=Pe("pencil",TS);const NS=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],cp=Pe("plus",NS);const LS=[["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"}]],Ks=Pe("server",LS);const BS=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],lp=Pe("smartphone",BS);const _S=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],DS=Pe("terminal",_S);const OS=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],FS=Pe("x",OS);let Br=null;function MS(t){return!Br||!t?!1:(Br(t),!0)}function Qk(t){Br=t;const e=r=>{const{text:n,nonce:o}=r.detail??{};!n||Br!==t||(t(n),r.stopImmediatePropagation(),o&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:o,ok:!0}})))};return window.addEventListener("termdock-insert-reference",e,!0),()=>{Br===t&&(Br=null),window.removeEventListener("termdock-insert-reference",e,!0)}}const jS=/^[A-Za-z0-9_@%+=:,./-]$/;function US(t){return Array.from(t,e=>(e.codePointAt(0)??0)>127||jS.test(e)?e:`\\${e}`).join("")}function $S(t,e){if(!e)return!1;try{const r=new URL(e.serviceOrigin||e.url);return r.origin===t&&/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})$/.test(r.hostname)&&!(e.routes??[]).some(n=>n.targetPeerId!==e.targetPeerId)}catch{return!1}}function HS(t){const e=s=>s.target instanceof Element?s.target.closest("[data-termdock-terminal-dropzone]"):null,r=()=>!$S(location.origin,Or()),n=s=>{const i=e(s);!i||!r()||!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||!r())return;s.preventDefault(),s.stopImmediatePropagation();const c=i.dataset.termdockTerminalDropzone??"";i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="uploading",Vt(async()=>{const{uploadFiles:l}=await Promise.resolve().then(()=>sA);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",n,!0),window.addEventListener("drop",o,!0),()=>{window.removeEventListener("dragover",n,!0),window.removeEventListener("drop",o,!0)}}function dp(){return typeof window>"u"?null:window.termdockDesktop??null}const Ai=new Set;let Nd=!1;function eI(t){const e=dp();if(!e)return()=>{};if(Ai.add(t),!Nd){const r=n=>{if(!MS(n.paths.map(US).join(" ")+" "))for(const o of Ai)o(n)};HS(r),e.onNativeFileDrop(r),Nd=!0}return()=>{Ai.delete(t)}}function up(t=navigator.userAgent,e=navigator.maxTouchPoints){const r=/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":"设备",n=/Electron/.test(t)?"Termdock":/Edg\//.test(t)?"Edge":/Firefox|FxiOS/.test(t)?"Firefox":/Chrome|CriOS/.test(t)?"Chrome":/Safari/.test(t)?"Safari":"浏览器";return`${r} · ${n}`}let qS;function KS(){return qS??=(async()=>{const t=navigator.userAgent,[e,r]=up().split(" · "),n=/(?:Edg|Firefox|FxiOS|Chrome|CriOS|Version)\/([\d.]+)/g,o=[...t.matchAll(n)],s=/(?:CPU (?:iPhone )?OS |Mac OS X |Android )([\d._]+)/.exec(t)?.[1]?.replaceAll("_","."),i={system:`${e}${s?` ${s}`:""}`,client:`${r}${o.length?` ${o.at(-1)[1]}`:""}`,mode:matchMedia("(display-mode: standalone)").matches||navigator.standalone?"已安装的网页应用":"网页"},a=dp();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 zS({service:t,onBusyChange:e,onConnect:r,onConnectWithPassword:n}){const[o,s]=F.useState(),[i,a]=F.useState(!0),[c,l]=F.useState(!1),[d,u]=F.useState(""),[f,h]=F.useState(0),[g,m]=F.useState(),[y,w]=F.useState("");F.useEffect(()=>{let k=!1;return a(!0),u(""),s(void 0),Jx(t).then(B=>{k||s(B)}).catch(B=>{k||u(B instanceof Error?B.message:"暂时无法读取中转列表,请重试。")}).finally(()=>{k||a(!1)}),()=>{k=!0}},[t.id,t.url,f]);const I=async k=>{if(!c){l(!0),e(!0),u("");try{await k()}catch(B){u(B instanceof Error?B.message:"暂时无法连接,请重试。")}finally{l(!1),e(!1)}}},v=async k=>{const B=await Qx(o.route,k.serviceId);try{await r(B)}catch(R){if(!(R instanceof Ge))throw R;m(B)}};return p.jsxs("div",{className:"service-form",children:[g?p.jsxs("form",{className:"service-form",onSubmit:k=>{k.preventDefault(),I(async()=>{try{await n?.(g,y)}finally{w("")}})},children:[p.jsxs("p",{className:"service-help",children:["已通过“",t.label,"”连接到“",g.serviceName,"”。请登录目标服务,完成此设备的访问授权。"]}),n?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:y,disabled:c,onChange:k=>w(k.target.value)})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:c||!y,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(k=>k+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(He,{size:16,className:"service-spinning"}),"正在读取可中转的服务…"]}):o&&p.jsxs("div",{className:"service-list",children:[o.items.map(k=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:c||!k.available,onClick:()=>{I(()=>v(k))},children:[p.jsx("span",{className:"service-icon",children:p.jsx(Ks,{size:19})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:k.label||(k.url?new URL(k.url).host:`中转服务 ${k.serviceId.slice(0,8)}`)}),p.jsx("span",{className:"service-description",children:k.available?k.authorized?"已获中转授权 · 连接":"授权此设备并连接":"中转暂不可用"})]}),p.jsx(fr,{size:16})]},k.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(He,{size:16,className:"service-spinning"}),"正在授权并连接目标服务…"]}),!i&&p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>h(k=>k+1),children:"刷新列表"})]}),d&&p.jsx("p",{className:"service-error",role:"alert",children:d})]})}const Fa="#termdock-invite=";function fp(t){const e=new URL(t.entryUrl);e.hash="",e.search="",e.pathname="/";const r=new TextEncoder().encode(JSON.stringify(t));return e.hash=Fa.slice(1)+btoa(String.fromCharCode(...r)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.href}function Es(t){const e=new URL(t);if(!["https:","http:"].includes(e.protocol)||!e.hash.startsWith(Fa))throw new Error("这不是有效的 Termdock 邀请链接");const r=e.hash.slice(Fa.length);if(r.length>8192)throw new Error("邀请链接过长");let n;try{const i=r.replace(/-/g,"+").replace(/_/g,"/");n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(atob(i),a=>a.charCodeAt(0))))}catch{throw new Error("邀请链接不完整,请重新复制")}if(n.v!==1||typeof n.serviceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(n.serviceId)||n.routeOnly!==!0&&(typeof n.code!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(n.code)))throw new Error("邀请信息无效或版本不兼容");const o=new URL(n.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(n.entryServiceId!==void 0&&(typeof n.entryServiceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(n.entryServiceId)))throw new Error("邀请入口身份无效");if(n.routeCode!==void 0&&(typeof n.routeCode!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(n.routeCode)||!n.entryServiceId))throw new Error("邀请入口权限无效");if(n.routeOnly===!0&&(!n.entryServiceId||!n.routeCode||n.code!==void 0))throw new Error("备用连接邀请不完整");let s=o.origin;if(n.serviceUrl!==void 0){const i=new URL(n.serviceUrl);if(!["https:","http:"].includes(i.protocol)||i.username||i.password)throw new Error("目标服务地址无效");s=n.entryServiceId&&n.entryServiceId!==n.serviceId?i.origin:o.origin}return{url:o.origin,targetPeerId:n.serviceId,pairingCode:n.code,...n.routeOnly===!0?{routeOnly:!0}:{},serviceOrigin:s,serviceName:typeof n.name=="string"?n.name.slice(0,120):void 0,entryServiceId:n.entryServiceId,routeCode:n.routeCode}}function WS({service:t,onBusyChange:e}){const r={...t,targetPeerId:t.targetPeerId,serviceName:t.label},[n,o]=F.useState(()=>t.routes??dr(r)),[s,i]=F.useState([]),[a,c]=F.useState(!0),[l,d]=F.useState(!1),[u,f]=F.useState(""),h=D=>{d(D),e(D)},[g,m]=F.useState(),[y,w]=F.useState(""),[I,v]=F.useState(""),[k,B]=F.useState(""),[R,N]=F.useState(!1),[A,x]=F.useState(),[S,T]=F.useState(),[P,b]=F.useState(!1);F.useEffect(()=>{let D=!1;return Xe().then(_=>{D||i(_.filter(O=>O.targetPeerId&&O.targetPeerId!==t.targetPeerId))}).catch(()=>{D||f("暂时无法读取可用服务。")}).finally(()=>{D||c(!1)}),()=>{D=!0}},[t.targetPeerId]);const E=D=>s.find(_=>_.targetPeerId===D.targetPeerId)?.label||new URL(D.url).host,C=async D=>{h(!0),f(""),B("");try{await D()}catch(_){const O=_ instanceof Error?_.message:"";f(/AUTHORIZATION|DENIED/.test(O)?"当前设备没有入口管理权限。请让管理员分享备用连接邀请,或使用入口密码授权。":"暂时无法完成。请确认入口能连接目标服务,且目标地址、证书和授权有效。")}finally{h(!1)}},L=async(D,_)=>{const O={url:D.serviceOrigin||D.url,targetPeerId:D.targetPeerId};await C(async()=>{const q=await eS(O,r.targetPeerId);if(!q.grants.some(K=>K.active)){if(!q.canManage&&_===void 0){m(D);return}await tS(r,O,_)}const H=[...n.filter(K=>K.targetPeerId!==O.targetPeerId),O];await Ko(t,H),o(H),m(void 0),w("")})};if(S)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:S,onFocus:D=>D.target.select()})]}),p.jsxs("button",{type:"button",className:"service-button service-primary",onClick:()=>{navigator.clipboard.writeText(S).then(()=>b(!0)).catch(()=>f("无法自动复制,请长按链接复制。"))},children:[p.jsx(ap,{size:16}),P?"已复制":"复制邀请链接"]}),p.jsx("button",{type:"button",className:"service-button service-secondary",onClick:()=>{T(void 0),b(!1)},children:"返回备用连接"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});if(g)return p.jsxs("form",{className:"service-form",onSubmit:D=>{D.preventDefault(),L(g,y).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:y,onChange:D=>w(D.target.value),autoComplete:"current-password",disabled:l,autoFocus:!0})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||!y,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 M=n.filter(D=>D.targetPeerId===r.targetPeerId),$=n.filter(D=>D.targetPeerId!==r.targetPeerId),j=async()=>{if(!l){h(!0),N(!0),f(""),B("");try{o(await nS({...t,routes:n},I)),v(""),B("备用地址已验证并保存。")}catch(D){f(D instanceof Error?D.message:"暂时无法添加地址,请重试。")}finally{h(!1),N(!1)}}};return p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"电脑换了网络?添加它在新网络下的地址,原地址连不上时会自动尝试。只接受同一台服务。"}),p.jsxs("form",{className:"service-form",onSubmit:D=>{D.preventDefault(),j()},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用地址"}),p.jsx("input",{value:I,onChange:D=>{v(D.target.value),f(""),B("")},required:!0,disabled:l||n.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||n.length>=4||!I.trim(),children:R?p.jsxs(p.Fragment,{children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在验证…"]}):"验证并添加"})]}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u}),k&&p.jsx("p",{role:"status",className:"service-help",children:k}),n.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})]}),M.length>0&&p.jsx("div",{className:"service-list",children:M.map(D=>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:D.url}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`移除地址 ${D.url}`,disabled:l,onClick:()=>x(D),children:"移除"})]}),A?.targetPeerId===D.targetPeerId&&A.url===D.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:()=>x(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{C(async()=>{const _=n.filter(O=>O.targetPeerId!==D.targetPeerId||O.url!==D.url);await Ko(t,_),o(_),x(void 0)})},children:"确认移除"})]})]})]},D.url))}),p.jsxs("details",{className:"service-relay-options",children:[p.jsxs("summary",{children:["通过其他服务中转",$.length?`(${$.length})`:""]}),p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"所有直连地址都不可用时,尝试下方已授权入口;直连恢复后自动切回。"}),$.length>0&&p.jsx("div",{className:"service-list",children:$.map(D=>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(Ks,{size:18})}),p.jsx("span",{className:"service-name",children:E(D)}),p.jsx(Oc,{size:16,className:"service-selected"})]}),A?.targetPeerId===D.targetPeerId?p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["撤销此设备经“",E(D),"”连接目标的权限?如当前无法直连,目标服务将断开。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>x(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{C(async()=>{await rS(r.targetPeerId,D);const _=n.filter(O=>O.targetPeerId!==D.targetPeerId);await Ko(t,_),o(_),x(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:()=>{C(async()=>{const _=await rp(r,D);T(fp({v:1,routeOnly:!0,serviceId:r.targetPeerId,name:t.label,serviceUrl:t.serviceOrigin||t.url,entryUrl:D.url,entryServiceId:D.targetPeerId,routeCode:_.routeCode}))})},children:"分享备用连接"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>x(D),children:"撤销授权"})]})]},D.targetPeerId))}),a?p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"添加中转入口"}),s.filter(D=>!n.some(_=>_.targetPeerId===D.targetPeerId)).map(D=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:l||n.length>=4,onClick:()=>{L(D)},children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:D.label}),p.jsx("span",{className:"service-description",children:"验证并授权后启用"})]}),p.jsx(fr,{size:16})]},D.id)),s.length===0&&p.jsx("p",{className:"service-empty",children:"添加并登录另一台服务后,可以将它设为中转入口。"})]})]})]}),l&&!R&&p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在验证连接与授权…"]})]})}function VS({current:t,renderRoutes:e,renderRelayServices:r,onOpen:n,onAdd:o,onInvite:s,hideHeader:i,onNavigation:a,onBusyChange:c,initiallyAdding:l=!1}){const[d,u]=F.useState([]),[f,h]=F.useState(!0),[g,m]=F.useState(l?{kind:"add"}:{kind:"list"}),[y,w]=F.useState(!1),I=F.useCallback(b=>{w(b),c?.(b)},[c]),[v,k]=F.useState(""),B=F.useCallback(()=>{m(b=>b.kind==="routes"||b.kind==="relay-services"?{kind:"edit",service:b.service}:{kind:"list"}),k("")},[]),R=g.kind==="add"?"添加服务":g.kind==="edit"?"服务设置":g.kind==="routes"?"备用连接":g.kind==="relay-services"?"可中转的服务":void 0;F.useEffect(()=>{a?.({title:R,...R?{back:B}:{}})},[R,B,a]),F.useEffect(()=>{let b=!1,E=0;const C=async()=>{const M=++E;try{const $=await Xe();!b&&E===M&&(u($),k(""))}catch{!b&&E===M&&k("暂时无法读取服务列表,请重试。")}finally{!b&&E===M&&h(!1)}};C();const L=ju(()=>{C()});return()=>{b=!0,L()}},[]);const N=async b=>{if(!y){I(!0),k("");try{await b()}catch(E){k(E instanceof Error?E.message:"暂时无法完成,请重试。")}finally{I(!1)}}},A=g.kind==="edit"||g.kind==="routes"||g.kind==="relay-services"?d.find(b=>yt(b,g.service))||g.service:void 0,x=t?d.find(b=>yt(b,t))||t:void 0,S=d.filter(b=>!t||!yt(b,t)),T=x?[x,...S]:S,P=p.jsxs(p.Fragment,{children:[f?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{className:"service-list",children:[T.map(b=>{const E=!!t&&yt(b,t);return p.jsxs("div",{className:"service-row",children:[p.jsxs("button",{type:"button",className:"service-row-open",disabled:y||E,onClick:()=>{N(async()=>{(await n(b))?.passwordRequired&&m({kind:"add",input:b.serviceOrigin||b.url,passwordRequired:!0})})},"aria-label":E?`当前服务 ${b.label}`:`打开 ${b.label}`,children:[p.jsx("span",{className:"service-icon",children:p.jsx(Ks,{size:20})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:b.label}),p.jsx("span",{className:"service-description",children:E?"当前服务":new URL(b.serviceOrigin||b.url).host})]}),E?p.jsx(Oc,{size:17,className:"service-selected"}):p.jsx(fr,{size:16,className:"service-muted"})]}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`管理 ${b.label}`,disabled:y,onClick:()=>{m({kind:"edit",service:b}),k("")},children:p.jsx(kS,{size:19})})]},b.id)}),T.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:y,onClick:()=>{m({kind:"add"}),k("")},children:[p.jsx(cp,{size:16}),"添加服务"]}),s&&p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:y,onClick:s,children:[p.jsx(lp,{size:16}),"邀请设备"]})]})]});return p.jsxs("div",{className:"service-manager",children:[!i&&p.jsxs("div",{className:"service-heading",children:[R&&p.jsx("button",{type:"button",className:"service-icon-button","aria-label":"返回服务",disabled:y,onClick:B,children:p.jsx(ip,{size:20})}),p.jsx("h2",{children:R||"服务"})]}),g.kind==="relay-services"?r?.(A,I):g.kind==="routes"?e?.(A,I):g.kind==="list"?P:g.kind==="add"?p.jsx(GS,{onSave:b=>N(async()=>{const E=_e(b);u(await At({id:E,url:E,label:new URL(E).host})),B()}),initialInput:g.input,passwordRequired:g.passwordRequired,busy:y,onSubmit:async(b,E)=>{let C;return await N(async()=>{C=await o(b,E),C?.passwordRequired||B()}),C}}):p.jsx(XS,{onRelayServices:r&&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:A,busy:y,canRemove:!t||!yt(g.service,t),onSave:b=>{N(async()=>{u(await At({...A,label:b})),B()})},onRemove:()=>{N(async()=>{u(await Ag(g.service.id)),B()})}}),v&&p.jsx("p",{className:"service-error",role:"alert",children:v})]})}function GS({busy:t,onSubmit:e,onSave:r,initialInput:n="",passwordRequired:o=!1}){const[s,i]=F.useState(n),[a,c]=F.useState(""),[l,d]=F.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:()=>{r(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(He,{size:16,className:"service-spinning"}),"正在连接…"]}):l?"登录并连接":"继续"})]})}function XS({service:t,busy:e,canRemove:r,onSave:n,onRemove:o,onRoutes:s,onRelayServices:i}){const[a,c]=F.useState(t.label),[l,d]=F.useState(!1);return p.jsxs("form",{className:"service-form",onSubmit:u=>{u.preventDefault(),n(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(fr,{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(fr,{size:16})]}),r&&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 Cr={},ki,Ld;function YS(){return Ld||(Ld=1,ki=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),ki}var Ii={},Ot={},Bd;function mr(){if(Bd)return Ot;Bd=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 Ot.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},Ot.getSymbolTotalCodewords=function(n){return e[n]},Ot.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Ot.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');t=n},Ot.isKanjiModeEnabled=function(){return typeof t<"u"},Ot.toSJIS=function(n){return t(n)},Ot}var Ci={},_d;function Fc(){return _d||(_d=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.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: "+r)}}t.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},t.from=function(n,o){if(t.isValid(n))return n;try{return e(n)}catch{return o}}})(Ci)),Ci}var Ri,Dd;function ZS(){if(Dd)return Ri;Dd=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(e){const r=Math.floor(e/8);return(this.buffer[r]>>>7-e%8&1)===1},put:function(e,r){for(let n=0;n<r;n++)this.putBit((e>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),e&&(this.buffer[r]|=128>>>this.length%8),this.length++}},Ri=t,Ri}var Ti,Od;function JS(){if(Od)return Ti;Od=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,r,n,o){const s=e*this.size+r;this.data[s]=n,o&&(this.reservedBit[s]=!0)},t.prototype.get=function(e,r){return this.data[e*this.size+r]},t.prototype.xor=function(e,r,n){this.data[e*this.size+r]^=n},t.prototype.isReserved=function(e,r){return this.reservedBit[e*this.size+r]},Ti=t,Ti}var Pi={},Fd;function QS(){return Fd||(Fd=1,(function(t){const e=mr().getSymbolSize;t.getRowColCoords=function(n){if(n===1)return[];const o=Math.floor(n/7)+2,s=e(n),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(n){const o=[],s=t.getRowColCoords(n),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}})(Pi)),Pi}var Ni={},Md;function eE(){if(Md)return Ni;Md=1;const t=mr().getSymbolSize,e=7;return Ni.getPositions=function(n){const o=t(n);return[[0,0],[o-e,0],[0,o-e]]},Ni}var Li={},jd;function tE(){return jd||(jd=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 r(n,o,s){switch(n){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:"+n)}}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,r(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}})(Li)),Li}var _o={},Ud;function hp(){if(Ud)return _o;Ud=1;const t=Fc(),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],r=[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 _o.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}},_o.getTotalCodewordsCount=function(o,s){switch(s){case t.L:return r[(o-1)*4+0];case t.M:return r[(o-1)*4+1];case t.Q:return r[(o-1)*4+2];case t.H:return r[(o-1)*4+3];default:return}},_o}var Bi={},Sn={},$d;function rE(){if($d)return Sn;$d=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let n=1;for(let o=0;o<255;o++)t[o]=n,e[n]=o,n<<=1,n&256&&(n^=285);for(let o=255;o<512;o++)t[o]=t[o-255]})(),Sn.log=function(n){if(n<1)throw new Error("log("+n+")");return e[n]},Sn.exp=function(n){return t[n]},Sn.mul=function(n,o){return n===0||o===0?0:t[e[n]+e[o]]},Sn}var Hd;function nE(){return Hd||(Hd=1,(function(t){const e=rE();t.mul=function(n,o){const s=new Uint8Array(n.length+o.length-1);for(let i=0;i<n.length;i++)for(let a=0;a<o.length;a++)s[i+a]^=e.mul(n[i],o[a]);return s},t.mod=function(n,o){let s=new Uint8Array(n);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(n){let o=new Uint8Array([1]);for(let s=0;s<n;s++)o=t.mul(o,new Uint8Array([1,e.exp(s)]));return o}})(Bi)),Bi}var _i,qd;function oE(){if(qd)return _i;qd=1;const t=nE();function e(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(n){this.degree=n,this.genPoly=t.generateECPolynomial(this.degree)},e.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(n.length+this.degree);o.set(n);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},_i=e,_i}var Di={},Oi={},Fi={},Kd;function pp(){return Kd||(Kd=1,Fi.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),Fi}var at={},zd;function gp(){if(zd)return at;zd=1;const t="[0-9]+",e="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/passwordBootstrap-ftNAkf2B.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/App-ecJnsxAe.js","assets/gestureArbiter-DWSSfkze.js","assets/gestureArbiter-C2J0D0kV.css","assets/referenceLongPress-CFKfzfAt.js","assets/triangle-alert-B3n8oGh0.js","assets/DagPlayground-CVDZjmaY.js","assets/ChangeWalkthroughPanel-cwW3KamQ.js","assets/sparkles-iNhURufY.js","assets/DiffLab-DhGouK9C.js","assets/DiffViewer-8g1tSLXq.js","assets/DiffViewer-T3uj2-aP.css","assets/DiffReviewLab-DOV2Vv34.js","assets/DiffReview-BkQ5C7W4.js"])))=>i.map(i=>d[i]);
2
+ import{r as rc,a as lg,g as Du}from"./react-XDCjal2T.js";import{b as F,r as dg,R as $e}from"./dnd-BCFAPC0L.js";import{L as ug,l as fg}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"]'))n(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"&&n(i)}).observe(document,{childList:!0,subtree:!0});function r(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 n(o){if(o.ep)return;o.ep=!0;const s=r(o);fetch(o.href,s)}})();const hg="modulepreload",pg=function(t){return"/"+t},il={},Vt=function(e,r,n){let o=Promise.resolve();if(r&&r.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(r.map(l=>{if(l=pg(l),l in il)return;il[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":hg,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 Qs={exports:{}},fn={};var al;function gg(){if(al)return fn;al=1;var t=rc(),e=Symbol.for("react.element"),r=Symbol.for("react.fragment"),n=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)n.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 fn.Fragment=r,fn.jsx=i,fn.jsxs=i,fn}var cl;function mg(){return cl||(cl=1,Qs.exports=gg()),Qs.exports}var p=mg();const ir="termdock-secure-target-v1",nc="termdock-secure-entry-v1",wg=new Set([ir,nc,"termdock-color-theme","termdock:locale","termdock.federation.connections.v1"]),po=typeof Storage>"u"?void 0:Storage.prototype.getItem,ei=typeof Storage>"u"?void 0:Storage.prototype.setItem,ll="termdock-secure-legacy-owner",Wn=typeof window<"u"&&window.parent!==window&&location.pathname==="/workspace.html";function yg(){if(typeof window>"u")return null;try{if(Wn){const e=new URLSearchParams(location.search).get("termdock-workspace"),r=JSON.parse(localStorage.getItem("termdock.federation.connections.v1")||"[]"),n=Array.isArray(r)?r.find(o=>o?.targetPeerId===e):void 0;return n&&typeof n.url=="string"&&typeof n.targetPeerId=="string"?{...n,serviceName:n.label||n.serviceName}:null}const t=JSON.parse(sessionStorage.getItem(ir)??localStorage.getItem(ir)??"null");return t&&typeof t.url=="string"&&typeof t.targetPeerId=="string"?t:null}catch{return null}}let Rs=yg();const Dr=Rs?.targetPeerId??"unpaired";function Or(){return Rs}function Ou(t){if(Rs=t,Wn)return;const e=JSON.stringify(t);sessionStorage.setItem(ir,e),localStorage.setItem(ir,e)}function bg(){Rs=null,!Wn&&(localStorage.removeItem(ir),sessionStorage.removeItem(ir),localStorage.removeItem(nc))}function Fn(t,e=Dr){return wg.has(t)||t.startsWith("termdock-secure-")?t:`termdock-service:${e}:${t}`}function vg(t){if(!(!po||!ei))try{if(po.call(localStorage,ll))return;ei.call(localStorage,ll,t);for(const r of[localStorage,sessionStorage]){const n=Array.from({length:r.length},(o,s)=>r.key(s)).filter(o=>!!o);for(const o of n){if(o.startsWith("termdock-service:")||Fn(o,t)===o)continue;const s=Fn(o,t),i=po.call(r,o);i!==null&&po.call(r,s)===null&&ei.call(r,s,i)}}}catch{}}let dl=!1;function xg(){if(dl||typeof Storage>"u")return;dl=!0;const t=Storage.prototype.getItem,e=Storage.prototype.setItem,r=Storage.prototype.removeItem;Storage.prototype.getItem=function(n){return t.call(this,Fn(String(n)))},Storage.prototype.setItem=function(n,o){e.call(this,Fn(String(n)),o)},Storage.prototype.removeItem=function(n){r.call(this,Fn(String(n)))}}xg();const ul={pending:0,failed:1,expired:1,delivered:2,read:3},go=32768,Yo="remote:";function Je(t,e){return e.startsWith(Yo)?e:`${Yo}${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function Ke(t){if(!t.startsWith(Yo))return null;const e=t.slice(Yo.length).split(":");if(e.length!==2)return null;try{return{origin:decodeURIComponent(e[0]),id:decodeURIComponent(e[1])}}catch{return null}}function ti(t,e){const r=Ke(e);return r?.origin===t?r.id:e}function mo(t,e){return{...t,fromSessionId:t.fromSessionId?e(t.fromSessionId):null,toSessionId:e(t.toSessionId)}}function ri(t,e){if(!t)return;const r=Object.fromEntries(Object.entries(t).map(([n,o])=>[e(n),o]));return Object.keys(r).length?r:void 0}class Sg{constructor(e){this.services=e}services;snapshots=new Map;reachable=new Set;groups=new Map;messages=new Map;sessions=new Map;diagnostics=new Map;serviceErrors=new Map;inFlight=null;catalogInFlight=null;async refresh(){return this.inFlight?this.inFlight:(this.inFlight=this.synchronize().finally(()=>{this.inFlight=null}),this.inFlight)}async refreshCatalog(){return this.catalogInFlight?this.catalogInFlight:(this.catalogInFlight=this.discover().finally(()=>{this.catalogInFlight=null}),this.catalogInFlight)}async discover(){const e=this.services();this.serviceErrors.clear();const r=await Promise.all(e.map(async n=>{try{const o=await n.request("/collaboration-federation");if(!Array.isArray(o.groups)||!Array.isArray(o.sessions)||!Array.isArray(o.messages))throw new Error("协作目录响应无效,请更新服务");return{service:n,data:o}}catch(o){return this.serviceErrors.set(n.origin,o instanceof Error?o.message.slice(0,300):"协作目录请求失败"),null}}));this.reachable.clear();for(const n of r){if(!n)continue;const{service:o,data:s}=n;for(const[i,a]of Object.entries(s.transportDiagnostics??{}))(!this.diagnostics.has(i)||a.checked_at>this.diagnostics.get(i).checked_at)&&this.diagnostics.set(i,a);this.reachable.add(o.origin),this.snapshots.set(o.origin,s);for(const i of s.groups){const a={...i,sessionIds:i.sessionIds.map(l=>Je(o.origin,l)),roles:ri(i.roles,l=>Je(o.origin,l))},c=this.groups.get(i.id);(!c||a.updatedAt>c.updatedAt)&&this.groups.set(i.id,a)}for(const i of s.messages)this.mergeMessage(mo(i,a=>Je(o.origin,a)))}this.sessions.clear();for(const n of this.groups.values())for(const o of n.remoteSessions??[])this.sessions.set(o.sessionId,{...o,serviceConnected:!1,status:"offline",serviceCheckedAt:Date.now()});for(const[n,o]of this.snapshots){const s=this.reachable.has(n);for(const i of o.sessions){const a=Je(n,i.sessionId);this.sessions.set(a,{...i,sessionId:a,serviceOrigin:n,serviceLabel:e.find(c=>c.origin===n)?.label??n,serviceConnected:s,serviceCheckedAt:Date.now(),status:s?i.status:"offline"})}}}async synchronize(){await this.refreshCatalog();const e=this.services();for(const r of this.messages.values()){const n=Ke(r.toSessionId)?.origin;if(r.status==="pending"&&n&&!this.reachable.has(n)){const o=this.diagnostics.get(r.id);this.diagnostics.set(r.id,{...o,relay_online:!0,peer_reachable:!1,attempt_count:o?.attempt_count??0,next_retry_at:Date.now()+2e3,last_error:"PEER_UNREACHABLE",checked_at:Date.now()})}}await Promise.all(e.filter(r=>this.reachable.has(r.origin)).map(async r=>{for(const n of this.groups.values())if(!(!this.snapshots.get(r.origin)?.groups.some(s=>s.id===n.id)&&!n.sessionIds.some(s=>Ke(s)?.origin===r.origin)))try{await this.push(r,n)}catch{this.reachable.delete(r.origin)}})),await Promise.all(e.filter(r=>this.reachable.has(r.origin)).map(async r=>{if(!((this.snapshots.get(r.origin)?.protocolVersion??1)<2))for(const n of this.groups.values()){if(n.deleted||!n.sessionIds.some(s=>Ke(s)?.origin===r.origin))continue;const o=[...this.diagnostics].filter(([s])=>this.messages.get(s)?.groupId===n.id).map(([s,i])=>({message_id:s,diagnostic:i,...this.messages.get(s)?.status==="failed"?{failure_reason:this.messages.get(s)?.failureReason}:{}}));if(o.length)try{await r.request("/collaboration-federation","POST",{group:this.groupForService(n,r.origin),messages:[],transport:o})}catch{}}}))}mergeMessage(e){const r=this.messages.get(e.id),n=ul;(!r||n[e.status]>n[r.status])&&this.messages.set(e.id,e);const o=this.messages.get(e.id);if(o&&(r?.shellConfirmed===!0||e.shellConfirmed===!0)&&(o.shellConfirmed=!0),this.messages.size>2e3){const s=[...this.messages.values()].find(i=>i.status!=="pending"&&i.status!=="failed");s&&this.messages.delete(s.id)}}groupForService(e,r){const n=e.sessionIds.filter(o=>Ke(o)?.origin!==r).map(o=>{const s=Ke(o),i=this.sessions.get(o);return{sessionId:o,name:i?.name??s.id,cwd:i?.cwd??"",status:i?.status??"offline",capability:i?.capability??"",currentTask:i?.currentTask??"",updatedAt:i?.updatedAt??0,agent:i?.agent??null,backendSessionId:null,agentNativeSessionId:null,serviceOrigin:s.origin,serviceLabel:i?.serviceLabel??s.origin,serviceConnected:this.reachable.has(s.origin),serviceCheckedAt:Date.now()}});return{...e,sessionIds:e.sessionIds.map(o=>ti(r,o)),remoteSessions:n,roles:ri(e.roles,o=>ti(r,o))}}async push(e,r){const n=ul,o=new Map((this.snapshots.get(e.origin)?.messages??[]).map(i=>[i.id,i])),s=[...this.messages.values()].filter(i=>i.groupId===r.id&&(!o.has(i.id)||n[i.status]>n[o.get(i.id).status]||i.shellConfirmed===!0&&o.get(i.id)?.shellConfirmed!==!0)).map(i=>mo(i,a=>ti(e.origin,a)));if(!s.length){await e.request("/collaboration-federation","POST",{group:this.groupForService(r,e.origin),messages:[]});return}for(const i of s){const a=this.messages.get(i.id),c=Ke(a.toSessionId)?.origin===e.origin,l=this.diagnostics.get(i.id);if(c&&l?.next_retry_at&&l.next_retry_at>Date.now()&&l.last_error!=="PEER_UNREACHABLE")continue;const d={relay_online:!0,peer_reachable:!0,attempt_count:(l?.attempt_count??0)+(c?1:0),next_retry_at:null,last_error:null,checked_at:Date.now(),fragments_sent:0,fragments_total:0},u=this.snapshots.get(e.origin)?.protocolVersion??1;if(u<2&&(String(i.content??"").length>2e4||i.responseKind||i.task||i.metadata||i.expiresAt||i.status==="failed"||i.status==="expired")){c&&(this.messages.set(i.id,{...a,status:"failed",failureReason:"PEER_UPGRADE_REQUIRED"}),this.diagnostics.set(i.id,{...d,last_error:"PEER_UPGRADE_REQUIRED"}));continue}try{const f=new TextEncoder().encode(JSON.stringify(i));if(u>=2&&f.length>go&&!o.has(i.id)){const h=Math.ceil(f.length/go),g=Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",f)),m=>m.toString(16).padStart(2,"0")).join("");d.fragments_total=h;for(let m=0;m<h;m++){const y=await e.request("/collaboration-federation","POST",{group:this.groupForService(r,e.origin),messages:[],fragments:[{message_id:i.id,group_id:r.id,index:m,total:h,sha256:g,data:btoa(String.fromCharCode(...f.subarray(m*go,(m+1)*go)))}]}),w=y.fragmentReceipts?.find(I=>I.message_id===i.id);if(!w||m===h-1&&!w.complete)throw new Error("FRAGMENT_ACK_MISSING");d.fragments_sent=w.received;for(const I of y.messages??[])this.mergeMessage(mo(I,v=>Je(e.origin,v)));if(c){this.diagnostics.set(i.id,{...d,checked_at:Date.now()});const I=this.services().find(v=>v.origin===Ke(a.fromSessionId??"")?.origin);I&&I.origin!==e.origin&&(this.snapshots.get(I.origin)?.protocolVersion??1)>=2&&await I.request("/collaboration-federation","POST",{group:this.groupForService(r,I.origin),messages:[],transport:[{message_id:i.id,diagnostic:d}]}).catch(()=>{})}}}else{const h=await e.request("/collaboration-federation","POST",{group:this.groupForService(r,e.origin),messages:[i]});if(!(h.messages??[]).some(g=>g.id===i.id))throw new Error("PEER_REJECTED_MESSAGE");for(const g of h.messages??[])this.mergeMessage(mo(g,m=>Je(e.origin,m)))}c&&this.diagnostics.set(i.id,{...d,checked_at:Date.now()})}catch(f){c&&this.diagnostics.set(i.id,{...d,checked_at:Date.now(),peer_reachable:null,last_error:f instanceof Error?f.message.slice(0,300):"RELAY_REQUEST_FAILED",next_retry_at:Date.now()+Math.min(3e4,1e3*2**Math.min(d.attempt_count,5))})}}}async peers(e){if(!this.services().some(r=>r.origin===e))throw new Error("当前服务未连接");return await this.refreshCatalog(),{protocolVersion:2,origin:e,sessions:[...this.sessions.values()].filter(r=>Ke(r.sessionId)?.origin!==e),services:[...this.snapshots.keys(),...this.services().map(r=>r.origin)].filter((r,n,o)=>o.indexOf(r)===n).map(r=>({origin:r,label:this.services().find(n=>n.origin===r)?.label??r,connected:this.reachable.has(r),error:this.serviceErrors.get(r)}))}}async list(e){const r=this.services().find(s=>s.origin===e);if(!r)throw new Error("当前服务未连接");const[n,o]=await Promise.all([this.peers(e),r.request("/collaboration-groups")]);return{groups:o.groups,sessions:[...n.sessions,...o.sessions]}}async save(e,r){await this.refreshCatalog();const n=this.services().find(u=>u.origin===e);if(!n)throw new Error("当前服务未连接");const o=await n.request("/collaboration-groups"),s=r.id?o.groups.find(u=>u.id===r.id):void 0;if(r.id&&!s)throw new Error("协作组已删除,请刷新列表");if(s&&r.expectedUpdatedAt!==void 0&&r.expectedUpdatedAt!==s.updatedAt)throw new Error("协作组已被修改,请重新打开成员管理后再保存");for(const u of this.sessions.keys())Ke(u)?.origin===e&&this.sessions.delete(u);for(const u of o.sessions){const f=Je(e,u.sessionId);this.sessions.set(f,{...u,sessionId:f,serviceOrigin:e,serviceLabel:n.label,serviceConnected:!0})}if(!r.id?.startsWith("cross-")&&!r.sessionIds.some(u=>Ke(u)))return n.request("/collaboration-groups","POST",r);if(!this.reachable.has(e))throw new Error("当前服务需要升级 Termdock 后才能跨服务组队");const i=[...new Set(r.sessionIds.map(u=>Je(e,u)))],a=new Set(s?.sessionIds.map(u=>Je(e,u))??[]);if(!r.name?.trim()||i.length<2||i.some(u=>!a.has(u)&&(!this.sessions.has(u)||!this.reachable.has(Ke(u).origin))))throw new Error("所选成员已变化或服务不可达,请刷新后重新选择;尚未保存任何修改");const c=s?.federated?{...s,sessionIds:s.sessionIds.map(u=>Je(e,u))}:void 0,l=ri(s?.roles,u=>Je(e,u)),d={id:c?.id??`cross-${crypto.randomUUID()}`,name:r.name.trim(),sessionIds:i,...l?{roles:Object.fromEntries(Object.entries(l).filter(([u])=>i.includes(u)))}:{},createdAt:c?.createdAt??Date.now(),updatedAt:Math.max(Date.now(),(c?.updatedAt??0)+1),federated:!0};if(s&&!s.federated){if(o.capabilities?.groupPromotion!==1)throw new Error("当前服务需要升级后才能将已有组转换为跨服务组;原组和记录均未修改");const u=await n.request(`/collaboration-groups/${encodeURIComponent(s.id)}/promote`,"POST",{group:this.groupForService(d,e),expectedUpdatedAt:r.expectedUpdatedAt??s.updatedAt});d.updatedAt=u.group.updatedAt,d.createdAt=u.group.createdAt}else await n.request("/collaboration-federation","POST",{group:this.groupForService(d,e),messages:[],...c?{expectedUpdatedAt:r.expectedUpdatedAt??c.updatedAt}:{}});return this.groups.set(d.id,d),{group:this.groupForService(d,e)}}async remove(e,r){const n=this.services().find(o=>o.origin===e);if(!n)throw new Error("当前服务未连接");await n.request(`/collaboration-groups/${encodeURIComponent(r)}`,"DELETE")}}const Ts="termdock.federation.connections.v1",ia="termdock:services-changed",oc="termdock-secure-removed-services",Zo=t=>[t.id,t.targetPeerId,t.serviceOrigin||t.url].filter(e=>!!e);function sc(){try{const t=JSON.parse(localStorage.getItem(oc)||"[]");return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}catch{return[]}}function _e(t){const e=t.trim();if(!e)throw new Error("请输入服务地址。");const r=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(e)?e:`https://${e}`);r.protocol==="wss:"&&(r.protocol="https:"),r.protocol==="ws:"&&(r.protocol="http:");const n=["localhost","127.0.0.1","[::1]"].includes(r.hostname);if(!["https:","http:"].includes(r.protocol)||r.protocol==="http:"&&!n)throw new Error("请使用 HTTPS 服务地址。");if(r.username||r.password||r.search||r.hash||!["/","/api/federation/secure"].includes(r.pathname))throw new Error("请输入服务首页地址,不要包含账号或额外参数。");return r.origin}function Ps(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.url=="string")try{const r=_e(e.url),n=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(r).host;return{id:typeof e.id=="string"&&e.id?e.id:n||r,url:r,label:o,...n?{targetPeerId:n}:{},...typeof e.serviceOrigin=="string"?{serviceOrigin:_e(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:_e(s.url),targetPeerId:s.targetPeerId}]:[]}catch{return[]}})}:{}}}catch{return}}function yt(t,e){return t.targetPeerId&&e.targetPeerId?t.targetPeerId===e.targetPeerId:(t.serviceOrigin||t.url)===(e.serviceOrigin||e.url)}function Fu(t){const e=[];for(const r of t){const n=e.findIndex(o=>yt(o,r));n<0?e.push(r):e[n]={...e[n],...r,id:e[n].id}}return e}function to(){return typeof window>"u"?void 0:window.termdockDesktop}function Kt(){try{const t=JSON.parse(localStorage.getItem(Ts)||"[]");return Array.isArray(t)?Fu(t.map(Ps).filter(e=>!!e)):[]}catch{return[]}}function Mu(t){localStorage.setItem(Ts,JSON.stringify(t.map(e=>({...e,serviceName:e.label})))),window.dispatchEvent(new Event(ia))}let hn;async function Xe(){const t=to();if(!t?.serviceConnections||!t.saveServiceConnection)return Kt();if(hn)return hn;hn=(async()=>{let e=await t.serviceConnections();const r=Kt();for(const n of r)e.some(o=>yt(o,n))||(e=await(t.importServiceConnection||t.saveServiceConnection)(n));return r.length&&localStorage.removeItem(Ts),e})();try{return await hn}finally{hn=void 0}}async function At(t){const e=Ps(t);if(!e)throw new Error("服务地址无效。");const r=to();if(r?.saveServiceConnection)return r.saveServiceConnection(e);const n=Kt(),o=n.find(a=>a.id===e.id||yt(a,e)),s=new Set([...Zo(e),...o?Zo(o):[]]);localStorage.setItem(oc,JSON.stringify(sc().filter(a=>!s.has(a))));const i=Fu([...n.filter(a=>a!==o),{...o,...e,id:o?.id||e.id}]);return Mu(i),i}async function Eg(t){const e=Ps(t);if(!e)throw new Error("服务地址无效。");const r=to();if(r?.importServiceConnection)return r.importServiceConnection(e);if(r?.serviceConnections){const n=await r.serviceConnections();return n.some(o=>yt(o,e))?At(e):n}return Zo(e).some(n=>sc().includes(n))?Kt():At(e)}async function Ag(t){const e=to();if(e?.removeServiceConnection)return e.removeServiceConnection(t);const r=Kt(),n=r.find(s=>s.id===t);n&&localStorage.setItem(oc,JSON.stringify([...new Set([...sc(),...Zo(n)])].slice(-768)));const o=r.filter(s=>s.id!==t);return Mu(o),o}function ju(t){const e=n=>{(n.key===Ts||n.key===null)&&t()};window.addEventListener(ia,t),window.addEventListener("storage",e);const r=to()?.onServiceConnections?.(t);return()=>{window.removeEventListener(ia,t),window.removeEventListener("storage",e),r?.()}}class kg extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}let Ig=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},rt=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};class Uu extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class $u extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}}class Cg extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class Rg extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class Ns extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}const Hu=Symbol.for("@libp2p/peer-id");function Tg(t){return typeof t?.handleEvent=="function"}function Pg(t){return t===!0||t===!1}function Ng(t){return Pg(t)?t:t?.capture??!1}function aa(t){const e={capture:Ng(t),once:!!t?.once};return t?.passive!=null&&(e.passive=t?.passive),t?.signal!=null&&(e.signal=t?.signal),e}function fl(t,e){return aa(t).capture===aa(e).capture}class Lg extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){const o=aa(n);if(o?.signal?.aborted===!0)return;const s=l=>{o.once&&this.removeEventListener(e,r,o),Tg(r)?r.handleEvent(l):r(l)};let i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(l=>l.callback!==r?!1:fl(l.options,o)))return;super.addEventListener(e,s,o);const c=()=>{this.removeEventListener(e,r,o)};o.signal?.addEventListener("abort",c),i.push({callback:r,wrapper:s,options:o,onAbort:c})}removeEventListener(e,r,n){const o=this.#e.get(e);if(o==null){super.removeEventListener(e,r??null,n);return}this.#e.set(e,o.filter(s=>s.callback===r&&fl(s.options,n)?(super.removeEventListener(e,s.wrapper,n),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}}const Bg=Symbol.for("@libp2p/service-capabilities");function _g(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function Ls(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 Dg(t){return new TextEncoder().encode(t)}function Og(t){return new TextDecoder().decode(t)}function Fg(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[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,y=0,w=0,I=g.length;w!==I&&g[w]===0;)w++,m++;for(var v=(I-w)*d+1>>>0,k=new Uint8Array(v);w!==I;){for(var B=g[w],R=0,N=v-1;(B!==0||R<y)&&N!==-1;N--,R++)B+=256*k[N]>>>0,k[N]=B%a>>>0,B=B/a>>>0;if(B!==0)throw new Error("Non-zero carry");y=R,w++}for(var A=v-y;A!==v&&k[A]===0;)A++;for(var x=c.repeat(m);A<v;++A)x+=t.charAt(k[A]);return x}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 y=0,w=0;g[m]===c;)y++,m++;for(var I=(g.length-m)*l+1>>>0,v=new Uint8Array(I);g[m];){var k=r[g.charCodeAt(m)];if(k===255)return;for(var B=0,R=I-1;(k!==0||B<w)&&R!==-1;R--,B++)k+=a*v[R]>>>0,v[R]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");w=B,m++}if(g[m]!==" "){for(var N=I-w;N!==I&&v[N]===0;)N++;for(var A=new Uint8Array(y+(I-N)),x=y;N!==I;)A[x++]=v[N++];return A}}}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 Mg=Fg,jg=Mg;class Ug{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class $g{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;const o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}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 qu(this,e)}}class Hg{decoders;constructor(e){this.decoders=e}or(e){return qu(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function qu(t,e){return new Hg({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}class qg{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Ug(e,r,n),this.decoder=new $g(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function Bs({name:t,prefix:e,encode:r,decode:n}){return new qg(t,e,r,n)}function ro({name:t,prefix:e,alphabet:r}){const{encode:n,decode:o}=jg(r,t);return Bs({prefix:e,name:t,encode:n,decode:s=>Ls(o(s))})}function Kg(t,e,r,n){let o=t.length;for(;t[o-1]==="=";)--o;const s=new Uint8Array(o*r/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-${n} character`);a=a<<r|d,i+=r,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function zg(t,e,r){const n=e[e.length-1]==="=",o=(1<<r)-1;let s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function Wg(t){const e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function Ae({name:t,prefix:e,bitsPerChar:r,alphabet:n}){const o=Wg(n);return Bs({prefix:e,name:t,encode(s){return zg(s,n,r)},decode(s){return Kg(s,o,r,t)}})}const Le=ro({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Vg=ro({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Gg=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Le,base58flickr:Vg},Symbol.toStringTag,{value:"Module"})),Mn=Ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Xg=Ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Yg=Ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Zg=Ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Jg=Ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Qg=Ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),em=Ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),tm=Ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),rm=Ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),nm=Object.freeze(Object.defineProperty({__proto__:null,base32:Mn,base32hex:Jg,base32hexpad:em,base32hexpadupper:tm,base32hexupper:Qg,base32pad:Yg,base32padupper:Zg,base32upper:Xg,base32z:rm},Symbol.toStringTag,{value:"Module"})),jo=ro({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),om=ro({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),sm=Object.freeze(Object.defineProperty({__proto__:null,base36:jo,base36upper:om},Symbol.toStringTag,{value:"Module"}));var im=Ku,hl=128,am=-128,cm=Math.pow(2,31);function Ku(t,e,r){e=e||[],r=r||0;for(var n=r;t>=cm;)e[r++]=t&255|hl,t/=128;for(;t&am;)e[r++]=t&255|hl,t>>>=7;return e[r]=t|0,Ku.bytes=r-n+1,e}var lm=ca,dm=128,pl=127;function ca(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw ca.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&pl)<<o:(i&pl)*Math.pow(2,o),o+=7}while(i>=dm);return ca.bytes=s-n,r}var um=Math.pow(2,7),fm=Math.pow(2,14),hm=Math.pow(2,21),pm=Math.pow(2,28),gm=Math.pow(2,35),mm=Math.pow(2,42),wm=Math.pow(2,49),ym=Math.pow(2,56),bm=Math.pow(2,63),vm=function(t){return t<um?1:t<fm?2:t<hm?3:t<pm?4:t<gm?5:t<mm?6:t<wm?7:t<ym?8:t<bm?9:10},xm={encode:im,decode:lm,encodingLength:vm},Jo=xm;function la(t,e=0){return[Jo.decode(t,e),Jo.decode.bytes]}function Qo(t,e,r=0){return Jo.encode(t,e,r),e}function es(t){return Jo.encodingLength(t)}function no(t,e){const r=e.byteLength,n=es(t),o=n+es(r),s=new Uint8Array(o+r);return Qo(t,s,0),Qo(r,s,n),s.set(e,o),new ic(t,r,e,s)}function zu(t){const e=Ls(t),[r,n]=la(e),[o,s]=la(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new ic(r,o,i,e)}function Sm(t,e){if(t===e)return!0;{const r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&_g(t.bytes,r.bytes)}}class ic{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}}function gl(t,e){const{bytes:r,version:n}=t;return n===0?Am(r,da(t),e??Le.encoder):km(r,da(t),e??Mn.encoder)}const ml=new WeakMap;function da(t){const e=ml.get(t);if(e==null){const r=new Map;return ml.set(t,r),r}return e}class ce{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,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:r}=this;if(e!==pn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Im)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return ce.createV0(r)}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:r}=this.multihash,n=no(e,r);return ce.createV1(this.code,n)}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 ce.equals(this,e)}static equals(e,r){const n=r;return n!=null&&e.code===n.code&&e.version===n.version&&Sm(e.multihash,n.multihash)}toString(e){return gl(this,e)}toJSON(){return{"/":gl(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 r=e;if(r instanceof ce)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){const{version:n,code:o,multihash:s,bytes:i}=r;return new ce(n,o,s,i??wl(n,o,s.bytes))}else if(r[Cm]===!0){const{version:n,multihash:o,code:s}=r,i=zu(o);return ce.create(n,s,i)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==pn)throw new Error(`Version 0 CID must use dag-pb (code: ${pn}) block encoding`);return new ce(e,r,n,n.bytes)}case 1:{const o=wl(e,r,n.bytes);return new ce(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return ce.create(0,pn,e)}static createV1(e,r){return ce.create(1,e,r)}static decode(e){const[r,n]=ce.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){const r=ce.inspectBytes(e),n=r.size-r.multihashSize,o=Ls(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");const s=o.subarray(r.multihashSize-r.digestSize),i=new ic(r.multihashCode,r.digestSize,s,o);return[r.version===0?ce.createV0(i):ce.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0;const n=()=>{const[u,f]=la(e.subarray(r));return r+=f,u};let o=n(),s=pn;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);const i=r,a=n(),c=n(),l=r+c,d=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:d,size:l}}static parse(e,r){const[n,o]=Em(e,r),s=ce.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return da(s).set(n,e),s}}function Em(t,e){switch(t[0]){case"Q":{const r=e??Le;return[Le.prefix,r.decode(`${Le.prefix}${t}`)]}case Le.prefix:{const r=e??Le;return[Le.prefix,r.decode(t)]}case Mn.prefix:{const r=e??Mn;return[Mn.prefix,r.decode(t)]}case jo.prefix:{const r=e??jo;return[jo.prefix,r.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 Am(t,e,r){const{prefix:n}=r;if(n!==Le.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const o=e.get(n);if(o==null){const s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function km(t,e,r){const{prefix:n}=r,o=e.get(n);if(o==null){const s=r.encode(t);return e.set(n,s),s}else return o}const pn=112,Im=18;function wl(t,e,r){const n=es(t),o=n+es(e),s=new Uint8Array(o+r.byteLength);return Qo(t,s,0),Qo(e,s,n),s.set(r,o),s}const Cm=Symbol.for("@ipld/js-cid/CID"),Wu=0,Rm="identity",Vu=Ls;function Tm(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 no(Wu,Vu(t))}const oo={code:Wu,name:Rm,encode:Vu,digest:Tm};function nt(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function De(t=0){return new Uint8Array(t)}function kt(t=0){return new Uint8Array(t)}function ua(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));const r=kt(e);let n=0;for(const o of t)r.set(o,n),n+=o.length;return r}const Gu=Symbol.for("@achingbrain/uint8arraylist");function yl(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(const n of t){const o=r+n.byteLength;if(e<o)return{buf:n,index:e-r};r=o}throw new RangeError("index is out of bounds")}function wo(t){return!!t?.[Gu]}class ne{bufs;length;[Gu]=!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 r=0;for(const n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(wo(n)){r+=n.byteLength;for(const o of n.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...e){this.prependAll(e)}prependAll(e){let r=0;for(const n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(wo(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(e){const r=yl(this.bufs,e);return r.buf[r.index]}set(e,r){const n=yl(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(wo(e))for(let n=0;n<e.length;n++)this.set(r+n,e.get(n));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,r){const{bufs:n,length:o}=this._subList(e,r);return ua(n,o)}subarray(e,r){const{bufs:n,length:o}=this._subList(e,r);return n.length===1?n[0]:ua(n,o)}sublist(e,r){const{bufs:n,length:o}=this._subList(e,r),s=new ne;return s.length=o,s.bufs=n,s}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};const n=[];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=r>a&&r<=c;if(l&&d){if(e===a&&r===c){n.push(i);break}const u=e-a;n.push(i.subarray(u,u+(r-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(d){if(r===c){n.push(i);break}n.push(i.subarray(0,r-a));break}n.push(i)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!wo(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const n=e instanceof Uint8Array?e:e.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.length===0)return r>this.length?this.length:r;const o=n.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[n[u]]=u;const a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1;let d;for(let u=r;u<=c;u+=d){d=0;for(let f=l;f>=0;f--){const h=this.get(u+f);if(n[f]!==h){d=Math.max(1,f-a[h]);break}}if(d===0)return u}return-1}getInt8(e){const r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){const n=kt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){const n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){const o=De(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,e)}getInt32(e,r){const n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){const o=De(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,e)}getBigInt64(e,r){const n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){const o=De(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,e)}getUint8(e){const r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){const n=kt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){const n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){const o=De(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,e)}getUint32(e,r){const n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){const o=De(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,e)}getBigUint64(e,r){const n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){const o=De(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,e)}getFloat32(e,r){const n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){const o=De(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,e)}getFloat64(e,r){const n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){const o=De(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof ne)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!nt(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){const n=new ne;return n.bufs=e,r==null&&(r=e.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}}const Pm=ro({prefix:"9",name:"base10",alphabet:"0123456789"}),Nm=Object.freeze(Object.defineProperty({__proto__:null,base10:Pm},Symbol.toStringTag,{value:"Module"})),Lm=Ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Bm=Ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),_m=Object.freeze(Object.defineProperty({__proto__:null,base16:Lm,base16upper:Bm},Symbol.toStringTag,{value:"Module"})),Dm=Ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Om=Object.freeze(Object.defineProperty({__proto__:null,base2:Dm},Symbol.toStringTag,{value:"Module"})),Xu=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Fm=Xu.reduce((t,e,r)=>(t[r]=e,t),[]),Mm=Xu.reduce((t,e,r)=>{const n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function jm(t){return t.reduce((e,r)=>(e+=Fm[r],e),"")}function Um(t){const e=[];for(const r of t){const n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);const o=Mm[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}const $m=Bs({prefix:"🚀",name:"base256emoji",encode:jm,decode:Um}),Hm=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:$m},Symbol.toStringTag,{value:"Module"})),qm=Ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Km=Ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),zm=Ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Wm=Ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Vm=Object.freeze(Object.defineProperty({__proto__:null,base64:qm,base64pad:Km,base64url:zm,base64urlpad:Wm},Symbol.toStringTag,{value:"Module"})),Gm=Ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Xm=Object.freeze(Object.defineProperty({__proto__:null,base8:Gm},Symbol.toStringTag,{value:"Module"})),Ym=Bs({prefix:"\0",name:"identity",encode:t=>Og(t),decode:t=>Dg(t)}),Zm=Object.freeze(Object.defineProperty({__proto__:null,identity:Ym},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const Jm=20;function Qm({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new ew(t,e,r,n,o)}class ew{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??Jm,this.maxDigestLength=s}digest(e,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?bl(n,this.code,r?.truncate):n.then(o=>bl(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}}function bl(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return no(e,t)}function tw(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}const ac=Qm({name:"sha2-256",code:18,encode:tw("SHA-256")}),vl={...Zm,...Om,...Xm,...Nm,..._m,...nm,...sm,...Gg,...Vm,...Hm};function Yu(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const xl=Yu("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ni=Yu("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=kt(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Zu={utf8:xl,"utf-8":xl,hex:vl.base16,latin1:ni,ascii:ni,binary:ni,...vl};function we(t,e="utf8"){const r=Zu[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function Q(t,e="utf8"){const r=Zu[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}const rw=parseInt("11111",2),fa=parseInt("10000000",2),nw=parseInt("01111111",2),Sl={0:gn,1:gn,2:ow,3:aw,4:cw,5:iw,6:sw,16:gn,22:gn,48:gn};function sn(t,e={offset:0}){const r=t[e.offset]&rw;if(e.offset++,Sl[r]!=null)return Sl[r](t,e);throw new Error("No decoder for tag "+r)}function so(t,e){let r=0;if((t[e.offset]&fa)===fa){const n=t[e.offset]&nw;let o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=t[e.offset].toString(16).padStart(2,"0");r=parseInt(o,16)}else r=t[e.offset],e.offset++;return r}function gn(t,e){so(t,e);const r=[];for(;!(e.offset>=t.byteLength);){const n=sn(t,e);if(n===null)break;r.push(n)}return r}function ow(t,e){const r=so(t,e),n=e.offset,o=e.offset+r,s=[];for(let i=n;i<o;i++)i===n&&t[i]===0||s.push(t[i]);return e.offset+=r,Uint8Array.from(s)}function sw(t,e){const r=so(t,e),n=e.offset+r,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<n;){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 iw(t,e){return e.offset++,null}function aw(t,e){const r=so(t,e),n=t[e.offset];e.offset++;const o=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function cw(t,e){const r=so(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function lw(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);const r=new ne;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function _s(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);const e=lw(t.byteLength);return new ne(Uint8Array.from([e.byteLength|fa]),e)}function Ue(t){const e=new ne,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new ne(Uint8Array.from([2]),_s(e),e)}function cc(t){const e=Uint8Array.from([0]),r=new ne(e,t);return new ne(Uint8Array.from([3]),_s(r),r)}function dw(t){return new ne(Uint8Array.from([4]),_s(t),t)}function St(t,e=48){const r=new ne;for(const n of t)r.append(n);return new ne(Uint8Array.from([e]),_s(r),r)}async function uw(t,e,r){const n=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["sign"]);r?.signal?.throwIfAborted();const o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function fw(t,e,r,n){const o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();const s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,r.subarray());return n?.signal?.throwIfAborted(),s}const hw=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),pw=Uint8Array.from([6,5,43,129,4,0,34]),gw=Uint8Array.from([6,5,43,129,4,0,35]),Ju={ext:!0,kty:"EC",crv:"P-256"},Qu={ext:!0,kty:"EC",crv:"P-384"},ef={ext:!0,kty:"EC",crv:"P-521"},Fr=32,Mr=48,jr=66;function mw(t){const e=sn(t);return ww(e)}function ww(t){const e=t[1],r=Q(e,"base64url"),n=t[2][1][0],o=1;let s,i;if(e.byteLength===Fr)return s=Q(n.subarray(o,o+Fr),"base64url"),i=Q(n.subarray(o+Fr),"base64url"),new oi({...Ju,key_ops:["sign"],d:r,x:s,y:i});if(e.byteLength===Mr)return s=Q(n.subarray(o,o+Mr),"base64url"),i=Q(n.subarray(o+Mr),"base64url"),new oi({...Qu,key_ops:["sign"],d:r,x:s,y:i});if(e.byteLength===jr)return s=Q(n.subarray(o,o+jr),"base64url"),i=Q(n.subarray(o+jr),"base64url"),new oi({...ef,key_ops:["sign"],d:r,x:s,y:i});throw new rt(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function tf(t){const e=sn(t);return yw(e)}function yw(t){const e=t[1][1][0],r=1;let n,o;if(e.byteLength===Fr*2+1)return n=Q(e.subarray(r,r+Fr),"base64url"),o=Q(e.subarray(r+Fr),"base64url"),new Uo({...Ju,key_ops:["verify"],x:n,y:o});if(e.byteLength===Mr*2+1)return n=Q(e.subarray(r,r+Mr),"base64url"),o=Q(e.subarray(r+Mr),"base64url"),new Uo({...Qu,key_ops:["verify"],x:n,y:o});if(e.byteLength===jr*2+1)return n=Q(e.subarray(r,r+jr),"base64url"),o=Q(e.subarray(r+jr),"base64url"),new Uo({...ef,key_ops:["verify"],x:n,y:o});throw new rt(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function bw(t){return St([Ue(Uint8Array.from([1])),dw(we(t.d??"","base64url")),St([rf(t.crv)],160),St([cc(new ne(Uint8Array.from([4]),we(t.x??"","base64url"),we(t.y??"","base64url")))],161)]).subarray()}function vw(t){return St([Ue(Uint8Array.from([1])),St([rf(t.crv)],160),St([cc(new ne(Uint8Array.from([4]),we(t.x??"","base64url"),we(t.y??"","base64url")))],161)]).subarray()}function rf(t){if(t==="P-256")return hw;if(t==="P-384")return pw;if(t==="P-521")return gw;throw new rt(`Invalid curve ${t}`)}class Uo{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=vw(this.jwk)),this._raw}toMultihash(){return oo.digest(Us(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return Le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:nt(this.raw,e.raw)}async verify(e,r,n){return fw(this.jwk,r,e,n)}}class oi{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new Uo({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=bw(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:nt(this.raw,e.raw)}async sign(e,r){return uw(this.jwk,e,r)}}const Ar=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 ha(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function hr(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 nf(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ha(t.outputLen),ha(t.blockLen)}function ts(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 xw(t,e){hr(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Yr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function si(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function st(t,e){return t<<32-e|t>>>e}const of=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Sw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function rr(t){if(hr(t),of)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Sw[t[r]];return e}const ht={_0:48,_9:57,A:65,F:70,a:97,f:102};function El(t){if(t>=ht._0&&t<=ht._9)return t-ht._0;if(t>=ht.A&&t<=ht.F)return t-(ht.A-10);if(t>=ht.a&&t<=ht.f)return t-(ht.a-10)}function rs(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(of)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){const i=El(t.charCodeAt(s)),a=El(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)}n[o]=i*16+a}return n}function Ew(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function lc(t){return typeof t=="string"&&(t=Ew(t)),hr(t),t}function ct(...t){let e=0;for(let n=0;n<t.length;n++){const o=t[n];hr(o),e+=o.length}const r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){const s=t[n];r.set(s,o),o+=s.length}return r}class sf{}function af(t){const e=n=>t().update(lc(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function dc(t=32){if(Ar&&typeof Ar.getRandomValues=="function")return Ar.getRandomValues(new Uint8Array(t));if(Ar&&typeof Ar.randomBytes=="function")return Uint8Array.from(Ar.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function Aw(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,l=n?0:4;t.setUint32(e+c,i,n),t.setUint32(e+l,a,n)}function kw(t,e,r){return t&e^~t&r}function Iw(t,e,r){return t&e^t&r^e&r}let cf=class extends sf{constructor(e,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=si(this.buffer)}update(e){ts(this),e=lc(e),hr(e);const{view:r,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(o-this.pos,s-i);if(a===o){const c=si(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ts(this),xw(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:o,isLE:s}=this;let{pos:i}=this;r[i++]=128,Yr(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let u=i;u<o;u++)r[u]=0;Aw(n,o-8,BigInt(this.length*8),s),this.process(n,0);const a=si(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const Pt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ke=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),yo=BigInt(2**32-1),Al=BigInt(32);function Cw(t,e=!1){return e?{h:Number(t&yo),l:Number(t>>Al&yo)}:{h:Number(t>>Al&yo)|0,l:Number(t&yo)|0}}function Rw(t,e=!1){const r=t.length;let n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){const{h:i,l:a}=Cw(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}const kl=(t,e,r)=>t>>>r,Il=(t,e,r)=>t<<32-r|e>>>r,kr=(t,e,r)=>t>>>r|e<<32-r,Ir=(t,e,r)=>t<<32-r|e>>>r,bo=(t,e,r)=>t<<64-r|e>>>r-32,vo=(t,e,r)=>t>>>r-32|e<<64-r;function pt(t,e,r,n){const o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}const Tw=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Pw=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Nw=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Lw=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,Bw=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),_w=(t,e,r,n,o,s)=>e+r+n+o+s+(t/2**32|0)|0,Dw=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]),Nt=new Uint32Array(64);class Ow extends cf{constructor(e=32){super(64,e,8,!1),this.A=Pt[0]|0,this.B=Pt[1]|0,this.C=Pt[2]|0,this.D=Pt[3]|0,this.E=Pt[4]|0,this.F=Pt[5]|0,this.G=Pt[6]|0,this.H=Pt[7]|0}get(){const{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,r){for(let u=0;u<16;u++,r+=4)Nt[u]=e.getUint32(r,!1);for(let u=16;u<64;u++){const f=Nt[u-15],h=Nt[u-2],g=st(f,7)^st(f,18)^f>>>3,m=st(h,17)^st(h,19)^h>>>10;Nt[u]=m+Nt[u-7]+g+Nt[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=st(a,6)^st(a,11)^st(a,25),h=d+f+kw(a,c,l)+Dw[u]+Nt[u]|0,m=(st(n,2)^st(n,13)^st(n,22))+Iw(n,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+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(n,o,s,i,a,c,l,d)}roundClean(){Yr(Nt)}destroy(){this.set(0,0,0,0,0,0,0,0),Yr(this.buffer)}}const lf=Rw(["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))),Fw=lf[0],Mw=lf[1],Lt=new Uint32Array(80),Bt=new Uint32Array(80);class jw extends cf{constructor(e=64){super(128,e,16,!1),this.Ah=ke[0]|0,this.Al=ke[1]|0,this.Bh=ke[2]|0,this.Bl=ke[3]|0,this.Ch=ke[4]|0,this.Cl=ke[5]|0,this.Dh=ke[6]|0,this.Dl=ke[7]|0,this.Eh=ke[8]|0,this.El=ke[9]|0,this.Fh=ke[10]|0,this.Fl=ke[11]|0,this.Gh=ke[12]|0,this.Gl=ke[13]|0,this.Hh=ke[14]|0,this.Hl=ke[15]|0}get(){const{Ah:e,Al:r,Bh:n,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:y}=this;return[e,r,n,o,s,i,a,c,l,d,u,f,h,g,m,y]}set(e,r,n,o,s,i,a,c,l,d,u,f,h,g,m,y){this.Ah=e|0,this.Al=r|0,this.Bh=n|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=y|0}process(e,r){for(let v=0;v<16;v++,r+=4)Lt[v]=e.getUint32(r),Bt[v]=e.getUint32(r+=4);for(let v=16;v<80;v++){const k=Lt[v-15]|0,B=Bt[v-15]|0,R=kr(k,B,1)^kr(k,B,8)^kl(k,B,7),N=Ir(k,B,1)^Ir(k,B,8)^Il(k,B,7),A=Lt[v-2]|0,x=Bt[v-2]|0,S=kr(A,x,19)^bo(A,x,61)^kl(A,x,6),T=Ir(A,x,19)^vo(A,x,61)^Il(A,x,6),P=Nw(N,T,Bt[v-7],Bt[v-16]),b=Lw(P,R,S,Lt[v-7],Lt[v-16]);Lt[v]=b|0,Bt[v]=P|0}let{Ah:n,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:y,Hh:w,Hl:I}=this;for(let v=0;v<80;v++){const k=kr(u,f,14)^kr(u,f,18)^bo(u,f,41),B=Ir(u,f,14)^Ir(u,f,18)^vo(u,f,41),R=u&h^~u&m,N=f&g^~f&y,A=Bw(I,B,N,Mw[v],Bt[v]),x=_w(A,w,k,R,Fw[v],Lt[v]),S=A|0,T=kr(n,o,28)^bo(n,o,34)^bo(n,o,39),P=Ir(n,o,28)^vo(n,o,34)^vo(n,o,39),b=n&s^n&a^s&a,E=o&i^o&c^i&c;w=m|0,I=y|0,m=h|0,y=g|0,h=u|0,g=f|0,{h:u,l:f}=pt(l|0,d|0,x|0,S|0),l=a|0,d=c|0,a=s|0,c=i|0,s=n|0,i=o|0;const C=Tw(S,P,E);n=Pw(C,x,T,b),o=C|0}({h:n,l:o}=pt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=pt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=pt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=pt(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:f}=pt(this.Eh|0,this.El|0,u|0,f|0),{h,l:g}=pt(this.Fh|0,this.Fl|0,h|0,g|0),{h:m,l:y}=pt(this.Gh|0,this.Gl|0,m|0,y|0),{h:w,l:I}=pt(this.Hh|0,this.Hl|0,w|0,I|0),this.set(n,o,s,i,a,c,l,d,u,f,h,g,m,y,w,I)}roundClean(){Yr(Lt,Bt)}destroy(){Yr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const df=af(()=>new Ow),Uw=af(()=>new jw);const uc=BigInt(0),pa=BigInt(1);function ar(t,e=""){if(typeof t!="boolean"){const r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function tt(t,e,r=""){const n=io(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){const i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function xo(t){const e=t.toString(16);return e.length&1?"0"+e:e}function uf(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?uc:BigInt("0x"+t)}function Ds(t){return uf(rr(t))}function Vn(t){return hr(t),uf(rr(Uint8Array.from(t).reverse()))}function fc(t,e){return rs(t.toString(16).padStart(e*2,"0"))}function ff(t,e){return fc(t,e).reverse()}function fe(t,e,r){let n;if(typeof e=="string")try{n=rs(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(io(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const o=n.length;if(typeof r=="number"&&o!==r)throw new Error(t+" of length "+r+" expected, got "+o);return n}function Cl(t){return Uint8Array.from(t)}const ii=t=>typeof t=="bigint"&&uc<=t;function $w(t,e,r){return ii(t)&&ii(e)&&ii(r)&&e<=t&&t<r}function ga(t,e,r,n){if(!$w(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function hf(t){let e;for(e=0;t>uc;t>>=pa,e+=1);return e}const ao=t=>(pa<<BigInt(t))-pa;function Hw(t,e,r){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 r!="function")throw new Error("hmacFn must be a function");const n=h=>new Uint8Array(h),o=h=>Uint8Array.of(h);let s=n(t),i=n(t),a=0;const c=()=>{s.fill(1),i.fill(0),a=0},l=(...h)=>r(i,s,...h),d=(h=n(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 ct(...g)};return(h,g)=>{c(),d(h);let m;for(;!(m=g(u()));)d();return c(),m}}function co(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(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])=>n(o,s,!1)),Object.entries(r).forEach(([o,s])=>n(o,s,!0))}function ns(t){const e=new WeakMap;return(r,...n)=>{const o=e.get(r);if(o!==void 0)return o;const s=t(r,...n);return e.set(r,s),s}}const Oe=BigInt(0),Ee=BigInt(1),Zt=BigInt(2),pf=BigInt(3),gf=BigInt(4),mf=BigInt(5),qw=BigInt(7),wf=BigInt(8),Kw=BigInt(9),yf=BigInt(16);function ye(t,e){const r=t%e;return r>=Oe?r:e+r}function ue(t,e,r){let n=t;for(;e-- >Oe;)n*=n,n%=r;return n}function Rl(t,e){if(t===Oe)throw new Error("invert: expected non-zero number");if(e<=Oe)throw new Error("invert: expected positive modulus, got "+e);let r=ye(t,e),n=e,o=Oe,s=Ee;for(;r!==Oe;){const a=n/r,c=n%r,l=o-s*a;n=r,r=c,o=s,s=l}if(n!==Ee)throw new Error("invert: does not exist");return ye(o,e)}function hc(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function bf(t,e){const r=(t.ORDER+Ee)/gf,n=t.pow(e,r);return hc(t,n,e),n}function zw(t,e){const r=(t.ORDER-mf)/wf,n=t.mul(e,Zt),o=t.pow(n,r),s=t.mul(e,o),i=t.mul(t.mul(s,Zt),o),a=t.mul(s,t.sub(i,t.ONE));return hc(t,a,e),a}function Ww(t){const e=pr(t),r=vf(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+qw)/yf;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,n);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),y=a.cmov(l,d,m);return hc(a,y,c),y}}function vf(t){if(t<pf)throw new Error("sqrt is not defined for small field");let e=t-Ee,r=0;for(;e%Zt===Oe;)e/=Zt,r++;let n=Zt;const o=pr(t);for(;Tl(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return bf;let s=o.pow(n,e);const i=(e+Ee)/Zt;return function(c,l){if(c.is0(l))return l;if(Tl(c,l)!==1)throw new Error("Cannot find square root");let d=r,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 y=Ee<<BigInt(d-g-1),w=c.pow(u,y);d=g,u=c.sqr(w),f=c.mul(f,u),h=c.mul(h,w)}return h}}function Vw(t){return t%gf===pf?bf:t%wf===mf?zw:t%yf===Kw?Ww(t):vf(t)}const Gw=(t,e)=>(ye(t,e)&Ee)===Ee,Xw=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yw(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=Xw.reduce((n,o)=>(n[o]="function",n),e);return co(t,r),t}function Zw(t,e,r){if(r<Oe)throw new Error("invalid exponent, negatives unsupported");if(r===Oe)return t.ONE;if(r===Ee)return e;let n=t.ONE,o=e;for(;r>Oe;)r&Ee&&(n=t.mul(n,o)),o=t.sqr(o),r>>=Ee;return n}function xf(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),o=e.reduce((i,a,c)=>t.is0(a)?i:(n[c]=i,t.mul(i,a)),t.ONE),s=t.inv(o);return e.reduceRight((i,a,c)=>t.is0(a)?i:(n[c]=t.mul(i,n[c]),t.mul(i,a)),s),n}function Tl(t,e){const r=(t.ORDER-Ee)/Zt,n=t.pow(e,r),o=t.eql(n,t.ONE),s=t.eql(n,t.ZERO),i=t.eql(n,t.neg(t.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function Sf(t,e){e!==void 0&&ha(e);const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function pr(t,e,r=!1,n={}){if(t<=Oe)throw new Error("invalid field: expected ORDER > 0, got "+t);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||r)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"&&(r=f.isLE),typeof f.modFromBytes=="boolean"&&(i=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(o=e),n.sqrt&&(s=n.sqrt);const{nBitLength:c,nByteLength:l}=Sf(t,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:l,MASK:ao(c),ZERO:Oe,ONE:Ee,allowedLengths:a,create:f=>ye(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return Oe<=f&&f<t},is0:f=>f===Oe,isValidNot0:f=>!u.is0(f)&&u.isValid(f),isOdd:f=>(f&Ee)===Ee,neg:f=>ye(-f,t),eql:(f,h)=>f===h,sqr:f=>ye(f*f,t),add:(f,h)=>ye(f+h,t),sub:(f,h)=>ye(f-h,t),mul:(f,h)=>ye(f*h,t),pow:(f,h)=>Zw(u,f,h),div:(f,h)=>ye(f*Rl(h,t),t),sqrN:f=>f*f,addN:(f,h)=>f+h,subN:(f,h)=>f-h,mulN:(f,h)=>f*h,inv:f=>Rl(f,t),sqrt:s||(f=>(d||(d=Vw(t)),d(u,f))),toBytes:f=>r?ff(f,l):fc(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,r?0:m.length-f.length),f=m}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let g=r?Vn(f):Ds(f);if(i&&(g=ye(g,t)),!h&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:f=>xf(u,f),cmov:(f,h,g)=>g?h:f});return Object.freeze(u)}function Ef(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 Af(t){const e=Ef(t);return e+Math.ceil(e/2)}function Jw(t,e,r=!1){const n=t.length,o=Ef(e),s=Af(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const i=r?Vn(t):Ds(t),a=ye(i,e-Ee)+Ee;return r?ff(a,o):fc(a,o)}const Zr=BigInt(0),Jt=BigInt(1);function os(t,e){const r=e.negate();return t?r:e}function Qt(t,e){const r=xf(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function kf(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ai(t,e){kf(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1),o=2**t,s=ao(t),i=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Pl(t,e,r){const{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r;let a=Number(t&o),c=t>>i;a>n&&(a-=s,c+=Jt);const l=e*n,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 Qw(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function ey(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const ci=new WeakMap,If=new WeakMap;function li(t){return If.get(t)||1}function Nl(t){if(t!==Zr)throw new Error("invalid wNAF")}class Cf{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let o=e;for(;r>Zr;)r&Jt&&(n=n.add(o)),o=o.double(),r>>=Jt;return n}precomputeWindow(e,r){const{windows:n,windowSize:o}=ai(r,this.bits),s=[];let i=e,a=i;for(let c=0;c<n;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,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE;const i=ai(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:f,offsetF:h}=Pl(n,a,i);n=c,d?s=s.add(os(f,r[h])):o=o.add(os(u,r[l]))}return Nl(n),{p:o,f:s}}wNAFUnsafe(e,r,n,o=this.ZERO){const s=ai(e,this.bits);for(let i=0;i<s.windows&&n!==Zr;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=Pl(n,i,s);if(n=a,!l){const u=r[c];o=o.add(d?u.negate():u)}}return Nl(n),o}getPrecomputes(e,r,n){let o=ci.get(r);return o||(o=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(o=n(o)),ci.set(r,o))),o}cached(e,r,n){const o=li(e);return this.wNAF(o,this.getPrecomputes(o,e,n),r)}unsafe(e,r,n,o){const s=li(e);return s===1?this._unsafeLadder(e,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),r,o)}createCache(e,r){kf(r,this.bits),If.set(e,r),ci.delete(e)}hasCache(e){return li(e)!==1}}function ty(t,e,r,n){let o=e,s=t.ZERO,i=t.ZERO;for(;r>Zr||n>Zr;)r&Jt&&(s=s.add(o)),n&Jt&&(i=i.add(o)),o=o.double(),r>>=Jt,n>>=Jt;return{p1:s,p2:i}}function Rf(t,e,r,n){Qw(r,t),ey(n,e);const o=r.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,a=hf(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=ao(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 y=n[m],w=Number(y>>BigInt(h)&l);d[w]=d[w].add(r[m])}let g=i;for(let m=d.length-1,y=i;m>0;m--)y=y.add(d[m]),g=g.add(y);if(f=f.add(g),h!==0)for(let m=0;m<c;m++)f=f.double()}return f}function Ll(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Yw(e),e}else return pr(t,{isLE:r})}function Tf(t,e,r={},n){if(n===void 0&&(n=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>Zr))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Ll(e.p,r.Fp,n),s=Ll(e.n,r.Fn,n),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),be=BigInt(1),di=BigInt(2),ry=BigInt(8);function ny(t,e,r,n){const o=t.sqr(r),s=t.sqr(n),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 oy(t,e={}){const r=Tf("edwards",t,e,e.FpFnLE),{Fp:n,Fn:o}=r;let s=r.CURVE;const{h:i}=s;co(e,{},{uvRatio:"function"});const a=di<<BigInt(o.BYTES*8)-be,c=y=>n.create(y),l=e.uvRatio||((y,w)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,w))}}catch{return{isValid:!1,value:_t}}});if(!ny(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function d(y,w,I=!1){const v=I?be:_t;return ga("coordinate "+y,w,v,a),w}function u(y){if(!(y instanceof g))throw new Error("ExtendedPoint expected")}const f=ns((y,w)=>{const{X:I,Y:v,Z:k}=y,B=y.is0();w==null&&(w=B?ry:n.inv(k));const R=c(I*w),N=c(v*w),A=n.mul(k,w);if(B)return{x:_t,y:be};if(A!==be)throw new Error("invZ was invalid");return{x:R,y:N}}),h=ns(y=>{const{a:w,d:I}=s;if(y.is0())throw new Error("bad point: ZERO");const{X:v,Y:k,Z:B,T:R}=y,N=c(v*v),A=c(k*k),x=c(B*B),S=c(x*x),T=c(N*w),P=c(x*c(T+A)),b=c(S+c(I*c(N*A)));if(P!==b)throw new Error("bad point: equation left != right (1)");const E=c(v*k),C=c(B*R);if(E!==C)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(w,I,v,k){this.X=d("x",w),this.Y=d("y",I),this.Z=d("z",v,!0),this.T=d("t",k),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:v}=w||{};return d("x",I),d("y",v),new g(I,v,be,c(I*v))}static fromBytes(w,I=!1){const v=n.BYTES,{a:k,d:B}=s;w=Cl(tt(w,v,"point")),ar(I,"zip215");const R=Cl(w),N=w[v-1];R[v-1]=N&-129;const A=Vn(R),x=I?a:n.ORDER;ga("point.y",A,_t,x);const S=c(A*A),T=c(S-be),P=c(B*S-k);let{isValid:b,value:E}=l(T,P);if(!b)throw new Error("bad point: invalid y coordinate");const C=(E&be)===be,L=(N&128)!==0;if(!I&&E===_t&&L)throw new Error("bad point: x=0 and x_0=1");return L!==C&&(E=c(-E)),g.fromAffine({x:E,y:A})}static fromHex(w,I=!1){return g.fromBytes(fe("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(di),this}assertValidity(){h(this)}equals(w){u(w);const{X:I,Y:v,Z:k}=this,{X:B,Y:R,Z:N}=w,A=c(I*N),x=c(B*k),S=c(v*N),T=c(R*k);return A===x&&S===T}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:v,Z:k}=this,B=c(I*I),R=c(v*v),N=c(di*c(k*k)),A=c(w*B),x=I+v,S=c(c(x*x)-B-R),T=A+R,P=T-N,b=A-R,E=c(S*P),C=c(T*b),L=c(S*b),M=c(P*T);return new g(E,C,M,L)}add(w){u(w);const{a:I,d:v}=s,{X:k,Y:B,Z:R,T:N}=this,{X:A,Y:x,Z:S,T}=w,P=c(k*A),b=c(B*x),E=c(N*v*T),C=c(R*S),L=c((k+B)*(A+x)-P-b),M=C-E,$=C+E,j=c(b-I*P),D=c(L*M),_=c($*j),O=c(L*j),q=c(M*$);return new g(D,_,q,O)}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:v}=m.cached(this,w,k=>Qt(g,k));return Qt(g,[I,v])[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===be?this:m.unsafe(this,w,v=>Qt(g,v),I)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(w){return f(this,w)}clearCofactor(){return i===be?this:this.multiplyUnsafe(i)}toBytes(){const{x:w,y:I}=this.toAffine(),v=n.toBytes(I);return v[v.length-1]|=w&be?128:0,v}toHex(){return rr(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 Qt(g,w)}static msm(w,I){return Rf(g,o,w,I)}_setWindowSize(w){this.precompute(w)}toRawBytes(){return this.toBytes()}}g.BASE=new g(s.Gx,s.Gy,be,c(s.Gx*s.Gy)),g.ZERO=new g(_t,be,be,_t),g.Fp=n,g.Fn=o;const m=new Cf(g,o.BITS);return g.BASE.precompute(8),g}function sy(t,e,r={}){if(typeof e!="function")throw new Error('"hash" function param is required');co(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:o,Fp:s,Fn:i}=t,a=r.randomBytes||dc,c=r.adjustScalarBytes||(x=>x),l=r.domain||((x,S,T)=>{if(ar(T,"phflag"),S.length||T)throw new Error("Contexts/pre-hash are not supported");return x});function d(x){return i.create(Vn(x))}function u(x){const S=v.secretKey;x=fe("private key",x,S);const T=fe("hashed private key",e(x),2*S),P=c(T.slice(0,S)),b=T.slice(S,2*S),E=d(P);return{head:P,prefix:b,scalar:E}}function f(x){const{head:S,prefix:T,scalar:P}=u(x),b=o.multiply(P),E=b.toBytes();return{head:S,prefix:T,scalar:P,point:b,pointBytes:E}}function h(x){return f(x).pointBytes}function g(x=Uint8Array.of(),...S){const T=ct(...S);return d(e(l(T,fe("context",x),!!n)))}function m(x,S,T={}){x=fe("message",x),n&&(x=n(x));const{prefix:P,scalar:b,pointBytes:E}=f(S),C=g(T.context,P,x),L=o.multiply(C).toBytes(),M=g(T.context,L,E,x),$=i.create(C+M*b);if(!i.isValid($))throw new Error("sign failed: invalid s");const j=ct(L,i.toBytes($));return tt(j,v.signature,"result")}const y={zip215:!0};function w(x,S,T,P=y){const{context:b,zip215:E}=P,C=v.signature;x=fe("signature",x,C),S=fe("message",S),T=fe("publicKey",T,v.publicKey),E!==void 0&&ar(E,"zip215"),n&&(S=n(S));const L=C/2,M=x.subarray(0,L),$=Vn(x.subarray(L,C));let j,D,_;try{j=t.fromBytes(T,E),D=t.fromBytes(M,E),_=o.multiplyUnsafe($)}catch{return!1}if(!E&&j.isSmallOrder())return!1;const O=g(b,D.toBytes(),j.toBytes(),S);return D.add(j.multiplyUnsafe(O)).subtract(_).clearCofactor().is0()}const I=s.BYTES,v={secretKey:I,publicKey:I,signature:2*I,seed:I};function k(x=a(v.seed)){return tt(x,v.seed,"seed")}function B(x){const S=A.randomSecretKey(x);return{secretKey:S,publicKey:h(S)}}function R(x){return io(x)&&x.length===i.BYTES}function N(x,S){try{return!!t.fromBytes(x,S)}catch{return!1}}const A={getExtendedPublicKey:f,randomSecretKey:k,isValidSecretKey:R,isValidPublicKey:N,toMontgomery(x){const{y:S}=t.fromBytes(x),T=v.publicKey,P=T===32;if(!P&&T!==57)throw new Error("only defined for 25519 and 448");const b=P?s.div(be+S,be-S):s.div(S-be,S+be);return s.toBytes(b)},toMontgomerySecret(x){const S=v.secretKey;tt(x,S);const T=e(x.subarray(0,S));return c(T).subarray(0,S)},randomPrivateKey:k,precompute(x=8,S=t.BASE){return S.precompute(x,!1)}};return Object.freeze({keygen:B,getPublicKey:h,sign:m,verify:w,utils:A,Point:t,lengths:v})}function iy(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},r=t.Fp,n=pr(e.n,t.nBitLength,!0),o={Fp:r,Fn:n,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 ay(t,e){const r=e.Point;return Object.assign({},e,{ExtendedPoint:r,CURVE:t,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function cy(t){const{CURVE:e,curveOpts:r,hash:n,eddsaOpts:o}=iy(t),s=oy(e,r),i=sy(s,n,o);return ay(t,i)}const ly=BigInt(1),Bl=BigInt(2);BigInt(3);const dy=BigInt(5),uy=BigInt(8),pc=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Pf={p:pc,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:uy,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function fy(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=pc,a=t*t%s*t%s,c=ue(a,Bl,s)*a%s,l=ue(c,ly,s)*t%s,d=ue(l,dy,s)*l%s,u=ue(d,e,s)*d%s,f=ue(u,r,s)*u%s,h=ue(f,n,s)*f%s,g=ue(h,o,s)*h%s,m=ue(g,o,s)*h%s,y=ue(m,e,s)*d%s;return{pow_p_5_8:ue(y,Bl,s)*t%s,b2:a}}function hy(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const _l=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function py(t,e){const r=pc,n=ye(e*e*e,r),o=ye(n*n*e,r),s=fy(t*o).pow_p_5_8;let i=ye(t*n*s,r);const a=ye(e*i*i,r),c=i,l=ye(i*_l,r),d=a===t,u=a===ye(-t,r),f=a===ye(-t*_l,r);return d&&(i=c),(u||f)&&(i=l),Gw(i,r)&&(i=ye(-i,r)),{isValid:d||u,value:i}}const gy=pr(Pf.p,{isLE:!0}),my={...Pf,Fp:gy,hash:Uw,adjustScalarBytes:hy,uvRatio:py},ss=cy(my);class Dl extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}}class Ol extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class wy extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}const It={get(t=globalThis){const e=t.crypto;if(e?.subtle==null)throw new wy("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}},is=32,mt=64,ma=32;let Ur;const Nf=(async()=>{try{return await It.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function yy(){const t=ss.utils.randomPrivateKey(),e=ss.getPublicKey(t);return{privateKey:ky(t,e),publicKey:e}}async function by(t,e){let r;t.length===mt?r=t.subarray(0,32):r=t;const n={crv:"Ed25519",kty:"OKP",x:Q(t.subarray(32),"base64url"),d:Q(r,"base64url"),ext:!0,key_ops:["sign"]},o=await It.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),s=await It.get().subtle.sign({name:"Ed25519"},o,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(s,0,s.byteLength)}function vy(t,e){const r=t.subarray(0,ma);return ss.sign(e instanceof Uint8Array?e:e.subarray(),r)}async function xy(t,e){return Ur==null&&(Ur=await Nf),Ur?by(t,e):vy(t,e)}async function Sy(t,e,r){if(t.buffer instanceof ArrayBuffer){const n=await It.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await It.get().subtle.verify({name:"Ed25519"},n,e,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Ey(t,e,r){return ss.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function Ay(t,e,r){return Ur==null&&(Ur=await Nf),Ur?Sy(t,e,r):Ey(t,e,r)}function ky(t,e){const r=new Uint8Array(mt);for(let n=0;n<ma;n++)r[n]=t[n],r[ma+n]=e[n];return r}function Os(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}class Lf{type="Ed25519";raw;constructor(e){this.raw=Gn(e,is)}toMultihash(){return oo.digest(Us(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return Le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:nt(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();const o=Ay(this.raw,r,e);return Os(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}}class wa{type="Ed25519";raw;publicKey;constructor(e,r){this.raw=Gn(e,mt),this.publicKey=new Lf(r)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:nt(this.raw,e.raw)}sign(e,r){r?.signal?.throwIfAborted();const n=xy(this.raw,e);return Os(n)?n.then(o=>(r?.signal?.throwIfAborted(),o)):(r?.signal?.throwIfAborted(),n)}}function Iy(t){if(t.length>mt){t=Gn(t,mt+is);const n=t.subarray(0,mt),o=t.subarray(mt,t.length);return new wa(n,o)}t=Gn(t,mt);const e=t.subarray(0,mt),r=t.subarray(is);return new wa(e,r)}function Bf(t){return t=Gn(t,is),new Lf(t)}async function Cy(){const{privateKey:t,publicKey:e}=yy();return new wa(t,e)}function Gn(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new rt(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}const Ry=Math.pow(2,7),Ty=Math.pow(2,14),Py=Math.pow(2,21),gc=Math.pow(2,28),mc=Math.pow(2,35),wc=Math.pow(2,42),yc=Math.pow(2,49),te=128,Ce=127;function gr(t){if(t<Ry)return 1;if(t<Ty)return 2;if(t<Py)return 3;if(t<gc)return 4;if(t<mc)return 5;if(t<wc)return 6;if(t<yc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function _f(t,e,r=0){switch(gr(t)){case 8:e[r++]=t&255|te,t/=128;case 7:e[r++]=t&255|te,t/=128;case 6:e[r++]=t&255|te,t/=128;case 5:e[r++]=t&255|te,t/=128;case 4:e[r++]=t&255|te,t>>>=7;case 3:e[r++]=t&255|te,t>>>=7;case 2:e[r++]=t&255|te,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Ny(t,e,r=0){switch(gr(t)){case 8:e.set(r++,t&255|te),t/=128;case 7:e.set(r++,t&255|te),t/=128;case 6:e.set(r++,t&255|te),t/=128;case 5:e.set(r++,t&255|te),t/=128;case 4:e.set(r++,t&255|te),t>>>=7;case 3:e.set(r++,t&255|te),t>>>=7;case 2:e.set(r++,t&255|te),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function Df(t,e){let r=t[e],n=0;if(n+=r&Ce,r<te||(r=t[e+1],n+=(r&Ce)<<7,r<te)||(r=t[e+2],n+=(r&Ce)<<14,r<te)||(r=t[e+3],n+=(r&Ce)<<21,r<te)||(r=t[e+4],n+=(r&Ce)*gc,r<te)||(r=t[e+5],n+=(r&Ce)*mc,r<te)||(r=t[e+6],n+=(r&Ce)*wc,r<te)||(r=t[e+7],n+=(r&Ce)*yc,r<te))return n;throw new RangeError("Could not decode varint")}function Ly(t,e){let r=t.get(e),n=0;if(n+=r&Ce,r<te||(r=t.get(e+1),n+=(r&Ce)<<7,r<te)||(r=t.get(e+2),n+=(r&Ce)<<14,r<te)||(r=t.get(e+3),n+=(r&Ce)<<21,r<te)||(r=t.get(e+4),n+=(r&Ce)*gc,r<te)||(r=t.get(e+5),n+=(r&Ce)*mc,r<te)||(r=t.get(e+6),n+=(r&Ce)*wc,r<te)||(r=t.get(e+7),n+=(r&Ce)*yc,r<te))return n;throw new RangeError("Could not decode varint")}function By(t,e,r=0){return e==null&&(e=kt(gr(t))),e instanceof Uint8Array?_f(t,e,r):Ny(t,e,r)}function Of(t,e=0){return t instanceof Uint8Array?Df(t,e):Ly(t,e)}const bc=new Float32Array([-0]),Ht=new Uint8Array(bc.buffer);function _y(t,e,r){bc[0]=t,e[r]=Ht[0],e[r+1]=Ht[1],e[r+2]=Ht[2],e[r+3]=Ht[3]}function Dy(t,e){return Ht[0]=t[e],Ht[1]=t[e+1],Ht[2]=t[e+2],Ht[3]=t[e+3],bc[0]}const vc=new Float64Array([-0]),Re=new Uint8Array(vc.buffer);function Oy(t,e,r){vc[0]=t,e[r]=Re[0],e[r+1]=Re[1],e[r+2]=Re[2],e[r+3]=Re[3],e[r+4]=Re[4],e[r+5]=Re[5],e[r+6]=Re[6],e[r+7]=Re[7]}function Fy(t,e){return Re[0]=t[e],Re[1]=t[e+1],Re[2]=t[e+2],Re[3]=t[e+3],Re[4]=t[e+4],Re[5]=t[e+5],Re[6]=t[e+6],Re[7]=t[e+7],vc[0]}const My=BigInt(Number.MAX_SAFE_INTEGER),jy=BigInt(Number.MIN_SAFE_INTEGER);class Te{lo;hi;constructor(e,r){this.lo=e|0,this.hi=r|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){const r=~this.lo+1>>>0;let n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*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 r=~this.lo+1>>>0;let n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<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,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return nr;if(e<My&&e>jy)return this.fromNumber(Number(e));const r=e<0n;r&&(e=-e);let n=e>>32n,o=e-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>Fl&&(o=0n,++n>Fl&&(n=0n))),new Te(Number(o),Number(n))}static fromNumber(e){if(e===0)return nr;const r=e<0;r&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new Te(n,o)}static from(e){return typeof e=="number"?Te.fromNumber(e):typeof e=="bigint"?Te.fromBigInt(e):typeof e=="string"?Te.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new Te(e.low>>>0,e.high>>>0):nr}}const nr=new Te(0,0);nr.toBigInt=function(){return 0n};nr.zzEncode=nr.zzDecode=function(){return this};nr.length=function(){return 1};const Fl=4294967296n;function Uy(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(r&64512)===55296&&(t.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function $y(t,e,r){if(r-e<1)return"";let o;const s=[];let i=0,a;for(;e<r;)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 Ff(t,e,r){const n=r;let o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128);return r-n}function Qe(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function So(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}class Hy{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Qe(this,10);return e}int32(){return this.uint32()|0}sint32(){const e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Qe(this,4);return So(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Qe(this,4);return So(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Qe(this,4);const e=Dy(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Qe(this,4);const e=Fy(this.buf,this.pos);return this.pos+=8,e}bytes(){const e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw Qe(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){const e=this.bytes();return $y(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Qe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Qe(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new Te(0,0);let r=0;if(this.len-this.pos>4){for(;r<4;++r)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*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;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw Qe(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,e}if(this.len-this.pos>4){for(;r<5;++r)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;r<5;++r){if(this.pos>=this.len)throw Qe(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Qe(this,8);const e=So(this.buf,this.pos+=4),r=So(this.buf,this.pos+=4);return new Te(e,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=Df(this.buf,this.pos);return this.pos+=gr(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 qy(t){return new Hy(t instanceof Uint8Array?t:t.subarray())}function Fs(t,e,r){const n=qy(t);return e.decode(n,void 0,r)}function Ky(t){let n,o=8192;return function(i){if(i<1||i>4096)return kt(i);o+i>8192&&(n=kt(8192),o=0);const a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}class Nn{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}}function ui(){}class zy{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const Wy=Ky();function Vy(t){return globalThis.Buffer!=null?kt(t):Wy(t)}class ya{len;head;tail;states;constructor(){this.len=0,this.head=new Nn(ui,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new Nn(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Xy((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(Eo,10,Te.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const r=Te.fromBigInt(e);return this._push(Eo,r.length(),r)}uint64Number(e){return this._push(_f,gr(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 r=Te.fromBigInt(e).zzEncode();return this._push(Eo,r.length(),r)}sint64Number(e){const r=Te.fromNumber(e).zzEncode();return this._push(Eo,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(fi,1,e?1:0)}fixed32(e){return this._push(mn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const r=Te.fromBigInt(e);return this._push(mn,4,r.lo)._push(mn,4,r.hi)}fixed64Number(e){const r=Te.fromNumber(e);return this._push(mn,4,r.lo)._push(mn,4,r.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(_y,4,e)}double(e){return this._push(Oy,8,e)}bytes(e){const r=e.length>>>0;return r===0?this._push(fi,1,0):this.uint32(r)._push(Yy,r,e)}string(e){const r=Uy(e);return r!==0?this.uint32(r)._push(Ff,r,e):this._push(fi,1,0)}fork(){return this.states=new zy(this),this.head=this.tail=new Nn(ui,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 Nn(ui,0,0),this.len=0),this}ldelim(){const e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=r,this.len+=n),this}finish(){let e=this.head.next;const r=Vy(this.len);let n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}}function fi(t,e,r){e[r]=t&255}function Gy(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}class Xy extends Nn{next;constructor(e,r){super(Gy,e,r),this.next=void 0}}function Eo(t,e,r){for(;t.hi!==0;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}function mn(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function Yy(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(ya.prototype.bytes=function(t){const e=t.length>>>0;return this.uint32(e),e>0&&this._push(Zy,e,t),this},ya.prototype.string=function(t){const e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(Jy,e,t),this});function Zy(t,e,r){e.set(t,r)}function Jy(t,e,r){t.length<40?Ff(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(we(t),r)}function Qy(){return new ya}function Ms(t,e){const r=Qy();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var as;(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"})(as||(as={}));function Mf(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function eb(t){function e(o){if(t[o.toString()]==null)throw new Error("Invalid enum value");return t[o]}const r=function(s,i){const a=e(s);i.int32(a)},n=function(s){const i=s.int32();return e(i)};return Mf("enum",as.VARINT,r,n)}function js(t,e){return Mf("message",as.LENGTH_DELIMITED,t,e)}class Ml extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var le;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(le||(le={}));var ba;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(ba||(ba={}));(function(t){t.codec=()=>eb(ba)})(le||(le={}));var cr;(function(t){let e;t.codec=()=>(e==null&&(e=js((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),le.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{const s={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){const a=r.uint32();switch(a>>>3){case 1:{s.Type=le.codec().decode(r);break}case 2:{s.Data=r.bytes();break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ms(r,t.codec()),t.decode=(r,n)=>Fs(r,t.codec(),n)})(cr||(cr={}));var cs;(function(t){let e;t.codec=()=>(e==null&&(e=js((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),le.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{const s={},i=n==null?r.len:r.pos+n;for(;r.pos<i;){const a=r.uint32();switch(a>>>3){case 1:{s.Type=le.codec().decode(r);break}case 2:{s.Data=r.bytes();break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ms(r,t.codec()),t.decode=(r,n)=>Fs(r,t.codec(),n)})(cs||(cs={}));const jf=df;class Uf{type="RSA";jwk;_raw;_multihash;constructor(e,r){this.jwk=e,this._multihash=r}get raw(){return this._raw==null&&(this._raw=Hf(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ce.createV1(114,this._multihash)}toString(){return Le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:nt(this.raw,e.raw)}verify(e,r,n){return gb(this.jwk,r,e,n)}}class tb{type="RSA";jwk;_raw;publicKey;constructor(e,r){this.jwk=e,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=ib(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:nt(this.raw,e.raw)}sign(e,r){return pb(this.jwk,e,r)}}const rb=8192,$f=18,nb=1062,ob=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function sb(t){return{n:Q(t[1],"base64url"),e:Q(t[2],"base64url"),d:Q(t[3],"base64url"),p:Q(t[4],"base64url"),q:Q(t[5],"base64url"),dp:Q(t[6],"base64url"),dq:Q(t[7],"base64url"),qi:Q(t[8],"base64url"),kty:"RSA"}}function ib(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 rt("JWK was missing components");return St([Ue(Uint8Array.from([0])),Ue(we(t.n,"base64url")),Ue(we(t.e,"base64url")),Ue(we(t.d,"base64url")),Ue(we(t.p,"base64url")),Ue(we(t.q,"base64url")),Ue(we(t.dp,"base64url")),Ue(we(t.dq,"base64url")),Ue(we(t.qi,"base64url"))]).subarray()}function ab(t){const e=sn(t[1],{offset:0});return{kty:"RSA",n:Q(e[0],"base64url"),e:Q(e[1],"base64url")}}function Hf(t){if(t.n==null||t.e==null)throw new rt("JWK was missing components");return St([ob,cc(St([Ue(we(t.n,"base64url")),Ue(we(t.e,"base64url"))]))]).subarray()}function cb(t){const e=sn(t);return lb(e)}function lb(t){const e=sb(t);return fb(e)}function db(t,e){if(t.byteLength>=nb)throw new Uu("Key size is too large");const r=sn(t,{offset:0});return ub(r,t,e)}function ub(t,e,r){const n=ab(t);if(r==null){const o=jf(cr.encode({Type:le.RSA,Data:e}));r=no($f,o)}return new Uf(n,r)}function fb(t){if(mb(t)>rb)throw new rt("Key size is too large");const e=hb(t),r=jf(cr.encode({Type:le.RSA,Data:Hf(e.publicKey)})),n=no($f,r);return new tb(e.privateKey,new Uf(e.publicKey,n))}function hb(t){if(t==null)throw new rt("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function pb(t,e,r){const n=await It.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();const o=await It.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function gb(t,e,r,n){const o=await It.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();const s=await It.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),s}function mb(t){if(t.kty!=="RSA")throw new rt("invalid key type");if(t.n==null)throw new rt("invalid key modulus");return we(t.n,"base64url").length*8}class qf extends sf{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,nf(e);const n=lc(r);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(n.length>o?e.create().update(n).digest():n);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),Yr(s)}update(e){return ts(this),this.iHash.update(e),this}digestInto(e){ts(this),hr(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:r,iHash:n,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=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Kf=(t,e,r)=>new qf(t,e).update(r).digest();Kf.create=(t,e)=>new qf(t,e);const jl=(t,e)=>(t+(t>=0?e:-e)/zf)/e;function wb(t,e,r){const[[n,o],[s,i]]=e,a=jl(i*t,r),c=jl(-o*t,r);let l=t-a*n-c*s,d=-a*o-c*i;const u=l<bt,f=d<bt;u&&(l=-l),f&&(d=-d);const h=ao(Math.ceil(hf(r)/2))+$r;if(l<bt||l>=h||d<bt||d>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:f,k2:d}}function va(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function hi(t,e){const r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return ar(r.lowS,"lowS"),ar(r.prehash,"prehash"),r.format!==void 0&&va(r.format),r}class yb extends Error{constructor(e=""){super(e)}}const wt={Err:yb,_tlv:{encode:(t,e)=>{const{Err:r}=wt;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const n=e.length/2,o=xo(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?xo(o.length/2|128):"";return xo(t)+s+o+e},decode(t,e){const{Err:r}=wt;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const o=e[n++],s=!!(o&128);let i=0;if(!s)i=o;else{const c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(n,n+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){const{Err:e}=wt;if(t<bt)throw new e("integer: negative integers are not allowed");let r=xo(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=wt;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 Ds(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=wt,o=fe("signature",t),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,s),{v:l,l:d}=n.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(t){const{_tlv:e,_int:r}=wt,n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}},bt=BigInt(0),$r=BigInt(1),zf=BigInt(2),Ao=BigInt(3),bb=BigInt(4);function Lr(t,e){const{BYTES:r}=t;let n;if(typeof e=="bigint")n=e;else{let o=fe("private key",e);try{n=t.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function vb(t,e={}){const r=Tf("weierstrass",t,e),{Fp:n,Fn:o}=r;let s=r.CURVE;const{h:i,n:a}=s;co(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Vf(n,o);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(P,b,E){const{x:C,y:L}=b.toAffine(),M=n.toBytes(C);if(ar(E,"isCompressed"),E){d();const $=!n.isOdd(L);return ct(Wf($),M)}else return ct(Uint8Array.of(4),M,n.toBytes(L))}function f(P){tt(P,void 0,"Point");const{publicKey:b,publicKeyUncompressed:E}=l,C=P.length,L=P[0],M=P.subarray(1);if(C===b&&(L===2||L===3)){const $=n.fromBytes(M);if(!n.isValid($))throw new Error("bad point: is not on curve, wrong x");const j=m($);let D;try{D=n.sqrt(j)}catch(q){const H=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}d();const _=n.isOdd(D);return(L&1)===1!==_&&(D=n.neg(D)),{x:$,y:D}}else if(C===E&&L===4){const $=n.BYTES,j=n.fromBytes(M.subarray(0,$)),D=n.fromBytes(M.subarray($,$*2));if(!y(j,D))throw new Error("bad point: is not on curve");return{x:j,y:D}}else throw new Error(`bad point: got length ${C}, expected compressed=${b} or uncompressed=${E}`)}const h=e.toBytes||u,g=e.fromBytes||f;function m(P){const b=n.sqr(P),E=n.mul(b,P);return n.add(n.add(E,n.mul(P,s.a)),s.b)}function y(P,b){const E=n.sqr(b),C=m(P);return n.eql(E,C)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const w=n.mul(n.pow(s.a,Ao),bb),I=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(w,I)))throw new Error("bad curve params: a or b");function v(P,b,E=!1){if(!n.isValid(b)||E&&n.is0(b))throw new Error(`bad point coordinate ${P}`);return b}function k(P){if(!(P instanceof x))throw new Error("ProjectivePoint expected")}function B(P){if(!c||!c.basises)throw new Error("no endo");return wb(P,c.basises,o.ORDER)}const R=ns((P,b)=>{const{X:E,Y:C,Z:L}=P;if(n.eql(L,n.ONE))return{x:E,y:C};const M=P.is0();b==null&&(b=M?n.ONE:n.inv(L));const $=n.mul(E,b),j=n.mul(C,b),D=n.mul(L,b);if(M)return{x:n.ZERO,y:n.ZERO};if(!n.eql(D,n.ONE))throw new Error("invZ was invalid");return{x:$,y:j}}),N=ns(P=>{if(P.is0()){if(e.allowInfinityPoint&&!n.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:b,y:E}=P.toAffine();if(!n.isValid(b)||!n.isValid(E))throw new Error("bad point: x or y not field elements");if(!y(b,E))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function A(P,b,E,C,L){return E=new x(n.mul(E.X,P),E.Y,E.Z),b=os(C,b),E=os(L,E),b.add(E)}class x{constructor(b,E,C){this.X=v("x",b),this.Y=v("y",E,!0),this.Z=v("z",C),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){const{x:E,y:C}=b||{};if(!b||!n.isValid(E)||!n.isValid(C))throw new Error("invalid affine point");if(b instanceof x)throw new Error("projective point not allowed");return n.is0(E)&&n.is0(C)?x.ZERO:new x(E,C,n.ONE)}static fromBytes(b){const E=x.fromAffine(g(tt(b,void 0,"point")));return E.assertValidity(),E}static fromHex(b){return x.fromBytes(fe("pointHex",b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,E=!0){return T.createCache(this,b),E||this.multiply(Ao),this}assertValidity(){N(this)}hasEvenY(){const{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){k(b);const{X:E,Y:C,Z:L}=this,{X:M,Y:$,Z:j}=b,D=n.eql(n.mul(E,j),n.mul(M,L)),_=n.eql(n.mul(C,j),n.mul($,L));return D&&_}negate(){return new x(this.X,n.neg(this.Y),this.Z)}double(){const{a:b,b:E}=s,C=n.mul(E,Ao),{X:L,Y:M,Z:$}=this;let j=n.ZERO,D=n.ZERO,_=n.ZERO,O=n.mul(L,L),q=n.mul(M,M),H=n.mul($,$),K=n.mul(L,M);return K=n.add(K,K),_=n.mul(L,$),_=n.add(_,_),j=n.mul(b,_),D=n.mul(C,H),D=n.add(j,D),j=n.sub(q,D),D=n.add(q,D),D=n.mul(j,D),j=n.mul(K,j),_=n.mul(C,_),H=n.mul(b,H),K=n.sub(O,H),K=n.mul(b,K),K=n.add(K,_),_=n.add(O,O),O=n.add(_,O),O=n.add(O,H),O=n.mul(O,K),D=n.add(D,O),H=n.mul(M,$),H=n.add(H,H),O=n.mul(H,K),j=n.sub(j,O),_=n.mul(H,q),_=n.add(_,_),_=n.add(_,_),new x(j,D,_)}add(b){k(b);const{X:E,Y:C,Z:L}=this,{X:M,Y:$,Z:j}=b;let D=n.ZERO,_=n.ZERO,O=n.ZERO;const q=s.a,H=n.mul(s.b,Ao);let K=n.mul(E,M),z=n.mul(C,$),V=n.mul(L,j),X=n.add(E,C),G=n.add(M,$);X=n.mul(X,G),G=n.add(K,z),X=n.sub(X,G),G=n.add(E,L);let Y=n.add(M,j);return G=n.mul(G,Y),Y=n.add(K,V),G=n.sub(G,Y),Y=n.add(C,L),D=n.add($,j),Y=n.mul(Y,D),D=n.add(z,V),Y=n.sub(Y,D),O=n.mul(q,G),D=n.mul(H,V),O=n.add(D,O),D=n.sub(z,O),O=n.add(z,O),_=n.mul(D,O),z=n.add(K,K),z=n.add(z,K),V=n.mul(q,V),G=n.mul(H,G),z=n.add(z,V),V=n.sub(K,V),V=n.mul(q,V),G=n.add(G,V),K=n.mul(z,G),_=n.add(_,K),K=n.mul(Y,G),D=n.mul(X,D),D=n.sub(D,K),K=n.mul(X,z),O=n.mul(Y,O),O=n.add(O,K),new x(D,_,O)}subtract(b){return this.add(b.negate())}is0(){return this.equals(x.ZERO)}multiply(b){const{endo:E}=e;if(!o.isValidNot0(b))throw new Error("invalid scalar: out of range");let C,L;const M=$=>T.cached(this,$,j=>Qt(x,j));if(E){const{k1neg:$,k1:j,k2neg:D,k2:_}=B(b),{p:O,f:q}=M(j),{p:H,f:K}=M(_);L=q.add(K),C=A(E.beta,O,H,$,D)}else{const{p:$,f:j}=M(b);C=$,L=j}return Qt(x,[C,L])[0]}multiplyUnsafe(b){const{endo:E}=e,C=this;if(!o.isValid(b))throw new Error("invalid scalar: out of range");if(b===bt||C.is0())return x.ZERO;if(b===$r)return C;if(T.hasCache(this))return this.multiply(b);if(E){const{k1neg:L,k1:M,k2neg:$,k2:j}=B(b),{p1:D,p2:_}=ty(x,C,M,j);return A(E.beta,D,_,L,$)}else return T.unsafe(C,b)}multiplyAndAddUnsafe(b,E,C){const L=this.multiplyUnsafe(E).add(b.multiplyUnsafe(C));return L.is0()?void 0:L}toAffine(b){return R(this,b)}isTorsionFree(){const{isTorsionFree:b}=e;return i===$r?!0:b?b(x,this):T.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:b}=e;return i===$r?this:b?b(x,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(b=!0){return ar(b,"isCompressed"),this.assertValidity(),h(x,this,b)}toHex(b=!0){return rr(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(b=!0){return this.toBytes(b)}_setWindowSize(b){this.precompute(b)}static normalizeZ(b){return Qt(x,b)}static msm(b,E){return Rf(x,o,b,E)}static fromPrivateKey(b){return x.BASE.multiply(Lr(o,b))}}x.BASE=new x(s.Gx,s.Gy,n.ONE),x.ZERO=new x(n.ZERO,n.ONE,n.ZERO),x.Fp=n,x.Fn=o;const S=o.BITS,T=new Cf(x,e.endo?Math.ceil(S/2):S);return x.BASE.precompute(8),x}function Wf(t){return Uint8Array.of(t?2:3)}function Vf(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function xb(t,e={}){const{Fn:r}=t,n=e.randomBytes||dc,o=Object.assign(Vf(t.Fp,r),{seed:Af(r.ORDER)});function s(h){try{return!!Lr(r,h)}catch{return!1}}function i(h,g){const{publicKey:m,publicKeyUncompressed:y}=o;try{const w=h.length;return g===!0&&w!==m||g===!1&&w!==y?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=n(o.seed)){return Jw(tt(h,o.seed,"seed"),r.ORDER)}function c(h,g=!0){return t.BASE.multiply(Lr(r,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:y}=o;if(r.allowedLengths||g===m)return;const w=fe("key",h).length;return w===m||w===y}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 y=Lr(r,h);return t.fromHex(g).multiply(y).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=>Lr(r,h),precompute(h=8,g=t.BASE){return g.precompute(h,!1)}},lengths:o})}function Sb(t,e,r={}){nf(e),co(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=r.randomBytes||dc,o=r.hmac||((E,...C)=>Kf(e,E,ct(...C))),{Fp:s,Fn:i}=t,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h}=xb(t,r),g={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function y(E){const C=a>>$r;return E>C}function w(E,C){if(!i.isValidNot0(C))throw new Error(`invalid signature ${E}: out of range 1..Point.Fn.ORDER`);return C}function I(E,C){va(C);const L=h.signature,M=C==="compact"?L:C==="recovered"?L+1:void 0;return tt(E,M,`${C} signature`)}class v{constructor(C,L,M){this.r=w("r",C),this.s=w("s",L),M!=null&&(this.recovery=M),Object.freeze(this)}static fromBytes(C,L=m){I(C,L);let M;if(L==="der"){const{r:_,s:O}=wt.toSig(tt(C));return new v(_,O)}L==="recovered"&&(M=C[0],L="compact",C=C.subarray(1));const $=i.BYTES,j=C.subarray(0,$),D=C.subarray($,$*2);return new v(i.fromBytes(j),i.fromBytes(D),M)}static fromHex(C,L){return this.fromBytes(rs(C),L)}addRecoveryBit(C){return new v(this.r,this.s,C)}recoverPublicKey(C){const L=s.ORDER,{r:M,s:$,recovery:j}=this;if(j==null||![0,1,2,3].includes(j))throw new Error("recovery id invalid");if(a*zf<L&&j>1)throw new Error("recovery id is ambiguous for h>1 curve");const _=j===2||j===3?M+a:M;if(!s.isValid(_))throw new Error("recovery id 2 or 3 invalid");const O=s.toBytes(_),q=t.fromBytes(ct(Wf((j&1)===0),O)),H=i.inv(_),K=B(fe("msgHash",C)),z=i.create(-K*H),V=i.create($*H),X=t.BASE.multiplyUnsafe(z).add(q.multiplyUnsafe(V));if(X.is0())throw new Error("point at infinify");return X.assertValidity(),X}hasHighS(){return y(this.s)}toBytes(C=m){if(va(C),C==="der")return rs(wt.hexFromSig(this));const L=i.toBytes(this.r),M=i.toBytes(this.s);if(C==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return ct(Uint8Array.of(this.recovery),L,M)}return ct(L,M)}toHex(C){return rr(this.toBytes(C))}assertValidity(){}static fromCompact(C){return v.fromBytes(fe("sig",C),"compact")}static fromDER(C){return v.fromBytes(fe("sig",C),"der")}normalizeS(){return this.hasHighS()?new v(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return rr(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return rr(this.toBytes("compact"))}}const k=r.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");const L=Ds(C),M=C.length*8-c;return M>0?L>>BigInt(M):L},B=r.bits2int_modN||function(C){return i.create(k(C))},R=ao(c);function N(E){return ga("num < 2^"+c,E,bt,R),i.toBytes(E)}function A(E,C){return tt(E,void 0,"message"),C?tt(e(E),void 0,"prehashed message"):E}function x(E,C,L){if(["recovered","canonical"].some(z=>z in L))throw new Error("sign() legacy options not supported");const{lowS:M,prehash:$,extraEntropy:j}=hi(L,g);E=A(E,$);const D=B(E),_=Lr(i,C),O=[N(_),N(D)];if(j!=null&&j!==!1){const z=j===!0?n(h.secretKey):j;O.push(fe("extraEntropy",z))}const q=ct(...O),H=D;function K(z){const V=k(z);if(!i.isValidNot0(V))return;const X=i.inv(V),G=t.BASE.multiply(V).toAffine(),Y=i.create(G.x);if(Y===bt)return;const se=i.create(X*i.create(H+Y*_));if(se===bt)return;let Ne=(G.x===Y?0:2)|Number(G.y&$r),Me=se;return M&&y(se)&&(Me=i.neg(se),Ne^=1),new v(Y,Me,Ne)}return{seed:q,k2sig:K}}function S(E,C,L={}){E=fe("message",E);const{seed:M,k2sig:$}=x(E,C,L);return Hw(e.outputLen,i.BYTES,o)(M,$)}function T(E){let C;const L=typeof E=="string"||io(E),M=!L&&E!==null&&typeof E=="object"&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!L&&!M)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(M)C=new v(E.r,E.s);else if(L){try{C=v.fromBytes(fe("sig",E),"der")}catch($){if(!($ instanceof wt.Err))throw $}if(!C)try{C=v.fromBytes(fe("sig",E),"compact")}catch{return!1}}return C||!1}function P(E,C,L,M={}){const{lowS:$,prehash:j,format:D}=hi(M,g);if(L=fe("publicKey",L),C=A(fe("message",C),j),"strict"in M)throw new Error("options.strict was renamed to lowS");const _=D===void 0?T(E):v.fromBytes(fe("sig",E),D);if(_===!1)return!1;try{const O=t.fromBytes(L);if($&&_.hasHighS())return!1;const{r:q,s:H}=_,K=B(C),z=i.inv(H),V=i.create(K*z),X=i.create(q*z),G=t.BASE.multiplyUnsafe(V).add(O.multiplyUnsafe(X));return G.is0()?!1:i.create(G.x)===q}catch{return!1}}function b(E,C,L={}){const{prehash:M}=hi(L,g);return C=A(C,M),v.fromBytes(E,"recovered").recoverPublicKey(C).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h,Point:t,sign:S,verify:P,recoverPublicKey:b,Signature:v,hash:e})}function Eb(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},r=t.Fp;let n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0;const o=pr(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),s={Fp:r,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 Ab(t){const{CURVE:e,curveOpts:r}=Eb(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}function kb(t,e){const r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,Sf(r.Fn.ORDER,r.Fn.BITS))})}function Ib(t){const{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:o}=Ab(t),s=vb(e,r),i=Sb(s,n,o);return kb(t,i)}function Cb(t,e){const r=n=>Ib({...t,hash:n});return{...r(e),create:r}}const xc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Rb={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Ul=BigInt(2);function Tb(t){const e=xc.p,r=BigInt(3),n=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=ue(d,r,e)*d%e,f=ue(u,r,e)*d%e,h=ue(f,Ul,e)*l%e,g=ue(h,o,e)*h%e,m=ue(g,s,e)*g%e,y=ue(m,a,e)*m%e,w=ue(y,c,e)*y%e,I=ue(w,a,e)*m%e,v=ue(I,r,e)*d%e,k=ue(v,i,e)*g%e,B=ue(k,n,e)*l%e,R=ue(B,Ul,e);if(!xa.eql(xa.sqr(R),t))throw new Error("Cannot find square root");return R}const xa=pr(xc.p,{sqrt:Tb}),zt=Cb({...xc,Fp:xa,lowS:!0,endo:Rb},df);function Pb(t,e,r){const n=ac.digest(e instanceof Uint8Array?e:e.subarray());if(Os(n))return n.then(({digest:o})=>(r?.signal?.throwIfAborted(),zt.sign(o,t).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new Dl(String(o))});try{return zt.sign(n.digest,t).toDERRawBytes()}catch(o){throw new Dl(String(o))}}function Nb(t,e,r,n){const o=ac.digest(r instanceof Uint8Array?r:r.subarray());if(Os(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),zt.verify(e,s,t))).catch(s=>{throw s.name==="AbortError"?s:new Ol(String(s))});try{return n?.signal?.throwIfAborted(),zt.verify(e,o.digest,t)}catch(s){throw new Ol(String(s))}}class Gf{type="secp256k1";raw;_key;constructor(e){this._key=Ob(e),this.raw=_b(this._key)}toMultihash(){return oo.digest(Us(this))}toCID(){return ce.createV1(114,this.toMultihash())}toString(){return Le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:nt(this.raw,e.raw)}verify(e,r,n){return Nb(this._key,r,e,n)}}class Lb{type="secp256k1";raw;publicKey;constructor(e,r){this.raw=Db(e),this.publicKey=new Gf(r??Fb(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:nt(this.raw,e.raw)}sign(e,r){return Pb(this.raw,e,r)}}function Bb(t){return new Lb(t)}function Xf(t){return new Gf(t)}function _b(t){return zt.ProjectivePoint.fromHex(t).toRawBytes(!0)}function Db(t){try{return zt.getPublicKey(t,!0),t}catch(e){throw new $u(String(e))}}function Ob(t){try{return zt.ProjectivePoint.fromHex(t),t}catch(e){throw new Uu(String(e))}}function Fb(t){try{return zt.getPublicKey(t,!0)}catch(e){throw new $u(String(e))}}async function Mb(t,e){return Cy()}function Sa(t,e){const{Type:r,Data:n}=cr.decode(t),o=n??new Uint8Array;switch(r){case le.RSA:return db(o,e);case le.Ed25519:return Bf(o);case le.secp256k1:return Xf(o);case le.ECDSA:return tf(o);default:throw new Ns}}function jb(t){const{Type:e,Data:r}=cr.decode(t.digest),n=r??new Uint8Array;switch(e){case le.Ed25519:return Bf(n);case le.secp256k1:return Xf(n);case le.ECDSA:return tf(n);default:throw new Ns}}function Us(t){return cr.encode({Type:le[t.type],Data:t.raw})}function Ub(t){const e=cs.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case le.RSA:return cb(r);case le.Ed25519:return Iy(r);case le.secp256k1:return Bb(r);case le.ECDSA:return mw(r);default:throw new Ns}}function $b(t){return cs.encode({Type:le[t.type],Data:t.raw})}const Yf=Symbol.for("nodejs.util.inspect.custom"),Hb=114;class Sc{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()})`}[Hu]=!0;toString(){return this.string==null&&(this.string=Le.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ce.createV1(Hb,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return nt(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return nt(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Yf](){return`PeerId(${this.toString()})`}}class Zf extends Sc{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class Jf extends Sc{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class Qf extends Sc{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}const qb=2336;class eh{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=oo.digest(we(this.url))}[Yf](){return`PeerId(${this.url})`}[Hu]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ce.createV1(qb,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=Q(e)),e.toString()===this.toString())}}const Kb=114,$l=2336;function zb(t,e){let r;if(t.charAt(0)==="1"||t.charAt(0)==="Q")r=zu(Le.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return Wb(ce.parse(t));throw new rt('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return th(r)}function Jr(t){if(t.type==="Ed25519")return new Jf({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new Qf({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new Zf({multihash:t.toCID().multihash,publicKey:t});throw new Ns}function th(t){if(Gb(t))return new Zf({multihash:t});if(Vb(t))try{const e=jb(t);if(e.type==="Ed25519")return new Jf({multihash:t,publicKey:e});if(e.type==="secp256k1")return new Qf({multihash:t,publicKey:e})}catch{const r=Q(t.digest);return new eh(new URL(r))}throw new Rg("Supplied PeerID Multihash is invalid")}function Wb(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==Kb&&t.code!==$l)throw new Cg("Supplied PeerID CID is invalid");if(t.code===$l){const e=Q(t.multihash.digest);return new eh(new URL(e))}return th(t.multihash)}function Vb(t){return t.code===oo.code}function Gb(t){return t.code===ac.code}class rh extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class Xb extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class wn extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class Hl extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}}class Yb extends Event{data;constructor(e,r){super("message",r),this.data=e}}class Ec extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}}class Zb extends Ec{constructor(e,r){super(!0,e,r)}}class Jb extends Ec{constructor(e,r){super(!1,e,r)}}const Qb=t=>t/2**32|0,e0=t=>t>>>0;function t0(t,e,r,n){const o=Qb(r),s=e0(r);t.setUint32(e,n?s:o,n),t.setUint32(e+4,n?o:s,n)}function Ea(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const Aa=t=>t?`"${t}" `:"";function Ct(t,e=""){if(typeof t!="number")throw new TypeError(Aa(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(Aa(e)+"expected integer >= 0, got "+t);return t}function Rt(t,e,r=""){if(Ea(t)&&(e===void 0||t.length===e))return t;e!==void 0&&Ct(e,"length");const n=Ea(t),o=e!==void 0?` of length ${e}`:"",s=n?`length=${t.length}`:`type=${typeof t}`,i=Aa(r)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}function Ac(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Ct(t.outputLen),Ct(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}const r0=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)},ql=(t,e)=>{r0(t,e);const r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function ls(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function nh(t,e){Rt(t,void 0,"output");const r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function Vk(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function or(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function pi(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function it(t,e){return t<<32-e|t>>>e}function Gk(t,e){return t<<e|t>>>32-e>>>0}const n0=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function o0(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function s0(t){for(let e=0;e<t.length;e++)t[e]=o0(t[e]);return t}const Xk=n0?t=>t:s0,oh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",i0=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function kc(t){if(Rt(t),oh)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=i0[t[r]];return e}function Kl(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function sh(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(oh)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}const e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){const i=Kl(t.charCodeAt(s)),a=Kl(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)}n[o]=i*16+a}return n}function a0(t){const e=globalThis;if(typeof e.scheduler?.yield=="function"){const r=e.scheduler.yield();return t&&r.catch(t),r}return new Promise(r=>e.setTimeout(r,0))}async function Yk(t,e,r,n){if(Ct(t,"iters"),Ct(e,"tick"),typeof r!="function")throw new TypeError("callback must be a function");let o=Date.now();for(let s=0;s<t;s++){r(s);const i=Date.now()-o;i>=0&&i<e||(await a0(n),o=Date.now())}}function c0(t){if(typeof t!="string")throw new TypeError("string expected");const e=new TextEncoder().encode(t);try{return new Uint8Array(e)}finally{or(e)}}function Zk(t,e=""){return typeof t=="string"?c0(t):Rt(t,void 0,e)}function l0(t,e,r="opts"){return ql(t,"defaults"),e!==void 0&&ql(e,r),Object.assign(Object.create(null),t,e)}function d0(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=l0({},e,"info");const r=(o,s)=>t(s).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function u0(t=32){Ct(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 f0=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function h0(t,e,r){return t&e^~t&r}function p0(t,e,r){return t&e^t&r^e&r}class g0{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,o){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=pi(this.buffer)}update(e){ls(this),Rt(e);const{view:r,buffer:n,blockLen:o}=this,s=e.length;let i=!1;for(let a=0;a<s;){const c=Math.min(o-this.pos,s-a);if(c===o){const l=pi(e);for(;o<=s-a;a+=o)this.process(l,a);i=!0;continue}n.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(r,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){ls(this),nh(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:o,isLE:s}=this;let{pos:i}=this;r[i++]=128,r.fill(0,i),this.padOffset>o-i&&(this.process(n,0),r.fill(0)),t0(n,o-8,this.length*8,s),this.process(n,0),this.roundClean();const a=e===r?n:pi(e),c=this.outputLen,l=c/4,d=this.get();if(c%4||l>d.length)throw new Error("invalid outputLen");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneIntoMeta(e){const{buffer:r,length:n,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=n,e.pos=i,i&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const m0=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),w0=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Dt=new Uint32Array(64);class y0 extends g0{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,r){super(64,e,8,!1),this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){const{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|0,this.C=n|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,r){for(let u=0;u<16;u++,r+=4)Dt[u]=e.getUint32(r,!1);for(let u=16;u<64;u++){const f=Dt[u-15],h=Dt[u-2],g=it(f,7)^it(f,18)^f>>>3,m=it(h,17)^it(h,19)^h>>>10;Dt[u]=m+Dt[u-7]+g+Dt[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=it(a,6)^it(a,11)^it(a,25),h=d+f+h0(a,c,l)+w0[u]+Dt[u]|0,m=(it(n,2)^it(n,13)^it(n,22))+p0(n,o,s)|0;d=l,l=c,c=a,a=i+h|0,i=s,s=o,o=n,n=h+m|0}n=n+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(n,o,s,i,a,c,l,d)}roundClean(){or(Dt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),or(this.buffer)}}class b0 extends y0{constructor(){super(32,m0)}}const gi=d0(()=>new b0,f0(1));function ih(t,e,r=()=>{}){if(!Array.isArray(t))throw new TypeError(`"${e}" expected array, got type=${typeof t}`);for(let n=0;n<t.length;n++)r(t[n],`${e}[${n}]`);return t}const Hr=(t,e,r)=>Rt(t,e,r),ah=Ct;function qr(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 jn(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}const v0=kc,x0=t=>sh(t),ch=Ea,lh=t=>u0(t),ds=BigInt(0),zl=BigInt(1),S0=t=>t?`"${t}" `:"";function $s(t,e=""){if(typeof t!="boolean")throw new TypeError(S0(e)+"expected boolean, got type="+typeof t);return t}function E0(t){if(typeof t=="bigint"){if(!sr(t))throw new RangeError("positive bigint expected, got "+t)}else ah(t);return t}function ka(t,e=""){if(typeof t!="number"){const r=e&&`"${e}" `;throw new TypeError(r+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){const r=e&&`"${e}" `;throw new RangeError(r+"expected safe integer, got "+t)}}function dh(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?ds:BigInt("0x"+t)}function uh(t){return dh(kc(t))}function us(t){return dh(kc(Xn(Rt(t)).reverse()))}function fh(t,e){if(Ct(e),e===0)throw new Error("zero output length is invalid");t=E0(t);const r=e*2,n=t.toString(16);if(n.length>r)throw new RangeError("number is too large");return sh(n.padStart(r,"0"))}function hh(t,e){return fh(t,e).reverse()}function Xn(t){return Uint8Array.from(Hr(t))}function sr(t){return typeof t=="bigint"&&ds<=t}function ph(t,e,r){return sr(t)&&sr(e)&&sr(r)&&e<=t&&t<r}function Un(t,e,r,n){if(!ph(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function A0(t){if(t<ds)throw new Error("expected non-negative bigint, got "+t);return t===ds?0:t.toString(2).length}const k0=t=>(ka(t,"n"),(zl<<BigInt(t))-zl);function fs(t,e={},r={},n="object"){qr(t,n),qr(e,"fields"),qr(r,"optFields");function o(i,a,c){const l=n==="object"?`param "${String(i)}"`:`"${n}.${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(r,!0)}const xe=BigInt(0),ae=BigInt(1),er=BigInt(2),gh=BigInt(3),Ic=BigInt(4),mh=BigInt(5),I0=BigInt(7),wh=BigInt(8),C0=BigInt(9),R0=BigInt(15),yh=BigInt(16),T0=BigInt("0x10000000000000000");function ie(t,e){if(e<=xe)throw new Error("mod: expected positive modulus, got "+e);const r=t%e;return r>=xe?r:e+r}function P0(t,e,r){if(r<=ae)throw new Error("pow: expected modulus > 1, got "+r);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<xe)throw new Error("invalid exponent, negatives unsupported");if(e===xe)return ae;if(e===ae)return t;let n=t%r;if(n<xe&&(n+=r),e<T0){let a=ae;for(;e>xe;)e&ae&&(a=a*n%r),n=n*n%r,e>>=ae;return a}const o=[];for(;e>xe;)o.push(Number(e&R0)),e>>=Ic;const s=new Array(16);s[0]=ae,s[1]=n;for(let a=2;a<16;a++)s[a]=s[a-1]*n%r;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%r,i=i*i%r,i=i*i%r,i=i*i%r;const c=o[a];c!==0&&(i=i*s[c]%r)}return i}function et(t,e,r){if(r<=ae)throw new Error("pow2: expected modulus > 1, got "+r);if(e<xe)throw new Error("pow2: expected non-negative exponent, got "+e);let n=t;for(;e-- >xe;)n*=n,n%=r;return n}function Wl(t,e){if(t===xe)throw new Error("invert: expected non-zero number");if(e<=ae)throw new Error("invert: expected modulus > 1, got "+e);let r=ie(t,e),n=e,o=xe,s=ae;for(;r!==xe;){const a=n/r,c=n-r*a,l=o-s*a;n=r,r=c,o=s,s=l}if(n!==ae)throw new Error("invert: does not exist");return ie(o,e)}function Cc(t,e,r){const n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function Rc(t,e){if((t&ae)===xe)throw new Error(e+": expected odd modulus, got "+t)}function bh(t,e){const r=t,n=(r.ORDER+ae)/Ic,o=r.pow(e,n);return Cc(r,o,e),o}function N0(t,e){const r=t,n=(r.ORDER-mh)/wh,o=r.mul(e,er),s=r.pow(o,n),i=r.mul(e,s),a=r.mul(r.mul(i,er),s),c=r.mul(i,r.sub(a,r.ONE));return Cc(r,c,e),c}function L0(t){const e=Tc(t),r=vh(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+I0)/yh;return((a,c)=>{const l=a;let d=l.pow(c,i),u=l.mul(d,n);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 y=l.eql(l.sqr(u),c),w=l.cmov(d,u,y);return Cc(l,w,c),w})}function vh(t){if(t<gh)throw new Error("sqrt is not defined for small field");Rc(t,"tonelliShanks");let e=t-ae,r=0;for(;e%er===xe;)e/=er,r++;let n=er;const o=Tc(t);for(;hs(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return bh;let s=o.pow(n,e);const i=(e+ae)/er;return function(c,l){const d=c;if(d.is0(l))return l;if(hs(d,l)!==1)throw new Error("Cannot find square root");let u=r,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,y=d.sqr(h);for(;!d.eql(y,d.ONE);)if(m++,y=d.sqr(y),m===u)throw new Error("Cannot find square root");const w=ae<<BigInt(u-m-1),I=d.pow(f,w);u=m,f=d.sqr(I),h=d.mul(h,f),g=d.mul(g,I)}return g}}function B0(t){return Rc(t,"Fp.sqrt"),t%Ic===gh?bh:t%wh===mh?N0:t%yh===C0?L0(t):vh(t)}const _0=(t,e)=>(ie(t,e)&ae)===ae,D0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yn(t){if(qr(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);ka(t.BYTES,"BYTES"),ka(t.BITS,"BITS");for(const e of D0)jn(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=ae)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function xh(t,e,r=!1){Yn(t),ih(e,"nums"),$s(r,"passZero");const n=t,o=new Array(e.length).fill(r?n.ZERO:void 0),s=e.reduce((a,c,l)=>n.is0(c)?a:(o[l]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,l)=>n.is0(c)?a:(o[l]=n.mul(a,o[l]),n.mul(a,c)),i),o}function hs(t,e){Yn(t);const r=t;Rc(r.ORDER,"FpLegendre");const n=(r.ORDER-ae)/er,o=r.pow(e,n),s=r.eql(o,r.ONE),i=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function O0(t,e){if(e!==void 0&&ah(e),t<=xe)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 r=A0(t);if(e!==void 0&&e<r)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${r})`);const n=e!==void 0?e:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}const Vl=new WeakMap;class Gl{ORDER;BITS;BYTES;isLE;ZERO=xe;ONE=ae;_lengths;_mod;constructor(e,r={}){if(e<=ae)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:o,nByteLength:s}=O0(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return ie(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return xe<=e&&e<this.ORDER}is0(e){return e===xe}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ae)===ae}neg(e){return ie(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return ie(e*e,this.ORDER)}add(e,r){return ie(e+r,this.ORDER)}sub(e,r){return ie(e-r,this.ORDER)}mul(e,r){return ie(e*r,this.ORDER)}pow(e,r){return P0(e,r,this.ORDER)}div(e,r){return ie(e*Wl(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Wl(e,this.ORDER)}sqrt(e){let r=Vl.get(this);return r||Vl.set(this,r=B0(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?hh(e,this.BYTES):fh(e,this.BYTES)}fromBytes(e,r=!1){Hr(e);const{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" 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?us(e):uh(e);if(a&&(c=ie(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return xh(this,e,!0)}cmov(e,r,n){return $s(n,"condition"),n?r:e}}function Tc(t,e={}){return Object.freeze(Gl.prototype),new Gl(t,e)}const Pc=BigInt(0),Zn=BigInt(1),F0=BigInt(4),mi=16,Xl=128,M0=5,Yl=2**31;function Nc(t){const e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);jn(e.fromAffine,"Point.fromAffine"),jn(e.fromBytes,"Point.fromBytes"),jn(e.fromHex,"Point.fromHex"),qr(e.BASE,"Point.BASE"),qr(e.ZERO,"Point.ZERO"),Yn(e.Fp),Yn(e.Fn)}function j0(t,e){Nc(t),Sh(e,t);const r=xh(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function U0(t,e,r=1){if(!Number.isSafeInteger(t)||t<r||t>e)throw new Error("invalid window size, expected ["+r+".."+e+"], got W="+t)}function $0(t,e){const r=t*(4*e+128);if(r>Yl)throw new Error("invalid window size: table would need ~"+Math.ceil(r/2**20)+" MiB, max "+Yl/2**20+" MiB")}function H0(t,e){if(t!==void 0){jn(t,"randomBytes");try{const r=t(e);if(!ch(r)||r.length!==e)return}catch{return}return t}}function Sh(t,e){ih(t,"points"),t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function q0(t,e,r){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,o)=>{if(!(r===void 0?e.isValid(n):sr(n)&&n<r))throw new Error("invalid scalar at index "+o)})}const Eh=new WeakMap;function wi(t){return Eh.get(t)||1}function K0(t,e){const r=t.double(),n=[t];for(let o=1;o<e;o++)n.push(n[o-1].add(r));return n}function z0(t,e){const r=2**e,n=r/2,o=BigInt(r-1),s=[];for(;t>Pc;){let i=0;t&Zn&&(i=Number(t&o),i>=n&&(i-=r),t-=BigInt(i)),s.push(i),t>>=Zn}return s}function W0(t,e,r){const n=2**e,o=n/2,s=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<r;c++){let l=Number(t&s);t>>=i,l>o&&(l-=n,t+=Zn),a.push(l)}if(t!==Pc)throw new Error("invalid wnaf");return a}function V0(t,e,r){let n=0;for(const s of r)n=Math.max(n,s.length);let o=t;for(let s=n-1;s>=0;s--){s!==n-1&&(o=o.double());for(let i=0;i<r.length;i++){const a=r[i][s];if(a){const c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}class G0{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,r){Nc(e),this.randomBytes=H0(r,mi),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,r,n){const o=Math.ceil(n/r)+1,s=2**(r-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:r,bits:n,windows:o,comp:i}}wnafCachedCT(e,r){const{W:n,windows:o,comp:s}=e,i=2**(n-1),a=W0(r,n,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 y=1;y<i;y++)g=y===h?s[f+y]: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,r,n,o){let s=this.wnafPrecomputes.get(r),i=s?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(r,e,n),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(r,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,r){if(this.assertPoint(e),!ph(r,Zn,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,r,n,o){const s=wi(e);return s===1?this.fixedWindowCT(e,r,n):this.wnafCachedCT(this.getWnafPrecomputes(s,e,n,o),r)}mulCT(e,r,n){return this.validateMulInput(e,r),this.runCT(e,r,this.bits,n)}mulCTBlinded(e,r,n){if(this.validateMulInput(e,r),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");const o=this.Point.Fn.BITS+Xl,s=this.randomBytes(mi);if(!ch(s)||s.length!==mi)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;const i=r+uh(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,n)}fixedWindowCT(e,r,n){const o=M0,s=1<<o,i=k0(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(n/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(r>>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,r){return this.randomBytes===void 0?!1:r===Zn?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,r,n,o){return this.shouldBlind(e,n)?this.mulCTBlinded(e,r,o):this.mulCT(e,r,o)}mulUnsafe(e,r,n){if(this.assertPoint(e),!sr(r))throw new Error("invalid scalar");const o=wi(e);if(o===1||r>=this.Point.Fn.ORDER)return X0(this.Point,[e],[r],!0);const s=this.getWnafPrecomputes(o,e,this.bits,n);return this.wnafCachedCT(s,r).p}setWindowSize(e,r){this.assertPoint(e),U0(r,this.bits);const n=Math.ceil((this.bits+Xl)/r)+1;$0(n*2**(r-1),this.Point.Fp.BYTES),Eh.set(e,r),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return wi(e)!==1}}function X0(t,e,r,n=!1){if(Nc(t),Sh(e,t),$s(n,"allowOversized"),q0(r,t.Fn,n?t.Fn.ORDER**F0:void 0),e.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const o=e.map(i=>K0(i,4)),s=r.map(i=>z0(i,4));return V0(t.ZERO,o,s)}function Zl(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Yn(e),e}else return Tc(t,{isLE:r})}function Y0(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);fs(r);for(const c of["p","n","h"]){const l=e[c];if(!(sr(l)&&l!==Pc))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Zl(e.p,r.Fp,n),s=Zl(e.n,r.Fn,n),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 Z0(t,e){return function(n){const o=t(n);return{secretKey:o,publicKey:e(o)}}}const ko=BigInt(0),Io=BigInt(1),Co=BigInt(2),J0=BigInt(4),Jl=BigInt(8);function Q0(t,e,r,n){const o=t.sqr(r),s=t.sqr(n),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 ev(t,e={}){fs(e,{},{},"extraOpts");const r=e,n=Y0("edwards",t,r,r.FpFnLE),{Fp:o,Fn:s}=n;let i=n.CURVE;const{h:a}=i;if(hs(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(hs(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");fs(r,{},{uvRatio:"function",randomBytes:"function"});const c=r.randomBytes===void 0?lh:r.randomBytes,l=Co<<BigInt(o.BYTES*8)-Io;function d(I){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(I)}const u=r.uvRatio===void 0?(I,v)=>{try{return{isValid:!0,value:o.sqrt(o.div(I,v))}}catch{return{isValid:!1,value:ko}}}:r.uvRatio;if(!Q0(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,v,k=!1){const B=k?Io:ko;return Un("coordinate "+I,v,B,l),v}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(v,k,B,R){this.X=h("x",v),this.Y=h("y",k),this.Z=h("z",B,!0),this.T=h("t",R),Object.freeze(this)}static CURVE(){return i}static fromAffine(v){if(v instanceof m)throw new Error("extended point not allowed");const{x:k,y:B}=v||{};return h("x",k),h("y",B),new m(k,B,o.ONE,o.mul(k,B))}static fromBytes(v,k=!1){const B=o.BYTES,{a:R,d:N}=i;v=Xn(Hr(v,B,"point")),$s(k,"zip215");const A=Xn(v),x=v[B-1];A[B-1]=x&-129;const S=us(A),T=k?l:o.ORDER;Un("point.y",S,ko,T);const P=o.sqr(S),b=o.sub(P,o.ONE),E=o.sub(o.mulN(N,P),R);let{isValid:C,value:L}=u(b,E);if(!C)throw new Error("bad point: invalid y coordinate");const M=d(L),$=(x&128)!==0;if(!k&&o.is0(L)&&$)throw new Error("bad point: x=0 and x_0=1");return $!==M&&(L=o.neg(L)),m.fromAffine({x:L,y:S})}static fromHex(v,k=!1){return m.fromBytes(x0(v),k)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=6,k=!0){return w.setWindowSize(this,v),k||this.multiply(Co),this}assertValidity(){const v=this,{a:k,d:B}=i;if(v.is0())throw new Error("bad point: ZERO");const{X:R,Y:N,Z:A,T:x}=v,S=o.sqr(R),T=o.sqr(N),P=o.sqr(A),b=o.sqr(P),E=o.mul(S,k),C=o.mul(o.add(E,T),P),L=o.add(b,o.mul(B,o.mul(S,T)));if(!o.eql(C,L))throw new Error("bad point: equation left != right (1)");const M=o.mul(R,N),$=o.mul(A,x);if(!o.eql(M,$))throw new Error("bad point: equation left != right (2)")}equals(v){g(v);const{X:k,Y:B,Z:R}=this,{X:N,Y:A,Z:x}=v,S=o.mul(k,x),T=o.mul(N,R),P=o.mul(B,x),b=o.mul(A,R);return o.eql(S,T)&&o.eql(P,b)}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:v,Y:k,Z:B}=this,R=o.sqr(v),N=o.sqr(k),A=o.mul(o.sqr(B),Co),x=f(R),S=o.addN(v,k),T=o.sub(o.subN(o.sqr(S),R),N),P=o.addN(x,N),b=o.subN(P,A),E=o.subN(x,N),C=o.mul(T,b),L=o.mul(P,E),M=o.mul(T,E),$=o.mul(b,P);return new m(C,L,$,M)}add(v){g(v);const{d:k}=i,{X:B,Y:R,Z:N,T:A}=this,{X:x,Y:S,Z:T,T:P}=v,b=o.mul(B,x),E=o.mul(R,S),C=o.mul(o.mulN(A,k),P),L=o.mul(N,T),M=o.sub(o.subN(o.mulN(o.addN(B,R),o.addN(x,S)),b),E),$=o.subN(L,C),j=o.addN(L,C),D=o.sub(E,f(b)),_=o.mul(M,$),O=o.mul(j,D),q=o.mul(M,D),H=o.mul($,j);return new m(_,O,H,q)}subtract(v){return g(v),this.add(v.negate())}multiply(v){if(!s.isValidNot0(v))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");const{p:k,f:B}=w.mulSecret(this,v,a,y);return y([k,B])[0]}multiplyUnsafe(v){if(!s.isValid(v))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return v===ko?m.ZERO:this.is0()||v===Io?this:w.mulUnsafe(this,v,y)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.mulUnsafe(this,i.n).is0()}toAffine(v){const k=this;let B=v;if(B!=null&&typeof B!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof B);const{X:R,Y:N,Z:A}=k,x=k.is0();B==null&&(B=x?o.create(Jl):o.inv(A));const S=o.mul(R,B),T=o.mul(N,B),P=o.mul(A,B);if(x)return{x:o.ZERO,y:o.ONE};if(!o.eql(P,o.ONE))throw new Error("invZ was invalid");return{x:S,y:T}}clearCofactor(){return a===Io?this:a===Co?this.double():a===J0?this.double().double():a===Jl?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){const{x:v,y:k}=this.toAffine(),B=o.toBytes(k);return B[B.length-1]|=d(v)?128:0,B}toHex(){return v0(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const y=I=>j0(m,I),w=new G0(m,c);return w.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}const Xt=BigInt(0),We=BigInt(1),Ro=BigInt(2);function Ql(t,e){return t+e-(e>>We<<We)}function tv(t){const e=BigInt(6)*t;return(r,n,o)=>{const s=n+o,a=((e+o-n)*r+n)%t;return{x_2:a,x_3:s-a}}}function rv(t){return fs(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...t})}function nv(t){const e=rv(t),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=e.scalarMultBase,c=n==="x25519";if(!c&&n!=="x448")throw new Error("invalid type");const l=i===void 0?lh:i,d=c?255:448,u=tv(r),f=c?32:56,h=BigInt(c?9:5),g=BigInt(c?121665:39081),m=c?Ro**BigInt(254):Ro**BigInt(447),y=c?BigInt(8)*(Ro**BigInt(251)-We):BigInt(4)*(Ro**BigInt(445)-We),w=m+y+We,I=L=>ie(L,r),v=k(h);function k(L){return hh(I(L),f)}function B(L){const M=Xn(Hr(L,f,"uCoordinate"));return c&&(M[31]&=127),I(us(M))}function R(L){return us(o(Xn(Hr(L,f,"scalar"))))}const N=new Set(c?[Xt,We,r-We,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[Xt,We,r-We]);function A(L,M){const $=B(M);if(N.has($))throw new Error("invalid private or public key received");const j=P($,R(L));if(j===Xt)throw new Error("invalid private or public key received");return k(j)}function x(L){if(a===void 0)return A(L,v);const M=R(L);Un("scalar",M,m,w);const $=I(a(M));if($===Xt)throw new Error("invalid private or public key received");return k($)}const S=x,T=A;function P(L,M){Un("u",L,Xt,r),Un("scalar",M,m,w);const $=M,j=L;let D=We,_=Xt,O=L,q=We;const H=$^$>>We;for(let V=BigInt(d-1);V>=Xt;V--){const X=Ql(r,H>>V);({x_2:D,x_3:O}=u(X,D,O)),{x_2:_,x_3:q}=u(X,_,q);const G=D+_,Y=I(G*G),se=D-_,Ne=I(se*se),Me=Y-Ne,oe=O+q,ot=O-q,vr=I(ot*G),Tt=I(oe*se),Ze=vr+Tt,fo=vr-Tt;O=I(Ze*Ze),q=I(j*I(fo*fo)),D=I(Y*Ne),_=I(Me*(Y+I(g*Me)))}const K=Ql(r,$);({x_2:D,x_3:O}=u(K,D,O)),{x_2:_,x_3:q}=u(K,_,q);const z=s(_);return I(D*z)}const b={secretKey:f,publicKey:f,seed:f},E=L=>(L=L===void 0?l(f):L,Hr(L,b.seed,"seed"),L),C={randomSecretKey:E};return Object.freeze(b),Object.freeze(C),Object.freeze({keygen:Z0(E,S),getSharedSecret:T,getPublicKey:S,scalarMult:A,scalarMultBase:x,utils:C,GuBytes:v.slice(),lengths:b})}const ed=BigInt(0),ov=BigInt(1),td=BigInt(2),sv=BigInt(3),iv=BigInt(5),av=BigInt(8),Hs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),cv={p:Hs,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:av,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ah(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=Hs,a=t*t%s*t%s,c=et(a,td,s)*a%s,l=et(c,ov,s)*t%s,d=et(l,iv,s)*l%s,u=et(d,e,s)*d%s,f=et(u,r,s)*u%s,h=et(f,n,s)*f%s,g=et(h,o,s)*h%s,m=et(g,o,s)*h%s,y=et(m,e,s)*d%s;return{pow_p_5_8:et(y,td,s)*t%s,b2:a}}function lv(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const rd=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function dv(t,e){const r=Hs,n=ie(e*e*e,r),o=ie(n*n*e,r),s=Ah(t*o).pow_p_5_8;let i=ie(t*n*s,r);const a=ie(e*i*i,r),c=i,l=ie(i*rd,r),d=a===t,u=a===ie(-t,r),f=a===ie(-t*rd,r);return d&&(i=c),(u||f)&&(i=l),_0(i,r)&&(i=ie(-i,r)),{isValid:d||u,value:i}}const nd=ev(cv,{uvRatio:dv}),To=(()=>{const t=Hs,e=r=>{const{pow_p_5_8:n,b2:o}=Ah(r);return ie(et(n,sv,t)*o,t)};return nv({P:t,type:"x25519",powPminus2:e,adjustScalarBytes:lv,scalarMultBase:r=>{const n=ie(r,nd.Fn.ORDER);if(n===ed)return ed;const o=nd.BASE.multiply(n);return ie((o.Z+o.Y)*e(ie(o.Z-o.Y,t)),t)}})})();class od{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(Ac(e),Rt(r,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 n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);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),or(o)}update(e){return ls(this),this.iHash.update(e),this}digestInto(e){ls(this),nh(e,this),this.finished=!0;const r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),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:r,iHash:n,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=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const kh=(()=>{const t=((e,r,n)=>new od(e,r).update(n).digest());return t.create=(e,r)=>new od(e,r),t})();function sd(){const t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}class id{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 id(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 r=this.head;this.head=r.next=new id(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){const r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}class uv extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}}function fv(t={}){return hv(r=>{const n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function hv(t,e){e=e??{};let r=e.onEnd,n=new yi,o,s,i,a=sd();const c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,w)=>{s=I=>{s=null,n.push(I);try{y(t(n))}catch(v){w(v)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=sd()})}},l=y=>s!=null?s(y):(n.push(y),o),d=y=>(n=new yi,s!=null?s({error:y}):(n.push({error:y}),o)),u=y=>{if(i)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},f=y=>i?o:(i=!0,y!=null?d(y):l({done:!0})),h=()=>(n=new yi,f(),{done:!0}),g=y=>(f(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:g,push:u,end:f,get readableLength(){return n.size},onEmpty:async y=>{const w=y?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let I,v;w!=null&&(I=new Promise((k,B)=>{v=()=>{B(new uv)},w.addEventListener("abort",v)}));try{await Promise.race([a.promise,I])}finally{v!=null&&w!=null&&w?.removeEventListener("abort",v)}}},r==null)return o;const m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(y){return m.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return m.return(),r!=null&&(r(),r=void 0),{done:!0}},push:u,end(y){return m.end(y),r!=null&&(r(y),r=void 0),o},get readableLength(){return m.readableLength},onEmpty:y=>m.onEmpty(y)},o}class Lc extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,Lc)}}const ad=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function pv(t,e){const{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e;let a,c;const d=new Promise((u,f)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){f(ad(i));return}if(i&&(c=()=>{f(ad(i))},i.addEventListener("abort",c,{once:!0})),t.then(u,f),r===Number.POSITIVE_INFINITY)return;const h=new Lc;a=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}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 ${r} milliseconds`,f(h))},r)}).finally(()=>{d.clear(),c&&i&&i.removeEventListener("abort",c)});return d.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},d}const gv=t=>{const e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function mv(t,e,r){let n;const o=new Promise((s,i)=>{if(r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();const a=[e].flat(),c=[],{addListener:l,removeListener:d}=gv(t),u=async(...h)=>{const g=r.multiArgs?h:h[0];if(r.filter)try{if(!await r.filter(g))return}catch(m){n(),i(m);return}c.push(g),r.count===c.length&&(n(),s(c))},f=(...h)=>{n(),i(r.rejectionMultiArgs?h:h[0])};n=()=>{for(const h of a)d(h,u);for(const h of r.rejectionEvents)a.includes(h)||d(h,f)};for(const h of a)l(h,u);for(const h of r.rejectionEvents)a.includes(h)||l(h,f);r.signal&&r.signal.addEventListener("abort",()=>{f(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){const s=pv(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function wv(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};const n=mv(t,e,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}class ps extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class yv extends Error{static name="StreamClosedError";name="StreamClosedError"}function bv(t){return t.reason}function Ih(t,e,r){if(e==null||t==null)return t;const n=bv;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let o;return Promise.race([t,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}const vv=Math.pow(2,20)*4;class Ch extends Lg{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??vv,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new ne,this.writeBuffer=new ne,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);const r=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);const n=o=>{this.onDrainPromise?.reject(o.error??new yv)};this.addEventListener("close",n)}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()),Ih(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;const e=fv(),r=s=>{e.push(s.data)};this.addEventListener("message",r);const n=s=>{e.end(s.error)};this.addEventListener("close",n);const o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new wn(`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(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new Zb(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new wn("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 wn("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 wn(`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 wn(`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 Xb;this.dispatchEvent(new Jb(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 Ec))}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 r=this.writeBuffer.byteLength;let n=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 ne(s);this.writeBuffer.consume(s.byteLength);const a=this.sendData(s);if(e=a.canSendMore,n+=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",n,r,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 Yb(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 Hl(`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 Hl(`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 xv=4194304;class cd extends Error{static name="UnwrappedError";name="UnwrappedError"}class Rh extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class Sv extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class Ev extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function Av(t){return typeof t?.closeRead=="function"}function kv(t){return typeof t?.close=="function"}function bi(t){return Av(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:kv(t)?t.status!=="open":!1}function Iv(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function Cv(t,e){const r=e?.maxBufferSize??xv,n=new ne;let o,s=!1;if(!Iv(t))throw new rh("Argument should be a Stream or a Multiaddr");const i=d=>{if(n.append(d.data),n.byteLength>r){const u=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${u} > ${r}`))}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:n,async read(d){if(s===!0)throw new cd("Stream was unwrapped");if(bi(t)){if(d?.bytes==null)return null;if(n.byteLength<d.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,d.bytes),new ps(`Unexpected EOF - stream closed after reading ${n.byteLength}/${d.bytes} bytes`)}const u=d?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=u){o.resolve();break}if(await Ih(o.promise,d?.signal),bi(t)){if(n.byteLength===0&&d?.bytes==null)return null;break}o=Promise.withResolvers()}const f=d?.bytes??n.byteLength;if(n.byteLength<f){if(bi(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,f),new ps(`Unexpected EOF - stream closed while reading ${n.byteLength}/${f} bytes`);return l.read(d)}const h=n.sublist(0,f);return n.consume(f),h},async write(d,u){if(s===!0)throw new cd("Stream was unwrapped");t.send(d)||await wv(t,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",i),t.removeEventListener("close",a),t.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.push(n))),t}};return l}function ld(t,e={}){const r=Cv(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=gr(e.maxDataLength));const n=e?.lengthDecoder??Of,o=e?.lengthEncoder??By;return{async read(i){let a=-1;const c=new ne;for(;;){const d=await r.read({...i,bytes:1});if(d==null)break;c.append(d);try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Rh("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Ev(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Sv(`Message length too long - ${a} > ${e.maxDataLength}`);const l=await r.read({...i,bytes:a});if(l==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new ps(`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 ps(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await r.write(new ne(o(i.byteLength),i),a)},async writeV(i,a){const c=new ne(...i.flatMap(l=>[o(l.byteLength),l]));await r.write(c,a)},unwrap(){return r.unwrap()}}}const Rv=1024*1024*4,Tv=1024*1024*4;class Pv{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new ne,this.maxBufferSize=e.maxBufferSize??Rv,this.maxDataLength=e.maxDataLength??Tv,this.lengthDecoder=e.lengthDecoder??Of,this.encodingLength=e.encodingLength??gr}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new rh(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let r;try{r=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(r<0||r>this.maxDataLength)throw new Rh("Invalid message length");const n=this.encodingLength(r),o=n+r;if(this.buffer.byteLength>=o){const s=this.buffer.sublist(n,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}}var Nv={};const Jn=65535,dd=Jn-16,lo=!!Nv?.DUMP_SESSION_KEYS,ud=16;function Ia(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}const gs=t=>t?`"${t}" `:"";function Ca(t,e=""){if(typeof t!="boolean")throw new TypeError(gs(e)+"expected boolean, got type="+typeof t);return t}function Kr(t,e=""){if(typeof t!="number")throw new TypeError(gs(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(gs(e)+"expected integer >= 0, got "+t);return t}function ve(t,e,r=""){if(Ia(t)&&(e===void 0||t.length===e))return t;e!==void 0&&Kr(e,"length");const n=Ia(t),o=e!==void 0?` of length ${e}`:"",s=n?`length=${t.length}`:`type=${typeof t}`,i=gs(r)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}const fd=(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 hd(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function Lv(t,e){ve(t,void 0,"output");const r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function vt(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function qt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Bv(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const zr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function _v(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]=_v(t[e]);return t}const tr=zr?t=>t:Dv;function Ov(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 Fv(t,e){if(Ov(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function Mv(t,e){return fd(t,"defaults"),fd(e,"opts"),Object.assign(t,e)}function jv(t,e){if(t=ve(t),e=ve(e),t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Uv(t,e,r){const n=e,o=(()=>[]),s=(a,c)=>n(c,...o(a)).update(a).digest(),i=n(new Uint8Array(t),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>n(a,...c),s}const $v=(t,e)=>{function r(n,...o){if(ve(n,void 0,"key"),t.nonceLength!==void 0){const u=o[0];ve(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}const s=t.tagLength,i=t.nonceLength!==void 0?1:0;if(!t.withAAD){for(let u=i;u<o.length;u++)if(Ia(o[u]))throw new Error("AAD not supported")}t.withAAD&&o[i]!==void 0&&ve(o[i],void 0,"AAD");const a=e(n,...o),c=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");ve(f,void 0,"output")}};let l=!1;return{encrypt(u,f){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,ve(u,void 0,"data"),c(a.encrypt.length,f),a.encrypt(u,f)},decrypt(u,f){if(ve(u,void 0,"data"),s&&u.length<s)throw new Error('"ciphertext" expected length >= tagLength='+s);return c(a.decrypt.length,f),a.decrypt(u,f)}}}return Object.assign(r,t),r};function Ra(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(ve(e,t,"output"),r&&!ms(e))throw new Error("invalid output, must be aligned");return e}function Hv(t,e,r){Kr(t),Kr(e),Ca(r);const n=new Uint8Array(16),o=Bv(n);return o.setBigUint64(0,BigInt(e),r),o.setBigUint64(8,BigInt(t),r),n}function ms(t){return t.byteOffset%4===0}function ws(t){return Uint8Array.from(ve(t))}const Th=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),qv=tr(vt(Th("expand 16-byte k"))),Kv=tr(vt(Th("expand 32-byte k")));function ee(t,e){return t<<e|t>>>32-e}const yn=64,zv=16,Ta=2**32-1,pd=Uint32Array.of();function Wv(t,e,r,n,o,s,i,a){const c=o.length,l=new Uint8Array(yn),d=vt(l),u=zr&&ms(o)&&ms(s),f=u?vt(o):pd,h=u?vt(s):pd;if(!zr){for(let g=0;g<c;i++){if(t(e,r,n,d,i,a),tr(d),i>=Ta)throw new Error("arx: counter overflow");const m=Math.min(yn,c-g);for(let y=0,w;y<m;y++)w=g+y,s[w]=o[w]^l[y];g+=m}return}for(let g=0;g<c;i++){if(t(e,r,n,d,i,a),i>=Ta)throw new Error("arx: counter overflow");const m=Math.min(yn,c-g);if(u&&m===yn){const y=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,I;w<zv;w++)I=y+w,h[I]=f[I]^d[w];g+=yn;continue}for(let y=0,w;y<m;y++)w=g+y,s[w]=o[w]^l[y];g+=m}}function Vv(t,e){const{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Mv({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Kr(o),Kr(i),Ca(s),Ca(r),(a,c,l,d,u=0)=>{ve(a,void 0,"key"),ve(c,void 0,"nonce"),ve(l,void 0,"data");const f=l.length,h=d!==void 0;if(d=Ra(f,d,!1),h&&Fv(l,d),Kr(u),u<0||u>=Ta)throw new Error("arx: counter overflow");const g=[];let m=a.length,y,w;if(m===32)g.push(y=ws(a)),w=Kv;else if(m===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),w=qv,g.push(y);else throw ve(a,32,"arx key"),new Error("invalid key size");(!zr||!ms(c))&&g.push(c=ws(c));let I=vt(y);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");const B=c.subarray(0,16);if(zr)n(w,I,vt(B),I);else{const R=tr(Uint32Array.from(w));n(R,I,vt(B),I),qt(R),tr(I)}c=c.subarray(16)}else zr||tr(I);const v=16-o;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){const B=new Uint8Array(12);B.set(c,s?0:12-c.length),c=B,g.push(c)}const k=tr(vt(c));try{return Wv(t,w,I,k,l,d,u,i),d}finally{qt(...g)}}}function Se(t,e){return t[e++]&255|(t[e++]&255)<<8}class Gv{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=ws(ve(e,32,"key"));const r=Se(e,0),n=Se(e,2),o=Se(e,4),s=Se(e,6),i=Se(e,8),a=Se(e,10),c=Se(e,12),l=Se(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>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]=Se(e,16+2*d)}process(e,r,n=!1){const o=n?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],y=i[9],w=Se(e,r+0),I=Se(e,r+2),v=Se(e,r+4),k=Se(e,r+6),B=Se(e,r+8),R=Se(e,r+10),N=Se(e,r+12),A=Se(e,r+14);let x=s[0]+(w&8191),S=s[1]+((w>>>13|I<<3)&8191),T=s[2]+((I>>>10|v<<6)&8191),P=s[3]+((v>>>7|k<<9)&8191),b=s[4]+((k>>>4|B<<12)&8191),E=s[5]+(B>>>1&8191),C=s[6]+((B>>>14|R<<2)&8191),L=s[7]+((R>>>11|N<<5)&8191),M=s[8]+((N>>>8|A<<8)&8191),$=s[9]+(A>>>5|o),j=0,D=j+x*a+S*(5*y)+T*(5*m)+P*(5*g)+b*(5*h);j=D>>>13,D&=8191,D+=E*(5*f)+C*(5*u)+L*(5*d)+M*(5*l)+$*(5*c),j+=D>>>13,D&=8191;let _=j+x*c+S*a+T*(5*y)+P*(5*m)+b*(5*g);j=_>>>13,_&=8191,_+=E*(5*h)+C*(5*f)+L*(5*u)+M*(5*d)+$*(5*l),j+=_>>>13,_&=8191;let O=j+x*l+S*c+T*a+P*(5*y)+b*(5*m);j=O>>>13,O&=8191,O+=E*(5*g)+C*(5*h)+L*(5*f)+M*(5*u)+$*(5*d),j+=O>>>13,O&=8191;let q=j+x*d+S*l+T*c+P*a+b*(5*y);j=q>>>13,q&=8191,q+=E*(5*m)+C*(5*g)+L*(5*h)+M*(5*f)+$*(5*u),j+=q>>>13,q&=8191;let H=j+x*u+S*d+T*l+P*c+b*a;j=H>>>13,H&=8191,H+=E*(5*y)+C*(5*m)+L*(5*g)+M*(5*h)+$*(5*f),j+=H>>>13,H&=8191;let K=j+x*f+S*u+T*d+P*l+b*c;j=K>>>13,K&=8191,K+=E*a+C*(5*y)+L*(5*m)+M*(5*g)+$*(5*h),j+=K>>>13,K&=8191;let z=j+x*h+S*f+T*u+P*d+b*l;j=z>>>13,z&=8191,z+=E*c+C*a+L*(5*y)+M*(5*m)+$*(5*g),j+=z>>>13,z&=8191;let V=j+x*g+S*h+T*f+P*u+b*d;j=V>>>13,V&=8191,V+=E*l+C*c+L*a+M*(5*y)+$*(5*m),j+=V>>>13,V&=8191;let X=j+x*m+S*g+T*h+P*f+b*u;j=X>>>13,X&=8191,X+=E*d+C*l+L*c+M*a+$*(5*y),j+=X>>>13,X&=8191;let G=j+x*y+S*m+T*g+P*h+b*f;j=G>>>13,G&=8191,G+=E*u+C*d+L*l+M*c+$*a,j+=G>>>13,G&=8191,j=(j<<2)+j|0,j=j+D|0,D=j&8191,j=j>>>13,_+=j,s[0]=D,s[1]=_,s[2]=O,s[3]=q,s[4]=H,s[5]=K,s[6]=z,s[7]=V,s[8]=X,s[9]=G}finalize(){const{h:e,pad:r}=this,n=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,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[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]+r[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+r[a]|0)+(i>>>16)|0,e[a]=i&65535;qt(n)}update(e){hd(this),ve(e),e=ws(e);const{buffer:r,blockLen:n}=this,o=e.length;for(let s=0;s<o;){const i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,qt(this.h,this.r,this.buffer,this.pad)}digestInto(e){hd(this),Lv(e,this),this.finished=!0;const{buffer:r,h:n}=this;let{pos:o}=this;if(o){for(r[o++]=1;o<16;o++)r[o]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}}const Xv=Uv(32,t=>new Gv(t));function Yv(t,e,r,n,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],y=e[6],w=e[7],I=o,v=r[0],k=r[1],B=r[2],R=i,N=a,A=c,x=l,S=d,T=u,P=f,b=h,E=g,C=m,L=y,M=w,$=I,j=v,D=k,_=B;for(let q=0;q<s;q+=2)R=R+S|0,$=ee($^R,16),E=E+$|0,S=ee(S^E,12),R=R+S|0,$=ee($^R,8),E=E+$|0,S=ee(S^E,7),N=N+T|0,j=ee(j^N,16),C=C+j|0,T=ee(T^C,12),N=N+T|0,j=ee(j^N,8),C=C+j|0,T=ee(T^C,7),A=A+P|0,D=ee(D^A,16),L=L+D|0,P=ee(P^L,12),A=A+P|0,D=ee(D^A,8),L=L+D|0,P=ee(P^L,7),x=x+b|0,_=ee(_^x,16),M=M+_|0,b=ee(b^M,12),x=x+b|0,_=ee(_^x,8),M=M+_|0,b=ee(b^M,7),R=R+T|0,_=ee(_^R,16),L=L+_|0,T=ee(T^L,12),R=R+T|0,_=ee(_^R,8),L=L+_|0,T=ee(T^L,7),N=N+P|0,$=ee($^N,16),M=M+$|0,P=ee(P^M,12),N=N+P|0,$=ee($^N,8),M=M+$|0,P=ee(P^M,7),A=A+b|0,j=ee(j^A,16),E=E+j|0,b=ee(b^E,12),A=A+b|0,j=ee(j^A,8),E=E+j|0,b=ee(b^E,7),x=x+S|0,D=ee(D^x,16),C=C+D|0,S=ee(S^C,12),x=x+S|0,D=ee(D^x,8),C=C+D|0,S=ee(S^C,7);let O=0;n[O++]=i+R|0,n[O++]=a+N|0,n[O++]=c+A|0,n[O++]=l+x|0,n[O++]=d+S|0,n[O++]=u+T|0,n[O++]=f+P|0,n[O++]=h+b|0,n[O++]=g+E|0,n[O++]=m+C|0,n[O++]=y+L|0,n[O++]=w+M|0,n[O++]=I+$|0,n[O++]=v+j|0,n[O++]=k+D|0,n[O++]=B+_|0}const Zv=Vv(Yv,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Jv=new Uint8Array(16),gd=(t,e)=>{t.update(e);const r=e.length%16;r&&t.update(Jv.subarray(r))},Qv=new Uint8Array(32);function md(t,e,r,n,o){o!==void 0&&ve(o,void 0,"AAD");const s=t(e,r,Qv),i=Hv(n.length,o?o.length:0,!0),a=Xv.create(s);o&&gd(a,o),gd(a,n),a.update(i);const c=a.digest();return qt(s,i),c}const ex=t=>(e,r,n)=>({encrypt(s,i){const a=s.length;i=Ra(a+16,i,!1),i.set(s);const c=i.subarray(0,-16);t(e,r,c,c,1);const l=md(t,e,r,c,n);return i.set(l,a),qt(l),i},decrypt(s,i){i=Ra(s.length-16,i,!1);const a=s.subarray(0,-16),c=s.subarray(-16),l=md(t,e,r,a,n);if(!jv(c,l))throw qt(l),new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,r,i,i,1),qt(l),i}}),wd=$v({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},ex(Zv));function tx(t,e,r){return Ac(t),r===void 0&&(r=new Uint8Array(t.outputLen)),kh(t,r,e)}const bn=Uint8Array.of(0),rx=Uint8Array.of();function nx(t,e,r,n=32,o){Ac(t),Ct(n,"length"),Rt(e,void 0,"prk");const s=t.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(n>255*s)throw new Error("Length must be <= 255*HashLen");const i=Math.ceil(n/s);if(r===void 0?r=rx:Rt(r,void 0,"info"),!i)return new Uint8Array;const a=new Uint8Array(i*s),{iHash:c,oHash:l}=kh.create(t,e),d=new Uint8Array(s),u=i>1?t.create():void 0;for(let h=0;h<i-1;h++){bn[0]=h+1;const g=c._cloneInto(u);h&&g.update(d),g.update(r).update(bn).digestInto(d),l._cloneInto(u).update(d).digestInto(d),a.set(d,s*h)}if(bn[0]=i,i>1&&c.update(d),c.update(r).update(bn).digestInto(d),l.update(d).digestInto(d),a.set(d,s*(i-1)),c.destroy(),l.destroy(),u?.destroy(),d!==a&&or(d),or(bn),n===a.length)return a;const f=a.slice(0,n);return or(a),f}const Ph={hashSHA256(t){return gi(t.subarray())},getHKDF(t,e){const r=tx(gi,e,t),o=nx(gi,r,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=To.utils.randomSecretKey();return{publicKey:To.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:To.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return To.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,r,n){return wd(n,e,r).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,r,n,o){return wd(n,e,r).decrypt(t.subarray(),o)}},ox=Ph;function sx(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,r)=>t.generateX25519SharedKey(e.privateKey,r).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}const ys=t=>{const e=kt(2);return e[0]=t>>8,e[1]=t,e};ys.bytes=2;const bs=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)};bs.bytes=2;function ix(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 Nh(t,e){!e.enabled||!lo||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${Q(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${Q(t.privateKey,"hex")}`)):e("Missing local static keys."))}function Lh(t,e){!e.enabled||!lo||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${Q(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${Q(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function ax(t,e){!e.enabled||!lo||e(t?`REMOTE_STATIC_PUBLIC_KEY ${Q(t.subarray(),"hex")}`:"Missing remote static public key.")}function Bh(t,e){!e.enabled||!lo||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${Q(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function _h(t,e,r){!r.enabled||!lo||(r(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&Q(t.k,"hex")}`),r(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&Q(e.k,"hex")}`))}class $n extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=$n.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}const cx=0,lx=4294967295,dx="Cipherstate has reached maximum n, a new handshake must be performed";class ux{n;bytes;view;constructor(e=cx){this.n=e,this.bytes=De(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>lx)throw new Error(dx)}}const Wr=De(0);class Po{k;n;crypto;constructor(e,r=void 0,n=0){this.crypto=e,this.k=r,this.n=new ux(n)}hasKey(){return!!this.k}encryptWithAd(e,r){if(!this.hasKey())return r;this.n.assertValue();const n=this.crypto.encrypt(r,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,r,n){if(!this.hasKey())return r;this.n.assertValue();const o=this.crypto.decrypt(r,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}}class fx{cs;ck;h;crypto;constructor(e,r){this.crypto=e;const n=we(r,"utf-8");this.h=px(e,n),this.ck=this.h,this.cs=new Po(e)}mixKey(e){const[r,n]=this.crypto.hkdf(this.ck,e);this.ck=r,this.cs=new Po(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new ne(this.h,e))}encryptAndHash(e){const r=this.cs.encryptWithAd(this.h,e);return this.mixHash(r),r}decryptAndHash(e){const r=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),r}split(){const[e,r]=this.crypto.hkdf(this.ck,Wr);return[new Po(this.crypto,e),new Po(this.crypto,r)]}}class hx{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:r,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=r,this.ss=new fx(r,n),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,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<r+32)throw new Error("message is not long enough");this.re=e.sublist(r,r+32),this.ss.mixHash(this.re)}readS(e,r=0){if(this.rs)throw new Error("remote static public key is already set");const n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<r+n)throw new Error("message is not long enough");const o=e.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class Dh extends hx{writeMessageA(e){return new ne(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const r=this.writeE();this.writeEE();const n=this.writeS();return this.writeES(),new ne(r,n,this.ss.encryptAndHash(e))}writeMessageC(e){const r=this.writeS();return this.writeSE(),new ne(r,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(r){throw new $n(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();const r=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+r))}catch(r){throw new $n(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(e){try{const r=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(r))}catch(r){throw new $n(`handshake stage 2 validation fail: ${r.message}`)}}}function px(t,e){if(e.length<=32){const r=De(32);return r.set(e),r}else return t.hash(e)}var vs;(function(t){let e;t.codec=()=>(e==null&&(e=js((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.webtransportCerthashes!=null)for(const s of r.webtransportCerthashes)n.uint32(10),n.bytes(s);if(r.streamMuxers!=null)for(const s of r.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{const s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?r.len:r.pos+n;for(;r.pos<i;){const a=r.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new Ml('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(r.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new Ml('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(r.string());break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ms(r,t.codec()),t.decode=(r,n)=>Fs(r,t.codec(),n)})(vs||(vs={}));var xs;(function(t){let e;t.codec=()=>(e==null&&(e=js((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.identityKey!=null&&r.identityKey.byteLength>0&&(n.uint32(10),n.bytes(r.identityKey)),r.identitySig!=null&&r.identitySig.byteLength>0&&(n.uint32(18),n.bytes(r.identitySig)),r.extensions!=null&&(n.uint32(34),vs.codec().encode(r.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{const s={identityKey:De(0),identitySig:De(0)},i=n==null?r.len:r.pos+n;for(;r.pos<i;){const a=r.uint32();switch(a>>>3){case 1:{s.identityKey=r.bytes();break}case 2:{s.identitySig=r.bytes();break}case 4:{s.extensions=vs.codec().decode(r,r.uint32(),{limits:o.limits?.extensions});break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ms(r,t.codec()),t.decode=(r,n)=>Fs(r,t.codec(),n)})(xs||(xs={}));async function Oh(t,e,r){const n=await t.sign(Mh(e));return xs.encode({identityKey:Us(t.publicKey),identitySig:n,extensions:r})}async function Fh(t,e,r){try{const n=xs.decode(t),o=Sa(n.identityKey);if(r?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${r}`);if(!e)throw new Error("Remote static does not exist");const s=Mh(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new kg(n.message)}}function Mh(t){const e=we("noise-libp2p-static-key:");return t instanceof Uint8Array?ua([e,t],e.length+t.length):(t.prepend(e),t)}class gx extends Ch{stream;handshake;metrics;decoder;constructor(e,r,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=r,this.metrics=n,this.decoder=new Pv({lengthDecoder:bs,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 r=new ne;for(let n=0;n<e.byteLength;n+=dd){let o=n+dd;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),r.append(ys(s.byteLength)),r.append(s)}return r}decrypt(e){const r=new ne;for(let n=0;n<e.byteLength;n+=Jn){let o=n+Jn;if(o>e.byteLength&&(o=e.byteLength),o-ud<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);const i=e.subarray(n,o-ud);try{const a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),r.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return r}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}}function yd(t,e,r){return new gx(t,e,r)}async function mx(t,e){const{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Oh(s,a.publicKey,l),u=new Dh({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Nh(u.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(u.writeMessageA(Wr),e),r.trace("Stage 0 - Initiator finished sending first message."),Lh(u.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");const f=u.readMessageB(await n.read(e));r.trace("Stage 1 - Initiator received the message."),Bh(u.re,r),ax(u.rs,r),r.trace("Initiator going to check remote's signature...");const h=await Fh(f,u.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(u.writeMessageC(d),e),r.trace("Stage 2 - Initiator sent message with signed payload.");const[g,m]=u.ss.split();return _h(g,m,r),{payload:h,encrypt:y=>g.encryptWithAd(Wr,y),decrypt:(y,w)=>m.decryptWithAd(Wr,y,w)}}async function wx(t,e){const{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=t,d=await Oh(s,a.publicKey,l),u=new Dh({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Nh(u.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await n.read(e)),r.trace("Stage 0 - Responder received first message."),Bh(u.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(u.writeMessageB(d),e),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Lh(u.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");const f=u.readMessageC(await n.read(e));r.trace("Stage 2 - Responder received the message, finished handshake.");const h=await Fh(f,u.rs,c),[g,m]=u.ss.split();return _h(g,m,r),{payload:h,encrypt:y=>m.encryptWithAd(Wr,y),decrypt:(y,w)=>g.decryptWithAd(Wr,y,w)}}class yx{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,r={}){const{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=r,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");const c=s??ox;this.crypto=sx(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?ix(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??De(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Bg]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,r){const n=e.log?.newScope("noise")??this.log,o=ld(e,{lengthEncoder:ys,lengthDecoder:bs,maxDataLength:Jn}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=Sa(s.payload.identityKey);return{connection:yd(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Jr(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;const r=this.components.upgrader.getStreamMuxers();if(r!=null)for(const n of e){const o=r.get(n);if(o!=null)return o}if(e.length)throw new Ig("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,r){const n=e.log?.newScope("noise")??this.log,o=ld(e,{lengthEncoder:ys,lengthDecoder:bs,maxDataLength:Jn}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=Sa(s.payload.identityKey);return{connection:yd(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Jr(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,r,n,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await mx({connection:e,privateKey:r,remoteIdentityKey:o,log:n.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,r,n,o,s){let i;const a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await wx({connection:e,privateKey:r,remoteIdentityKey:o,log:n.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 bx(t={}){return e=>new yx(e,t)}const vx="termdock-e2ee-v1",Pa=3600*1e3,bd=512*1024*1024,Na=4*1024*1024,$o=()=>{},qs=Object.assign($o,{enabled:!1,error:$o,trace:$o,newScope:()=>qs});Object.freeze(qs);async function jh(){const t=await Mb();return{privateKey:t,peerId:Jr(t.publicKey).toString()}}function xx(t){return btoa(String.fromCharCode(...$b(t.privateKey)))}function vd(t){if(t.length>512||!/^[A-Za-z0-9+/]+={0,2}$/.test(t))throw new Error("Invalid identity encoding");const e=Ub(Uint8Array.from(atob(t),r=>r.charCodeAt(0)));if(e.type!=="Ed25519")throw new Error("Only Ed25519 device identities are supported");return{privateKey:e,peerId:Jr(e.publicKey).toString()}}class Uh{constructor(e=$o){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>Na)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(r=>{this.wake=r})}}}}class Sx extends Ch{constructor(e,r){super({log:qs,direction:r?"outbound":"inbound",maxReadBufferLength:Na,maxWriteBufferLength:Na}),this.duplex=e,this.finished=e.sink(this.outgoing).catch(n=>{this.abort(Qr(n))}),this.readTransport()}duplex;outgoing=new Uh(()=>this.onMuxerDrain());finished;async readTransport(){try{for await(const e of this.duplex.source)this.onData(e.slice());this.onTransportClosed()}catch(e){this.onTransportClosed(Qr(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 Qr(t){return t instanceof Error?t:new Error("Secure transport failed")}class Ex extends Error{code="E2EE_REHANDSHAKE_REQUIRED";constructor(){super("Encrypted connection lifetime reached; establish a new handshake without replaying pending input")}}function Ax(t){const e=t?.maxAgeMs??Pa,r=t?.maxBytesPerDirection??bd;if(!Number.isSafeInteger(e)||e<=0||e>Pa||!Number.isSafeInteger(r)||r<=0||r>bd)throw new Error("Encrypted connection limits cannot exceed the production maximum");return{maxAgeMs:e,maxBytesPerDirection:r}}async function kx(t){const{identity:e,duplex:r,initiator:n,targetPinnedPeerId:o,signal:s}=t,i=Ax(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(n&&!o)throw new Error("A pinned target identity is required");const a=o?zb(o):void 0;if(a&&a.type!=="Ed25519")throw new Error("Only Ed25519 target identities are supported");if(e.peerId!==Jr(e.privateKey.publicKey).toString())throw new Error("Local identity mismatch");if(s?.aborted)throw s.reason??new Error("Connection aborted");const c=new Sx(r,n),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(Qr(s?.reason))};s?.addEventListener("abort",u,{once:!0}),c.addEventListener("close",()=>s?.removeEventListener("abort",u),{once:!0});const f=bx({crypto:Ph,prologueBytes:new TextEncoder().encode(vx)})({privateKey:e.privateKey,peerId:Jr(e.privateKey.publicKey),logger:{forComponent:()=>qs},upgrader:{getStreamMuxers:()=>new Map}});try{const h=await(n?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:Ix(h.connection,i)}}catch(h){throw c.abort(Qr(h)),h}finally{clearTimeout(d),s?.removeEventListener("abort",u)}}function Ix(t,e){const r=new Uh,n=performance.now(),o=Date.now();let s=0,i=0,a;const c=()=>(a??=new Ex,r.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()-n,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,r.push(f.data.subarray())}catch(h){t.abort(Qr(h))}}),t.addEventListener("close",f=>{clearTimeout(l),r.end(f.error)},{once:!0});let u=!1;return{source:r,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(Qr(h)),h}},close(f){f?t.abort(f):t.close()}}}const $h=1012,Hh="Encrypted transport renewed";class Bc{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(r=>{this.wake=r}),this.wake=void 0}}}const vi=2*1024*1024,Cx=new TextEncoder,Rx=new TextDecoder("utf-8",{fatal:!0});class Tx{constructor(e){this.duplex=e;const r=this;this.done=e.sink((async function*(){for await(const n of r.outgoing)try{yield n}finally{r.outgoingBytes-=n.byteLength}})()),this.done.catch(n=>this.close(n instanceof Error?n:new Error("Transport failed")))}duplex;outgoing=new Bc(256);outgoingBytes=0;get hasPendingWrites(){return this.outgoingBytes>0}done;send(e){const r=Cx.encode(JSON.stringify(e));if(r.length>vi)throw new Error("Record too large");const n=new Uint8Array(r.length+4);if(new DataView(n.buffer).setUint32(0,r.length),n.set(r,4),this.outgoingBytes+n.byteLength>4*1024*1024)throw new Error("Record queue byte budget exceeded");this.outgoingBytes+=n.byteLength;try{this.outgoing.push(n)}catch(o){throw this.outgoingBytes-=n.byteLength,o}}close(e){this.outgoing.end(e),this.duplex.close?.(e)}async*read(){let e=new Uint8Array(0);for await(const r of this.duplex.source){if(e.length+r.length>vi*2+8)throw new Error("Record buffer exceeded");const n=new Uint8Array(e.length+r.length);for(n.set(e),n.set(r,e.length),e=n;e.length>=4;){const o=new DataView(e.buffer,e.byteOffset,4).getUint32(0);if(o>vi||o===0)throw new Error("Invalid record size");if(e.length<o+4)break;const s=JSON.parse(Rx.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 qh(t){let e="";for(let r=0;r<t.length;r+=8192)e+=String.fromCharCode(...t.subarray(r,r+8192));return btoa(e)}function Kh(t){const e=atob(t);return Uint8Array.from(e,r=>r.charCodeAt(0))}function Px(t){const e=new Bc(64);t.binaryType="arraybuffer";const r=n=>{e.end(n),t.close(1e3)};return t.addEventListener("message",n=>{try{if(!(n.data instanceof ArrayBuffer)||n.data.byteLength>1024*1024)throw new Error("Invalid encrypted frame");e.push(new Uint8Array(n.data))}catch{r(new Error("Encrypted transport rejected frame"))}}),t.addEventListener("close",()=>e.end()),t.addEventListener("error",()=>e.end(new Error("Encrypted transport disconnected"))),{source:e,close:r,async sink(n){try{for await(const o of n)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 r(o instanceof Error?o:new Error("Encrypted transport failed")),o}}}}const zh=8,Wh=128,Nx=5*1024*1024,Lx=Wh+zh+8,Bx=256,No=3e4,vn=64*1024;function jt(t){return t instanceof Error?t:new Error(String(t??"Secure connection closed"))}function xd(t){if(!t.startsWith("/")||t.startsWith("//")||t.includes("#"))throw new Error("A local API path is required");return t}class Vh extends EventTarget{constructor(e,r,n){super(),this.url=e,this.transmit=r,this.disconnect=n}url;transmit;disconnect;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;binaryType="arraybuffer";bufferedAmount=0;protocol="termdock-e2ee-v1";extensions="";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;send(e){if(this.readyState!==1)throw new Error("Secure socket is not open");if(typeof e!="string"||new TextEncoder().encode(e).length>1024*1024)throw new Error("Unsupported socket payload");this.transmit(e)}close(e=1e3,r=""){this.readyState!==3&&(this.disconnect(),this.finish(e,r))}accept(e){if(this.readyState!==3)if(e.type==="ws-ready"){this.readyState=1;const r=new Event("open");this.dispatchEvent(r),this.onopen?.(r)}else if(e.type==="ws-data"&&typeof e.data=="string"){const r=new MessageEvent("message",{data:e.data});this.dispatchEvent(r),this.onmessage?.(r)}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(jt(e.error))}fail(e){if(this.readyState===3)return;const r=new Event("error");this.dispatchEvent(r),this.onerror?.(r),this.finish(1006,e.message)}finish(e,r){if(this.readyState===3)return;this.readyState=3;const n=new CloseEvent("close",{code:e,reason:r,wasClean:e===1e3});this.dispatchEvent(n),this.onclose?.(n)}}class _x{constructor(e,r,n){this.channel=e,this.identity=r,this.targetPeerId=n,this.read().catch(o=>this.close(jt(o))),e.done.catch(o=>this.close(jt(o)))}channel;identity;targetPeerId;establishedAt=performance.now();establishedWallTime=Date.now();lastInputAt=-1/0;pending=new Map;waiting=[];stopped=!1;closeReason;get canSwitchTransport(){return!this.channel.hasPendingWrites&&performance.now()-this.lastInputAt>=2e3&&![...this.pending.values()].some(e=>e.kind!=="socket")&&!this.waiting.some(e=>e.kind!=="socket")}get renewalDue(){return!this.stopped&&Math.max(performance.now()-this.establishedAt,Date.now()-this.establishedWallTime)>=Pa-5*6e4}get closed(){return this.stopped}hasCapacity(e){if(this.pending.size>=Lx)return!1;const r=[...this.pending.values()].filter(n=>n.kind===e).length;return e==="http"?r<zh:e==="socket"?r<Wh:!0}allocate(e){if(this.stopped)throw this.closeReason??new Error("Secure connection closed");const r=crypto.randomUUID(),n=new Bc(4);return this.pending.set(r,{queue:n,kind:e}),{id:r,queue:n}}reserve(e,r){return r?.aborted?Promise.reject(r.reason):this.stopped?Promise.reject(this.closeReason??new Error("Secure connection closed")):this.hasCapacity(e)?Promise.resolve(this.allocate(e)):this.waiting.length>=Bx?Promise.reject(new Error("连接繁忙,请稍后重试。")):new Promise((n,o)=>{const s=l=>{this.waiting=this.waiting.filter(d=>d!==c),c.cleanup(),o(l)},i=()=>s(r?.reason??new Error("Request aborted")),a=setTimeout(()=>s(new Error("连接等待超时,请重试。")),No),c={kind:e,resolve:n,reject:o,cleanup:()=>{clearTimeout(a),r?.removeEventListener("abort",i)}};this.waiting.push(c),r?.addEventListener("abort",i,{once:!0})})}dispatchWaiting(){if(!this.stopped)for(let e=0;e<this.waiting.length;){const r=this.waiting[e];if(!this.hasCapacity(r.kind)){e++;continue}this.waiting.splice(e,1),r.cleanup(),r.resolve(this.allocate(r.kind))}}async read(){try{for await(const e of this.channel.read()){const r=this.pending.get(e.id);r&&(r.socket?(r.socket.accept(e),(e.type==="ws-close"||e.type==="error")&&this.release(e.id)):(r.queue.push(e),(e.type==="end"||e.type==="error")&&(r.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,r){const{id:n,queue:o}=await this.reserve("request"),s=setTimeout(()=>this.close(new Error("Secure connection timed out")),Math.max(1e3,Math.min(No,r?.timeoutMs??No)));try{if(this.stopped)throw this.closeReason;this.channel.send({...e,id:n});const i=(await o[Symbol.asyncIterator]().next()).value;if(!i)throw new Error("Secure request closed");if(i.type==="error")throw jt(i.error);return i}finally{clearTimeout(s),this.release(n)}}openSocket(e){xd(e);let r;const n=new AbortController,o=new Vh(e,s=>{if(r){try{JSON.parse(s)?.type==="input"&&(this.lastInputAt=performance.now())}catch{}this.channel.send({id:r,type:"ws-data",data:s})}},()=>{if(n.abort(),r)try{this.channel.send({id:r,type:"ws-close"})}finally{this.release(r)}});return this.reserve("socket",n.signal).then(s=>{if(r=s.id,o.readyState===3){this.release(r);return}const i=this.pending.get(r);if(!i)throw new Error("Secure connection closed");i.socket=o,this.channel.send({id:r,type:"ws-open",path:e})}).catch(s=>{r&&this.release(r),o.fail(jt(s))}),o}async fetch(e,r){const n=typeof location>"u"?"https://termdock.invalid":location.origin,o=e instanceof Request?e:null,s=new URL(o?.url??String(e),n);if(s.origin!==n)throw new Error("Only current-service API requests are supported");const i=new Request(s,o?new Request(o,r):r),a=i.method.toUpperCase(),c=xd(s.pathname+s.search),l=s.pathname==="/api/terminal/fs/upload"?110*1024*1024:Nx;if(i.signal.aborted)throw i.signal.reason;const d={};i.headers.forEach((k,B)=>{["cookie","authorization","host","connection","content-length"].includes(B)||(d[B]=k)});const{id:u,queue:f}=await this.reserve("http",i.signal),h=f[Symbol.asyncIterator]();let g;const m=()=>{g?.cancel().catch(()=>{})},y=this.pending.get(u);if(!y)throw new Error("Secure connection closed");y.cancelUpload=m;const w=()=>{m();try{this.channel.send({id:u,type:"cancel"})}catch{}f.end(jt(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)},v=async()=>{let k;try{const B=(await Promise.race([h.next(),new Promise((R,N)=>{k=setTimeout(()=>N(new Error("服务响应超时,请重试。")),No)})])).value;if(!B)throw new Error("Secure response ended unexpectedly");if(B.type==="error")throw jt(B.error);return B}finally{clearTimeout(k)}};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 A=i.body.getReader();g=A;let x=0,S=0;try{for(;;){const{done:T,value:P}=await A.read();if(T)break;if(x+=P.byteLength,x>l)throw new Error("Request body exceeds upload limit");for(let b=0;b<P.byteLength;b+=vn){if(this.channel.send({id:u,type:"upload",data:qh(P.subarray(b,b+vn))}),(await v()).type!=="upload-ack")throw new Error("Invalid upload acknowledgement");S+=Math.min(vn,P.byteLength-b),r?.onUploadProgress?.(S)}}}catch(T){throw await A.cancel(T).catch(()=>{}),T}finally{g=void 0,A.releaseLock()}}if(i.signal.aborted||this.stopped)throw new Error("Request aborted");this.channel.send({id:u,type:"upload-end"});const k=await v();if(k.type!=="head"||typeof k.status!="number")throw new Error("Invalid response header");const B=new Headers(k.headers);if(a==="HEAD"||[204,205,304].includes(k.status)){if((await v()).type!=="end")throw new Error("Unexpected response body");return I(),new Response(null,{status:k.status,headers:B})}let R=!1;const N=new ReadableStream({pull:async A=>{try{R&&(this.channel.send({id:u,type:"ack"}),R=!1);const x=await v();if(x.type==="end"){A.close(),I();return}if(x.type!=="chunk"||typeof x.data!="string")throw new Error("Invalid response chunk");const S=Kh(x.data);if(S.length>vn)throw new Error("Response chunk exceeds budget");A.enqueue(S),R=!0}catch(x){A.error(x),w(),I()}},cancel:()=>{w(),I()}},{highWaterMark:vn,size:A=>A.byteLength});return new Response(N,{status:k.status,headers:B})}catch(k){throw w(),I(),k}}retire(){for(const e of this.pending.values())e.socket?.accept({id:"",type:"ws-close",code:$h,reason:Hh});this.close()}close(e=new Error("Secure connection closed")){if(!this.stopped){this.stopped=!0,this.closeReason=e;for(const r of this.waiting.splice(0))r.cleanup(),r.reject(e);for(const r of this.pending.values())r.queue.end(e),r.cancelUpload?.(),r.socket?.fail(e);this.pending.clear(),this.channel.close(e)}}}async function lr(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 r=t.identity??await jh(),n=(t.socketFactory??(c=>new WebSocket(c)))(e.href),o=Px(n),s=new AbortController,i=setTimeout(()=>s.abort(new Error("Secure handshake timed out")),2e4),a=t.signal?AbortSignal.any([t.signal,s.signal]):s.signal;try{await new Promise((d,u)=>{if(a.aborted){u(a.reason);return}const f=()=>{a.removeEventListener("abort",m),n.removeEventListener("open",h),n.removeEventListener("error",g),n.removeEventListener("close",g)},h=()=>{f(),d()},g=()=>{f(),u(new Error("Secure transport unavailable"))},m=()=>{f(),u(a.reason)};a.addEventListener("abort",m,{once:!0}),n.addEventListener("open",h),n.addEventListener("error",g),n.addEventListener("close",g),n.readyState===1&&h()});const c=await kx({identity:r,duplex:o,initiator:!0,targetPinnedPeerId:t.targetPeerId,signal:a}),l=new _x(new Tx(c.duplex),r,c.authenticatedPeerId);if(t.pairingCode)try{await l.request({type:"pair",code:t.pairingCode})}catch(d){throw l.close(jt(d)),d}return l}catch(c){throw n.close(),c}finally{clearTimeout(i)}}const Sd=256*1024,Dx=1024*1024;class Ox extends EventTarget{constructor(e,r,n=o=>new WebSocket(o)){if(super(),this.url=e,!/^[a-zA-Z0-9_.:-]{1,160}$/.test(r))throw new Error("Invalid target identity");this.upstream=n(e),this.deadline=setTimeout(()=>this.fail("Relay connection timed out"),2e4),this.upstream.addEventListener("message",o=>{if(this.readyState!==3)try{if(typeof o.data!="string"||new TextEncoder().encode(o.data).length>Sd)throw new Error("Invalid relay envelope");const s=JSON.parse(o.data);if(s.type==="ready"&&!this.requested){this.requested=!0,this.transmit({type:"open",streamId:this.streamId,serviceId:r});return}if(s.streamId!==this.streamId)return;if(s.type==="opened"&&this.readyState===0){clearTimeout(this.deadline),this.readyState=1;const l=new Event("open");this.dispatchEvent(l),this.onopen?.(l);return}if(s.type==="close"){this.finish(1001,"Relay route closed"),this.upstream.close();return}if(s.type!=="data"||this.readyState!==1||s.encoding!=="base64"||typeof s.payload!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(s.payload))throw new Error("Invalid ciphertext relay frame");const i=Kh(s.payload),a=this.binaryType==="blob"?new Blob([i]):i.buffer,c=new MessageEvent("message",{data:a});this.dispatchEvent(c),this.onmessage?.(c)}catch{this.fail("Relay protocol rejected frame")}}),this.upstream.addEventListener("close",o=>this.finish(o.code||1006,"Relay disconnected")),this.upstream.addEventListener("error",()=>this.fail("Relay transport unavailable"))}url;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;protocol="";extensions="";binaryType="arraybuffer";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;upstream;streamId=crypto.randomUUID();requested=!1;deadline;get bufferedAmount(){return this.upstream.bufferedAmount}transmit(e){const r=JSON.stringify(e);if(this.upstream.readyState!==1||this.upstream.bufferedAmount+r.length>Dx||r.length>Sd)throw new Error("Relay unavailable or congested");this.upstream.send(r)}send(e){if(this.readyState!==1)throw new Error("Relay socket is not open");let r;if(ArrayBuffer.isView(e))r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof ArrayBuffer)r=new Uint8Array(e);else throw new Error("Relay secure transport requires binary bytes");try{this.transmit({type:"data",streamId:this.streamId,encoding:"base64",payload:qh(r)})}catch(n){throw this.fail("Relay transport congested"),n}}close(e=1e3,r=""){if(this.readyState!==3){try{this.requested&&this.transmit({type:"close",streamId:this.streamId})}catch{}this.finish(e,r),this.upstream.close()}}fail(e){if(this.readyState===3)return;const r=new Event("error");this.dispatchEvent(r),this.onerror?.(r),this.finish(1006,e),this.upstream.close()}finish(e,r){if(this.readyState===3)return;clearTimeout(this.deadline),this.readyState=3;const n=new CloseEvent("close",{code:e,reason:r,wasClean:e===1e3});this.dispatchEvent(n),this.onclose?.(n)}}function Gh(t){return e=>new Ox(e,t)}function Fx(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 n=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 n.endsWith("/")&&!n.startsWith("/api/terminal/fs/preview/")?null:n}catch{return null}}function Mx(t){if(!("serviceWorker"in navigator))return()=>{};const e=new Set,r=n=>{if(n.source!==navigator.serviceWorker.controller||n.data?.type!=="termdock-secure-fetch"||n.ports.length!==1)return;const o=n.ports[0],{path:s,method:i,headers:a,body:c,expectedTargetPeerId:l,previewPrefix:d}=n.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)||!Fx(u.pathname)?.startsWith(d))){o.postMessage({type:"error"}),o.close();return}const f=new AbortController;let h,g,m=!1,y=!1;const w=()=>{y||(y=!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||y||(m=!0,(async()=>{if(!h){o.postMessage({type:"end"}),w();return}if(!g?.length){const k=await h.read();if(k.done){o.postMessage({type:"end"}),w();return}g=k.value}const v=g.slice(0,64*1024);g=g.subarray(v.length),o.postMessage({type:"chunk",data:v.buffer},[v.buffer])})().catch(()=>{o.postMessage({type:"error"}),w()}).finally(()=>{m=!1}))},o.onmessageerror=w,o.start(),(async()=>{const I=await t();if(y)return;if(l&&l!==I.targetPeerId)throw new Error("Preview target changed");const v=await I.fetch(u.pathname+u.search,{method:i,headers:a,body:["GET","HEAD"].includes(i)?void 0:c,signal:f.signal});if(y){await v.body?.cancel();return}h=v.body?.getReader();const k={};v.headers.forEach((B,R)=>{k[R]=B}),o.postMessage({type:"head",status:v.status,headers:k,bodyless:!h,targetPeerId:I.targetPeerId})})().catch(()=>{y||(o.postMessage({type:"error"}),w())})};return navigator.serviceWorker.addEventListener("message",r),()=>{navigator.serviceWorker.removeEventListener("message",r);for(const n of[...e])n()}}class Ge extends Error{constructor(){super("Device authorization expired or revoked")}}const Lo=new WeakMap;function an(t,e={}){const r=Lo.get(t);if(!t.closed&&r&&(!r.settled||Date.now()-r.at<(e.maxAgeMs??1e3)))return r.pending;const n={at:Date.now(),settled:!1,pending:void 0},o=jx(t,e.timeoutMs??5e3).then(s=>(n.at=Date.now(),n.settled=!0,s),s=>{throw Lo.get(t)===n&&Lo.delete(t),s});return n.pending=o,Lo.set(t,n),o}async function jx(t,e){const r=await t.request({type:"permissions"},{timeoutMs:e});if(r.type!=="result"||typeof r.fullService!="boolean"||!Array.isArray(r.grants))throw new Error("Invalid permission response");const n=r.grants,o=r.fullService===!0;if(!o&&n.length===0)throw new Ge;return{fullService:o,grants:n,canManage:o&&n.length>0||n.some(s=>s.actions.includes("authorization.manage"))}}const Xh="termdock-secure-last-path:",Ux=10*6e4;function Yh(t){try{const e=JSON.parse(sessionStorage.getItem(Xh+t)||"null");return e&&typeof e.key=="string"&&Date.now()-e.at<Ux?e.key:void 0}catch{return}}function La(t,e){try{sessionStorage.setItem(Xh+t,JSON.stringify({key:e,at:Date.now()}))}catch{}}function Zh(t,e,r=!1){return new Promise((n,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>=(r?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}})},y=new AbortController;d.add(y),i++,h.run(y.signal).then(w=>{if(m(!0),d.delete(y),a){e(w);return}a=!0,u(),n({value:w,key:h.key})},w=>{if(m(!1),d.delete(y),i--,!a){if(c=w,w instanceof Ge){a=!0,u(),o(w);return}f()}}),clearTimeout(l),!r&&s<t.length&&(l=setTimeout(f,400))};f()})}const Jh="termdock-workspace",Ba="termdock:workspace-visibility",_a="termdock:workspace-activate";function _c(){return window.parent!==window&&location.pathname==="/workspace.html"&&new URLSearchParams(location.search).get(Jh)||"root"}let Ed,Ad;function Et(){try{if(window.parent===window)return window.__termdockWorkspaceHost;const t=window.parent.__termdockWorkspaceHost;return t&&t!==Ed&&(Ed=t,Ad={...t,subscribe(e){const r=t.subscribe(e),n=o=>{o.persisted||r()};return window.addEventListener("pagehide",n),()=>{r(),window.removeEventListener("pagehide",n)}}}),t?Ad:void 0}catch{return}}function xi(){const t=Et();return!t||t.snapshot().activeKey===_c()}function Ss(t,e=!0){return Et()?.activate(t,e)??!1}function Ln(t){Et()?.report(_c(),t)}const Da="termdock-secure-workspace-session:";function Jk(t){if(t)try{const e=JSON.parse(localStorage.getItem(Da+t)||"null");return localStorage.removeItem(Da+t),e&&typeof e.sessionId=="string"&&Date.now()-e.at<6e4?e.sessionId:void 0}catch{return}}function $x(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 c=sessionStorage.getItem("termdock-secure-last-workspace"),l=t&&c!==t.targetPeerId?Kt().find(d=>d.targetPeerId===c):void 0;l?.targetPeerId&&(e={activeKey:l.targetPeerId,items:[...e.items,{key:l.targetPeerId,service:l,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]})}catch{}const r=new Set,n=new Map([["root",window]]),o=new Set,s=()=>{for(const c of[...r])c()},i=(c,l)=>{try{const d=l.document.createEvent("CustomEvent");if(d.initCustomEvent(Ba,!1,!1,{active:e.activeKey===c}),l.dispatchEvent(d),e.activeKey===c){const u=l.document.createEvent("Event");if(u.initEvent("resize",!1,!1),l.dispatchEvent(u),o.delete(c)){const f=l.document.createEvent("Event");f.initEvent(_a,!1,!1),l.dispatchEvent(f)}}else l.document.activeElement?.blur?.()}catch{}},a={snapshot:()=>e,subscribe:c=>(r.add(c),()=>{r.delete(c)}),activate(c,l=!0){const d=Ps(c);if(!d?.targetPeerId)return!1;const u=e.items.find(g=>g.service?.targetPeerId===d.targetPeerId),f=u?.key||d.targetPeerId,h=u?{...u,service:d,touchedAt:Date.now()}:{key:f,service:d,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()};e={activeKey:f,items:u?e.items.map(g=>g===u?h:g):[...e.items,h]};try{sessionStorage.setItem("termdock-secure-last-workspace",d.targetPeerId)}catch{}l&&o.add(f),s();for(const[g,m]of n)i(g,m);return!0},report(c,l){const d=e.items.find(f=>f.key===c);if(!d||l.service&&d.service?.targetPeerId&&l.service.targetPeerId!==d.service.targetPeerId)return;const u={...d,...l};JSON.stringify(u)!==JSON.stringify(d)&&(e={...e,items:e.items.map(f=>f===d?u:f)},s())},attach(c,l){l?(n.set(c,l),i(c,l)):n.delete(c)},focusSession(c,l){const d=Kt().find(f=>f.targetPeerId===c);if(!d)return!1;try{localStorage.setItem(Da+c,JSON.stringify({sessionId:l,at:Date.now()}))}catch{return!1}a.activate(d,!1);const u=n.get(e.activeKey);if(u){const f=u.document.createEvent("CustomEvent");f.initCustomEvent("termdock:workspace-session",!1,!1,null),u.dispatchEvent(f)}return!0}};return window.__termdockWorkspaceHost=a,a}let Si;async function Ye(){return Si||(Si=(async()=>{const t=await new Promise((e,r)=>{const n=indexedDB.open("termdock-device-identity",1);n.onupgradeneeded=()=>n.result.createObjectStore("keys"),n.onsuccess=()=>e(n.result),n.onerror=()=>r(n.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 vd(e);const r=await jh();let n=r;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"?n=vd(c.result):a.put(xx(r),"identity")},i.oncomplete=()=>o(),i.onerror=()=>s(i.error)}),n}finally{t.close()}})()),Si}const Wt="termdock:secure-state";let J,Pr,Be,en="direct",Ho=!1,kd=0,qo=!1,Id=-1/0;const tn=globalThis.fetch.bind(globalThis);function re(){return Or()}function xn(){return J}function Hx(){return Be}function Qh(){J?.close(),Be?.close(),J=void 0,Be=void 0}async function ep(){const t=await tn("/api/auth/status",{signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error("Failed to query auth status");return t.json()}async function qx(){if(re()){await lt();return}if((await ep()).enabled)return;const t=await tn("/api/auth/open/parameters",{cache:"no-store"});if(!t.ok)throw new Error("Open service unavailable");const{serviceIdentity:e}=await t.json();if(typeof e!="string"||!e)throw new Error("Invalid service identity");await Ve({url:location.origin,targetPeerId:e,serviceName:location.hostname})}async function Kx(t,e){const{startPasswordBootstrap:r,finishPasswordBootstrap:n}=await Vt(async()=>{const{startPasswordBootstrap:l,finishPasswordBootstrap:d}=await import("./passwordBootstrap-ftNAkf2B.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 tn(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 Ye(),c=await r(e,i);try{const l=await s("/api/auth/password/start",{startLoginRequest:c.startLoginRequest,clientIdentity:a.peerId});let d;try{d=await n(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 Dc(t,e){const r=re();if(r&&(r.serviceOrigin||r.url)===t)return await Oa(r,e),r;try{return await Kx(t,e)}catch(n){if(!(n instanceof TypeError)&&!(n instanceof DOMException))throw n;const o=(await Xe()).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 Oa(s,e),s}}async function Oa(t,e){const r=await tp(t),{startPasswordBootstrap:n,finishPasswordBootstrap:o}=await Vt(async()=>{const{startPasswordBootstrap:i,finishPasswordBootstrap:a}=await import("./passwordBootstrap-ftNAkf2B.js");return{startPasswordBootstrap:i,finishPasswordBootstrap:a}},__vite__mapDeps([0,1,2,3]));let s;try{const i=await r.request({type:"password-parameters"},{timeoutMs:5e3});s=await n(e,String(i.saltHex));const a=await r.request({type:"password-start",startLoginRequest:s.startLoginRequest,origin:location.origin}),c=await o(s,a,{clientIdentity:(await Ye()).peerId,origin:location.origin});if(c.serverIdentity!==t.targetPeerId)throw new Error("服务身份发生变化。");await r.request({type:"password-finish",attemptId:c.attemptId,finishLoginRequest:c.finishLoginRequest})}catch{throw new Error("暂时无法登录,请检查目标服务密码与入口授权后重试。")}finally{s&&(s.passwordKey=""),r.close()}}async function zx(t){try{const e=re(),r=e?.serviceOrigin||location.origin,n=await Dc(r,t);return await Ve({...n,routes:e?.routes,serviceName:e?.serviceName||n.serviceName}),Response.json({ok:!0})}catch(e){return Response.json({error:e instanceof Error?e.message:"暂时无法登录,请重试。",code:"INVALID_PASSWORD"},{status:401})}}async function Cd(t,e){const r=_e(t),n=(await Xe()).find(i=>(i.serviceOrigin||i.url)===r&&i.targetPeerId);if(e===void 0&&n?.targetPeerId)try{return await Ve({...n,targetPeerId:n.targetPeerId,serviceName:n.label}),{}}catch(i){if(!(i instanceof Ge))throw i}if(e!==void 0){const i=await Dc(r,e);if(n?.targetPeerId&&n.targetPeerId!==i.targetPeerId)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await Ve({...i,routes:n?.routes,serviceName:n?.label||i.serviceName}),{}}const o=await tn(new URL("/api/auth/open/parameters",r).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(n?.targetPeerId&&n.targetPeerId!==s)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await Ve({url:r,targetPeerId:s,serviceName:n?.label||new URL(r).host,serviceOrigin:r}),{}}function dr(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 r=JSON.parse(localStorage.getItem(nc)||"null");r&&r.targetPeerId!==t.targetPeerId&&new URL(r.url).host===new URL(t.url).host&&e.push(r)}catch{}return e.flatMap((r,n)=>{try{return r.targetPeerId&&r.targetPeerId!==t.targetPeerId&&e.findIndex(o=>o.targetPeerId===r.targetPeerId)===n?[{url:_e(r.url),targetPeerId:r.targetPeerId}]:[]}catch{return[]}}).slice(0,4)}function uo(t){const e=dr(t),r=[t.serviceOrigin||t.url,...(t.routes||[]).slice(0,4).filter(o=>o.targetPeerId===t.targetPeerId).map(o=>o.url)],n=new Set;for(const o of r)try{const s=_e(o);e.some(i=>i.url===s)||n.add(s)}catch{}return[...n]}function ur(t){const e=new URL("/api/federation/secure",_e(t));return e.protocol=e.protocol==="https:"?"wss:":"ws:",e.href}async function Gt(t,e){return lr({url:ur(t.url),targetPeerId:t.targetPeerId,identity:await Ye(),signal:e?AbortSignal.any([e,AbortSignal.timeout(5e3)]):AbortSignal.timeout(5e3)})}async function tp(t,e){const r=await Ye(),n=uo(t).map(i=>({key:`direct:${i}`,run:a=>lr({url:ur(i),targetPeerId:t.targetPeerId,identity:r,signal:AbortSignal.any([a,AbortSignal.timeout(8e3),...e?[e]:[]])})}));for(const i of dr(t))n.push({key:`relay:${i.targetPeerId}:${i.url}`,run:async a=>{e&&(a=AbortSignal.any([a,e]));const c=[J,Be].find(d=>d&&!d.closed&&d.targetPeerId===i.targetPeerId),l=c||await Gt(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(ur(i.url));return u.pathname="/api/federation/relay",u.searchParams.set("routeToken",d.routeToken),await lr({url:u.href,targetPeerId:t.targetPeerId,identity:r,socketFactory:Gh(t.targetPeerId),signal:AbortSignal.any([a,AbortSignal.timeout(8e3)])})}finally{c||l.close()}}});const o=Yh(t.targetPeerId);n.sort((i,a)=>+(a.key===o)-+(i.key===o));const s=await Zh(n,i=>i.close());return La(t.targetPeerId,s.key),s.value}async function Wx(t,e){const r=await tp(t,e),n=()=>r.close();e.addEventListener("abort",n,{once:!0});try{if(e.aborted||(await an(r,{timeoutMs:3e3}),e.aborted))throw e.reason;return r}catch(o){throw r.close(),o}finally{e.removeEventListener("abort",n)}}async function Ve(t,e={}){const r=J,n=Be,o=await Ye(),s=_e(t.serviceOrigin||t.url),i=(await Xe()).find(w=>w.targetPeerId===t.targetPeerId),a={...t,routes:t.routes??i?.routes},c=dr(a),l=uo(a);let d,u,f=t.pairingCode,h="direct";const g=new Set,m=new Map,y=async(w,I)=>{if(r&&!r.closed&&r.targetPeerId===w.targetPeerId)return r;if(n&&!n.closed&&n.targetPeerId===w.targetPeerId)return n;const v=m.get(w.targetPeerId);if(v&&!v.closed)return v;const k=await Gt(w,I);return g.add(k),m.set(w.targetPeerId,k),k};try{if(t.routeCode&&t.entryServiceId){const A=c.find(T=>T.targetPeerId===t.entryServiceId);if(!A)throw new Error("邀请缺少入口信息。");if((await(await y(A)).request({type:"route-pair",code:t.routeCode})).serviceId!==t.targetPeerId)throw new Error("邀请的目标服务不一致。");t.routeOnly&&await At({id:t.targetPeerId,url:s,label:t.serviceName||new URL(s).host,targetPeerId:t.targetPeerId,serviceOrigin:s,routes:c})}const w=[],I=async(A,x)=>{const S=()=>A.close();x.addEventListener("abort",S,{once:!0});try{if(x.aborted||(await an(A),x.aborted))throw x.reason}catch(T){throw A.close(),T}finally{x.removeEventListener("abort",S)}};for(const A of l)w.push({key:`direct:${A}`,run:async x=>{const S=await lr({url:ur(A),targetPeerId:t.targetPeerId,pairingCode:f,identity:o,signal:AbortSignal.any([x,AbortSignal.timeout(8e3)])});return f=void 0,await I(S,x),{client:S,path:"direct"}}});for(const A of c)w.push({key:`relay:${A.targetPeerId}:${A.url}`,run:async x=>{let S,T;try{if(S=await y(A,x),x.aborted)throw x.reason;const P=await S.request({type:"route-ticket",serviceId:t.targetPeerId},{timeoutMs:5e3});if(x.aborted)throw x.reason;if(typeof P.routeToken!="string"||!P.routeToken)throw new Error("入口未允许此设备连接该服务。");const b=new URL(ur(A.url));return b.pathname="/api/federation/relay",b.searchParams.set("routeToken",P.routeToken),T=await lr({url:b.href,targetPeerId:t.targetPeerId,pairingCode:f,identity:o,socketFactory:Gh(t.targetPeerId),signal:AbortSignal.any([x,AbortSignal.timeout(8e3)])}),f=void 0,await I(T,x),{client:T,entry:S,path:"relay"}}catch(P){throw T?.close(),S&&S!==n&&S!==r&&S.close(),P}}});const v=Yh(t.targetPeerId);w.sort((A,x)=>+(x.key===v)-+(A.key===v));const k=await Zh(w,A=>{A.client.close(),A.entry&&A.entry!==r&&A.entry!==n&&A.entry.close()},!!f);if(d=k.value.client,u=k.value.entry,h=k.value.path,e.renewIfCurrent){if(J!==e.renewIfCurrent||r!==e.renewIfCurrent||r.closed||!r.canSwitchTransport||re()?.targetPeerId!==t.targetPeerId){d.close();for(const A of g)A!==Be&&A!==J&&A.close();return J??r}J=d,en=h,Be=u,La(t.targetPeerId,k.key),r.retire();for(const A of new Set([n,...g]))A&&A!==r&&A!==d&&A!==u&&A.close();return window.dispatchEvent(new Event(Wt)),d}if(La(t.targetPeerId,k.key),J!==r&&J&&!J.closed&&J.targetPeerId===t.targetPeerId){d.close();for(const A of g)A!==Be&&A.close();return J}h==="direct"&&new URL(s).host===location.host&&vg(t.targetPeerId);const B=(await Xe()).find(A=>A.targetPeerId===t.targetPeerId||!A.targetPeerId&&(A.serviceOrigin||A.url)===s),R=B?.label||t.serviceName||new URL(s).host,N={url:s,targetPeerId:t.targetPeerId,serviceName:R,serviceOrigin:s,routes:a.routes??c};if(await(e.rememberOnly?Eg:At)({id:B?.id||t.targetPeerId,...N,label:R}),Dr!=="unpaired"&&Dr!==t.targetPeerId&&Et()&&Ss({id:B?.id||t.targetPeerId,...N,label:R})){d.close();for(const A of g)A!==r&&A!==n&&A.close();return r||d}Ou(N),J=d,en=h,Be=u;for(const A of new Set([r,n,...g]))A&&A!==d&&A!==u&&A.close();return Dr!==t.targetPeerId?(location.reload(),new Promise(()=>{})):(window.dispatchEvent(new Event(Wt)),d)}catch(w){d?.close();for(const I of g)I!==n&&I.close();throw w}}async function Vx(){const t=J,e=re();if(!(qo||Ho||Pr||!t?.renewalDue||!t.canSwitchTransport||!e||performance.now()-Id<3e4)){Id=performance.now(),qo=!0;try{await Ve(e,{renewIfCurrent:t})}catch(r){console.debug("[connection] renewal deferred",{reason:r instanceof Error?r.message:"unknown"})}finally{qo=!1}}}async function Gx(){const t=J,e=re();if(Date.now()-kd<6e4||qo||Ho||en!=="relay"||!t||t.closed||!t.canSwitchTransport||!e?.serviceOrigin)return;Ho=!0,kd=Date.now();let r;try{for(const o of uo(e))try{r=await lr({url:ur(o),targetPeerId:e.targetPeerId,identity:await Ye(),signal:AbortSignal.timeout(3e3)}),await an(r);break}catch(s){if(r?.close(),r=void 0,s instanceof Ge)throw s}if(!r||J!==t||!t.canSwitchTransport)return;const n=Be;J=r,r=void 0,Be=void 0,en="direct",t.close(),n?.close(),window.dispatchEvent(new Event(Wt))}catch(n){n instanceof Ge&&J===t&&(Qh(),window.dispatchEvent(new Event("auth:unauthorized")))}finally{r?.close(),Ho=!1}}function Xx(){return en}async function lt(){if(J&&!J.closed){const e=J;return Vx(),e}if(J=void 0,Pr)return Pr;const t=re();if(!t)throw new Error("DEVICE_PAIRING_REQUIRED");return Pr=Ve(t,{rememberOnly:!0}).catch(e=>{if(J&&!J.closed&&J.targetPeerId===t.targetPeerId)return J;throw e}).finally(()=>{Pr=void 0}),Pr}function Yx(t){const e=new URL(t,location.href);if(J&&!J.closed)return J.openSocket(e.pathname+e.search);let r;const n=new Vh(t,o=>r?.send(o),()=>r?.close());return lt().then(o=>{n.readyState!==3&&(r=o.openSocket(e.pathname+e.search),r.onopen=()=>n.accept({type:"ws-ready",id:""}),r.onmessage=s=>n.accept({type:"ws-data",id:"",data:s.data}),r.onclose=s=>n.accept({type:"ws-close",id:"",code:s.code,reason:s.reason}),r.onerror=()=>n.fail(new Error("Encrypted connection unavailable")))}).catch(o=>n.fail(o)),n}function Zx(){Mx(lt),window.fetch=async(t,e)=>{const r=new URL(t instanceof Request?t.url:String(t),location.href);if(!r.pathname.startsWith("/api/"))return tn(t,e);if(r.origin!==location.origin)throw new Error("Remote business API requires a paired encrypted service");if(r.pathname==="/api/meta")return tn(t,e);if(r.pathname==="/api/auth/status"){if(!re()){const o=await ep();return Response.json({enabled:o.enabled,authenticated:!1})}try{const o=await an(await lt());return Response.json({enabled:o.grants.length>0,authenticated:!0})}catch(o){if(o instanceof Ge)return Response.json({enabled:!0,authenticated:!1});throw o}}if(r.pathname==="/api/auth/login"){const s=await new Request(t instanceof Request?t:r.href,e).json();return zx(typeof s.password=="string"?s.password:"")}if(r.pathname==="/api/csrf-token")return Response.json({csrfToken:"encrypted-device-channel"});if(r.pathname==="/api/auth/logout")return J&&!J.closed&&await J.request({type:"logout"}),J?.close(),Be?.close(),J=void 0,Be=void 0,bg(),location.reload(),Response.json({ok:!0});const n=await lt();return t instanceof Request?n.fetch(t,e):n.fetch(r.pathname+r.search,e)}}async function Jx(t){if(!t.targetPeerId)throw new Error("请先连接这台服务,再查看可中转的服务。");for(const e of uo({...t,targetPeerId:t.targetPeerId})){let r;const n={url:e,targetPeerId:t.targetPeerId};try{r=await Gt(n)}catch{continue}try{const o=await r.request({type:"route-targets"},{timeoutMs:5e3});if(!Array.isArray(o.items))throw new Error("入口服务需要更新后才能查看中转列表。");return{route:n,canManage:o.canManage===!0,items:o.items}}catch(o){throw o instanceof Error&&/UNKNOWN|UNSUPPORTED/i.test(o.message)?new Error("入口服务需要更新后才能查看中转列表。"):o}finally{r.close()}}throw new Error("暂时连不上中转入口,请检查地址和网络后重试。")}async function Qx(t,e){const r=await Gt(t);try{const n=await r.request({type:"route-targets"},{timeoutMs:5e3}),o=(Array.isArray(n.items)?n.items:[]).find(c=>c.serviceId===e);if(!o)throw new Error("该服务已不可见,请刷新列表或请入口管理员授权。");if(!o.available)throw new Error("入口暂时无法中转到这台服务,请稍后重试。");const s=(await Xe()).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(!n.canManage)throw new Error("请先让入口管理员授权此设备。");await r.request({type:"route-grant",serviceId:o.serviceId,subjectId:(await Ye()).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{r.close()}}async function eS(t,e){const r=await Gt(t);try{const n=await r.request({type:"route-access"},{timeoutMs:5e3}),o=(await Ye()).peerId;return{canManage:n.canManage===!0,grants:(Array.isArray(n.grants)?n.grants:[]).filter(s=>s.subjectId===o&&s.targetServiceId===e)}}finally{r.close()}}async function tS(t,e,r){if(r!==void 0&&(await Dc(_e(e.url),r)).targetPeerId!==e.targetPeerId)throw new Error("入口服务的身份已改变,请重新连接并确认。");const n=await Gt(e);try{await n.request({type:"route-grant",serviceId:t.targetPeerId,subjectId:(await Ye()).peerId,url:_e(t.serviceOrigin||t.url)})}finally{n.close()}}async function rS(t,e){const r=await Gt(e);try{const n=await r.request({type:"route-access"},{timeoutMs:5e3}),o=(await Ye()).peerId,s=(Array.isArray(n.grants)?n.grants:[]).filter(i=>i.subjectId===o&&i.targetServiceId===t&&i.active);for(const i of s)await r.request({type:"route-revoke",grantId:i.id})}finally{r.close()}}async function rp(t,e){const r=await Gt(e);try{const n=await r.request({type:"route-invite-create",serviceId:t.targetPeerId});if(typeof n.routeCode!="string"||typeof n.expiresAt!="number")throw new Error("暂时无法生成备用连接邀请。");return{routeCode:n.routeCode,expiresAt:n.expiresAt}}finally{r.close()}}async function Ko(t,e){const r=(await Xe()).find(o=>o.id===t.id||t.targetPeerId&&o.targetPeerId===t.targetPeerId)||t;await At({...r,url:r.serviceOrigin||r.url,entryServiceId:void 0,routes:e});const n=re();n&&n.targetPeerId===t.targetPeerId&&Ou({...n,url:n.serviceOrigin||n.url,entryServiceId:void 0,routes:e})}async function nS(t,e){const r=t.targetPeerId;if(!r)throw new Error("请先连接这台服务,再添加备用地址。");let n;try{n=_e(e)}catch{throw new Error("请输入有效的 HTTPS 地址,例如 https://电脑地址:9834。")}const o=async()=>(await Xe()).find(a=>a.targetPeerId===r)||t,s=a=>{const c=a.routes??dr({...a,targetPeerId:r});if(_e(a.serviceOrigin||a.url)===n||c.some(l=>_e(l.url)===n))throw new Error("这个地址已经在连接列表中。");if(c.length>=4)throw new Error("最多保存 4 个备用地址或入口,请先移除不再使用的连接。");return[...c,{url:n,targetPeerId:r}]};s(await o());let i;try{try{i=await lr({url:ur(n),targetPeerId:r,identity:await Ye(),signal:AbortSignal.timeout(5e3)}),await an(i)}catch(l){throw l instanceof Ge?new Error("这台服务尚未授权当前设备,请先恢复设备授权。"):new Error("无法验证这个地址。请确认能访问该地址、HTTPS 证书受信任,且运行的是同一台 Termdock 服务。")}const a=await o(),c=s(a);if(await Ko(a,c),re()?.targetPeerId===r&&Dr===r&&(!J||J.closed)){const l=J,d=Be;J=i,i=void 0,Be=void 0,en="direct",l?.close(),d?.close(),window.dispatchEvent(new Event(Wt))}return c}finally{i?.close()}}async function Rd(t,e){await Oa(t,e),await Ve({...t,pairingCode:void 0,routeCode:void 0})}function oS(t,e){return e.aborted?Promise.reject(e.reason):new Promise((r,n)=>{const o=()=>n(e.reason);e.addEventListener("abort",o,{once:!0}),t.then(r,n).finally(()=>e.removeEventListener("abort",o))})}function np(){if(window.termdockDesktop||window.parent!==window)return;if(window.__termdockCollaboration)return window.__termdockCollaboration;const t=new Map;let e=[],r=!1;const n=l=>{const d=l.targetPeerId;if(re()?.targetPeerId===d)return lt();const u=t.get(d);if(u)return u.then(h=>h.closed?(t.get(d)===u&&t.delete(d),n(l)):h);const f=Wx({...l,targetPeerId:d},AbortSignal.timeout(12e3)).then(h=>{if(r||t.get(d)!==f)throw h.close(),new Error("服务连接已移除");return h}).catch(h=>{throw t.get(d)===f&&t.delete(d),h});return t.set(d,f),f},o=()=>{const l=re(),d=Kt();l&&!d.some(f=>f.targetPeerId===l.targetPeerId)&&d.push({...l,id:l.targetPeerId,label:l.serviceName||l.serviceOrigin||l.url});const u=new Set(d.map(f=>f.targetPeerId));for(const[f,h]of t)u.has(f)||(t.delete(f),h.then(g=>g.close()).catch(()=>{}));e=d.filter(f=>!!f.targetPeerId).map(f=>({origin:f.serviceOrigin||f.url,label:f.label,request:async(h,g="GET",m)=>{if(!/^\/collaboration-(?:federation|groups)(?:\/[^?#]*)?$/.test(h))throw new Error("无效的协作请求");const y=AbortSignal.timeout(18e3),w=await oS(n(f),y),I=new Headers({"Content-Type":"application/json"});if(g!=="GET"&&g!=="HEAD"){const B=await w.fetch("/api/csrf-token",{signal:y});if(!B.ok)throw new Error("无法读取目标服务的请求令牌");const R=await B.json();if(typeof R.csrfToken!="string")throw new Error("目标服务的请求令牌无效");I.set("X-XSRF-TOKEN",R.csrfToken)}const v=await w.fetch(`/api/terminal/operations${h}`,{method:g,headers:I,signal:y,...m===void 0?{}:{body:JSON.stringify(m)}}),k=v.status===204?void 0:await v.json();if(!v.ok)throw new Error(k?.error||"服务不可达或未授权协作访问");return k}}))},s=new Sg(()=>e),i={peers:l=>(o(),s.peers(l)),save:async(l,d)=>{o();const u=await s.save(l,d);return a(),u}},a=async()=>{r||document.hidden||!navigator.onLine||!re()||(o(),!(e.length<2)&&await s.refresh().catch(()=>{}))};window.__termdockCollaboration=i;const c=window.setInterval(()=>{a()},2e3);return document.addEventListener("visibilitychange",a),window.addEventListener("online",a),window.addEventListener("pageshow",a),window.addEventListener("pagehide",l=>{if(!l.persisted){r=!0,clearInterval(c);for(const d of t.values())d.then(u=>u.close()).catch(()=>{});t.clear()}}),a(),i}function op(){if(!window.termdockDesktop)try{if(window.parent===window)return np();if(location.pathname==="/workspace.html"&&window.parent.location.origin===location.origin)return window.parent.__termdockCollaboration}catch{}}var Bo={},Td;function sS(){if(Td)return Bo;Td=1;var t=lg();return Bo.createRoot=t.createRoot,Bo.hydrateRoot=t.hydrateRoot,Bo}var iS=sS();const aS=Du(iS);const sp=(...t)=>t.filter((e,r,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===r).join(" ").trim();const cS=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const lS=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,r,n)=>n?n.toUpperCase():r.toLowerCase());const Pd=t=>{const e=lS(t);return e.charAt(0).toUpperCase()+e.slice(1)};var Ei={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 dS=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1},uS=F.createContext({}),fS=()=>F.useContext(uS),hS=F.forwardRef(({color:t,size:e,strokeWidth:r,absoluteStrokeWidth:n,className:o="",children:s,iconNode:i,...a},c)=>{const{size:l=24,strokeWidth:d=2,absoluteStrokeWidth:u=!1,color:f="currentColor",className:h=""}=fS()??{},g=n??u?Number(r??d)*24/Number(e??l):r??d;return F.createElement("svg",{ref:c,...Ei,width:e??l??Ei.width,height:e??l??Ei.height,stroke:t??f,strokeWidth:g,className:sp("lucide",h,o),...!s&&!dS(a)&&{"aria-hidden":"true"},...a},[...i.map(([m,y])=>F.createElement(m,y)),...Array.isArray(s)?s:[s]])});const Pe=(t,e)=>{const r=F.forwardRef(({className:n,...o},s)=>F.createElement(hS,{ref:s,iconNode:e,className:sp(`lucide-${cS(Pd(t))}`,`lucide-${t}`,n),...o}));return r.displayName=Pd(t),r};const pS=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],ip=Pe("arrow-left",pS);const gS=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],mS=Pe("arrow-right",gS);const wS=[["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"}]],yS=Pe("bell-dot",wS);const bS=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Oc=Pe("check",bS);const vS=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],xS=Pe("chevron-down",vS);const SS=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],fr=Pe("chevron-right",SS);const ES=[["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"}]],ap=Pe("copy",ES);const AS=[["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"}]],kS=Pe("ellipsis",AS);const IS=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],He=Pe("loader-circle",IS);const CS=[["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"}]],RS=Pe("monitor",CS);const TS=[["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"}]],PS=Pe("pencil",TS);const NS=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],cp=Pe("plus",NS);const LS=[["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"}]],Ks=Pe("server",LS);const BS=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],lp=Pe("smartphone",BS);const _S=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],DS=Pe("terminal",_S);const OS=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],FS=Pe("x",OS);let Br=null;function MS(t){return!Br||!t?!1:(Br(t),!0)}function Qk(t){Br=t;const e=r=>{const{text:n,nonce:o}=r.detail??{};!n||Br!==t||(t(n),r.stopImmediatePropagation(),o&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:o,ok:!0}})))};return window.addEventListener("termdock-insert-reference",e,!0),()=>{Br===t&&(Br=null),window.removeEventListener("termdock-insert-reference",e,!0)}}const jS=/^[A-Za-z0-9_@%+=:,./-]$/;function US(t){return Array.from(t,e=>(e.codePointAt(0)??0)>127||jS.test(e)?e:`\\${e}`).join("")}function $S(t,e){if(!e)return!1;try{const r=new URL(e.serviceOrigin||e.url);return r.origin===t&&/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})$/.test(r.hostname)&&!(e.routes??[]).some(n=>n.targetPeerId!==e.targetPeerId)}catch{return!1}}function HS(t){const e=s=>s.target instanceof Element?s.target.closest("[data-termdock-terminal-dropzone]"):null,r=()=>!$S(location.origin,Or()),n=s=>{const i=e(s);!i||!r()||!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||!r())return;s.preventDefault(),s.stopImmediatePropagation();const c=i.dataset.termdockTerminalDropzone??"";i.dataset.nativeFileDrag="true",i.dataset.nativeFileDropState="uploading",Vt(async()=>{const{uploadFiles:l}=await Promise.resolve().then(()=>sA);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",n,!0),window.addEventListener("drop",o,!0),()=>{window.removeEventListener("dragover",n,!0),window.removeEventListener("drop",o,!0)}}function dp(){return typeof window>"u"?null:window.termdockDesktop??null}const Ai=new Set;let Nd=!1;function eI(t){const e=dp();if(!e)return()=>{};if(Ai.add(t),!Nd){const r=n=>{if(!MS(n.paths.map(US).join(" ")+" "))for(const o of Ai)o(n)};HS(r),e.onNativeFileDrop(r),Nd=!0}return()=>{Ai.delete(t)}}function up(t=navigator.userAgent,e=navigator.maxTouchPoints){const r=/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":"设备",n=/Electron/.test(t)?"Termdock":/Edg\//.test(t)?"Edge":/Firefox|FxiOS/.test(t)?"Firefox":/Chrome|CriOS/.test(t)?"Chrome":/Safari/.test(t)?"Safari":"浏览器";return`${r} · ${n}`}let qS;function KS(){return qS??=(async()=>{const t=navigator.userAgent,[e,r]=up().split(" · "),n=/(?:Edg|Firefox|FxiOS|Chrome|CriOS|Version)\/([\d.]+)/g,o=[...t.matchAll(n)],s=/(?:CPU (?:iPhone )?OS |Mac OS X |Android )([\d._]+)/.exec(t)?.[1]?.replaceAll("_","."),i={system:`${e}${s?` ${s}`:""}`,client:`${r}${o.length?` ${o.at(-1)[1]}`:""}`,mode:matchMedia("(display-mode: standalone)").matches||navigator.standalone?"已安装的网页应用":"网页"},a=dp();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 zS({service:t,onBusyChange:e,onConnect:r,onConnectWithPassword:n}){const[o,s]=F.useState(),[i,a]=F.useState(!0),[c,l]=F.useState(!1),[d,u]=F.useState(""),[f,h]=F.useState(0),[g,m]=F.useState(),[y,w]=F.useState("");F.useEffect(()=>{let k=!1;return a(!0),u(""),s(void 0),Jx(t).then(B=>{k||s(B)}).catch(B=>{k||u(B instanceof Error?B.message:"暂时无法读取中转列表,请重试。")}).finally(()=>{k||a(!1)}),()=>{k=!0}},[t.id,t.url,f]);const I=async k=>{if(!c){l(!0),e(!0),u("");try{await k()}catch(B){u(B instanceof Error?B.message:"暂时无法连接,请重试。")}finally{l(!1),e(!1)}}},v=async k=>{const B=await Qx(o.route,k.serviceId);try{await r(B)}catch(R){if(!(R instanceof Ge))throw R;m(B)}};return p.jsxs("div",{className:"service-form",children:[g?p.jsxs("form",{className:"service-form",onSubmit:k=>{k.preventDefault(),I(async()=>{try{await n?.(g,y)}finally{w("")}})},children:[p.jsxs("p",{className:"service-help",children:["已通过“",t.label,"”连接到“",g.serviceName,"”。请登录目标服务,完成此设备的访问授权。"]}),n?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:y,disabled:c,onChange:k=>w(k.target.value)})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:c||!y,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(k=>k+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(He,{size:16,className:"service-spinning"}),"正在读取可中转的服务…"]}):o&&p.jsxs("div",{className:"service-list",children:[o.items.map(k=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:c||!k.available,onClick:()=>{I(()=>v(k))},children:[p.jsx("span",{className:"service-icon",children:p.jsx(Ks,{size:19})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:k.label||(k.url?new URL(k.url).host:`中转服务 ${k.serviceId.slice(0,8)}`)}),p.jsx("span",{className:"service-description",children:k.available?k.authorized?"已获中转授权 · 连接":"授权此设备并连接":"中转暂不可用"})]}),p.jsx(fr,{size:16})]},k.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(He,{size:16,className:"service-spinning"}),"正在授权并连接目标服务…"]}),!i&&p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>h(k=>k+1),children:"刷新列表"})]}),d&&p.jsx("p",{className:"service-error",role:"alert",children:d})]})}const Fa="#termdock-invite=";function fp(t){const e=new URL(t.entryUrl);e.hash="",e.search="",e.pathname="/";const r=new TextEncoder().encode(JSON.stringify(t));return e.hash=Fa.slice(1)+btoa(String.fromCharCode(...r)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.href}function Es(t){const e=new URL(t);if(!["https:","http:"].includes(e.protocol)||!e.hash.startsWith(Fa))throw new Error("这不是有效的 Termdock 邀请链接");const r=e.hash.slice(Fa.length);if(r.length>8192)throw new Error("邀请链接过长");let n;try{const i=r.replace(/-/g,"+").replace(/_/g,"/");n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(atob(i),a=>a.charCodeAt(0))))}catch{throw new Error("邀请链接不完整,请重新复制")}if(n.v!==1||typeof n.serviceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(n.serviceId)||n.routeOnly!==!0&&(typeof n.code!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(n.code)))throw new Error("邀请信息无效或版本不兼容");const o=new URL(n.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(n.entryServiceId!==void 0&&(typeof n.entryServiceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(n.entryServiceId)))throw new Error("邀请入口身份无效");if(n.routeCode!==void 0&&(typeof n.routeCode!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(n.routeCode)||!n.entryServiceId))throw new Error("邀请入口权限无效");if(n.routeOnly===!0&&(!n.entryServiceId||!n.routeCode||n.code!==void 0))throw new Error("备用连接邀请不完整");let s=o.origin;if(n.serviceUrl!==void 0){const i=new URL(n.serviceUrl);if(!["https:","http:"].includes(i.protocol)||i.username||i.password)throw new Error("目标服务地址无效");s=n.entryServiceId&&n.entryServiceId!==n.serviceId?i.origin:o.origin}return{url:o.origin,targetPeerId:n.serviceId,pairingCode:n.code,...n.routeOnly===!0?{routeOnly:!0}:{},serviceOrigin:s,serviceName:typeof n.name=="string"?n.name.slice(0,120):void 0,entryServiceId:n.entryServiceId,routeCode:n.routeCode}}function WS({service:t,onBusyChange:e}){const r={...t,targetPeerId:t.targetPeerId,serviceName:t.label},[n,o]=F.useState(()=>t.routes??dr(r)),[s,i]=F.useState([]),[a,c]=F.useState(!0),[l,d]=F.useState(!1),[u,f]=F.useState(""),h=D=>{d(D),e(D)},[g,m]=F.useState(),[y,w]=F.useState(""),[I,v]=F.useState(""),[k,B]=F.useState(""),[R,N]=F.useState(!1),[A,x]=F.useState(),[S,T]=F.useState(),[P,b]=F.useState(!1);F.useEffect(()=>{let D=!1;return Xe().then(_=>{D||i(_.filter(O=>O.targetPeerId&&O.targetPeerId!==t.targetPeerId))}).catch(()=>{D||f("暂时无法读取可用服务。")}).finally(()=>{D||c(!1)}),()=>{D=!0}},[t.targetPeerId]);const E=D=>s.find(_=>_.targetPeerId===D.targetPeerId)?.label||new URL(D.url).host,C=async D=>{h(!0),f(""),B("");try{await D()}catch(_){const O=_ instanceof Error?_.message:"";f(/AUTHORIZATION|DENIED/.test(O)?"当前设备没有入口管理权限。请让管理员分享备用连接邀请,或使用入口密码授权。":"暂时无法完成。请确认入口能连接目标服务,且目标地址、证书和授权有效。")}finally{h(!1)}},L=async(D,_)=>{const O={url:D.serviceOrigin||D.url,targetPeerId:D.targetPeerId};await C(async()=>{const q=await eS(O,r.targetPeerId);if(!q.grants.some(K=>K.active)){if(!q.canManage&&_===void 0){m(D);return}await tS(r,O,_)}const H=[...n.filter(K=>K.targetPeerId!==O.targetPeerId),O];await Ko(t,H),o(H),m(void 0),w("")})};if(S)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:S,onFocus:D=>D.target.select()})]}),p.jsxs("button",{type:"button",className:"service-button service-primary",onClick:()=>{navigator.clipboard.writeText(S).then(()=>b(!0)).catch(()=>f("无法自动复制,请长按链接复制。"))},children:[p.jsx(ap,{size:16}),P?"已复制":"复制邀请链接"]}),p.jsx("button",{type:"button",className:"service-button service-secondary",onClick:()=>{T(void 0),b(!1)},children:"返回备用连接"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});if(g)return p.jsxs("form",{className:"service-form",onSubmit:D=>{D.preventDefault(),L(g,y).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:y,onChange:D=>w(D.target.value),autoComplete:"current-password",disabled:l,autoFocus:!0})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||!y,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 M=n.filter(D=>D.targetPeerId===r.targetPeerId),$=n.filter(D=>D.targetPeerId!==r.targetPeerId),j=async()=>{if(!l){h(!0),N(!0),f(""),B("");try{o(await nS({...t,routes:n},I)),v(""),B("备用地址已验证并保存。")}catch(D){f(D instanceof Error?D.message:"暂时无法添加地址,请重试。")}finally{h(!1),N(!1)}}};return p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"电脑换了网络?添加它在新网络下的地址,原地址连不上时会自动尝试。只接受同一台服务。"}),p.jsxs("form",{className:"service-form",onSubmit:D=>{D.preventDefault(),j()},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用地址"}),p.jsx("input",{value:I,onChange:D=>{v(D.target.value),f(""),B("")},required:!0,disabled:l||n.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||n.length>=4||!I.trim(),children:R?p.jsxs(p.Fragment,{children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在验证…"]}):"验证并添加"})]}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u}),k&&p.jsx("p",{role:"status",className:"service-help",children:k}),n.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})]}),M.length>0&&p.jsx("div",{className:"service-list",children:M.map(D=>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:D.url}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`移除地址 ${D.url}`,disabled:l,onClick:()=>x(D),children:"移除"})]}),A?.targetPeerId===D.targetPeerId&&A.url===D.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:()=>x(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{C(async()=>{const _=n.filter(O=>O.targetPeerId!==D.targetPeerId||O.url!==D.url);await Ko(t,_),o(_),x(void 0)})},children:"确认移除"})]})]})]},D.url))}),p.jsxs("details",{className:"service-relay-options",children:[p.jsxs("summary",{children:["通过其他服务中转",$.length?`(${$.length})`:""]}),p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"所有直连地址都不可用时,尝试下方已授权入口;直连恢复后自动切回。"}),$.length>0&&p.jsx("div",{className:"service-list",children:$.map(D=>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(Ks,{size:18})}),p.jsx("span",{className:"service-name",children:E(D)}),p.jsx(Oc,{size:16,className:"service-selected"})]}),A?.targetPeerId===D.targetPeerId?p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["撤销此设备经“",E(D),"”连接目标的权限?如当前无法直连,目标服务将断开。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>x(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{C(async()=>{await rS(r.targetPeerId,D);const _=n.filter(O=>O.targetPeerId!==D.targetPeerId);await Ko(t,_),o(_),x(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:()=>{C(async()=>{const _=await rp(r,D);T(fp({v:1,routeOnly:!0,serviceId:r.targetPeerId,name:t.label,serviceUrl:t.serviceOrigin||t.url,entryUrl:D.url,entryServiceId:D.targetPeerId,routeCode:_.routeCode}))})},children:"分享备用连接"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>x(D),children:"撤销授权"})]})]},D.targetPeerId))}),a?p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"添加中转入口"}),s.filter(D=>!n.some(_=>_.targetPeerId===D.targetPeerId)).map(D=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:l||n.length>=4,onClick:()=>{L(D)},children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:D.label}),p.jsx("span",{className:"service-description",children:"验证并授权后启用"})]}),p.jsx(fr,{size:16})]},D.id)),s.length===0&&p.jsx("p",{className:"service-empty",children:"添加并登录另一台服务后,可以将它设为中转入口。"})]})]})]}),l&&!R&&p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在验证连接与授权…"]})]})}function VS({current:t,renderRoutes:e,renderRelayServices:r,onOpen:n,onAdd:o,onInvite:s,hideHeader:i,onNavigation:a,onBusyChange:c,initiallyAdding:l=!1}){const[d,u]=F.useState([]),[f,h]=F.useState(!0),[g,m]=F.useState(l?{kind:"add"}:{kind:"list"}),[y,w]=F.useState(!1),I=F.useCallback(b=>{w(b),c?.(b)},[c]),[v,k]=F.useState(""),B=F.useCallback(()=>{m(b=>b.kind==="routes"||b.kind==="relay-services"?{kind:"edit",service:b.service}:{kind:"list"}),k("")},[]),R=g.kind==="add"?"添加服务":g.kind==="edit"?"服务设置":g.kind==="routes"?"备用连接":g.kind==="relay-services"?"可中转的服务":void 0;F.useEffect(()=>{a?.({title:R,...R?{back:B}:{}})},[R,B,a]),F.useEffect(()=>{let b=!1,E=0;const C=async()=>{const M=++E;try{const $=await Xe();!b&&E===M&&(u($),k(""))}catch{!b&&E===M&&k("暂时无法读取服务列表,请重试。")}finally{!b&&E===M&&h(!1)}};C();const L=ju(()=>{C()});return()=>{b=!0,L()}},[]);const N=async b=>{if(!y){I(!0),k("");try{await b()}catch(E){k(E instanceof Error?E.message:"暂时无法完成,请重试。")}finally{I(!1)}}},A=g.kind==="edit"||g.kind==="routes"||g.kind==="relay-services"?d.find(b=>yt(b,g.service))||g.service:void 0,x=t?d.find(b=>yt(b,t))||t:void 0,S=d.filter(b=>!t||!yt(b,t)),T=x?[x,...S]:S,P=p.jsxs(p.Fragment,{children:[f?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(He,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{className:"service-list",children:[T.map(b=>{const E=!!t&&yt(b,t);return p.jsxs("div",{className:"service-row",children:[p.jsxs("button",{type:"button",className:"service-row-open",disabled:y||E,onClick:()=>{N(async()=>{(await n(b))?.passwordRequired&&m({kind:"add",input:b.serviceOrigin||b.url,passwordRequired:!0})})},"aria-label":E?`当前服务 ${b.label}`:`打开 ${b.label}`,children:[p.jsx("span",{className:"service-icon",children:p.jsx(Ks,{size:20})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:b.label}),p.jsx("span",{className:"service-description",children:E?"当前服务":new URL(b.serviceOrigin||b.url).host})]}),E?p.jsx(Oc,{size:17,className:"service-selected"}):p.jsx(fr,{size:16,className:"service-muted"})]}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`管理 ${b.label}`,disabled:y,onClick:()=>{m({kind:"edit",service:b}),k("")},children:p.jsx(kS,{size:19})})]},b.id)}),T.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:y,onClick:()=>{m({kind:"add"}),k("")},children:[p.jsx(cp,{size:16}),"添加服务"]}),s&&p.jsxs("button",{type:"button",className:"service-button service-secondary",disabled:y,onClick:s,children:[p.jsx(lp,{size:16}),"邀请设备"]})]})]});return p.jsxs("div",{className:"service-manager",children:[!i&&p.jsxs("div",{className:"service-heading",children:[R&&p.jsx("button",{type:"button",className:"service-icon-button","aria-label":"返回服务",disabled:y,onClick:B,children:p.jsx(ip,{size:20})}),p.jsx("h2",{children:R||"服务"})]}),g.kind==="relay-services"?r?.(A,I):g.kind==="routes"?e?.(A,I):g.kind==="list"?P:g.kind==="add"?p.jsx(GS,{onSave:b=>N(async()=>{const E=_e(b);u(await At({id:E,url:E,label:new URL(E).host})),B()}),initialInput:g.input,passwordRequired:g.passwordRequired,busy:y,onSubmit:async(b,E)=>{let C;return await N(async()=>{C=await o(b,E),C?.passwordRequired||B()}),C}}):p.jsx(XS,{onRelayServices:r&&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:A,busy:y,canRemove:!t||!yt(g.service,t),onSave:b=>{N(async()=>{u(await At({...A,label:b})),B()})},onRemove:()=>{N(async()=>{u(await Ag(g.service.id)),B()})}}),v&&p.jsx("p",{className:"service-error",role:"alert",children:v})]})}function GS({busy:t,onSubmit:e,onSave:r,initialInput:n="",passwordRequired:o=!1}){const[s,i]=F.useState(n),[a,c]=F.useState(""),[l,d]=F.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:()=>{r(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(He,{size:16,className:"service-spinning"}),"正在连接…"]}):l?"登录并连接":"继续"})]})}function XS({service:t,busy:e,canRemove:r,onSave:n,onRemove:o,onRoutes:s,onRelayServices:i}){const[a,c]=F.useState(t.label),[l,d]=F.useState(!1);return p.jsxs("form",{className:"service-form",onSubmit:u=>{u.preventDefault(),n(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(fr,{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(fr,{size:16})]}),r&&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 Cr={},ki,Ld;function YS(){return Ld||(Ld=1,ki=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),ki}var Ii={},Ot={},Bd;function mr(){if(Bd)return Ot;Bd=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 Ot.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},Ot.getSymbolTotalCodewords=function(n){return e[n]},Ot.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Ot.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');t=n},Ot.isKanjiModeEnabled=function(){return typeof t<"u"},Ot.toSJIS=function(n){return t(n)},Ot}var Ci={},_d;function Fc(){return _d||(_d=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.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: "+r)}}t.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},t.from=function(n,o){if(t.isValid(n))return n;try{return e(n)}catch{return o}}})(Ci)),Ci}var Ri,Dd;function ZS(){if(Dd)return Ri;Dd=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(e){const r=Math.floor(e/8);return(this.buffer[r]>>>7-e%8&1)===1},put:function(e,r){for(let n=0;n<r;n++)this.putBit((e>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),e&&(this.buffer[r]|=128>>>this.length%8),this.length++}},Ri=t,Ri}var Ti,Od;function JS(){if(Od)return Ti;Od=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,r,n,o){const s=e*this.size+r;this.data[s]=n,o&&(this.reservedBit[s]=!0)},t.prototype.get=function(e,r){return this.data[e*this.size+r]},t.prototype.xor=function(e,r,n){this.data[e*this.size+r]^=n},t.prototype.isReserved=function(e,r){return this.reservedBit[e*this.size+r]},Ti=t,Ti}var Pi={},Fd;function QS(){return Fd||(Fd=1,(function(t){const e=mr().getSymbolSize;t.getRowColCoords=function(n){if(n===1)return[];const o=Math.floor(n/7)+2,s=e(n),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(n){const o=[],s=t.getRowColCoords(n),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}})(Pi)),Pi}var Ni={},Md;function eE(){if(Md)return Ni;Md=1;const t=mr().getSymbolSize,e=7;return Ni.getPositions=function(n){const o=t(n);return[[0,0],[o-e,0],[0,o-e]]},Ni}var Li={},jd;function tE(){return jd||(jd=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 r(n,o,s){switch(n){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:"+n)}}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,r(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}})(Li)),Li}var _o={},Ud;function hp(){if(Ud)return _o;Ud=1;const t=Fc(),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],r=[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 _o.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}},_o.getTotalCodewordsCount=function(o,s){switch(s){case t.L:return r[(o-1)*4+0];case t.M:return r[(o-1)*4+1];case t.Q:return r[(o-1)*4+2];case t.H:return r[(o-1)*4+3];default:return}},_o}var Bi={},Sn={},$d;function rE(){if($d)return Sn;$d=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let n=1;for(let o=0;o<255;o++)t[o]=n,e[n]=o,n<<=1,n&256&&(n^=285);for(let o=255;o<512;o++)t[o]=t[o-255]})(),Sn.log=function(n){if(n<1)throw new Error("log("+n+")");return e[n]},Sn.exp=function(n){return t[n]},Sn.mul=function(n,o){return n===0||o===0?0:t[e[n]+e[o]]},Sn}var Hd;function nE(){return Hd||(Hd=1,(function(t){const e=rE();t.mul=function(n,o){const s=new Uint8Array(n.length+o.length-1);for(let i=0;i<n.length;i++)for(let a=0;a<o.length;a++)s[i+a]^=e.mul(n[i],o[a]);return s},t.mod=function(n,o){let s=new Uint8Array(n);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(n){let o=new Uint8Array([1]);for(let s=0;s<n;s++)o=t.mul(o,new Uint8Array([1,e.exp(s)]));return o}})(Bi)),Bi}var _i,qd;function oE(){if(qd)return _i;qd=1;const t=nE();function e(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(n){this.degree=n,this.genPoly=t.generateECPolynomial(this.degree)},e.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(n.length+this.degree);o.set(n);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},_i=e,_i}var Di={},Oi={},Fi={},Kd;function pp(){return Kd||(Kd=1,Fi.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),Fi}var at={},zd;function gp(){if(zd)return at;zd=1;const t="[0-9]+",e="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
3
3
  ]))+`;at.KANJI=new RegExp(r,"g"),at.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),at.BYTE=new RegExp(n,"g"),at.NUMERIC=new RegExp(t,"g"),at.ALPHANUMERIC=new RegExp(e,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+t+"$"),i=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return at.testKanji=function(c){return o.test(c)},at.testNumeric=function(c){return s.test(c)},at.testAlphanumeric=function(c){return i.test(c)},at}var Wd;function wr(){return Wd||(Wd=1,(function(t){const e=pp(),r=gp();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 r.testNumeric(s)?t.NUMERIC:r.testAlphanumeric(s)?t.ALPHANUMERIC:r.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 n(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 n(s)}catch{return i}}})(Oi)),Oi}var Vd;function sE(){return Vd||(Vd=1,(function(t){const e=mr(),r=hp(),n=Fc(),o=wr(),s=pp(),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 y=l(m.mode,h);g+=y+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 y=e.getSymbolTotalCodewords(h),w=r.getTotalCodewordsCount(h,g),I=(y-w)*8;if(m===o.MIXED)return I;const v=I-l(m,h);switch(m){case o.NUMERIC:return Math.floor(v/10*3);case o.ALPHANUMERIC:return Math.floor(v/11*2);case o.KANJI:return Math.floor(v/13);case o.BYTE:default:return Math.floor(v/8)}},t.getBestVersionForData=function(h,g){let m;const y=n.from(g,n.M);if(Array.isArray(h)){if(h.length>1)return u(h,y);if(h.length===0)return 1;m=h[0]}else m=h;return c(m.mode,m.getLength(),y)},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}})(Di)),Di}var Mi={},Gd;function iE(){if(Gd)return Mi;Gd=1;const t=mr(),e=1335,r=21522,n=t.getBCHDigit(e);return Mi.getEncodedBits=function(s,i){const a=s.bit<<3|i;let c=a<<10;for(;t.getBCHDigit(c)-n>=0;)c^=e<<t.getBCHDigit(c)-n;return(a<<10|c)^r},Mi}var ji={},Ui,Xd;function aE(){if(Xd)return Ui;Xd=1;const t=wr();function e(r){this.mode=t.NUMERIC,this.data=r.toString()}return e.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%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(n){let o,s,i;for(o=0;o+3<=this.data.length;o+=3)s=this.data.substr(o,3),i=parseInt(s,10),n.put(i,10);const a=this.data.length-o;a>0&&(s=this.data.substr(o),i=parseInt(s,10),n.put(i,a*3+1))},Ui=e,Ui}var $i,Yd;function cE(){if(Yd)return $i;Yd=1;const t=wr(),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 r(n){this.mode=t.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.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)},$i=r,$i}var Hi,Zd;function lE(){if(Zd)return Hi;Zd=1;const t=wr();function e(r){this.mode=t.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return e.getBitsLength=function(n){return n*8},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(r){for(let n=0,o=this.data.length;n<o;n++)r.put(this.data[n],8)},Hi=e,Hi}var qi,Jd;function dE(){if(Jd)return qi;Jd=1;const t=wr(),e=mr();function r(n){this.mode=t.KANJI,this.data=n}return r.getBitsLength=function(o){return o*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){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),n.put(s,13)}},qi=r,qi}var Ki={exports:{}},Qd;function uE(){return Qd||(Qd=1,(function(t){var e={single_source_shortest_paths:function(r,n,o){var s={},i={};i[n]=0;var a=e.PriorityQueue.make();a.push(n,0);for(var c,l,d,u,f,h,g,m,y;!a.empty();){c=a.pop(),l=c.value,u=c.cost,f=r[l]||{};for(d in f)f.hasOwnProperty(d)&&(h=f[d],g=u+h,m=i[d],y=typeof i[d]>"u",(y||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 ",n," to ",o,"."].join("");throw new Error(w)}return s},extract_shortest_path_from_predecessor_list:function(r,n){for(var o=[],s=n;s;)o.push(s),r[s],s=r[s];return o.reverse(),o},find_path:function(r,n,o){var s=e.single_source_shortest_paths(r,n,o);return e.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(r){var n=e.PriorityQueue,o={},s;r=r||{};for(s in n)n.hasOwnProperty(s)&&(o[s]=n[s]);return o.queue=[],o.sorter=r.sorter||n.default_sorter,o},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var o={value:r,cost:n};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})(Ki)),Ki.exports}var eu;function fE(){return eu||(eu=1,(function(t){const e=wr(),r=aE(),n=cE(),o=lE(),s=dE(),i=gp(),a=mr(),c=uE();function l(w){return unescape(encodeURIComponent(w)).length}function d(w,I,v){const k=[];let B;for(;(B=w.exec(v))!==null;)k.push({data:B[0],index:B.index,mode:I,length:B[0].length});return k}function u(w){const I=d(i.NUMERIC,e.NUMERIC,w),v=d(i.ALPHANUMERIC,e.ALPHANUMERIC,w);let k,B;return a.isKanjiModeEnabled()?(k=d(i.BYTE,e.BYTE,w),B=d(i.KANJI,e.KANJI,w)):(k=d(i.BYTE_KANJI,e.BYTE,w),B=[]),I.concat(v,k,B).sort(function(N,A){return N.index-A.index}).map(function(N){return{data:N.data,mode:N.mode,length:N.length}})}function f(w,I){switch(I){case e.NUMERIC:return r.getBitsLength(w);case e.ALPHANUMERIC:return n.getBitsLength(w);case e.KANJI:return s.getBitsLength(w);case e.BYTE:return o.getBitsLength(w)}}function h(w){return w.reduce(function(I,v){const k=I.length-1>=0?I[I.length-1]:null;return k&&k.mode===v.mode?(I[I.length-1].data+=v.data,I):(I.push(v),I)},[])}function g(w){const I=[];for(let v=0;v<w.length;v++){const k=w[v];switch(k.mode){case e.NUMERIC:I.push([k,{data:k.data,mode:e.ALPHANUMERIC,length:k.length},{data:k.data,mode:e.BYTE,length:k.length}]);break;case e.ALPHANUMERIC:I.push([k,{data:k.data,mode:e.BYTE,length:k.length}]);break;case e.KANJI:I.push([k,{data:k.data,mode:e.BYTE,length:l(k.data)}]);break;case e.BYTE:I.push([{data:k.data,mode:e.BYTE,length:l(k.data)}])}}return I}function m(w,I){const v={},k={start:{}};let B=["start"];for(let R=0;R<w.length;R++){const N=w[R],A=[];for(let x=0;x<N.length;x++){const S=N[x],T=""+R+x;A.push(T),v[T]={node:S,lastCount:0},k[T]={};for(let P=0;P<B.length;P++){const b=B[P];v[b]&&v[b].node.mode===S.mode?(k[b][T]=f(v[b].lastCount+S.length,S.mode)-f(v[b].lastCount,S.mode),v[b].lastCount+=S.length):(v[b]&&(v[b].lastCount=S.length),k[b][T]=f(S.length,S.mode)+4+e.getCharCountIndicator(S.mode,I))}}B=A}for(let R=0;R<B.length;R++)k[B[R]].end=0;return{map:k,table:v}}function y(w,I){let v;const k=e.getBestModeForData(w);if(v=e.from(I,k),v!==e.BYTE&&v.bit<k.bit)throw new Error('"'+w+'" cannot be encoded with mode '+e.toString(v)+`.
5
5
  Suggested mode is: `+e.toString(k));switch(v===e.KANJI&&!a.isKanjiModeEnabled()&&(v=e.BYTE),v){case e.NUMERIC:return new r(w);case e.ALPHANUMERIC:return new n(w);case e.KANJI:return new s(w);case e.BYTE:return new o(w)}}t.fromArray=function(I){return I.reduce(function(v,k){return typeof k=="string"?v.push(y(k,null)):k.data&&v.push(y(k.data,k.mode)),v},[])},t.fromString=function(I,v){const k=u(I,a.isKanjiModeEnabled()),B=g(k),R=m(B,v),N=c.find_path(R.map,"start","end"),A=[];for(let x=1;x<N.length-1;x++)A.push(R.table[N[x]].node);return t.fromArray(h(A))},t.rawSplit=function(I){return t.fromArray(u(I,a.isKanjiModeEnabled()))}})(ji)),ji}var tu;function hE(){if(tu)return Ii;tu=1;const t=mr(),e=Fc(),r=ZS(),n=JS(),o=QS(),s=eE(),i=tE(),a=hp(),c=oE(),l=sE(),d=iE(),u=wr(),f=fE();function h(R,N){const A=R.size,x=s.getPositions(N);for(let S=0;S<x.length;S++){const T=x[S][0],P=x[S][1];for(let b=-1;b<=7;b++)if(!(T+b<=-1||A<=T+b))for(let E=-1;E<=7;E++)P+E<=-1||A<=P+E||(b>=0&&b<=6&&(E===0||E===6)||E>=0&&E<=6&&(b===0||b===6)||b>=2&&b<=4&&E>=2&&E<=4?R.set(T+b,P+E,!0,!0):R.set(T+b,P+E,!1,!0))}}function g(R){const N=R.size;for(let A=8;A<N-8;A++){const x=A%2===0;R.set(A,6,x,!0),R.set(6,A,x,!0)}}function m(R,N){const A=o.getPositions(N);for(let x=0;x<A.length;x++){const S=A[x][0],T=A[x][1];for(let P=-2;P<=2;P++)for(let b=-2;b<=2;b++)P===-2||P===2||b===-2||b===2||P===0&&b===0?R.set(S+P,T+b,!0,!0):R.set(S+P,T+b,!1,!0)}}function y(R,N){const A=R.size,x=l.getEncodedBits(N);let S,T,P;for(let b=0;b<18;b++)S=Math.floor(b/3),T=b%3+A-8-3,P=(x>>b&1)===1,R.set(S,T,P,!0),R.set(T,S,P,!0)}function w(R,N,A){const x=R.size,S=d.getEncodedBits(N,A);let T,P;for(T=0;T<15;T++)P=(S>>T&1)===1,T<6?R.set(T,8,P,!0):T<8?R.set(T+1,8,P,!0):R.set(x-15+T,8,P,!0),T<8?R.set(8,x-T-1,P,!0):T<9?R.set(8,15-T-1+1,P,!0):R.set(8,15-T-1,P,!0);R.set(x-8,8,1,!0)}function I(R,N){const A=R.size;let x=-1,S=A-1,T=7,P=0;for(let b=A-1;b>0;b-=2)for(b===6&&b--;;){for(let E=0;E<2;E++)if(!R.isReserved(S,b-E)){let C=!1;P<N.length&&(C=(N[P]>>>T&1)===1),R.set(S,b-E,C),T--,T===-1&&(P++,T=7)}if(S+=x,S<0||A<=S){S-=x,x=-x;break}}}function v(R,N,A){const x=new r;A.forEach(function(E){x.put(E.mode.bit,4),x.put(E.getLength(),u.getCharCountIndicator(E.mode,R)),E.write(x)});const S=t.getSymbolTotalCodewords(R),T=a.getTotalCodewordsCount(R,N),P=(S-T)*8;for(x.getLengthInBits()+4<=P&&x.put(0,4);x.getLengthInBits()%8!==0;)x.putBit(0);const b=(P-x.getLengthInBits())/8;for(let E=0;E<b;E++)x.put(E%2?17:236,8);return k(x,R,N)}function k(R,N,A){const x=t.getSymbolTotalCodewords(N),S=a.getTotalCodewordsCount(N,A),T=x-S,P=a.getBlocksCount(N,A),b=x%P,E=P-b,C=Math.floor(x/P),L=Math.floor(T/P),M=L+1,$=C-L,j=new c($);let D=0;const _=new Array(P),O=new Array(P);let q=0;const H=new Uint8Array(R.buffer);for(let G=0;G<P;G++){const Y=G<E?L:M;_[G]=H.slice(D,D+Y),O[G]=j.encode(_[G]),D+=Y,q=Math.max(q,Y)}const K=new Uint8Array(x);let z=0,V,X;for(V=0;V<q;V++)for(X=0;X<P;X++)V<_[X].length&&(K[z++]=_[X][V]);for(V=0;V<$;V++)for(X=0;X<P;X++)K[z++]=O[X][V];return K}function B(R,N,A,x){let S;if(Array.isArray(R))S=f.fromArray(R);else if(typeof R=="string"){let C=N;if(!C){const L=f.rawSplit(R);C=l.getBestVersionForData(L,A)}S=f.fromString(R,C||40)}else throw new Error("Invalid data");const T=l.getBestVersionForData(S,A);if(!T)throw new Error("The amount of data is too big to be stored in a QR Code");if(!N)N=T;else if(N<T)throw new Error(`
@@ -31,4 +31,4 @@ Stack:
31
31
  ${t.stack}`:"",e?`
32
32
  React component stack:
33
33
  ${e.trim()}`:""].filter(Boolean).join(`
34
- `)}async function fk(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 hk({error:t,componentStack:e}){const{t:r}=Yc(),[n,o]=$e.useState("idle"),s=async()=>{const i=uk(t,e,{url:window.location.href,userAgent:navigator.userAgent,capturedAt:new Date().toISOString()});o(await fk(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:r("errorBoundary.title")}),p.jsx("p",{className:"text-sm text-muted-foreground",children:t?.message||r("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:r(n==="copied"?"errorBoundary.copied":n==="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:r("errorBoundary.retry")})]})]})})}class pk extends $e.Component{state={hasError:!1,error:null,componentStack:""};static getDerivedStateFromError(e){return{hasError:!0,error:e,componentStack:""}}componentDidCatch(e,r){console.error("Terminal error caught by boundary:",e,r),this.setState({componentStack:r.componentStack??""})}render(){return this.state.hasError?this.props.fallback?this.props.fallback:p.jsx(hk,{error:this.state.error,componentStack:this.state.componentStack}):this.props.children}}function me(){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 gk="debug",mk="termdock:debug";function Cu(t){return t?new Set(t.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean)):new Set}function wk(){if(typeof window>"u")return new Set;const t=Cu(new URLSearchParams(window.location.search).get(gk));let e=new Set;try{e=Cu(window.localStorage.getItem(mk))}catch{e=new Set}const r=new Set([...t,...e]);return r.has("1")||r.has("true")||r.has("*")||r.has("all")?new Set(["*"]):r}function yk(t){const e=wk();return e.has("*")||e.has(t)}function bk(t){const e=yk(t);return(...r)=>{e&&console.log(`[debug:${t}]`,...r)}}const Ru=80,vk=60,xk="termdock:viewport-keyboard-change",Sk="termdock:viewport-layout-change",xt=240,Tu=640,Pu=360;function Ek({measuredHeight:t,documentVisible:e,editableFocused:r}){return e&&r&&t>0}function Nu(){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 Cs=t=>{const e=typeof t=="number"?t:Number.parseFloat(typeof t=="string"?t:"0");return Number.isFinite(e)&&e>0?Math.round(e):0},Yp=(t,e)=>{const r=t.map(Cs).filter(n=>n>0);return r.find(n=>n>=xt)??r[0]??e},zn=()=>typeof window>"u"?Tu:Yp([me().innerHeight,document.documentElement?.clientHeight,document.body?.clientHeight,me().visualViewport?.height,window.screen?.availHeight,window.screen?.height],Tu),Zp=()=>typeof window>"u"?Pu:Yp([me().innerWidth,document.documentElement?.clientWidth,document.body?.clientWidth,me().visualViewport?.width,window.screen?.availWidth,window.screen?.width],Pu),Mt=t=>{const e=Number.parseFloat(t||"0");return Number.isFinite(e)?Math.max(0,Math.round(e)):0},Ak=()=>typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,kk=()=>typeof window>"u"?!1:me().navigator.standalone===!0||me().matchMedia?.("(display-mode: standalone)").matches===!0,Jp=()=>{if(typeof window>"u"||!Ak()||!kk())return{top:0,right:0,bottom:0,left:0};if(!(zn()>=Zp()))return{top:0,right:0,bottom:0,left:0};const e=window.screen?.width||window.innerWidth,r=window.screen?.height||window.innerHeight,n=Math.min(e,r),o=Math.max(e,r);return n>=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 Ik(t="--app-vh"){if(typeof window>"u"||typeof document>"u")return;const e=Cs(me().visualViewport?.height),r=Math.max(0,Math.round(me().visualViewport?.offsetTop??0)),n=zn(),s=e>=xt?Math.min(n,e+r):n,i=Math.max(n,s),a=document.documentElement.style;a.setProperty(t,`${Math.max(s,xt)}px`),a.setProperty("--app-base-vh",`${Math.max(i,xt)}px`),a.setProperty("--app-visible-vh",`${Math.max(s,xt)}px`),a.setProperty("--app-vv-offset-top",`${r}px`),a.setProperty("--kb-translate-y","0px"),a.setProperty("--kb-margin-top","0px"),a.setProperty("--kb-height","0px");const c=Jp();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 dI(t={}){const{cssVarName:e="--app-vh"}=t,r=$e.useMemo(()=>bk("viewport"),[]),n=$e.useCallback(()=>{if(typeof window>"u")return 0;const d=me().visualViewport,u=zn();if(!d)return u;const f=Cs(d.height);if(f<xt&&u>=xt)return u;const h=d.offsetTop,m=f<u-1&&h>0&&h<=96?f+h:f,y=Math.max(0,Math.min(u,m));return y>0?Math.round(y):u},[]),[o,s]=$e.useState(n),i=$e.useRef(0),a=$e.useRef(0),c=$e.useRef(0),l=$e.useRef(!1);return $e.useEffect(()=>{if(typeof window>"u")return;let d=null,u=null;const f=()=>{if(u?.isConnected)return u;try{return u=document.createElement("div"),u.setAttribute("aria-hidden","true"),u.style.cssText=["position:fixed","top:0","left:0","width:0","height:0","visibility:hidden","pointer-events:none","padding-top:constant(safe-area-inset-top)","padding-top:env(safe-area-inset-top,0px)","padding-right:constant(safe-area-inset-right)","padding-right:env(safe-area-inset-right,0px)","padding-bottom:constant(safe-area-inset-bottom)","padding-bottom:env(safe-area-inset-bottom,0px)","padding-left:constant(safe-area-inset-left)","padding-left:env(safe-area-inset-left,0px)"].join(";"),(document.body||document.documentElement).appendChild(u),u}catch{}return null},h=()=>{let P={top:0,right:0,bottom:0,left:0};try{const L=f();if(L){const M=getComputedStyle(L);P={top:Mt(M.paddingTop),right:Mt(M.paddingRight),bottom:Mt(M.paddingBottom),left:Mt(M.paddingLeft)}}}catch{}const b=me();if(b!==window){const L=b.getComputedStyle(b.document.documentElement);P={top:Math.max(P.top,Mt(L.getPropertyValue("--safe-top-inset"))),right:Math.max(P.right,Mt(L.getPropertyValue("--safe-right-inset"))),bottom:Math.max(P.bottom,Mt(L.getPropertyValue("--safe-bottom-inset"))),left:Math.max(P.left,Mt(L.getPropertyValue("--safe-left-inset")))}}const E=Jp(),C={top:Math.max(P.top,E.top),right:Math.max(P.right,E.right),bottom:Math.max(P.bottom,E.bottom),left:Math.max(P.left,E.left)};return document.documentElement.style.setProperty("--safe-top-inset",`${C.top}px`),document.documentElement.style.setProperty("--safe-right-inset",`${C.right}px`),document.documentElement.style.setProperty("--safe-bottom-inset",`${C.bottom}px`),document.documentElement.style.setProperty("--safe-left-inset",`${C.left}px`),C},g=(P,b,E,C)=>{const L=Math.max(b,E);if(i.current===0){i.current=L,a.current=P,document.documentElement.style.setProperty("--app-base-vh",`${L}px`);return}const M=Math.abs(P-a.current),$=C<=Ru;(M>vk||$)&&(i.current=L,a.current=P,document.documentElement.style.setProperty("--app-base-vh",`${L}px`))},m=(P="event")=>{d=null;const b=n(),E=Math.round(me().visualViewport?.offsetTop??0),C=Cs(me().visualViewport?.height),L=C>=xt?C:b,M=zn(),$=Zp(),j=Math.max(0,L+E),D=h(),_=D.bottom,O=Math.max(0,i.current-j-_);g($,M,j,O),s(Tt=>Tt===b?Tt:b);const q=Number.parseInt(document.documentElement.style.getPropertyValue(e)||"0",10);document.documentElement.style.setProperty(e,`${b}px`),document.documentElement.style.setProperty("--app-vv-offset-top",`${E}px`);const H=i.current,K=Math.min(b,L),z=Math.max(0,Math.min(H,j)),V=Math.max(0,Math.round(H-z-_)),X=Nu(),G=Ek({measuredHeight:V,documentVisible:document.visibilityState==="visible",editableFocused:X}),Y=G?V:0,se=Y>=Ru,Ne=-Y,Me=Y;document.documentElement.style.setProperty("--kb-translate-y",`${Ne}px`),document.documentElement.style.setProperty("--kb-margin-top",`${Me}px`),document.documentElement.style.setProperty("--kb-height",`${Y}px`),document.documentElement.style.setProperty("--app-visible-vh",`${z}px`);const oe=Math.abs(Y-c.current)>1,ot=se!==l.current;(oe||ot)&&(c.current=Y,l.current=se,document.dispatchEvent(new CustomEvent(xk,{detail:{baseHeight:H,visibleHeight:z,visualViewportHeight:L,offsetTop:E,keyboardHeight:Y,isOpen:se,source:P}}))),(q!==b||E>0||oe||ot)&&r("sync",{cssVarName:e,innerHeight:M,baseHeight:H,rawViewportHeight:L,offsetTop:E,visibleHeight:z,rawHeight:b,appliedHeight:b,keyboardViewportHeight:K,measuredKeyboardHeight:V,editableFocused:X,applyKeyboardInset:G,keyboardHeight:Y,isKeyboardOpen:se,safeAreaInsets:D,source:P}),document.dispatchEvent(new CustomEvent(Sk,{detail:{height:b,baseHeight:H,visibleHeight:z,offsetTop:E,source:P}}))},y=(P="event")=>{(P.includes("visibilitychange")||P.includes("pageshow"))&&r("schedule",{source:P}),d===null&&(d=window.requestAnimationFrame(()=>m(P)))};y("mount");const w=()=>y("resize"),I=()=>y("orientationchange"),v=()=>y("visualViewport.resize"),k=()=>y("visualViewport.scroll"),B=()=>y("focusin"),R=()=>y("focusout"),N=P=>{const b=document.activeElement;b instanceof HTMLElement&&Nu()&&b.blur(),c.current=0,l.current=!1;const E=Math.max(i.current,zn(),xt),C=document.documentElement.style;C.setProperty(e,`${E}px`),C.setProperty("--app-visible-vh",`${E}px`),C.setProperty("--app-vv-offset-top","0px"),C.setProperty("--kb-translate-y","0px"),C.setProperty("--kb-margin-top","0px"),C.setProperty("--kb-height","0px"),s(L=>L===E?L:E),r("keyboard session reset",{source:P,baseHeight:E})};window.addEventListener("resize",w),window.addEventListener("orientationchange",I),me().visualViewport?.addEventListener("resize",v),me().visualViewport?.addEventListener("scroll",k),document.addEventListener("focusin",B),document.addEventListener("focusout",R);const A=P=>{r("resume",{source:P,innerHeight:Math.round(window.innerHeight),visualViewport:me().visualViewport?{width:Math.round(me().visualViewport.width),height:Math.round(me().visualViewport.height),offsetTop:Math.round(me().visualViewport.offsetTop)}:null,hidden:document.hidden}),y(P)},x=()=>{document.hidden?N("visibilitychange:hidden"):A("visibilitychange")},S=()=>A("pageshow"),T=()=>N("pagehide");return document.addEventListener("visibilitychange",x),window.addEventListener("pageshow",S),window.addEventListener("pagehide",T),()=>{window.removeEventListener("resize",w),window.removeEventListener("orientationchange",I),me().visualViewport?.removeEventListener("resize",v),me().visualViewport?.removeEventListener("scroll",k),document.removeEventListener("focusin",B),document.removeEventListener("focusout",R),document.removeEventListener("visibilitychange",x),window.removeEventListener("pageshow",S),window.removeEventListener("pagehide",T),d!==null&&window.cancelAnimationFrame(d),u?.remove()}},[e,r,n]),o}const Lu=5*6e4;let ec,Qp=!1,eg=!1,Bu=!1;const tc=new Set;function _u(){Qp=!0,tc.forEach(t=>t())}function Ck(){return F.useSyncExternalStore(t=>(tc.add(t),()=>{tc.delete(t)}),()=>Qp,()=>!1)}function Rk(){window.dispatchEvent(new Event("termdock:before-update")),eg=!0,ec?.waiting?ec.waiting.postMessage({type:"SKIP_WAITING"}):window.location.reload()}function Tk(t,e){let r=t;return()=>{if(!r){r=!0;return}e()}}function Pk(){if(Bu||typeof window>"u"||!("serviceWorker"in navigator))return;Bu=!0,navigator.serviceWorker.addEventListener("controllerchange",Tk(!!navigator.serviceWorker.controller,()=>{eg?window.location.reload():_u()}));const t=()=>{navigator.serviceWorker.register("/sw.js",{scope:"/",updateViaCache:"none"}).then(e=>{ec=e;const r=()=>{e.waiting&&_u()},n=()=>{const i=e.installing;i?.addEventListener("statechange",()=>{i.state==="installed"&&navigator.serviceWorker.controller&&r()})};e.addEventListener("updatefound",n),n(),r();let o=0;const s=()=>{document.visibilityState!=="visible"||Date.now()-o<Lu||(o=Date.now(),e.update().then(r).catch(()=>{}))};s(),window.setInterval(s,Lu),document.addEventListener("visibilitychange",s)}).catch(()=>{})};document.readyState==="complete"?t():window.addEventListener("load",t,{once:!0})}function Nk(){const t=Ck(),[e,r]=F.useState(!1),{locale:n}=Yc();if(!t||e)return null;const o=n==="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:Rk,children:o?"重新加载":"Reload"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-muted-foreground",onClick:()=>r(!0),children:o?"稍后":"Later"})]})}function tg(t){const e=document.querySelector('meta[name="theme-color"]');e&&e.setAttribute("content",t==="light"?"#FFFCF0":"#1C1B1A")}const Lk={activeKey:"root",items:[]},Bk=()=>()=>{},_k=()=>Lk;function Dk({host:t,item:e,active:r}){const n=F.useRef(null);return F.useEffect(()=>{n.current?.toggleAttribute("inert",!r)},[r]),F.useEffect(()=>()=>t.attach(e.key,null),[t,e.key]),p.jsx("iframe",{ref:n,title:e.service?.label||"服务工作区",src:`/workspace.html?${Jh}=${encodeURIComponent(e.key)}`,className:"fixed inset-0 w-full border-0 bg-[var(--chrome-bg)]",style:{height:"var(--app-base-vh, 100%)",visibility:r?"visible":"hidden",pointerEvents:r?"auto":"none"},"aria-hidden":!r,tabIndex:r?0:-1,allow:"clipboard-read; clipboard-write; fullscreen",onLoad:o=>t.attach(e.key,o.currentTarget.contentWindow)})}function Ok({children:t}){const e=window.parent===window?Et():void 0,r=F.useSyncExternalStore(e?.subscribe||Bk,e?.snapshot||_k),n=F.useRef(null);return F.useEffect(()=>{n.current?.toggleAttribute("inert",r.activeKey!=="root")},[r.activeKey]),F.useEffect(()=>{if(!e)return;const o=()=>{try{const s=JSON.parse(localStorage.getItem("termdock-color-theme")||"null");(s==="dark"||s==="light")&&(document.documentElement.dataset.theme=s,tg(s))}catch{}};return window.addEventListener("storage",o),()=>window.removeEventListener("storage",o)},[e]),F.useEffect(()=>{if(!e||!("serviceWorker"in navigator))return;const o=a=>{if(a.source!==navigator.serviceWorker.controller)return;const c=a.data;c?.type==="termdock:focus-session"&&typeof c.targetPeerId=="string"&&typeof c.sessionId=="string"&&e.focusSession(c.targetPeerId,c.sessionId)&&(a.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),a.stopImmediatePropagation())},s=async()=>{if("caches"in window)try{const a=await caches.open("termdock-notification-target-v1"),c=await a.match("/__termdock-notification-target");if(!c)return;const l=await c.json();typeof l.targetPeerId=="string"&&typeof l.sessionId=="string"&&Date.now()-l.clickedAt<3e4&&e.focusSession(l.targetPeerId,l.sessionId)&&await a.delete("/__termdock-notification-target")}catch{}},i=()=>{document.hidden||s()};return navigator.serviceWorker.addEventListener("message",o),document.addEventListener("visibilitychange",i),s(),()=>{navigator.serviceWorker.removeEventListener("message",o),document.removeEventListener("visibilitychange",i)}},[e]),e?p.jsxs("div",{className:"relative h-full w-full overflow-hidden bg-[var(--chrome-bg)]",children:[p.jsx("div",{ref:n,className:"h-full w-full","aria-hidden":r.activeKey!=="root",style:{visibility:r.activeKey==="root"?"visible":"hidden"},children:t}),r.items.filter(o=>o.key!=="root").map(o=>p.jsx(Dk,{host:e,item:o,active:r.activeKey===o.key},o.key))]}):t}const Fk=F.lazy(()=>Vt(()=>import("./App-CsLpah-H.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,3,7,8]))),Mk=F.lazy(()=>Vt(()=>import("./DagPlayground-DrW4_0hZ.js"),__vite__mapDeps([9,10,2,1,11,8,3])).then(t=>({default:t.DagPlayground}))),jk=F.lazy(()=>Vt(()=>import("./DiffLab-Dj9e4Fc7.js"),__vite__mapDeps([12,2,1,13,7,14,3])).then(t=>({default:t.DiffLab}))),Uk=F.lazy(()=>Vt(()=>import("./DiffReviewLab-D4w5pPtn.js"),__vite__mapDeps([15,2,1,16,5,6,11,13,7,14,3])).then(t=>({default:t.DiffReviewLab})));Ik();Zx();window.parent===window&&Pk();const On=re();On&&Vt(()=>import("./App-CsLpah-H.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,3,7,8])).catch(()=>{});!new URLSearchParams(location.search).has("dag-playground")&&!new URLSearchParams(location.search).has("diff-lab")&&!new URLSearchParams(location.search).has("diff-review-lab")&&($x(On?{...On,id:On.targetPeerId,label:On.serviceName||location.host}:void 0),np());try{const t=JSON.parse(window.localStorage.getItem("termdock-color-theme")||"null");(t==="dark"||t==="light")&&(document.documentElement.dataset.theme=t,tg(t))}catch{}aS.createRoot(document.getElementById("root")).render(p.jsx($e.StrictMode,{children:p.jsxs(uA,{children:[window.parent===window&&p.jsx(Nk,{}),p.jsx(pk,{children:p.jsx(F.Suspense,{fallback:p.jsx("div",{className:"termdock-boot",role:"status",children:"Loading Termdock"}),children:(()=>{const t=new URLSearchParams(window.location.search);return t.get("dag-playground")==="1"?p.jsx(Mk,{}):t.get("diff-review-lab")==="1"?p.jsx(Uk,{}):t.get("diff-lab")==="1"?p.jsx(jk,{}):p.jsx(Ok,{children:p.jsx(dk,{children:p.jsx(Fk,{})})})})()})})]})}));export{t1 as $,Kc as A,yS as B,Oc as C,or as D,vp as E,F2 as F,O2 as G,T1 as H,p1 as I,ME as J,r1 as K,He as L,bp as M,uo as N,dr as O,DA as P,Jk as Q,NA as R,Ks as S,DS as T,$1 as U,Sk as V,Ba as W,FS as X,bk as Y,Pe as Z,Vt as _,ip as a,y1 as a$,pi as a0,W1 as a1,A2 as a2,S1 as a3,z1 as a4,E2 as a5,US as a6,yp as a7,jE as a8,LA as a9,L1 as aA,b1 as aB,P1 as aC,M2 as aD,Np as aE,Et as aF,Nu as aG,sh as aH,kh as aI,x2 as aJ,M1 as aK,H1 as aL,Pp as aM,c2 as aN,d2 as aO,n2 as aP,a2 as aQ,s2 as aR,xi as aS,p as aT,Zk as aU,v1 as aV,q2 as aW,G1 as aX,Y2 as aY,rA as aZ,h2 as a_,w1 as aa,lt as ab,F1 as ac,O1 as ad,U1 as ae,e1 as af,D2 as ag,L2 as ah,N2 as ai,B2 as aj,B1 as ak,l2 as al,T2 as am,$2 as an,y2 as ao,j2 as ap,P2 as aq,I2 as ar,Q1 as as,_2 as at,Is as au,A1 as av,qn as aw,dp as ax,OE as ay,AE as az,mS as b,tg as b$,D1 as b0,J2 as b1,C2 as b2,kE as b3,k1 as b4,X1 as b5,o1 as b6,ut as b7,v2 as b8,w2 as b9,MS as bA,z2 as bB,U2 as bC,K2 as bD,Z2 as bE,re as bF,p2 as bG,oA as bH,Yx as bI,d1 as bJ,nA as bK,u1 as bL,a1 as bM,n1 as bN,l1 as bO,h1 as bP,W2 as bQ,eA as bR,Cp as bS,QE as bT,gi as bU,sI as bV,Q2 as bW,G2 as bX,eI as bY,i1 as bZ,Xk as b_,b2 as ba,S2 as bb,lI as bc,cI as bd,tI as be,s1 as bf,UE as bg,Qk as bh,ja as bi,V2 as bj,Y1 as bk,tA as bl,R1 as bm,C1 as bn,e2 as bo,Z1 as bp,N1 as bq,t2 as br,J1 as bs,f1 as bt,aI as bu,g1 as bv,x1 as bw,V1 as bx,X2 as by,Gk as bz,xS as c,Vk as c0,j1 as c1,K1 as c2,_1 as c3,I1 as c4,$t as c5,k2 as c6,Yc as c7,nI as c8,Ie as c9,dI as ca,me as cb,g2 as cc,qe as cd,oI as ce,rI as cf,fr as d,ap as e,kS as f,pk as g,PS as h,cp as i,wA as j,pe as k,c1 as l,Ac as m,Ct as n,H2 as o,Yk as p,u2 as q,i2 as r,kc as s,m2 as t,Fx as u,q1 as v,l0 as w,FE as x,m1 as y,iI as z};
34
+ `)}async function fk(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 hk({error:t,componentStack:e}){const{t:r}=Yc(),[n,o]=$e.useState("idle"),s=async()=>{const i=uk(t,e,{url:window.location.href,userAgent:navigator.userAgent,capturedAt:new Date().toISOString()});o(await fk(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:r("errorBoundary.title")}),p.jsx("p",{className:"text-sm text-muted-foreground",children:t?.message||r("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:r(n==="copied"?"errorBoundary.copied":n==="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:r("errorBoundary.retry")})]})]})})}class pk extends $e.Component{state={hasError:!1,error:null,componentStack:""};static getDerivedStateFromError(e){return{hasError:!0,error:e,componentStack:""}}componentDidCatch(e,r){console.error("Terminal error caught by boundary:",e,r),this.setState({componentStack:r.componentStack??""})}render(){return this.state.hasError?this.props.fallback?this.props.fallback:p.jsx(hk,{error:this.state.error,componentStack:this.state.componentStack}):this.props.children}}function me(){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 gk="debug",mk="termdock:debug";function Cu(t){return t?new Set(t.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean)):new Set}function wk(){if(typeof window>"u")return new Set;const t=Cu(new URLSearchParams(window.location.search).get(gk));let e=new Set;try{e=Cu(window.localStorage.getItem(mk))}catch{e=new Set}const r=new Set([...t,...e]);return r.has("1")||r.has("true")||r.has("*")||r.has("all")?new Set(["*"]):r}function yk(t){const e=wk();return e.has("*")||e.has(t)}function bk(t){const e=yk(t);return(...r)=>{e&&console.log(`[debug:${t}]`,...r)}}const Ru=80,vk=60,xk="termdock:viewport-keyboard-change",Sk="termdock:viewport-layout-change",xt=240,Tu=640,Pu=360;function Ek({measuredHeight:t,documentVisible:e,editableFocused:r}){return e&&r&&t>0}function Nu(){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 Cs=t=>{const e=typeof t=="number"?t:Number.parseFloat(typeof t=="string"?t:"0");return Number.isFinite(e)&&e>0?Math.round(e):0},Yp=(t,e)=>{const r=t.map(Cs).filter(n=>n>0);return r.find(n=>n>=xt)??r[0]??e},zn=()=>typeof window>"u"?Tu:Yp([me().innerHeight,document.documentElement?.clientHeight,document.body?.clientHeight,me().visualViewport?.height,window.screen?.availHeight,window.screen?.height],Tu),Zp=()=>typeof window>"u"?Pu:Yp([me().innerWidth,document.documentElement?.clientWidth,document.body?.clientWidth,me().visualViewport?.width,window.screen?.availWidth,window.screen?.width],Pu),Mt=t=>{const e=Number.parseFloat(t||"0");return Number.isFinite(e)?Math.max(0,Math.round(e)):0},Ak=()=>typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,kk=()=>typeof window>"u"?!1:me().navigator.standalone===!0||me().matchMedia?.("(display-mode: standalone)").matches===!0,Jp=()=>{if(typeof window>"u"||!Ak()||!kk())return{top:0,right:0,bottom:0,left:0};if(!(zn()>=Zp()))return{top:0,right:0,bottom:0,left:0};const e=window.screen?.width||window.innerWidth,r=window.screen?.height||window.innerHeight,n=Math.min(e,r),o=Math.max(e,r);return n>=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 Ik(t="--app-vh"){if(typeof window>"u"||typeof document>"u")return;const e=Cs(me().visualViewport?.height),r=Math.max(0,Math.round(me().visualViewport?.offsetTop??0)),n=zn(),s=e>=xt?Math.min(n,e+r):n,i=Math.max(n,s),a=document.documentElement.style;a.setProperty(t,`${Math.max(s,xt)}px`),a.setProperty("--app-base-vh",`${Math.max(i,xt)}px`),a.setProperty("--app-visible-vh",`${Math.max(s,xt)}px`),a.setProperty("--app-vv-offset-top",`${r}px`),a.setProperty("--kb-translate-y","0px"),a.setProperty("--kb-margin-top","0px"),a.setProperty("--kb-height","0px");const c=Jp();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 dI(t={}){const{cssVarName:e="--app-vh"}=t,r=$e.useMemo(()=>bk("viewport"),[]),n=$e.useCallback(()=>{if(typeof window>"u")return 0;const d=me().visualViewport,u=zn();if(!d)return u;const f=Cs(d.height);if(f<xt&&u>=xt)return u;const h=d.offsetTop,m=f<u-1&&h>0&&h<=96?f+h:f,y=Math.max(0,Math.min(u,m));return y>0?Math.round(y):u},[]),[o,s]=$e.useState(n),i=$e.useRef(0),a=$e.useRef(0),c=$e.useRef(0),l=$e.useRef(!1);return $e.useEffect(()=>{if(typeof window>"u")return;let d=null,u=null;const f=()=>{if(u?.isConnected)return u;try{return u=document.createElement("div"),u.setAttribute("aria-hidden","true"),u.style.cssText=["position:fixed","top:0","left:0","width:0","height:0","visibility:hidden","pointer-events:none","padding-top:constant(safe-area-inset-top)","padding-top:env(safe-area-inset-top,0px)","padding-right:constant(safe-area-inset-right)","padding-right:env(safe-area-inset-right,0px)","padding-bottom:constant(safe-area-inset-bottom)","padding-bottom:env(safe-area-inset-bottom,0px)","padding-left:constant(safe-area-inset-left)","padding-left:env(safe-area-inset-left,0px)"].join(";"),(document.body||document.documentElement).appendChild(u),u}catch{}return null},h=()=>{let P={top:0,right:0,bottom:0,left:0};try{const L=f();if(L){const M=getComputedStyle(L);P={top:Mt(M.paddingTop),right:Mt(M.paddingRight),bottom:Mt(M.paddingBottom),left:Mt(M.paddingLeft)}}}catch{}const b=me();if(b!==window){const L=b.getComputedStyle(b.document.documentElement);P={top:Math.max(P.top,Mt(L.getPropertyValue("--safe-top-inset"))),right:Math.max(P.right,Mt(L.getPropertyValue("--safe-right-inset"))),bottom:Math.max(P.bottom,Mt(L.getPropertyValue("--safe-bottom-inset"))),left:Math.max(P.left,Mt(L.getPropertyValue("--safe-left-inset")))}}const E=Jp(),C={top:Math.max(P.top,E.top),right:Math.max(P.right,E.right),bottom:Math.max(P.bottom,E.bottom),left:Math.max(P.left,E.left)};return document.documentElement.style.setProperty("--safe-top-inset",`${C.top}px`),document.documentElement.style.setProperty("--safe-right-inset",`${C.right}px`),document.documentElement.style.setProperty("--safe-bottom-inset",`${C.bottom}px`),document.documentElement.style.setProperty("--safe-left-inset",`${C.left}px`),C},g=(P,b,E,C)=>{const L=Math.max(b,E);if(i.current===0){i.current=L,a.current=P,document.documentElement.style.setProperty("--app-base-vh",`${L}px`);return}const M=Math.abs(P-a.current),$=C<=Ru;(M>vk||$)&&(i.current=L,a.current=P,document.documentElement.style.setProperty("--app-base-vh",`${L}px`))},m=(P="event")=>{d=null;const b=n(),E=Math.round(me().visualViewport?.offsetTop??0),C=Cs(me().visualViewport?.height),L=C>=xt?C:b,M=zn(),$=Zp(),j=Math.max(0,L+E),D=h(),_=D.bottom,O=Math.max(0,i.current-j-_);g($,M,j,O),s(Tt=>Tt===b?Tt:b);const q=Number.parseInt(document.documentElement.style.getPropertyValue(e)||"0",10);document.documentElement.style.setProperty(e,`${b}px`),document.documentElement.style.setProperty("--app-vv-offset-top",`${E}px`);const H=i.current,K=Math.min(b,L),z=Math.max(0,Math.min(H,j)),V=Math.max(0,Math.round(H-z-_)),X=Nu(),G=Ek({measuredHeight:V,documentVisible:document.visibilityState==="visible",editableFocused:X}),Y=G?V:0,se=Y>=Ru,Ne=-Y,Me=Y;document.documentElement.style.setProperty("--kb-translate-y",`${Ne}px`),document.documentElement.style.setProperty("--kb-margin-top",`${Me}px`),document.documentElement.style.setProperty("--kb-height",`${Y}px`),document.documentElement.style.setProperty("--app-visible-vh",`${z}px`);const oe=Math.abs(Y-c.current)>1,ot=se!==l.current;(oe||ot)&&(c.current=Y,l.current=se,document.dispatchEvent(new CustomEvent(xk,{detail:{baseHeight:H,visibleHeight:z,visualViewportHeight:L,offsetTop:E,keyboardHeight:Y,isOpen:se,source:P}}))),(q!==b||E>0||oe||ot)&&r("sync",{cssVarName:e,innerHeight:M,baseHeight:H,rawViewportHeight:L,offsetTop:E,visibleHeight:z,rawHeight:b,appliedHeight:b,keyboardViewportHeight:K,measuredKeyboardHeight:V,editableFocused:X,applyKeyboardInset:G,keyboardHeight:Y,isKeyboardOpen:se,safeAreaInsets:D,source:P}),document.dispatchEvent(new CustomEvent(Sk,{detail:{height:b,baseHeight:H,visibleHeight:z,offsetTop:E,source:P}}))},y=(P="event")=>{(P.includes("visibilitychange")||P.includes("pageshow"))&&r("schedule",{source:P}),d===null&&(d=window.requestAnimationFrame(()=>m(P)))};y("mount");const w=()=>y("resize"),I=()=>y("orientationchange"),v=()=>y("visualViewport.resize"),k=()=>y("visualViewport.scroll"),B=()=>y("focusin"),R=()=>y("focusout"),N=P=>{const b=document.activeElement;b instanceof HTMLElement&&Nu()&&b.blur(),c.current=0,l.current=!1;const E=Math.max(i.current,zn(),xt),C=document.documentElement.style;C.setProperty(e,`${E}px`),C.setProperty("--app-visible-vh",`${E}px`),C.setProperty("--app-vv-offset-top","0px"),C.setProperty("--kb-translate-y","0px"),C.setProperty("--kb-margin-top","0px"),C.setProperty("--kb-height","0px"),s(L=>L===E?L:E),r("keyboard session reset",{source:P,baseHeight:E})};window.addEventListener("resize",w),window.addEventListener("orientationchange",I),me().visualViewport?.addEventListener("resize",v),me().visualViewport?.addEventListener("scroll",k),document.addEventListener("focusin",B),document.addEventListener("focusout",R);const A=P=>{r("resume",{source:P,innerHeight:Math.round(window.innerHeight),visualViewport:me().visualViewport?{width:Math.round(me().visualViewport.width),height:Math.round(me().visualViewport.height),offsetTop:Math.round(me().visualViewport.offsetTop)}:null,hidden:document.hidden}),y(P)},x=()=>{document.hidden?N("visibilitychange:hidden"):A("visibilitychange")},S=()=>A("pageshow"),T=()=>N("pagehide");return document.addEventListener("visibilitychange",x),window.addEventListener("pageshow",S),window.addEventListener("pagehide",T),()=>{window.removeEventListener("resize",w),window.removeEventListener("orientationchange",I),me().visualViewport?.removeEventListener("resize",v),me().visualViewport?.removeEventListener("scroll",k),document.removeEventListener("focusin",B),document.removeEventListener("focusout",R),document.removeEventListener("visibilitychange",x),window.removeEventListener("pageshow",S),window.removeEventListener("pagehide",T),d!==null&&window.cancelAnimationFrame(d),u?.remove()}},[e,r,n]),o}const Lu=5*6e4;let ec,Qp=!1,eg=!1,Bu=!1;const tc=new Set;function _u(){Qp=!0,tc.forEach(t=>t())}function Ck(){return F.useSyncExternalStore(t=>(tc.add(t),()=>{tc.delete(t)}),()=>Qp,()=>!1)}function Rk(){window.dispatchEvent(new Event("termdock:before-update")),eg=!0,ec?.waiting?ec.waiting.postMessage({type:"SKIP_WAITING"}):window.location.reload()}function Tk(t,e){let r=t;return()=>{if(!r){r=!0;return}e()}}function Pk(){if(Bu||typeof window>"u"||!("serviceWorker"in navigator))return;Bu=!0,navigator.serviceWorker.addEventListener("controllerchange",Tk(!!navigator.serviceWorker.controller,()=>{eg?window.location.reload():_u()}));const t=()=>{navigator.serviceWorker.register("/sw.js",{scope:"/",updateViaCache:"none"}).then(e=>{ec=e;const r=()=>{e.waiting&&_u()},n=()=>{const i=e.installing;i?.addEventListener("statechange",()=>{i.state==="installed"&&navigator.serviceWorker.controller&&r()})};e.addEventListener("updatefound",n),n(),r();let o=0;const s=()=>{document.visibilityState!=="visible"||Date.now()-o<Lu||(o=Date.now(),e.update().then(r).catch(()=>{}))};s(),window.setInterval(s,Lu),document.addEventListener("visibilitychange",s)}).catch(()=>{})};document.readyState==="complete"?t():window.addEventListener("load",t,{once:!0})}function Nk(){const t=Ck(),[e,r]=F.useState(!1),{locale:n}=Yc();if(!t||e)return null;const o=n==="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:Rk,children:o?"重新加载":"Reload"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-muted-foreground",onClick:()=>r(!0),children:o?"稍后":"Later"})]})}function tg(t){const e=document.querySelector('meta[name="theme-color"]');e&&e.setAttribute("content",t==="light"?"#FFFCF0":"#1C1B1A")}const Lk={activeKey:"root",items:[]},Bk=()=>()=>{},_k=()=>Lk;function Dk({host:t,item:e,active:r}){const n=F.useRef(null);return F.useEffect(()=>{n.current?.toggleAttribute("inert",!r)},[r]),F.useEffect(()=>()=>t.attach(e.key,null),[t,e.key]),p.jsx("iframe",{ref:n,title:e.service?.label||"服务工作区",src:`/workspace.html?${Jh}=${encodeURIComponent(e.key)}`,className:"fixed inset-0 w-full border-0 bg-[var(--chrome-bg)]",style:{height:"var(--app-base-vh, 100%)",visibility:r?"visible":"hidden",pointerEvents:r?"auto":"none"},"aria-hidden":!r,tabIndex:r?0:-1,allow:"clipboard-read; clipboard-write; fullscreen",onLoad:o=>t.attach(e.key,o.currentTarget.contentWindow)})}function Ok({children:t}){const e=window.parent===window?Et():void 0,r=F.useSyncExternalStore(e?.subscribe||Bk,e?.snapshot||_k),n=F.useRef(null);return F.useEffect(()=>{n.current?.toggleAttribute("inert",r.activeKey!=="root")},[r.activeKey]),F.useEffect(()=>{if(!e)return;const o=()=>{try{const s=JSON.parse(localStorage.getItem("termdock-color-theme")||"null");(s==="dark"||s==="light")&&(document.documentElement.dataset.theme=s,tg(s))}catch{}};return window.addEventListener("storage",o),()=>window.removeEventListener("storage",o)},[e]),F.useEffect(()=>{if(!e||!("serviceWorker"in navigator))return;const o=a=>{if(a.source!==navigator.serviceWorker.controller)return;const c=a.data;c?.type==="termdock:focus-session"&&typeof c.targetPeerId=="string"&&typeof c.sessionId=="string"&&e.focusSession(c.targetPeerId,c.sessionId)&&(a.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),a.stopImmediatePropagation())},s=async()=>{if("caches"in window)try{const a=await caches.open("termdock-notification-target-v1"),c=await a.match("/__termdock-notification-target");if(!c)return;const l=await c.json();typeof l.targetPeerId=="string"&&typeof l.sessionId=="string"&&Date.now()-l.clickedAt<3e4&&e.focusSession(l.targetPeerId,l.sessionId)&&await a.delete("/__termdock-notification-target")}catch{}},i=()=>{document.hidden||s()};return navigator.serviceWorker.addEventListener("message",o),document.addEventListener("visibilitychange",i),s(),()=>{navigator.serviceWorker.removeEventListener("message",o),document.removeEventListener("visibilitychange",i)}},[e]),e?p.jsxs("div",{className:"relative h-full w-full overflow-hidden bg-[var(--chrome-bg)]",children:[p.jsx("div",{ref:n,className:"h-full w-full","aria-hidden":r.activeKey!=="root",style:{visibility:r.activeKey==="root"?"visible":"hidden"},children:t}),r.items.filter(o=>o.key!=="root").map(o=>p.jsx(Dk,{host:e,item:o,active:r.activeKey===o.key},o.key))]}):t}const Fk=F.lazy(()=>Vt(()=>import("./App-ecJnsxAe.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,3,7,8]))),Mk=F.lazy(()=>Vt(()=>import("./DagPlayground-CVDZjmaY.js"),__vite__mapDeps([9,10,2,1,11,8,3])).then(t=>({default:t.DagPlayground}))),jk=F.lazy(()=>Vt(()=>import("./DiffLab-DhGouK9C.js"),__vite__mapDeps([12,2,1,13,7,14,3])).then(t=>({default:t.DiffLab}))),Uk=F.lazy(()=>Vt(()=>import("./DiffReviewLab-DOV2Vv34.js"),__vite__mapDeps([15,2,1,16,5,6,11,13,7,14,3])).then(t=>({default:t.DiffReviewLab})));Ik();Zx();window.parent===window&&Pk();const On=re();On&&Vt(()=>import("./App-ecJnsxAe.js").then(t=>t.A),__vite__mapDeps([4,2,1,5,6,3,7,8])).catch(()=>{});!new URLSearchParams(location.search).has("dag-playground")&&!new URLSearchParams(location.search).has("diff-lab")&&!new URLSearchParams(location.search).has("diff-review-lab")&&($x(On?{...On,id:On.targetPeerId,label:On.serviceName||location.host}:void 0),np());try{const t=JSON.parse(window.localStorage.getItem("termdock-color-theme")||"null");(t==="dark"||t==="light")&&(document.documentElement.dataset.theme=t,tg(t))}catch{}aS.createRoot(document.getElementById("root")).render(p.jsx($e.StrictMode,{children:p.jsxs(uA,{children:[window.parent===window&&p.jsx(Nk,{}),p.jsx(pk,{children:p.jsx(F.Suspense,{fallback:p.jsx("div",{className:"termdock-boot",role:"status",children:"Loading Termdock"}),children:(()=>{const t=new URLSearchParams(window.location.search);return t.get("dag-playground")==="1"?p.jsx(Mk,{}):t.get("diff-review-lab")==="1"?p.jsx(Uk,{}):t.get("diff-lab")==="1"?p.jsx(jk,{}):p.jsx(Ok,{children:p.jsx(dk,{children:p.jsx(Fk,{})})})})()})})]})}));export{t1 as $,Kc as A,yS as B,Oc as C,or as D,vp as E,F2 as F,O2 as G,T1 as H,p1 as I,ME as J,r1 as K,He as L,bp as M,uo as N,dr as O,DA as P,Jk as Q,NA as R,Ks as S,DS as T,$1 as U,Sk as V,Ba as W,FS as X,bk as Y,Pe as Z,Vt as _,ip as a,y1 as a$,pi as a0,W1 as a1,A2 as a2,S1 as a3,z1 as a4,E2 as a5,US as a6,yp as a7,jE as a8,LA as a9,L1 as aA,b1 as aB,P1 as aC,M2 as aD,Np as aE,Et as aF,Nu as aG,sh as aH,kh as aI,x2 as aJ,M1 as aK,H1 as aL,Pp as aM,c2 as aN,d2 as aO,n2 as aP,a2 as aQ,s2 as aR,xi as aS,p as aT,Zk as aU,v1 as aV,q2 as aW,G1 as aX,Y2 as aY,rA as aZ,h2 as a_,w1 as aa,lt as ab,F1 as ac,O1 as ad,U1 as ae,e1 as af,D2 as ag,L2 as ah,N2 as ai,B2 as aj,B1 as ak,l2 as al,T2 as am,$2 as an,y2 as ao,j2 as ap,P2 as aq,I2 as ar,Q1 as as,_2 as at,Is as au,A1 as av,qn as aw,dp as ax,OE as ay,AE as az,mS as b,tg as b$,D1 as b0,J2 as b1,C2 as b2,kE as b3,k1 as b4,X1 as b5,o1 as b6,ut as b7,v2 as b8,w2 as b9,MS as bA,z2 as bB,U2 as bC,K2 as bD,Z2 as bE,re as bF,p2 as bG,oA as bH,Yx as bI,d1 as bJ,nA as bK,u1 as bL,a1 as bM,n1 as bN,l1 as bO,h1 as bP,W2 as bQ,eA as bR,Cp as bS,QE as bT,gi as bU,sI as bV,Q2 as bW,G2 as bX,eI as bY,i1 as bZ,Xk as b_,b2 as ba,S2 as bb,lI as bc,cI as bd,tI as be,s1 as bf,UE as bg,Qk as bh,ja as bi,V2 as bj,Y1 as bk,tA as bl,R1 as bm,C1 as bn,e2 as bo,Z1 as bp,N1 as bq,t2 as br,J1 as bs,f1 as bt,aI as bu,g1 as bv,x1 as bw,V1 as bx,X2 as by,Gk as bz,xS as c,Vk as c0,j1 as c1,K1 as c2,_1 as c3,I1 as c4,$t as c5,k2 as c6,Yc as c7,nI as c8,Ie as c9,dI as ca,me as cb,g2 as cc,qe as cd,oI as ce,rI as cf,fr as d,ap as e,kS as f,pk as g,PS as h,cp as i,wA as j,pe as k,c1 as l,Ac as m,Ct as n,H2 as o,Yk as p,u2 as q,i2 as r,kc as s,m2 as t,Fx as u,q1 as v,l0 as w,FE as x,m1 as y,iI as z};