termdock 1.4.336 → 1.4.337
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.
- package/dist/client/assets/App-DhHRFEY2.js +187 -0
- package/dist/client/assets/App-DhHRFEY2.js.br +0 -0
- package/dist/client/assets/App-DhHRFEY2.js.gz +0 -0
- package/dist/client/assets/{ArchitecturePanel-BOq2FG6t.js → ArchitecturePanel-DeMEq2Yq.js} +2 -2
- package/dist/client/assets/ArchitecturePanel-DeMEq2Yq.js.br +0 -0
- package/dist/client/assets/ArchitecturePanel-DeMEq2Yq.js.gz +0 -0
- package/dist/client/assets/{ChangeWalkthroughPanel-CxqwQxYc.js → ChangeWalkthroughPanel-DG4TnQvn.js} +1 -1
- package/dist/client/assets/ChangeWalkthroughPanel-DG4TnQvn.js.br +0 -0
- package/dist/client/assets/ChangeWalkthroughPanel-DG4TnQvn.js.gz +0 -0
- package/dist/client/assets/{CollaborationMainWorkspace-vvAVjIlQ.js → CollaborationMainWorkspace-D_yEJJy_.js} +1 -1
- package/dist/client/assets/CollaborationMainWorkspace-D_yEJJy_.js.br +0 -0
- package/dist/client/assets/CollaborationMainWorkspace-D_yEJJy_.js.gz +0 -0
- package/dist/client/assets/CollaborationTaskContent-BtFTzMVY.js +2 -0
- package/dist/client/assets/{ComputerControlView-mR6vlp9k.js → ComputerControlView-DGoBNNRA.js} +3 -3
- package/dist/client/assets/ComputerControlView-DGoBNNRA.js.br +0 -0
- package/dist/client/assets/ComputerControlView-DGoBNNRA.js.gz +0 -0
- package/dist/client/assets/{DagPlayground-nUK9xIql.js → DagPlayground-CiCwopwo.js} +1 -1
- package/dist/client/assets/DagPlayground-CiCwopwo.js.br +0 -0
- package/dist/client/assets/DagPlayground-CiCwopwo.js.gz +0 -0
- package/dist/client/assets/{DiffLab-D6XhZtPW.js → DiffLab-C8ItelM8.js} +1 -1
- package/dist/client/assets/DiffLab-C8ItelM8.js.br +0 -0
- package/dist/client/assets/DiffLab-C8ItelM8.js.gz +0 -0
- package/dist/client/assets/{DiffReview-BhyYqkD4.js → DiffReview-riYMjjAA.js} +1 -1
- package/dist/client/assets/DiffReview-riYMjjAA.js.br +0 -0
- package/dist/client/assets/DiffReview-riYMjjAA.js.gz +0 -0
- package/dist/client/assets/{DiffReviewLab-CvNWVrbl.js → DiffReviewLab-CXlrQWLJ.js} +1 -1
- package/dist/client/assets/DiffReviewLab-CXlrQWLJ.js.br +0 -0
- package/dist/client/assets/DiffReviewLab-CXlrQWLJ.js.gz +0 -0
- package/dist/client/assets/{DiffViewer-BSbMa2mq.js → DiffViewer-BxcK2w41.js} +1 -1
- package/dist/client/assets/DiffViewer-BxcK2w41.js.br +0 -0
- package/dist/client/assets/DiffViewer-BxcK2w41.js.gz +0 -0
- package/dist/client/assets/{ModelPreview-B_VPlNYr.js → ModelPreview-HzxWwmh4.js} +1 -1
- package/dist/client/assets/ModelPreview-HzxWwmh4.js.br +0 -0
- package/dist/client/assets/ModelPreview-HzxWwmh4.js.gz +0 -0
- package/dist/client/assets/{RightSidebar-Cakd9qUZ.js → RightSidebar-ChmJQUxz.js} +10 -10
- package/dist/client/assets/RightSidebar-ChmJQUxz.js.br +0 -0
- package/dist/client/assets/RightSidebar-ChmJQUxz.js.gz +0 -0
- package/dist/client/assets/{abnfDiagram-VCTEODGH-vWK7F-r_.js → abnfDiagram-VCTEODGH-BUDaRwTy.js} +1 -1
- package/dist/client/assets/abnfDiagram-VCTEODGH-BUDaRwTy.js.br +0 -0
- package/dist/client/assets/abnfDiagram-VCTEODGH-BUDaRwTy.js.gz +0 -0
- package/dist/client/assets/{app-BZBIr89q.js → app-D2M53LZx.js} +3 -3
- package/dist/client/assets/app-D2M53LZx.js.br +0 -0
- package/dist/client/assets/app-D2M53LZx.js.gz +0 -0
- package/dist/client/assets/{arc-Bdjvby9b.js → arc-DO-aRhWz.js} +1 -1
- package/dist/client/assets/arc-DO-aRhWz.js.br +0 -0
- package/dist/client/assets/arc-DO-aRhWz.js.gz +0 -0
- package/dist/client/assets/{architectureDiagram-5GKGNRK7-DTR5hJkG.js → architectureDiagram-5GKGNRK7-CMImzZR-.js} +1 -1
- package/dist/client/assets/architectureDiagram-5GKGNRK7-CMImzZR-.js.br +0 -0
- package/dist/client/assets/architectureDiagram-5GKGNRK7-CMImzZR-.js.gz +0 -0
- package/dist/client/assets/{blockDiagram-I7D4REHJ-DPz3axsu.js → blockDiagram-I7D4REHJ-DPC_EssA.js} +1 -1
- package/dist/client/assets/blockDiagram-I7D4REHJ-DPC_EssA.js.br +0 -0
- package/dist/client/assets/blockDiagram-I7D4REHJ-DPC_EssA.js.gz +0 -0
- package/dist/client/assets/{c4Diagram-7LVT6UL2-d5ZwPpcN.js → c4Diagram-7LVT6UL2-DJazaM0T.js} +1 -1
- package/dist/client/assets/c4Diagram-7LVT6UL2-DJazaM0T.js.br +0 -0
- package/dist/client/assets/c4Diagram-7LVT6UL2-DJazaM0T.js.gz +0 -0
- package/dist/client/assets/channel-BKGmfJ01.js +1 -0
- package/dist/client/assets/{chunk-2Q5K7J3B-BpEmNpto.js → chunk-2Q5K7J3B-BxDoppAq.js} +1 -1
- package/dist/client/assets/{chunk-5VM5RSS4-CXDCiEbN.js → chunk-5VM5RSS4-DFunSKh5.js} +1 -1
- package/dist/client/assets/{chunk-F27PBJKO-C1L__gXc.js → chunk-F27PBJKO-bLBUcK9l.js} +1 -1
- package/dist/client/assets/chunk-F27PBJKO-bLBUcK9l.js.br +0 -0
- package/dist/client/assets/chunk-F27PBJKO-bLBUcK9l.js.gz +0 -0
- package/dist/client/assets/{chunk-IMKFNOWR-CX0r7pV5.js → chunk-IMKFNOWR-CQzRDG_F.js} +1 -1
- package/dist/client/assets/chunk-IMKFNOWR-CQzRDG_F.js.br +0 -0
- package/dist/client/assets/chunk-IMKFNOWR-CQzRDG_F.js.gz +0 -0
- package/dist/client/assets/{chunk-JWPE2WC7-DkbhnrKh.js → chunk-JWPE2WC7-oYEx3lo8.js} +1 -1
- package/dist/client/assets/{chunk-POPQ4Y6H-CH-o5PVe.js → chunk-POPQ4Y6H-DiElQN3B.js} +1 -1
- package/dist/client/assets/{chunk-SVP7TREG-C1x5c5cy.js → chunk-SVP7TREG-Cf1eK48Z.js} +1 -1
- package/dist/client/assets/chunk-SVP7TREG-Cf1eK48Z.js.br +0 -0
- package/dist/client/assets/chunk-SVP7TREG-Cf1eK48Z.js.gz +0 -0
- package/dist/client/assets/{chunk-TICWLB2K-DAktkamN.js → chunk-TICWLB2K-CAsKSnF3.js} +1 -1
- package/dist/client/assets/chunk-TICWLB2K-CAsKSnF3.js.br +0 -0
- package/dist/client/assets/chunk-TICWLB2K-CAsKSnF3.js.gz +0 -0
- package/dist/client/assets/{chunk-XXDRQBXY-emNetBN1.js → chunk-XXDRQBXY-CnELf36-.js} +1 -1
- package/dist/client/assets/classDiagram-ZZMXUADV-M1OSgOBU.js +1 -0
- package/dist/client/assets/classDiagram-v2-VYDZK3BY-M1OSgOBU.js +1 -0
- package/dist/client/assets/{cose-bilkent-JH36ORCC-kBGroiho.js → cose-bilkent-JH36ORCC-BjkkSzWB.js} +1 -1
- package/dist/client/assets/cose-bilkent-JH36ORCC-BjkkSzWB.js.br +0 -0
- package/dist/client/assets/cose-bilkent-JH36ORCC-BjkkSzWB.js.gz +0 -0
- package/dist/client/assets/{cynefin-OW5HDTMX-C0TjwB46.js → cynefin-OW5HDTMX-DL9YtN7p.js} +1 -1
- package/dist/client/assets/cynefin-OW5HDTMX-DL9YtN7p.js.br +0 -0
- package/dist/client/assets/cynefin-OW5HDTMX-DL9YtN7p.js.gz +0 -0
- package/dist/client/assets/{cynefinDiagram-5FMLGOSQ-CbLSUTuV.js → cynefinDiagram-5FMLGOSQ-vSIBJhoT.js} +1 -1
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-vSIBJhoT.js.br +0 -0
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-vSIBJhoT.js.gz +0 -0
- package/dist/client/assets/{dagre-GXQ25YYZ-BoznXKfa.js → dagre-GXQ25YYZ-CJ8Milln.js} +1 -1
- package/dist/client/assets/dagre-GXQ25YYZ-CJ8Milln.js.br +0 -0
- package/dist/client/assets/dagre-GXQ25YYZ-CJ8Milln.js.gz +0 -0
- package/dist/client/assets/{diagram-S7CK7UJ4-iY9ia7F5.js → diagram-S7CK7UJ4-Ci6Vle0S.js} +1 -1
- package/dist/client/assets/diagram-S7CK7UJ4-Ci6Vle0S.js.br +0 -0
- package/dist/client/assets/diagram-S7CK7UJ4-Ci6Vle0S.js.gz +0 -0
- package/dist/client/assets/{diagram-UQ7AKVKN-DhnC8gBw.js → diagram-UQ7AKVKN-Cf1bxglx.js} +1 -1
- package/dist/client/assets/diagram-UQ7AKVKN-Cf1bxglx.js.br +0 -0
- package/dist/client/assets/diagram-UQ7AKVKN-Cf1bxglx.js.gz +0 -0
- package/dist/client/assets/{diagram-VSXAHHWV-JFg8cbqX.js → diagram-VSXAHHWV-MPVKDZTF.js} +1 -1
- package/dist/client/assets/diagram-VSXAHHWV-MPVKDZTF.js.br +0 -0
- package/dist/client/assets/diagram-VSXAHHWV-MPVKDZTF.js.gz +0 -0
- package/dist/client/assets/{diagram-VX7I27RA-dvyXUTpo.js → diagram-VX7I27RA-C9VznNFM.js} +1 -1
- package/dist/client/assets/diagram-VX7I27RA-C9VznNFM.js.br +0 -0
- package/dist/client/assets/diagram-VX7I27RA-C9VznNFM.js.gz +0 -0
- package/dist/client/assets/{diagram-Z3DM3KII-DmjwsCUU.js → diagram-Z3DM3KII-D3Z39FXB.js} +1 -1
- package/dist/client/assets/diagram-Z3DM3KII-D3Z39FXB.js.br +0 -0
- package/dist/client/assets/diagram-Z3DM3KII-D3Z39FXB.js.gz +0 -0
- package/dist/client/assets/{ebnfDiagram-PWID7BFC-BxCdDL0c.js → ebnfDiagram-PWID7BFC-CB6iYj5F.js} +1 -1
- package/dist/client/assets/ebnfDiagram-PWID7BFC-CB6iYj5F.js.br +0 -0
- package/dist/client/assets/ebnfDiagram-PWID7BFC-CB6iYj5F.js.gz +0 -0
- package/dist/client/assets/{erDiagram-RLTQ6QDP-BWvvnoz1.js → erDiagram-RLTQ6QDP-BbywGzIs.js} +1 -1
- package/dist/client/assets/erDiagram-RLTQ6QDP-BbywGzIs.js.br +0 -0
- package/dist/client/assets/erDiagram-RLTQ6QDP-BbywGzIs.js.gz +0 -0
- package/dist/client/assets/{flowDiagram-HODETNUW-CVU0l_6c.js → flowDiagram-HODETNUW-BIhsRkKW.js} +1 -1
- package/dist/client/assets/flowDiagram-HODETNUW-BIhsRkKW.js.br +0 -0
- package/dist/client/assets/flowDiagram-HODETNUW-BIhsRkKW.js.gz +0 -0
- package/dist/client/assets/{ganttDiagram-EL5Y4UJY-CjO521RP.js → ganttDiagram-EL5Y4UJY-0ov1Ht5f.js} +1 -1
- package/dist/client/assets/ganttDiagram-EL5Y4UJY-0ov1Ht5f.js.br +0 -0
- package/dist/client/assets/{ganttDiagram-EL5Y4UJY-CjO521RP.js.gz → ganttDiagram-EL5Y4UJY-0ov1Ht5f.js.gz} +0 -0
- package/dist/client/assets/{gestureArbiter-D_fs_PXp.js → gestureArbiter-DPFs4a-w.js} +1 -1
- package/dist/client/assets/gestureArbiter-DPFs4a-w.js.br +0 -0
- package/dist/client/assets/{gestureArbiter-D_fs_PXp.js.gz → gestureArbiter-DPFs4a-w.js.gz} +0 -0
- package/dist/client/assets/{gitGraphDiagram-WWUBYQGX-DbxNhHiO.js → gitGraphDiagram-WWUBYQGX-DPmWc8PK.js} +1 -1
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-DPmWc8PK.js.br +0 -0
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-DPmWc8PK.js.gz +0 -0
- package/dist/client/assets/{infoDiagram-27XIBGKW-DRcGAFqT.js → infoDiagram-27XIBGKW-CiGxOtMe.js} +1 -1
- package/dist/client/assets/{ishikawaDiagram-5VMMS53U-BPbgDJUg.js → ishikawaDiagram-5VMMS53U-CVQw2h65.js} +1 -1
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-CVQw2h65.js.br +0 -0
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-CVQw2h65.js.gz +0 -0
- package/dist/client/assets/{journeyDiagram-3NMN7TZE-D1nSzyjD.js → journeyDiagram-3NMN7TZE-CWyQl9rp.js} +1 -1
- package/dist/client/assets/journeyDiagram-3NMN7TZE-CWyQl9rp.js.br +0 -0
- package/dist/client/assets/journeyDiagram-3NMN7TZE-CWyQl9rp.js.gz +0 -0
- package/dist/client/assets/{kanban-definition-UXKFOSKX-CSCXZnir.js → kanban-definition-UXKFOSKX-QYWm-bRz.js} +1 -1
- package/dist/client/assets/kanban-definition-UXKFOSKX-QYWm-bRz.js.br +0 -0
- package/dist/client/assets/kanban-definition-UXKFOSKX-QYWm-bRz.js.gz +0 -0
- package/dist/client/assets/{layout-DTNe7C08.js → layout-wWwHCqP-.js} +1 -1
- package/dist/client/assets/layout-wWwHCqP-.js.br +0 -0
- package/dist/client/assets/layout-wWwHCqP-.js.gz +0 -0
- package/dist/client/assets/{linear-DELStaU_.js → linear-CxAeiA5o.js} +1 -1
- package/dist/client/assets/linear-CxAeiA5o.js.br +0 -0
- package/dist/client/assets/linear-CxAeiA5o.js.gz +0 -0
- package/dist/client/assets/{mermaid.core-D7uvx0E2.js → mermaid.core-Dy-VIGNi.js} +5 -5
- package/dist/client/assets/mermaid.core-Dy-VIGNi.js.br +0 -0
- package/dist/client/assets/mermaid.core-Dy-VIGNi.js.gz +0 -0
- package/dist/client/assets/{mindmap-definition-YA3MSWOX-C_fF6Gnh.js → mindmap-definition-YA3MSWOX-CaOlKAQP.js} +1 -1
- package/dist/client/assets/mindmap-definition-YA3MSWOX-CaOlKAQP.js.br +0 -0
- package/dist/client/assets/mindmap-definition-YA3MSWOX-CaOlKAQP.js.gz +0 -0
- package/dist/client/assets/{passwordBootstrap-Co17Xh3M.js → passwordBootstrap-DADiddYD.js} +1 -1
- package/dist/client/assets/passwordBootstrap-DADiddYD.js.br +0 -0
- package/dist/client/assets/passwordBootstrap-DADiddYD.js.gz +0 -0
- package/dist/client/assets/{pegDiagram-XKGWAZYB-BFOfbHg1.js → pegDiagram-XKGWAZYB-DbMiTSC0.js} +1 -1
- package/dist/client/assets/pegDiagram-XKGWAZYB-DbMiTSC0.js.br +0 -0
- package/dist/client/assets/pegDiagram-XKGWAZYB-DbMiTSC0.js.gz +0 -0
- package/dist/client/assets/{pieDiagram-E7YTZNPT-BkLXgY2Y.js → pieDiagram-E7YTZNPT-DHsbRsqO.js} +1 -1
- package/dist/client/assets/pieDiagram-E7YTZNPT-DHsbRsqO.js.br +0 -0
- package/dist/client/assets/pieDiagram-E7YTZNPT-DHsbRsqO.js.gz +0 -0
- package/dist/client/assets/{quadrantDiagram-AXDQQJYC-DIF7ynjD.js → quadrantDiagram-AXDQQJYC-ivXNY01m.js} +1 -1
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-ivXNY01m.js.br +0 -0
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-ivXNY01m.js.gz +0 -0
- package/dist/client/assets/{railroadDiagram-O6MQD6OU-DGeuv8o1.js → railroadDiagram-O6MQD6OU-B6XiBJ2p.js} +1 -1
- package/dist/client/assets/railroadDiagram-O6MQD6OU-B6XiBJ2p.js.br +0 -0
- package/dist/client/assets/railroadDiagram-O6MQD6OU-B6XiBJ2p.js.gz +0 -0
- package/dist/client/assets/{rdpSession-DZCrSxpu.js → rdpSession-tZqbe3lc.js} +1 -1
- package/dist/client/assets/rdpSession-tZqbe3lc.js.br +0 -0
- package/dist/client/assets/rdpSession-tZqbe3lc.js.gz +0 -0
- package/dist/client/assets/{referenceLongPress-DrY73BHe.js → referenceLongPress-l-iC26Y4.js} +1 -1
- package/dist/client/assets/referenceLongPress-l-iC26Y4.js.br +0 -0
- package/dist/client/assets/referenceLongPress-l-iC26Y4.js.gz +0 -0
- package/dist/client/assets/{requirementDiagram-BXWQKSXE-CoVdyMn3.js → requirementDiagram-BXWQKSXE-BVuulzR5.js} +1 -1
- package/dist/client/assets/requirementDiagram-BXWQKSXE-BVuulzR5.js.br +0 -0
- package/dist/client/assets/requirementDiagram-BXWQKSXE-BVuulzR5.js.gz +0 -0
- package/dist/client/assets/{sankeyDiagram-P5KCCOFB-BF-YvoEZ.js → sankeyDiagram-P5KCCOFB-DCiS6hhT.js} +1 -1
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-DCiS6hhT.js.br +0 -0
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-DCiS6hhT.js.gz +0 -0
- package/dist/client/assets/{sequenceDiagram-WJ2MYXX4-CMkePZOj.js → sequenceDiagram-WJ2MYXX4-vobocfD-.js} +1 -1
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-vobocfD-.js.br +0 -0
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-vobocfD-.js.gz +0 -0
- package/dist/client/assets/{sizeCapture-INFHLROL-C9N9vqvo.js → sizeCapture-INFHLROL-DY_P3bTc.js} +1 -1
- package/dist/client/assets/sizeCapture-INFHLROL-DY_P3bTc.js.br +0 -0
- package/dist/client/assets/sizeCapture-INFHLROL-DY_P3bTc.js.gz +0 -0
- package/dist/client/assets/{sparkles-DQ-Y24Kv.js → sparkles-iFcvD4yM.js} +1 -1
- package/dist/client/assets/{stateDiagram-D77RDMKH-DFk62G9u.js → stateDiagram-D77RDMKH-g9dDzGJR.js} +1 -1
- package/dist/client/assets/stateDiagram-D77RDMKH-g9dDzGJR.js.br +0 -0
- package/dist/client/assets/stateDiagram-D77RDMKH-g9dDzGJR.js.gz +0 -0
- package/dist/client/assets/stateDiagram-v2-MP3YSRHH-Bxp20Ww7.js +1 -0
- package/dist/client/assets/{swimlanes-42K2YHIH-CNpYAR3d.js → swimlanes-42K2YHIH-CC39tzCY.js} +1 -1
- package/dist/client/assets/swimlanes-42K2YHIH-CC39tzCY.js.br +0 -0
- package/dist/client/assets/swimlanes-42K2YHIH-CC39tzCY.js.gz +0 -0
- package/dist/client/assets/swimlanesDiagram-VR7AAH4N-bz2A714u.js +8 -0
- package/dist/client/assets/{timeline-definition-24CTP7MA-BVEhKc3h.js → timeline-definition-24CTP7MA-Bf-Np1KC.js} +1 -1
- package/dist/client/assets/timeline-definition-24CTP7MA-Bf-Np1KC.js.br +0 -0
- package/dist/client/assets/timeline-definition-24CTP7MA-Bf-Np1KC.js.gz +0 -0
- package/dist/client/assets/{triangle-alert-BIwj1bIH.js → triangle-alert-BeIpvW9N.js} +1 -1
- package/dist/client/assets/{vennDiagram-4TSXK5OY-DqKMbCx0.js → vennDiagram-4TSXK5OY-BA9Lil5m.js} +1 -1
- package/dist/client/assets/vennDiagram-4TSXK5OY-BA9Lil5m.js.br +0 -0
- package/dist/client/assets/vennDiagram-4TSXK5OY-BA9Lil5m.js.gz +0 -0
- package/dist/client/assets/{videoCompression-DhppheEu.js → videoCompression-ESn5rZIR.js} +1 -1
- package/dist/client/assets/videoCompression-ESn5rZIR.js.br +0 -0
- package/dist/client/assets/videoCompression-ESn5rZIR.js.gz +0 -0
- package/dist/client/assets/{wardleyDiagram-VM6X3IG4-Bnhg0vB7.js → wardleyDiagram-VM6X3IG4-BCDzPgJu.js} +1 -1
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-BCDzPgJu.js.br +0 -0
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-BCDzPgJu.js.gz +0 -0
- package/dist/client/assets/{xychartDiagram-S5SC5T6Z-BBRqvRXj.js → xychartDiagram-S5SC5T6Z-CXvxPVbT.js} +1 -1
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-CXvxPVbT.js.br +0 -0
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-CXvxPVbT.js.gz +0 -0
- package/dist/client/index.html +1 -1
- package/dist/client/index.html.br +0 -0
- package/dist/client/index.html.gz +0 -0
- package/dist/client/sw.js +1 -1
- package/dist/client/sw.js.br +0 -0
- package/dist/client/sw.js.gz +0 -0
- package/package.json +1 -1
- package/runtime-manifest.json +2 -2
- package/dist/client/assets/App-B1lqBSPB.js +0 -187
- package/dist/client/assets/App-B1lqBSPB.js.br +0 -0
- package/dist/client/assets/App-B1lqBSPB.js.gz +0 -0
- package/dist/client/assets/ArchitecturePanel-BOq2FG6t.js.br +0 -0
- package/dist/client/assets/ArchitecturePanel-BOq2FG6t.js.gz +0 -0
- package/dist/client/assets/ChangeWalkthroughPanel-CxqwQxYc.js.br +0 -0
- package/dist/client/assets/ChangeWalkthroughPanel-CxqwQxYc.js.gz +0 -0
- package/dist/client/assets/CollaborationMainWorkspace-vvAVjIlQ.js.br +0 -0
- package/dist/client/assets/CollaborationMainWorkspace-vvAVjIlQ.js.gz +0 -0
- package/dist/client/assets/CollaborationTaskContent-Bx6Z5gEL.js +0 -2
- package/dist/client/assets/ComputerControlView-mR6vlp9k.js.br +0 -0
- package/dist/client/assets/ComputerControlView-mR6vlp9k.js.gz +0 -0
- package/dist/client/assets/DagPlayground-nUK9xIql.js.br +0 -0
- package/dist/client/assets/DagPlayground-nUK9xIql.js.gz +0 -0
- package/dist/client/assets/DiffLab-D6XhZtPW.js.br +0 -0
- package/dist/client/assets/DiffLab-D6XhZtPW.js.gz +0 -0
- package/dist/client/assets/DiffReview-BhyYqkD4.js.br +0 -0
- package/dist/client/assets/DiffReview-BhyYqkD4.js.gz +0 -0
- package/dist/client/assets/DiffReviewLab-CvNWVrbl.js.br +0 -0
- package/dist/client/assets/DiffReviewLab-CvNWVrbl.js.gz +0 -0
- package/dist/client/assets/DiffViewer-BSbMa2mq.js.br +0 -0
- package/dist/client/assets/DiffViewer-BSbMa2mq.js.gz +0 -0
- package/dist/client/assets/ModelPreview-B_VPlNYr.js.br +0 -0
- package/dist/client/assets/ModelPreview-B_VPlNYr.js.gz +0 -0
- package/dist/client/assets/RightSidebar-Cakd9qUZ.js.br +0 -0
- package/dist/client/assets/RightSidebar-Cakd9qUZ.js.gz +0 -0
- package/dist/client/assets/abnfDiagram-VCTEODGH-vWK7F-r_.js.br +0 -0
- package/dist/client/assets/abnfDiagram-VCTEODGH-vWK7F-r_.js.gz +0 -0
- package/dist/client/assets/app-BZBIr89q.js.br +0 -0
- package/dist/client/assets/app-BZBIr89q.js.gz +0 -0
- package/dist/client/assets/arc-Bdjvby9b.js.br +0 -0
- package/dist/client/assets/arc-Bdjvby9b.js.gz +0 -0
- package/dist/client/assets/architectureDiagram-5GKGNRK7-DTR5hJkG.js.br +0 -0
- package/dist/client/assets/architectureDiagram-5GKGNRK7-DTR5hJkG.js.gz +0 -0
- package/dist/client/assets/blockDiagram-I7D4REHJ-DPz3axsu.js.br +0 -0
- package/dist/client/assets/blockDiagram-I7D4REHJ-DPz3axsu.js.gz +0 -0
- package/dist/client/assets/c4Diagram-7LVT6UL2-d5ZwPpcN.js.br +0 -0
- package/dist/client/assets/c4Diagram-7LVT6UL2-d5ZwPpcN.js.gz +0 -0
- package/dist/client/assets/channel-M_h_h55d.js +0 -1
- package/dist/client/assets/chunk-F27PBJKO-C1L__gXc.js.br +0 -0
- package/dist/client/assets/chunk-F27PBJKO-C1L__gXc.js.gz +0 -0
- package/dist/client/assets/chunk-IMKFNOWR-CX0r7pV5.js.br +0 -0
- package/dist/client/assets/chunk-IMKFNOWR-CX0r7pV5.js.gz +0 -0
- package/dist/client/assets/chunk-SVP7TREG-C1x5c5cy.js.br +0 -0
- package/dist/client/assets/chunk-SVP7TREG-C1x5c5cy.js.gz +0 -0
- package/dist/client/assets/chunk-TICWLB2K-DAktkamN.js.br +0 -0
- package/dist/client/assets/chunk-TICWLB2K-DAktkamN.js.gz +0 -0
- package/dist/client/assets/classDiagram-ZZMXUADV-BVuw_2Ox.js +0 -1
- package/dist/client/assets/classDiagram-v2-VYDZK3BY-BVuw_2Ox.js +0 -1
- package/dist/client/assets/cose-bilkent-JH36ORCC-kBGroiho.js.br +0 -0
- package/dist/client/assets/cose-bilkent-JH36ORCC-kBGroiho.js.gz +0 -0
- package/dist/client/assets/cynefin-OW5HDTMX-C0TjwB46.js.br +0 -0
- package/dist/client/assets/cynefin-OW5HDTMX-C0TjwB46.js.gz +0 -0
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-CbLSUTuV.js.br +0 -0
- package/dist/client/assets/cynefinDiagram-5FMLGOSQ-CbLSUTuV.js.gz +0 -0
- package/dist/client/assets/dagre-GXQ25YYZ-BoznXKfa.js.br +0 -0
- package/dist/client/assets/dagre-GXQ25YYZ-BoznXKfa.js.gz +0 -0
- package/dist/client/assets/diagram-S7CK7UJ4-iY9ia7F5.js.br +0 -0
- package/dist/client/assets/diagram-S7CK7UJ4-iY9ia7F5.js.gz +0 -0
- package/dist/client/assets/diagram-UQ7AKVKN-DhnC8gBw.js.br +0 -0
- package/dist/client/assets/diagram-UQ7AKVKN-DhnC8gBw.js.gz +0 -0
- package/dist/client/assets/diagram-VSXAHHWV-JFg8cbqX.js.br +0 -0
- package/dist/client/assets/diagram-VSXAHHWV-JFg8cbqX.js.gz +0 -0
- package/dist/client/assets/diagram-VX7I27RA-dvyXUTpo.js.br +0 -0
- package/dist/client/assets/diagram-VX7I27RA-dvyXUTpo.js.gz +0 -0
- package/dist/client/assets/diagram-Z3DM3KII-DmjwsCUU.js.br +0 -0
- package/dist/client/assets/diagram-Z3DM3KII-DmjwsCUU.js.gz +0 -0
- package/dist/client/assets/ebnfDiagram-PWID7BFC-BxCdDL0c.js.br +0 -0
- package/dist/client/assets/ebnfDiagram-PWID7BFC-BxCdDL0c.js.gz +0 -0
- package/dist/client/assets/erDiagram-RLTQ6QDP-BWvvnoz1.js.br +0 -0
- package/dist/client/assets/erDiagram-RLTQ6QDP-BWvvnoz1.js.gz +0 -0
- package/dist/client/assets/flowDiagram-HODETNUW-CVU0l_6c.js.br +0 -0
- package/dist/client/assets/flowDiagram-HODETNUW-CVU0l_6c.js.gz +0 -0
- package/dist/client/assets/ganttDiagram-EL5Y4UJY-CjO521RP.js.br +0 -0
- package/dist/client/assets/gestureArbiter-D_fs_PXp.js.br +0 -0
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-DbxNhHiO.js.br +0 -0
- package/dist/client/assets/gitGraphDiagram-WWUBYQGX-DbxNhHiO.js.gz +0 -0
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-BPbgDJUg.js.br +0 -0
- package/dist/client/assets/ishikawaDiagram-5VMMS53U-BPbgDJUg.js.gz +0 -0
- package/dist/client/assets/journeyDiagram-3NMN7TZE-D1nSzyjD.js.br +0 -0
- package/dist/client/assets/journeyDiagram-3NMN7TZE-D1nSzyjD.js.gz +0 -0
- package/dist/client/assets/kanban-definition-UXKFOSKX-CSCXZnir.js.br +0 -0
- package/dist/client/assets/kanban-definition-UXKFOSKX-CSCXZnir.js.gz +0 -0
- package/dist/client/assets/layout-DTNe7C08.js.br +0 -0
- package/dist/client/assets/layout-DTNe7C08.js.gz +0 -0
- package/dist/client/assets/linear-DELStaU_.js.br +0 -0
- package/dist/client/assets/linear-DELStaU_.js.gz +0 -0
- package/dist/client/assets/mermaid.core-D7uvx0E2.js.br +0 -0
- package/dist/client/assets/mermaid.core-D7uvx0E2.js.gz +0 -0
- package/dist/client/assets/mindmap-definition-YA3MSWOX-C_fF6Gnh.js.br +0 -0
- package/dist/client/assets/mindmap-definition-YA3MSWOX-C_fF6Gnh.js.gz +0 -0
- package/dist/client/assets/passwordBootstrap-Co17Xh3M.js.br +0 -0
- package/dist/client/assets/passwordBootstrap-Co17Xh3M.js.gz +0 -0
- package/dist/client/assets/pegDiagram-XKGWAZYB-BFOfbHg1.js.br +0 -0
- package/dist/client/assets/pegDiagram-XKGWAZYB-BFOfbHg1.js.gz +0 -0
- package/dist/client/assets/pieDiagram-E7YTZNPT-BkLXgY2Y.js.br +0 -0
- package/dist/client/assets/pieDiagram-E7YTZNPT-BkLXgY2Y.js.gz +0 -0
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-DIF7ynjD.js.br +0 -0
- package/dist/client/assets/quadrantDiagram-AXDQQJYC-DIF7ynjD.js.gz +0 -0
- package/dist/client/assets/railroadDiagram-O6MQD6OU-DGeuv8o1.js.br +0 -0
- package/dist/client/assets/railroadDiagram-O6MQD6OU-DGeuv8o1.js.gz +0 -0
- package/dist/client/assets/rdpSession-DZCrSxpu.js.br +0 -0
- package/dist/client/assets/rdpSession-DZCrSxpu.js.gz +0 -0
- package/dist/client/assets/referenceLongPress-DrY73BHe.js.br +0 -0
- package/dist/client/assets/referenceLongPress-DrY73BHe.js.gz +0 -0
- package/dist/client/assets/requirementDiagram-BXWQKSXE-CoVdyMn3.js.br +0 -0
- package/dist/client/assets/requirementDiagram-BXWQKSXE-CoVdyMn3.js.gz +0 -0
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-BF-YvoEZ.js.br +0 -0
- package/dist/client/assets/sankeyDiagram-P5KCCOFB-BF-YvoEZ.js.gz +0 -0
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-CMkePZOj.js.br +0 -0
- package/dist/client/assets/sequenceDiagram-WJ2MYXX4-CMkePZOj.js.gz +0 -0
- package/dist/client/assets/sizeCapture-INFHLROL-C9N9vqvo.js.br +0 -0
- package/dist/client/assets/sizeCapture-INFHLROL-C9N9vqvo.js.gz +0 -0
- package/dist/client/assets/stateDiagram-D77RDMKH-DFk62G9u.js.br +0 -0
- package/dist/client/assets/stateDiagram-D77RDMKH-DFk62G9u.js.gz +0 -0
- package/dist/client/assets/stateDiagram-v2-MP3YSRHH-Bnyl10vy.js +0 -1
- package/dist/client/assets/swimlanes-42K2YHIH-CNpYAR3d.js.br +0 -0
- package/dist/client/assets/swimlanes-42K2YHIH-CNpYAR3d.js.gz +0 -0
- package/dist/client/assets/swimlanesDiagram-VR7AAH4N-BwjcVbFS.js +0 -8
- package/dist/client/assets/timeline-definition-24CTP7MA-BVEhKc3h.js.br +0 -0
- package/dist/client/assets/timeline-definition-24CTP7MA-BVEhKc3h.js.gz +0 -0
- package/dist/client/assets/vennDiagram-4TSXK5OY-DqKMbCx0.js.br +0 -0
- package/dist/client/assets/vennDiagram-4TSXK5OY-DqKMbCx0.js.gz +0 -0
- package/dist/client/assets/videoCompression-DhppheEu.js.br +0 -0
- package/dist/client/assets/videoCompression-DhppheEu.js.gz +0 -0
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-Bnhg0vB7.js.br +0 -0
- package/dist/client/assets/wardleyDiagram-VM6X3IG4-Bnhg0vB7.js.gz +0 -0
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-BBRqvRXj.js.br +0 -0
- package/dist/client/assets/xychartDiagram-S5SC5T6Z-BBRqvRXj.js.gz +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/passwordBootstrap-
|
|
2
|
-
import{r as pl,a as Rw,g as gh}from"./react-XDCjal2T.js";import{b as N,R as lt,r as ms}from"./dnd-BCFAPC0L.js";import{L as Tw,l as Pw}from"./terminal-C7X98Amf.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();const Nw="modulepreload",Lw=function(e){return"/"+e},Id={},wn=function(t,n,r){let o=Promise.resolve();if(n&&n.length>0){let c=function(l){return Promise.all(l.map(d=>Promise.resolve(d).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),a=s?.nonce||s?.getAttribute("nonce");o=c(n.map(l=>{if(l=Lw(l),l in Id)return;Id[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":Nw,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 i(s){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=s,window.dispatchEvent(a),!a.defaultPrevented)throw s}return o.then(s=>{for(const a of s||[])a.status==="rejected"&&i(a.reason);return t().catch(i)})};var Xs={exports:{}},Hr={};var Rd;function Bw(){if(Rd)return Hr;Rd=1;var e=pl(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function s(a,c,l){var d,u={},f=null,h=null;l!==void 0&&(f=""+l),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(h=c.ref);for(d in c)r.call(c,d)&&!i.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:t,type:a,key:f,ref:h,props:u,_owner:o.current}}return Hr.Fragment=n,Hr.jsx=s,Hr.jsxs=s,Hr}var Td;function Dw(){return Td||(Td=1,Xs.exports=Bw()),Xs.exports}var p=Dw();const Dn="termdock-secure-target-v1",gl="termdock-secure-entry-v1",_w=new Set([Dn,gl,"termdock-color-theme","termdock:locale","termdock.federation.connections.v1"]),Go=typeof Storage>"u"?void 0:Storage.prototype.getItem,Ys=typeof Storage>"u"?void 0:Storage.prototype.setItem,Pd="termdock-secure-legacy-owner",ws=typeof window<"u"&&window.parent!==window&&location.pathname==="/workspace.html";function Ow(){if(typeof window>"u")return null;try{if(ws){const t=new URLSearchParams(location.search).get("termdock-workspace"),n=JSON.parse(localStorage.getItem("termdock.federation.connections.v1")||"[]"),r=Array.isArray(n)?n.find(o=>o?.targetPeerId===t):void 0;return r&&typeof r.url=="string"&&typeof r.targetPeerId=="string"?{...r,serviceName:r.label||r.serviceName}:null}const e=JSON.parse(sessionStorage.getItem(Dn)??localStorage.getItem(Dn)??"null");return e&&typeof e.url=="string"&&typeof e.targetPeerId=="string"?e:null}catch{return null}}let Oo=Ow();const ic=new Set,dr=Oo?.targetPeerId??"unpaired";function Qe(){return Oo}function $P(e){return ic.add(e),()=>ic.delete(e)}function mh(){for(const e of ic)e(Oo)}function wh(e){if(Oo=e,mh(),ws)return;const t=JSON.stringify(e);sessionStorage.setItem(Dn,t),localStorage.setItem(Dn,t)}function Fw(){Oo=null,mh(),!ws&&(localStorage.removeItem(Dn),sessionStorage.removeItem(Dn),localStorage.removeItem(gl))}function wo(e,t=dr){return _w.has(e)||e.startsWith("termdock-secure-")?e:`termdock-service:${t}:${e}`}function Mw(e){if(!(!Go||!Ys))try{if(Go.call(localStorage,Pd))return;Ys.call(localStorage,Pd,e);for(const n of[localStorage,sessionStorage]){const r=Array.from({length:n.length},(o,i)=>n.key(i)).filter(o=>!!o);for(const o of r){if(o.startsWith("termdock-service:")||wo(o,e)===o)continue;const i=wo(o,e),s=Go.call(n,o);s!==null&&Go.call(n,i)===null&&Ys.call(n,i,s)}}}catch{}}let Nd=!1;function jw(){if(Nd||typeof Storage>"u")return;Nd=!0;const e=Storage.prototype.getItem,t=Storage.prototype.setItem,n=Storage.prototype.removeItem;Storage.prototype.getItem=function(r){return e.call(this,wo(String(r)))},Storage.prototype.setItem=function(r,o){t.call(this,wo(String(r)),o)},Storage.prototype.removeItem=function(r){n.call(this,wo(String(r)))}}jw();const yh=8,bh=128,ml=2e4,ys="termdock.federation.connections.v1",sc="termdock:services-changed",wl="termdock-secure-removed-services",_i=e=>[e.id,e.targetPeerId,e.serviceOrigin||e.url].filter(t=>!!t);function yl(){try{const e=JSON.parse(localStorage.getItem(wl)||"[]");return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}catch{return[]}}function Re(e){const t=e.trim();if(!t)throw new Error("请输入服务地址。");const n=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(t)?t:`https://${t}`);n.protocol==="wss:"&&(n.protocol="https:"),n.protocol==="ws:"&&(n.protocol="http:");const r=["localhost","127.0.0.1","[::1]"].includes(n.hostname);if(!["https:","http:"].includes(n.protocol)||n.protocol==="http:"&&!r)throw new Error("请使用 HTTPS 服务地址。");if(n.username||n.password||n.search||n.hash||!["/","/api/federation/secure"].includes(n.pathname))throw new Error("请输入服务首页地址,不要包含账号或额外参数。");return n.origin}function bs(e){if(!e||typeof e!="object")return;const t=e;if(typeof t.url=="string")try{const n=Re(t.url),r=typeof t.targetPeerId=="string"&&t.targetPeerId?t.targetPeerId:void 0,o=(typeof t.label=="string"?t.label:typeof t.serviceName=="string"?t.serviceName:"").trim().slice(0,120)||new URL(n).host;return{id:typeof t.id=="string"&&t.id?t.id:r||n,url:n,label:o,...r?{targetPeerId:r}:{},...typeof t.serviceOrigin=="string"?{serviceOrigin:Re(t.serviceOrigin)}:{},...typeof t.entryServiceId=="string"&&t.entryServiceId?{entryServiceId:t.entryServiceId}:{},...Array.isArray(t.routes)?{routes:t.routes.slice(0,4).flatMap(i=>{try{return i&&typeof i.targetPeerId=="string"&&i.targetPeerId?[{url:Re(i.url),targetPeerId:i.targetPeerId}]:[]}catch{return[]}})}:{}}}catch{return}}function Kt(e,t){return e.targetPeerId&&t.targetPeerId?e.targetPeerId===t.targetPeerId:(e.serviceOrigin||e.url)===(t.serviceOrigin||t.url)}function vh(e){const t=[];for(const n of e){const r=t.findIndex(o=>Kt(o,n));r<0?t.push(n):t[r]={...t[r],...n,id:t[r].id}}return t}function Fo(){return typeof window>"u"?void 0:window.termdockDesktop}function _n(){try{const e=JSON.parse(localStorage.getItem(ys)||"[]");return Array.isArray(e)?vh(e.map(bs).filter(t=>!!t)):[]}catch{return[]}}function Sh(e){localStorage.setItem(ys,JSON.stringify(e.map(t=>({...t,serviceName:t.label})))),window.dispatchEvent(new Event(sc))}let $r;async function Ye(){const e=Fo();if(!e?.serviceConnections||!e.saveServiceConnection)return _n();if($r)return $r;$r=(async()=>{let t=await e.serviceConnections();const n=_n();for(const r of n)t.some(o=>Kt(o,r))||(t=await(e.importServiceConnection||e.saveServiceConnection)(r));return n.length&&localStorage.removeItem(ys),t})();try{return await $r}finally{$r=void 0}}async function Yt(e){const t=bs(e);if(!t)throw new Error("服务地址无效。");const n=Fo();if(n?.saveServiceConnection)return n.saveServiceConnection(t);const r=_n(),o=r.find(a=>a.id===t.id||Kt(a,t)),i=new Set([..._i(t),...o?_i(o):[]]);localStorage.setItem(wl,JSON.stringify(yl().filter(a=>!i.has(a))));const s=vh([...r.filter(a=>a!==o),{...o,...t,id:o?.id||t.id}]);return Sh(s),s}async function Uw(e){const t=bs(e);if(!t)throw new Error("服务地址无效。");const n=Fo();if(n?.importServiceConnection)return n.importServiceConnection(t);if(n?.serviceConnections){const r=await n.serviceConnections();return r.some(o=>Kt(o,t))?Yt(t):r}return _i(t).some(r=>yl().includes(r))?_n():Yt(t)}async function Hw(e){const t=Fo();if(t?.removeServiceConnection)return t.removeServiceConnection(e);const n=_n(),r=n.find(i=>i.id===e);r&&localStorage.setItem(wl,JSON.stringify([...new Set([...yl(),..._i(r)])].slice(-768)));const o=n.filter(i=>i.id!==e);return Sh(o),o}function vs(e){const t=r=>{(r.key===ys||r.key===null)&&e()};window.addEventListener(sc,e),window.addEventListener("storage",t);const n=Fo()?.onServiceConnections?.(e);return()=>{window.removeEventListener(sc,e),window.removeEventListener("storage",t),n?.()}}class $w extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}}let qw=class extends Error{static name="InvalidCryptoExchangeError";constructor(t="Invalid crypto exchange"){super(t),this.name="InvalidCryptoExchangeError"}},xt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};class xh extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}}class Eh extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}}class Kw extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}}class zw extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}}class Ss extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}}const Ah=Symbol.for("@libp2p/peer-id");function Vw(e){return typeof e?.handleEvent=="function"}function Ww(e){return e===!0||e===!1}function Gw(e){return Ww(e)?e:e?.capture??!1}function ac(e){const t={capture:Gw(e),once:!!e?.once};return e?.passive!=null&&(t.passive=e?.passive),e?.signal!=null&&(t.signal=e?.signal),t}function Ld(e,t){return ac(e).capture===ac(t).capture}class Xw extends EventTarget{#e=new Map;constructor(){super()}listenerCount(t){const n=this.#e.get(t);return n==null?0:n.length}addEventListener(t,n,r){const o=ac(r);if(o?.signal?.aborted===!0)return;const i=l=>{o.once&&this.removeEventListener(t,n,o),Vw(n)?n.handleEvent(l):n(l)};let s=this.#e.get(t);if(s==null&&(s=[],this.#e.set(t,s)),s.some(l=>l.callback!==n?!1:Ld(l.options,o)))return;super.addEventListener(t,i,o);const c=()=>{this.removeEventListener(t,n,o)};o.signal?.addEventListener("abort",c),s.push({callback:n,wrapper:i,options:o,onAbort:c})}removeEventListener(t,n,r){const o=this.#e.get(t);if(o==null){super.removeEventListener(t,n??null,r);return}this.#e.set(t,o.filter(i=>i.callback===n&&Ld(i.options,r)?(super.removeEventListener(t,i.wrapper,r),i.options?.signal?.removeEventListener("abort",i.onAbort),!1):!0))}safeDispatchEvent(t,n={}){return this.dispatchEvent(new CustomEvent(t,n))}}const Yw=Symbol.for("@libp2p/service-capabilities");function Zw(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0}function xs(e){if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}function Jw(e){return new TextEncoder().encode(e)}function Qw(e){return new TextDecoder().decode(e)}function ey(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var o=0;o<e.length;o++){var i=e.charAt(o),s=i.charCodeAt(0);if(n[s]!==255)throw new TypeError(i+" is ambiguous");n[s]=o}var a=e.length,c=e.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,v=0,w=0,S=g.length;w!==S&&g[w]===0;)w++,m++;for(var y=(S-w)*d+1>>>0,A=new Uint8Array(y);w!==S;){for(var R=g[w],E=0,C=y-1;(R!==0||E<v)&&C!==-1;C--,E++)R+=256*A[C]>>>0,A[C]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");v=E,w++}for(var k=y-v;k!==y&&A[k]===0;)k++;for(var b=c.repeat(m);k<y;++k)b+=e.charAt(A[k]);return b}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 v=0,w=0;g[m]===c;)v++,m++;for(var S=(g.length-m)*l+1>>>0,y=new Uint8Array(S);g[m];){var A=n[g.charCodeAt(m)];if(A===255)return;for(var R=0,E=S-1;(A!==0||R<w)&&E!==-1;E--,R++)A+=a*y[E]>>>0,y[E]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");w=R,m++}if(g[m]!==" "){for(var C=S-w;C!==S&&y[C]===0;)C++;for(var k=new Uint8Array(v+(S-C)),b=v;C!==S;)k[b++]=y[C++];return k}}}function h(g){var m=f(g);if(m)return m;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:f,decode:h}}var ty=ey,ny=ty;class ry{name;prefix;baseEncode;constructor(t,n,r){this.name=t,this.prefix=n,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}}class oy{name;prefix;baseDecode;prefixCodePoint;constructor(t,n,r){this.name=t,this.prefix=n;const o=n.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Ch(this,t)}}class iy{decoders;constructor(t){this.decoders=t}or(t){return Ch(this,t)}decode(t){const n=t[0],r=this.decoders[n];if(r!=null)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function Ch(e,t){return new iy({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}class sy{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,n,r,o){this.name=t,this.prefix=n,this.baseEncode=r,this.baseDecode=o,this.encoder=new ry(t,n,r),this.decoder=new oy(t,n,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}function Es({name:e,prefix:t,encode:n,decode:r}){return new sy(e,t,n,r)}function Mo({name:e,prefix:t,alphabet:n}){const{encode:r,decode:o}=ny(n,e);return Es({prefix:t,name:e,encode:r,decode:i=>xs(o(i))})}function ay(e,t,n,r){let o=e.length;for(;e[o-1]==="=";)--o;const i=new Uint8Array(o*n/8|0);let s=0,a=0,c=0;for(let l=0;l<o;++l){const d=t[e[l]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<n|d,s+=n,s>=8&&(s-=8,i[c++]=255&a>>s)}if(s>=n||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function cy(e,t,n){const r=t[t.length-1]==="=",o=(1<<n)-1;let i="",s=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],s+=8;s>n;)s-=n,i+=t[o&a>>s];if(s!==0&&(i+=t[o&a<<n-s]),r)for(;(i.length*n&7)!==0;)i+="=";return i}function ly(e){const t={};for(let n=0;n<e.length;++n)t[e[n]]=n;return t}function $e({name:e,prefix:t,bitsPerChar:n,alphabet:r}){const o=ly(r);return Es({prefix:t,name:e,encode(i){return cy(i,r,n)},decode(i){return ay(i,o,n,e)}})}const Ze=Mo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),dy=Mo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),uy=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Ze,base58flickr:dy},Symbol.toStringTag,{value:"Module"})),yo=$e({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),fy=$e({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hy=$e({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),py=$e({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),gy=$e({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),my=$e({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),wy=$e({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),yy=$e({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),by=$e({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),vy=Object.freeze(Object.defineProperty({__proto__:null,base32:yo,base32hex:gy,base32hexpad:wy,base32hexpadupper:yy,base32hexupper:my,base32pad:hy,base32padupper:py,base32upper:fy,base32z:by},Symbol.toStringTag,{value:"Module"})),bi=Mo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Sy=Mo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),xy=Object.freeze(Object.defineProperty({__proto__:null,base36:bi,base36upper:Sy},Symbol.toStringTag,{value:"Module"}));var Ey=kh,Bd=128,Ay=-128,Cy=Math.pow(2,31);function kh(e,t,n){t=t||[],n=n||0;for(var r=n;e>=Cy;)t[n++]=e&255|Bd,e/=128;for(;e&Ay;)t[n++]=e&255|Bd,e>>>=7;return t[n]=e|0,kh.bytes=n-r+1,t}var ky=cc,Iy=128,Dd=127;function cc(e,r){var n=0,r=r||0,o=0,i=r,s,a=e.length;do{if(i>=a)throw cc.bytes=0,new RangeError("Could not decode varint");s=e[i++],n+=o<28?(s&Dd)<<o:(s&Dd)*Math.pow(2,o),o+=7}while(s>=Iy);return cc.bytes=i-r,n}var Ry=Math.pow(2,7),Ty=Math.pow(2,14),Py=Math.pow(2,21),Ny=Math.pow(2,28),Ly=Math.pow(2,35),By=Math.pow(2,42),Dy=Math.pow(2,49),_y=Math.pow(2,56),Oy=Math.pow(2,63),Fy=function(e){return e<Ry?1:e<Ty?2:e<Py?3:e<Ny?4:e<Ly?5:e<By?6:e<Dy?7:e<_y?8:e<Oy?9:10},My={encode:Ey,decode:ky,encodingLength:Fy},Oi=My;function lc(e,t=0){return[Oi.decode(e,t),Oi.decode.bytes]}function Fi(e,t,n=0){return Oi.encode(e,t,n),t}function Mi(e){return Oi.encodingLength(e)}function jo(e,t){const n=t.byteLength,r=Mi(e),o=r+Mi(n),i=new Uint8Array(o+n);return Fi(e,i,0),Fi(n,i,r),i.set(t,o),new bl(e,n,t,i)}function Ih(e){const t=xs(e),[n,r]=lc(t),[o,i]=lc(t.subarray(r)),s=t.subarray(r+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new bl(n,o,s,t)}function jy(e,t){if(e===t)return!0;{const n=t;return e.code===n.code&&e.size===n.size&&n.bytes instanceof Uint8Array&&Zw(e.bytes,n.bytes)}}class bl{code;size;digest;bytes;constructor(t,n,r,o){this.code=t,this.size=n,this.digest=r,this.bytes=o}}function _d(e,t){const{bytes:n,version:r}=e;return r===0?Hy(n,dc(e),t??Ze.encoder):$y(n,dc(e),t??yo.encoder)}const Od=new WeakMap;function dc(e){const t=Od.get(e);if(t==null){const n=new Map;return Od.set(e,n),n}return t}class Ae{code;version;multihash;bytes;"/";constructor(t,n,r,o){this.code=n,this.version=t,this.multihash=r,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:t,multihash:n}=this;if(t!==qr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==qy)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Ae.createV0(n)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:t,digest:n}=this.multihash,r=jo(t,n);return Ae.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return Ae.equals(this,t)}static equals(t,n){const r=n;return r!=null&&t.code===r.code&&t.version===r.version&&jy(t.multihash,r.multihash)}toString(t){return _d(this,t)}toJSON(){return{"/":_d(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;const n=t;if(n instanceof Ae)return n;if(n["/"]!=null&&n["/"]===n.bytes||n.asCID===n){const{version:r,code:o,multihash:i,bytes:s}=n;return new Ae(r,o,i,s??Fd(r,o,i.bytes))}else if(n[Ky]===!0){const{version:r,multihash:o,code:i}=n,s=Ih(o);return Ae.create(r,i,s)}else return null}static create(t,n,r){if(typeof n!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(n!==qr)throw new Error(`Version 0 CID must use dag-pb (code: ${qr}) block encoding`);return new Ae(t,n,r,r.bytes)}case 1:{const o=Fd(t,n,r.bytes);return new Ae(t,n,r,o)}default:throw new Error("Invalid version")}}static createV0(t){return Ae.create(0,qr,t)}static createV1(t,n){return Ae.create(1,t,n)}static decode(t){const[n,r]=Ae.decodeFirst(t);if(r.length!==0)throw new Error("Incorrect length");return n}static decodeFirst(t){const n=Ae.inspectBytes(t),r=n.size-n.multihashSize,o=xs(t.subarray(r,r+n.multihashSize));if(o.byteLength!==n.multihashSize)throw new Error("Incorrect length");const i=o.subarray(n.multihashSize-n.digestSize),s=new bl(n.multihashCode,n.digestSize,i,o);return[n.version===0?Ae.createV0(s):Ae.createV1(n.codec,s),t.subarray(n.size)]}static inspectBytes(t){let n=0;const r=()=>{const[u,f]=lc(t.subarray(n));return n+=f,u};let o=r(),i=qr;if(o===18?(o=0,n=0):i=r(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);const s=n,a=r(),c=r(),l=n+c,d=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:d,size:l}}static parse(t,n){const[r,o]=Uy(t,n),i=Ae.decode(o);if(i.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return dc(i).set(r,t),i}}function Uy(e,t){switch(e[0]){case"Q":{const n=t??Ze;return[Ze.prefix,n.decode(`${Ze.prefix}${e}`)]}case Ze.prefix:{const n=t??Ze;return[Ze.prefix,n.decode(e)]}case yo.prefix:{const n=t??yo;return[yo.prefix,n.decode(e)]}case bi.prefix:{const n=t??bi;return[bi.prefix,n.decode(e)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function Hy(e,t,n){const{prefix:r}=n;if(r!==Ze.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);const o=t.get(r);if(o==null){const i=n.encode(e).slice(1);return t.set(r,i),i}else return o}function $y(e,t,n){const{prefix:r}=n,o=t.get(r);if(o==null){const i=n.encode(e);return t.set(r,i),i}else return o}const qr=112,qy=18;function Fd(e,t,n){const r=Mi(e),o=r+Mi(t),i=new Uint8Array(o+n.byteLength);return Fi(e,i,0),Fi(t,i,r),i.set(n,o),i}const Ky=Symbol.for("@ipld/js-cid/CID"),Rh=0,zy="identity",Th=xs;function Vy(e,t){if(t?.truncate!=null&&t.truncate!==e.byteLength){if(t.truncate<0||t.truncate>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,t.truncate)}return jo(Rh,Th(e))}const Uo={code:Rh,name:zy,encode:Th,digest:Vy};function Et(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0}function nt(e=0){return new Uint8Array(e)}function Zt(e=0){return new Uint8Array(e)}function uc(e,t){t==null&&(t=e.reduce((o,i)=>o+i.length,0));const n=Zt(t);let r=0;for(const o of e)n.set(o,r),r+=o.length;return n}const Ph=Symbol.for("@achingbrain/uint8arraylist");function Md(e,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let n=0;for(const r of e){const o=n+r.byteLength;if(t<o)return{buf:r,index:t-n};n=o}throw new RangeError("index is out of bounds")}function Xo(e){return!!e?.[Ph]}class ye{bufs;length;[Ph]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let n=0;for(const r of t)if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.push(r);else if(Xo(r)){n+=r.byteLength;for(const o of r.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=n}prepend(...t){this.prependAll(t)}prependAll(t){let n=0;for(const r of t.reverse())if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.unshift(r);else if(Xo(r))n+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=n}get(t){const n=Md(this.bufs,t);return n.buf[n.index]}set(t,n){const r=Md(this.bufs,t);r.buf[r.index]=n}write(t,n=0){if(t instanceof Uint8Array)for(let r=0;r<t.length;r++)this.set(n+r,t[r]);else if(Xo(t))for(let r=0;r<t.length;r++)this.set(n+r,t.get(r));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,n){const{bufs:r,length:o}=this._subList(t,n);return uc(r,o)}subarray(t,n){const{bufs:r,length:o}=this._subList(t,n);return r.length===1?r[0]:uc(r,o)}sublist(t,n){const{bufs:r,length:o}=this._subList(t,n),i=new ye;return i.length=o,i.bufs=r,i}_subList(t,n){if(t=t??0,n=n??this.length,t<0&&(t=this.length+t),n<0&&(n=this.length+n),t<0||n>this.length)throw new RangeError("index is out of bounds");if(t===n)return{bufs:[],length:0};if(t===0&&n===this.length)return{bufs:[...this.bufs],length:this.length};const r=[];let o=0;for(let i=0;i<this.bufs.length;i++){const s=this.bufs[i],a=o,c=a+s.byteLength;if(o=c,t>=c)continue;const l=t>=a&&t<c,d=n>a&&n<=c;if(l&&d){if(t===a&&n===c){r.push(s);break}const u=t-a;r.push(s.subarray(u,u+(n-t)));break}if(l){if(t===0){r.push(s);continue}r.push(s.subarray(t-a));continue}if(d){if(n===c){r.push(s);break}r.push(s.subarray(0,n-a));break}r.push(s)}return{bufs:r,length:n-t}}indexOf(t,n=0){if(!Xo(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=t instanceof Uint8Array?t:t.subarray();if(n=Number(n??0),isNaN(n)&&(n=0),n<0&&(n=this.length+n),n<0&&(n=0),t.length===0)return n>this.length?this.length:n;const o=r.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");const i=256,s=new Int32Array(i);for(let u=0;u<i;u++)s[u]=-1;for(let u=0;u<o;u++)s[r[u]]=u;const a=s,c=this.byteLength-r.byteLength,l=r.byteLength-1;let d;for(let u=n;u<=c;u+=d){d=0;for(let f=l;f>=0;f--){const h=this.get(u+f);if(r[f]!==h){d=Math.max(1,f-a[h]);break}}if(d===0)return u}return-1}getInt8(t){const n=this.subarray(t,t+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt8(0)}setInt8(t,n){const r=Zt(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,n),this.write(r,t)}getInt16(t,n){const r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,n)}setInt16(t,n,r){const o=nt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,n,r),this.write(o,t)}getInt32(t,n){const r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,n)}setInt32(t,n,r){const o=nt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,n,r),this.write(o,t)}getBigInt64(t,n){const r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,n)}setBigInt64(t,n,r){const o=nt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,n,r),this.write(o,t)}getUint8(t){const n=this.subarray(t,t+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint8(0)}setUint8(t,n){const r=Zt(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,n),this.write(r,t)}getUint16(t,n){const r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,n)}setUint16(t,n,r){const o=nt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,n,r),this.write(o,t)}getUint32(t,n){const r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,n)}setUint32(t,n,r){const o=nt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,n,r),this.write(o,t)}getBigUint64(t,n){const r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,n)}setBigUint64(t,n,r){const o=nt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,n,r),this.write(o,t)}getFloat32(t,n){const r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,n)}setFloat32(t,n,r){const o=nt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,n,r),this.write(o,t)}getFloat64(t,n){const r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,n)}setFloat64(t,n,r){const o=nt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,n,r),this.write(o,t)}equals(t){if(t==null||!(t instanceof ye)||t.bufs.length!==this.bufs.length)return!1;for(let n=0;n<this.bufs.length;n++)if(!Et(this.bufs[n],t.bufs[n]))return!1;return!0}static fromUint8Arrays(t,n){const r=new ye;return r.bufs=t,n==null&&(n=t.reduce((o,i)=>o+i.byteLength,0)),r.length=n,r}}const Wy=Mo({prefix:"9",name:"base10",alphabet:"0123456789"}),Gy=Object.freeze(Object.defineProperty({__proto__:null,base10:Wy},Symbol.toStringTag,{value:"Module"})),Xy=$e({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Yy=$e({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Zy=Object.freeze(Object.defineProperty({__proto__:null,base16:Xy,base16upper:Yy},Symbol.toStringTag,{value:"Module"})),Jy=$e({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Qy=Object.freeze(Object.defineProperty({__proto__:null,base2:Jy},Symbol.toStringTag,{value:"Module"})),Nh=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),eb=Nh.reduce((e,t,n)=>(e[n]=t,e),[]),tb=Nh.reduce((e,t,n)=>{const r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);return e[r]=n,e},[]);function nb(e){return e.reduce((t,n)=>(t+=eb[n],t),"")}function rb(e){const t=[];for(const n of e){const r=n.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${n}`);const o=tb[r];if(o==null)throw new Error(`Non-base256emoji character: ${n}`);t.push(o)}return new Uint8Array(t)}const ob=Es({prefix:"🚀",name:"base256emoji",encode:nb,decode:rb}),ib=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:ob},Symbol.toStringTag,{value:"Module"})),sb=$e({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ab=$e({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cb=$e({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),lb=$e({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),db=Object.freeze(Object.defineProperty({__proto__:null,base64:sb,base64pad:ab,base64url:cb,base64urlpad:lb},Symbol.toStringTag,{value:"Module"})),ub=$e({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),fb=Object.freeze(Object.defineProperty({__proto__:null,base8:ub},Symbol.toStringTag,{value:"Module"})),hb=Es({prefix:"\0",name:"identity",encode:e=>Qw(e),decode:e=>Jw(e)}),pb=Object.freeze(Object.defineProperty({__proto__:null,identity:hb},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const gb=20;function mb({name:e,code:t,encode:n,minDigestLength:r,maxDigestLength:o}){return new wb(e,t,n,r,o)}class wb{name;code;encode;minDigestLength;maxDigestLength;constructor(t,n,r,o,i){this.name=t,this.code=n,this.encode=r,this.minDigestLength=o??gb,this.maxDigestLength=i}digest(t,n){if(n?.truncate!=null){if(n.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&n.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){const r=this.encode(t);return r instanceof Uint8Array?jd(r,this.code,n?.truncate):r.then(o=>jd(o,this.code,n?.truncate))}else throw Error("Unknown type, must be binary type")}}function jd(e,t,n){if(n!=null&&n!==e.byteLength){if(n>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,n)}return jo(t,e)}function yb(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}const vl=mb({name:"sha2-256",code:18,encode:yb("SHA-256")}),Ud={...pb,...Qy,...fb,...Gy,...Zy,...vy,...xy,...uy,...db,...ib};function Lh(e,t,n,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:n},decoder:{decode:r}}}const Hd=Lh("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),Zs=Lh("ascii","a",e=>{let t="a";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t},e=>{e=e.substring(1);const t=Zt(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}),Bh={utf8:Hd,"utf-8":Hd,hex:Ud.base16,latin1:Zs,ascii:Zs,binary:Zs,...Ud};function Le(e,t="utf8"){const n=Bh[t];if(n==null)throw new Error(`Unsupported encoding "${t}"`);return n.decoder.decode(`${n.prefix}${e}`)}function ue(e,t="utf8"){const n=Bh[t];if(n==null)throw new Error(`Unsupported encoding "${t}"`);return n.encoder.encode(e).substring(1)}const bb=parseInt("11111",2),fc=parseInt("10000000",2),vb=parseInt("01111111",2),$d={0:Kr,1:Kr,2:Sb,3:Ab,4:Cb,5:Eb,6:xb,16:Kr,22:Kr,48:Kr};function Or(e,t={offset:0}){const n=e[t.offset]&bb;if(t.offset++,$d[n]!=null)return $d[n](e,t);throw new Error("No decoder for tag "+n)}function Ho(e,t){let n=0;if((e[t.offset]&fc)===fc){const r=e[t.offset]&vb;let o="0x";t.offset++;for(let i=0;i<r;i++,t.offset++)o+=e[t.offset].toString(16).padStart(2,"0");n=parseInt(o,16)}else n=e[t.offset],t.offset++;return n}function Kr(e,t){Ho(e,t);const n=[];for(;!(t.offset>=e.byteLength);){const r=Or(e,t);if(r===null)break;n.push(r)}return n}function Sb(e,t){const n=Ho(e,t),r=t.offset,o=t.offset+n,i=[];for(let s=r;s<o;s++)s===r&&e[s]===0||i.push(e[s]);return t.offset+=n,Uint8Array.from(i)}function xb(e,t){const n=Ho(e,t),r=t.offset+n,o=e[t.offset];t.offset++;let i=0,s=0;o<40?(i=0,s=o):o<80?(i=1,s=o-40):(i=2,s=o-80);let a=`${i}.${s}`,c=[];for(;t.offset<r;){const l=e[t.offset];if(t.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 Eb(e,t){return t.offset++,null}function Ab(e,t){const n=Ho(e,t),r=e[t.offset];t.offset++;const o=e.subarray(t.offset,t.offset+n-1);if(t.offset+=n,r!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Cb(e,t){const n=Ho(e,t),r=e.subarray(t.offset,t.offset+n);return t.offset+=n,r}function kb(e){let t=e.toString(16);t.length%2===1&&(t="0"+t);const n=new ye;for(let r=0;r<t.length;r+=2)n.append(Uint8Array.from([parseInt(`${t[r]}${t[r+1]}`,16)]));return n}function As(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);const t=kb(e.byteLength);return new ye(Uint8Array.from([t.byteLength|fc]),t)}function ct(e){const t=new ye,n=128;return(e.subarray()[0]&n)===n&&t.append(Uint8Array.from([0])),t.append(e),new ye(Uint8Array.from([2]),As(t),t)}function Sl(e){const t=Uint8Array.from([0]),n=new ye(t,e);return new ye(Uint8Array.from([3]),As(n),n)}function Ib(e){return new ye(Uint8Array.from([4]),As(e),e)}function Gt(e,t=48){const n=new ye;for(const r of e)n.append(r);return new ye(Uint8Array.from([t]),As(n),n)}async function Rb(e,t,n){const r=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["sign"]);n?.signal?.throwIfAborted();const o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,t.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Tb(e,t,n,r){const o=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();const i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,n.subarray());return r?.signal?.throwIfAborted(),i}const Pb=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Nb=Uint8Array.from([6,5,43,129,4,0,34]),Lb=Uint8Array.from([6,5,43,129,4,0,35]),Dh={ext:!0,kty:"EC",crv:"P-256"},_h={ext:!0,kty:"EC",crv:"P-384"},Oh={ext:!0,kty:"EC",crv:"P-521"},ur=32,fr=48,hr=66;function Bb(e){const t=Or(e);return Db(t)}function Db(e){const t=e[1],n=ue(t,"base64url"),r=e[2][1][0],o=1;let i,s;if(t.byteLength===ur)return i=ue(r.subarray(o,o+ur),"base64url"),s=ue(r.subarray(o+ur),"base64url"),new Js({...Dh,key_ops:["sign"],d:n,x:i,y:s});if(t.byteLength===fr)return i=ue(r.subarray(o,o+fr),"base64url"),s=ue(r.subarray(o+fr),"base64url"),new Js({..._h,key_ops:["sign"],d:n,x:i,y:s});if(t.byteLength===hr)return i=ue(r.subarray(o,o+hr),"base64url"),s=ue(r.subarray(o+hr),"base64url"),new Js({...Oh,key_ops:["sign"],d:n,x:i,y:s});throw new xt(`Private key length was wrong length, got ${t.byteLength}, expected 32, 48 or 66`)}function Fh(e){const t=Or(e);return _b(t)}function _b(e){const t=e[1][1][0],n=1;let r,o;if(t.byteLength===ur*2+1)return r=ue(t.subarray(n,n+ur),"base64url"),o=ue(t.subarray(n+ur),"base64url"),new vi({...Dh,key_ops:["verify"],x:r,y:o});if(t.byteLength===fr*2+1)return r=ue(t.subarray(n,n+fr),"base64url"),o=ue(t.subarray(n+fr),"base64url"),new vi({..._h,key_ops:["verify"],x:r,y:o});if(t.byteLength===hr*2+1)return r=ue(t.subarray(n,n+hr),"base64url"),o=ue(t.subarray(n+hr),"base64url"),new vi({...Oh,key_ops:["verify"],x:r,y:o});throw new xt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Ob(e){return Gt([ct(Uint8Array.from([1])),Ib(Le(e.d??"","base64url")),Gt([Mh(e.crv)],160),Gt([Sl(new ye(Uint8Array.from([4]),Le(e.x??"","base64url"),Le(e.y??"","base64url")))],161)]).subarray()}function Fb(e){return Gt([ct(Uint8Array.from([1])),Gt([Mh(e.crv)],160),Gt([Sl(new ye(Uint8Array.from([4]),Le(e.x??"","base64url"),Le(e.y??"","base64url")))],161)]).subarray()}function Mh(e){if(e==="P-256")return Pb;if(e==="P-384")return Nb;if(e==="P-521")return Lb;throw new xt(`Invalid curve ${e}`)}class vi{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Fb(this.jwk)),this._raw}toMultihash(){return Uo.digest(Ps(this))}toCID(){return Ae.createV1(114,this.toMultihash())}toString(){return Ze.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}async verify(t,n,r){return Tb(this.jwk,n,t,r)}}class Js{type="ECDSA";jwk;publicKey;_raw;constructor(t){this.jwk=t,this.publicKey=new vi({crv:t.crv,ext:t.ext,key_ops:["verify"],kty:"EC",x:t.x,y:t.y})}get raw(){return this._raw==null&&(this._raw=Ob(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}async sign(t,n){return Rb(this.jwk,t,n)}}const Yn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function $o(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function hc(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Hn(e,...t){if(!$o(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function jh(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");hc(e.outputLen),hc(e.blockLen)}function ji(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Mb(e,t){Hn(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function kr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Qs(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Rt(e,t){return e<<32-t|e>>>t}const Uh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",jb=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Tn(e){if(Hn(e),Uh)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=jb[e[n]];return t}const Ft={_0:48,_9:57,A:65,F:70,a:97,f:102};function qd(e){if(e>=Ft._0&&e<=Ft._9)return e-Ft._0;if(e>=Ft.A&&e<=Ft.F)return e-(Ft.A-10);if(e>=Ft.a&&e<=Ft.f)return e-(Ft.a-10)}function Ui(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(Uh)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){const s=qd(e.charCodeAt(i)),a=qd(e.charCodeAt(i+1));if(s===void 0||a===void 0){const c=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a}return r}function Ub(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function xl(e){return typeof e=="string"&&(e=Ub(e)),Hn(e),e}function Lt(...e){let t=0;for(let r=0;r<e.length;r++){const o=e[r];Hn(o),t+=o.length}const n=new Uint8Array(t);for(let r=0,o=0;r<e.length;r++){const i=e[r];n.set(i,o),o+=i.length}return n}class Hh{}function $h(e){const t=r=>e().update(xl(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function El(e=32){if(Yn&&typeof Yn.getRandomValues=="function")return Yn.getRandomValues(new Uint8Array(e));if(Yn&&typeof Yn.randomBytes=="function")return Uint8Array.from(Yn.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Hb(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const o=BigInt(32),i=BigInt(4294967295),s=Number(n>>o&i),a=Number(n&i),c=r?4:0,l=r?0:4;e.setUint32(t+c,s,r),e.setUint32(t+l,a,r)}function $b(e,t,n){return e&t^~e&n}function qb(e,t,n){return e&t^e&n^t&n}let qh=class extends Hh{constructor(t,n,r,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Qs(this.buffer)}update(t){ji(this),t=xl(t),Hn(t);const{view:n,buffer:r,blockLen:o}=this,i=t.length;for(let s=0;s<i;){const a=Math.min(o-this.pos,i-s);if(a===o){const c=Qs(t);for(;o<=i-s;s+=o)this.process(c,s);continue}r.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){ji(this),Mb(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:o,isLE:i}=this;let{pos:s}=this;n[s++]=128,kr(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let u=s;u<o;u++)n[u]=0;Hb(r,o-8,BigInt(this.length*8),i),this.process(r,0);const a=Qs(t),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],i)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=o,t.pos=a,o%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}};const tn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ve=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Yo=BigInt(2**32-1),Kd=BigInt(32);function Kb(e,t=!1){return t?{h:Number(e&Yo),l:Number(e>>Kd&Yo)}:{h:Number(e>>Kd&Yo)|0,l:Number(e&Yo)|0}}function zb(e,t=!1){const n=e.length;let r=new Uint32Array(n),o=new Uint32Array(n);for(let i=0;i<n;i++){const{h:s,l:a}=Kb(e[i],t);[r[i],o[i]]=[s,a]}return[r,o]}const zd=(e,t,n)=>e>>>n,Vd=(e,t,n)=>e<<32-n|t>>>n,Zn=(e,t,n)=>e>>>n|t<<32-n,Jn=(e,t,n)=>e<<32-n|t>>>n,Zo=(e,t,n)=>e<<64-n|t>>>n-32,Jo=(e,t,n)=>e>>>n-32|t<<64-n;function Mt(e,t,n,r){const o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:o|0}}const Vb=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Wb=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Gb=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Xb=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,Yb=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Zb=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0,Jb=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]),nn=new Uint32Array(64);class Qb extends qh{constructor(t=32){super(64,t,8,!1),this.A=tn[0]|0,this.B=tn[1]|0,this.C=tn[2]|0,this.D=tn[3]|0,this.E=tn[4]|0,this.F=tn[5]|0,this.G=tn[6]|0,this.H=tn[7]|0}get(){const{A:t,B:n,C:r,D:o,E:i,F:s,G:a,H:c}=this;return[t,n,r,o,i,s,a,c]}set(t,n,r,o,i,s,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,n){for(let u=0;u<16;u++,n+=4)nn[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const f=nn[u-15],h=nn[u-2],g=Rt(f,7)^Rt(f,18)^f>>>3,m=Rt(h,17)^Rt(h,19)^h>>>10;nn[u]=m+nn[u-7]+g+nn[u-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=Rt(a,6)^Rt(a,11)^Rt(a,25),h=d+f+$b(a,c,l)+Jb[u]+nn[u]|0,m=(Rt(r,2)^Rt(r,13)^Rt(r,22))+qb(r,o,i)|0;d=l,l=c,c=a,a=s+h|0,s=i,i=o,o=r,r=h+m|0}r=r+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,i,s,a,c,l,d)}roundClean(){kr(nn)}destroy(){this.set(0,0,0,0,0,0,0,0),kr(this.buffer)}}const Kh=zb(["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(e=>BigInt(e))),ev=Kh[0],tv=Kh[1],rn=new Uint32Array(80),on=new Uint32Array(80);class nv extends qh{constructor(t=64){super(128,t,16,!1),this.Ah=Ve[0]|0,this.Al=Ve[1]|0,this.Bh=Ve[2]|0,this.Bl=Ve[3]|0,this.Ch=Ve[4]|0,this.Cl=Ve[5]|0,this.Dh=Ve[6]|0,this.Dl=Ve[7]|0,this.Eh=Ve[8]|0,this.El=Ve[9]|0,this.Fh=Ve[10]|0,this.Fl=Ve[11]|0,this.Gh=Ve[12]|0,this.Gl=Ve[13]|0,this.Hh=Ve[14]|0,this.Hl=Ve[15]|0}get(){const{Ah:t,Al:n,Bh:r,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:f,Gh:h,Gl:g,Hh:m,Hl:v}=this;return[t,n,r,o,i,s,a,c,l,d,u,f,h,g,m,v]}set(t,n,r,o,i,s,a,c,l,d,u,f,h,g,m,v){this.Ah=t|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|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=v|0}process(t,n){for(let y=0;y<16;y++,n+=4)rn[y]=t.getUint32(n),on[y]=t.getUint32(n+=4);for(let y=16;y<80;y++){const A=rn[y-15]|0,R=on[y-15]|0,E=Zn(A,R,1)^Zn(A,R,8)^zd(A,R,7),C=Jn(A,R,1)^Jn(A,R,8)^Vd(A,R,7),k=rn[y-2]|0,b=on[y-2]|0,x=Zn(k,b,19)^Zo(k,b,61)^zd(k,b,6),T=Jn(k,b,19)^Jo(k,b,61)^Vd(k,b,6),L=Gb(C,T,on[y-7],on[y-16]),I=Xb(L,E,x,rn[y-7],rn[y-16]);rn[y]=I|0,on[y]=L|0}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:f,Fh:h,Fl:g,Gh:m,Gl:v,Hh:w,Hl:S}=this;for(let y=0;y<80;y++){const A=Zn(u,f,14)^Zn(u,f,18)^Zo(u,f,41),R=Jn(u,f,14)^Jn(u,f,18)^Jo(u,f,41),E=u&h^~u&m,C=f&g^~f&v,k=Yb(S,R,C,tv[y],on[y]),b=Zb(k,w,A,E,ev[y],rn[y]),x=k|0,T=Zn(r,o,28)^Zo(r,o,34)^Zo(r,o,39),L=Jn(r,o,28)^Jo(r,o,34)^Jo(r,o,39),I=r&i^r&a^i&a,P=o&s^o&c^s&c;w=m|0,S=v|0,m=h|0,v=g|0,h=u|0,g=f|0,{h:u,l:f}=Mt(l|0,d|0,b|0,x|0),l=a|0,d=c|0,a=i|0,c=s|0,i=r|0,s=o|0;const B=Vb(x,L,P);r=Wb(B,b,T,I),o=B|0}({h:r,l:o}=Mt(this.Ah|0,this.Al|0,r|0,o|0)),{h:i,l:s}=Mt(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Mt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=Mt(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:f}=Mt(this.Eh|0,this.El|0,u|0,f|0),{h,l:g}=Mt(this.Fh|0,this.Fl|0,h|0,g|0),{h:m,l:v}=Mt(this.Gh|0,this.Gl|0,m|0,v|0),{h:w,l:S}=Mt(this.Hh|0,this.Hl|0,w|0,S|0),this.set(r,o,i,s,a,c,l,d,u,f,h,g,m,v,w,S)}roundClean(){kr(rn,on)}destroy(){kr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const zh=$h(()=>new Qb),rv=$h(()=>new nv);const Al=BigInt(0),pc=BigInt(1);function On(e,t=""){if(typeof e!="boolean"){const n=t&&`"${t}"`;throw new Error(n+"expected boolean, got type="+typeof e)}return e}function vt(e,t,n=""){const r=$o(e),o=e?.length,i=t!==void 0;if(!r||i&&o!==t){const s=n&&`"${n}" `,a=i?` of length ${t}`:"",c=r?`length=${o}`:`type=${typeof e}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return e}function Qo(e){const t=e.toString(16);return t.length&1?"0"+t:t}function Vh(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?Al:BigInt("0x"+e)}function Cs(e){return Vh(Tn(e))}function Io(e){return Hn(e),Vh(Tn(Uint8Array.from(e).reverse()))}function Cl(e,t){return Ui(e.toString(16).padStart(t*2,"0"))}function Wh(e,t){return Cl(e,t).reverse()}function Ie(e,t,n){let r;if(typeof t=="string")try{r=Ui(t)}catch(i){throw new Error(e+" must be hex string or Uint8Array, cause: "+i)}else if($o(t))r=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");const o=r.length;if(typeof n=="number"&&o!==n)throw new Error(e+" of length "+n+" expected, got "+o);return r}function Wd(e){return Uint8Array.from(e)}const ea=e=>typeof e=="bigint"&&Al<=e;function ov(e,t,n){return ea(e)&&ea(t)&&ea(n)&&t<=e&&e<n}function gc(e,t,n,r){if(!ov(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Gh(e){let t;for(t=0;e>Al;e>>=pc,t+=1);return t}const qo=e=>(pc<<BigInt(e))-pc;function iv(e,t,n){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=h=>new Uint8Array(h),o=h=>Uint8Array.of(h);let i=r(e),s=r(e),a=0;const c=()=>{i.fill(1),s.fill(0),a=0},l=(...h)=>n(s,i,...h),d=(h=r(0))=>{s=l(o(0),h),i=l(),h.length!==0&&(s=l(o(1),h),i=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const g=[];for(;h<t;){i=l();const m=i.slice();g.push(m),h+=i.length}return Lt(...g)};return(h,g)=>{c(),d(h);let m;for(;!(m=g(u()));)d();return c(),m}}function Ko(e,t,n={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function r(o,i,s){const a=e[o];if(s&&a===void 0)return;const c=typeof a;if(c!==i||a===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${c}`)}Object.entries(t).forEach(([o,i])=>r(o,i,!1)),Object.entries(n).forEach(([o,i])=>r(o,i,!0))}function Hi(e){const t=new WeakMap;return(n,...r)=>{const o=t.get(n);if(o!==void 0)return o;const i=e(n,...r);return t.set(n,i),i}}const rt=BigInt(0),He=BigInt(1),En=BigInt(2),Xh=BigInt(3),Yh=BigInt(4),Zh=BigInt(5),sv=BigInt(7),Jh=BigInt(8),av=BigInt(9),Qh=BigInt(16);function Be(e,t){const n=e%t;return n>=rt?n:t+n}function ke(e,t,n){let r=e;for(;t-- >rt;)r*=r,r%=n;return r}function Gd(e,t){if(e===rt)throw new Error("invert: expected non-zero number");if(t<=rt)throw new Error("invert: expected positive modulus, got "+t);let n=Be(e,t),r=t,o=rt,i=He;for(;n!==rt;){const a=r/n,c=r%n,l=o-i*a;r=n,n=c,o=i,i=l}if(r!==He)throw new Error("invert: does not exist");return Be(o,t)}function kl(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function ep(e,t){const n=(e.ORDER+He)/Yh,r=e.pow(t,n);return kl(e,r,t),r}function cv(e,t){const n=(e.ORDER-Zh)/Jh,r=e.mul(t,En),o=e.pow(r,n),i=e.mul(t,o),s=e.mul(e.mul(i,En),o),a=e.mul(i,e.sub(s,e.ONE));return kl(e,a,t),a}function lv(e){const t=$n(e),n=tp(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+sv)/Qh;return(a,c)=>{let l=a.pow(c,s),d=a.mul(l,r);const u=a.mul(l,o),f=a.mul(l,i),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),v=a.cmov(l,d,m);return kl(a,v,c),v}}function tp(e){if(e<Xh)throw new Error("sqrt is not defined for small field");let t=e-He,n=0;for(;t%En===rt;)t/=En,n++;let r=En;const o=$n(e);for(;Xd(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return ep;let i=o.pow(r,t);const s=(t+He)/En;return function(c,l){if(c.is0(l))return l;if(Xd(c,l)!==1)throw new Error("Cannot find square root");let d=n,u=c.mul(c.ONE,i),f=c.pow(l,t),h=c.pow(l,s);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 v=He<<BigInt(d-g-1),w=c.pow(u,v);d=g,u=c.sqr(w),f=c.mul(f,u),h=c.mul(h,w)}return h}}function dv(e){return e%Yh===Xh?ep:e%Jh===Zh?cv:e%Qh===av?lv(e):tp(e)}const uv=(e,t)=>(Be(e,t)&He)===He,fv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hv(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=fv.reduce((r,o)=>(r[o]="function",r),t);return Ko(e,n),e}function pv(e,t,n){if(n<rt)throw new Error("invalid exponent, negatives unsupported");if(n===rt)return e.ONE;if(n===He)return t;let r=e.ONE,o=t;for(;n>rt;)n&He&&(r=e.mul(r,o)),o=e.sqr(o),n>>=He;return r}function np(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),o=t.reduce((s,a,c)=>e.is0(a)?s:(r[c]=s,e.mul(s,a)),e.ONE),i=e.inv(o);return t.reduceRight((s,a,c)=>e.is0(a)?s:(r[c]=e.mul(s,r[c]),e.mul(s,a)),i),r}function Xd(e,t){const n=(e.ORDER-He)/En,r=e.pow(t,n),o=e.eql(r,e.ONE),i=e.eql(r,e.ZERO),s=e.eql(r,e.neg(e.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function rp(e,t){t!==void 0&&hc(t);const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function $n(e,t,n=!1,r={}){if(e<=rt)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,i,s=!1,a;if(typeof t=="object"&&t!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const f=t;f.BITS&&(o=f.BITS),f.sqrt&&(i=f.sqrt),typeof f.isLE=="boolean"&&(n=f.isLE),typeof f.modFromBytes=="boolean"&&(s=f.modFromBytes),a=f.allowedLengths}else typeof t=="number"&&(o=t),r.sqrt&&(i=r.sqrt);const{nBitLength:c,nByteLength:l}=rp(e,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:qo(c),ZERO:rt,ONE:He,allowedLengths:a,create:f=>Be(f,e),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return rt<=f&&f<e},is0:f=>f===rt,isValidNot0:f=>!u.is0(f)&&u.isValid(f),isOdd:f=>(f&He)===He,neg:f=>Be(-f,e),eql:(f,h)=>f===h,sqr:f=>Be(f*f,e),add:(f,h)=>Be(f+h,e),sub:(f,h)=>Be(f-h,e),mul:(f,h)=>Be(f*h,e),pow:(f,h)=>pv(u,f,h),div:(f,h)=>Be(f*Gd(h,e),e),sqrN:f=>f*f,addN:(f,h)=>f+h,subN:(f,h)=>f-h,mulN:(f,h)=>f*h,inv:f=>Gd(f,e),sqrt:i||(f=>(d||(d=dv(e)),d(u,f))),toBytes:f=>n?Wh(f,l):Cl(f,l),fromBytes:(f,h=!0)=>{if(a){if(!a.includes(f.length)||f.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);const m=new Uint8Array(l);m.set(f,n?0:m.length-f.length),f=m}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let g=n?Io(f):Cs(f);if(s&&(g=Be(g,e)),!h&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:f=>np(u,f),cmov:(f,h,g)=>g?h:f});return Object.freeze(u)}function op(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function ip(e){const t=op(e);return t+Math.ceil(t/2)}function gv(e,t,n=!1){const r=e.length,o=op(t),i=ip(t);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const s=n?Io(e):Cs(e),a=Be(s,t-He)+He;return n?Wh(a,o):Cl(a,o)}const Ir=BigInt(0),An=BigInt(1);function $i(e,t){const n=t.negate();return e?n:t}function Cn(e,t){const n=np(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function sp(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function ta(e,t){sp(e,t);const n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,i=qo(e),s=BigInt(e);return{windows:n,windowSize:r,mask:i,maxNumber:o,shiftBy:s}}function Yd(e,t,n){const{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n;let a=Number(e&o),c=e>>s;a>r&&(a-=i,c+=An);const l=t*r,d=l+Math.abs(a)-1,u=a===0,f=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:f,isNegF:h,offsetF:l}}function mv(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function wv(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((n,r)=>{if(!t.isValid(n))throw new Error("invalid scalar at index "+r)})}const na=new WeakMap,ap=new WeakMap;function ra(e){return ap.get(e)||1}function Zd(e){if(e!==Ir)throw new Error("invalid wNAF")}class cp{constructor(t,n){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=n}_unsafeLadder(t,n,r=this.ZERO){let o=t;for(;n>Ir;)n&An&&(r=r.add(o)),o=o.double(),n>>=An;return r}precomputeWindow(t,n){const{windows:r,windowSize:o}=ta(n,this.bits),i=[];let s=t,a=s;for(let c=0;c<r;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(t,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE;const s=ta(t,this.bits);for(let a=0;a<s.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:f,offsetF:h}=Yd(r,a,s);r=c,d?i=i.add($i(f,n[h])):o=o.add($i(u,n[l]))}return Zd(r),{p:o,f:i}}wNAFUnsafe(t,n,r,o=this.ZERO){const i=ta(t,this.bits);for(let s=0;s<i.windows&&r!==Ir;s++){const{nextN:a,offset:c,isZero:l,isNeg:d}=Yd(r,s,i);if(r=a,!l){const u=n[c];o=o.add(d?u.negate():u)}}return Zd(r),o}getPrecomputes(t,n,r){let o=na.get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(o=r(o)),na.set(n,o))),o}cached(t,n,r){const o=ra(t);return this.wNAF(o,this.getPrecomputes(o,t,r),n)}unsafe(t,n,r,o){const i=ra(t);return i===1?this._unsafeLadder(t,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,r),n,o)}createCache(t,n){sp(n,this.bits),ap.set(t,n),na.delete(t)}hasCache(t){return ra(t)!==1}}function yv(e,t,n,r){let o=t,i=e.ZERO,s=e.ZERO;for(;n>Ir||r>Ir;)n&An&&(i=i.add(o)),r&An&&(s=s.add(o)),o=o.double(),n>>=An,r>>=An;return{p1:i,p2:s}}function lp(e,t,n,r){mv(n,e),wv(r,t);const o=n.length,i=r.length;if(o!==i)throw new Error("arrays of points and scalars must have equal length");const s=e.ZERO,a=Gh(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=qo(c),d=new Array(Number(l)+1).fill(s),u=Math.floor((t.BITS-1)/c)*c;let f=s;for(let h=u;h>=0;h-=c){d.fill(s);for(let m=0;m<i;m++){const v=r[m],w=Number(v>>BigInt(h)&l);d[w]=d[w].add(n[m])}let g=s;for(let m=d.length-1,v=s;m>0;m--)v=v.add(d[m]),g=g.add(v);if(f=f.add(g),h!==0)for(let m=0;m<c;m++)f=f.double()}return f}function Jd(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return hv(t),t}else return $n(e,{isLE:n})}function dp(e,t,n={},r){if(r===void 0&&(r=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(const c of["p","n","h"]){const l=t[c];if(!(typeof l=="bigint"&&l>Ir))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Jd(t.p,n.Fp,r),i=Jd(t.n,n.Fn,r),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(const c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}const sn=BigInt(0),Fe=BigInt(1),oa=BigInt(2),bv=BigInt(8);function vv(e,t,n,r){const o=e.sqr(n),i=e.sqr(r),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function Sv(e,t={}){const n=dp("edwards",e,t,t.FpFnLE),{Fp:r,Fn:o}=n;let i=n.CURVE;const{h:s}=i;Ko(t,{},{uvRatio:"function"});const a=oa<<BigInt(o.BYTES*8)-Fe,c=v=>r.create(v),l=t.uvRatio||((v,w)=>{try{return{isValid:!0,value:r.sqrt(r.div(v,w))}}catch{return{isValid:!1,value:sn}}});if(!vv(r,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function d(v,w,S=!1){const y=S?Fe:sn;return gc("coordinate "+v,w,y,a),w}function u(v){if(!(v instanceof g))throw new Error("ExtendedPoint expected")}const f=Hi((v,w)=>{const{X:S,Y:y,Z:A}=v,R=v.is0();w==null&&(w=R?bv:r.inv(A));const E=c(S*w),C=c(y*w),k=r.mul(A,w);if(R)return{x:sn,y:Fe};if(k!==Fe)throw new Error("invZ was invalid");return{x:E,y:C}}),h=Hi(v=>{const{a:w,d:S}=i;if(v.is0())throw new Error("bad point: ZERO");const{X:y,Y:A,Z:R,T:E}=v,C=c(y*y),k=c(A*A),b=c(R*R),x=c(b*b),T=c(C*w),L=c(b*c(T+k)),I=c(x+c(S*c(C*k)));if(L!==I)throw new Error("bad point: equation left != right (1)");const P=c(y*A),B=c(R*E);if(P!==B)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(w,S,y,A){this.X=d("x",w),this.Y=d("y",S),this.Z=d("z",y,!0),this.T=d("t",A),Object.freeze(this)}static CURVE(){return i}static fromAffine(w){if(w instanceof g)throw new Error("extended point not allowed");const{x:S,y}=w||{};return d("x",S),d("y",y),new g(S,y,Fe,c(S*y))}static fromBytes(w,S=!1){const y=r.BYTES,{a:A,d:R}=i;w=Wd(vt(w,y,"point")),On(S,"zip215");const E=Wd(w),C=w[y-1];E[y-1]=C&-129;const k=Io(E),b=S?a:r.ORDER;gc("point.y",k,sn,b);const x=c(k*k),T=c(x-Fe),L=c(R*x-A);let{isValid:I,value:P}=l(T,L);if(!I)throw new Error("bad point: invalid y coordinate");const B=(P&Fe)===Fe,D=(C&128)!==0;if(!S&&P===sn&&D)throw new Error("bad point: x=0 and x_0=1");return D!==B&&(P=c(-P)),g.fromAffine({x:P,y:k})}static fromHex(w,S=!1){return g.fromBytes(Ie("point",w),S)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,S=!0){return m.createCache(this,w),S||this.multiply(oa),this}assertValidity(){h(this)}equals(w){u(w);const{X:S,Y:y,Z:A}=this,{X:R,Y:E,Z:C}=w,k=c(S*C),b=c(R*A),x=c(y*C),T=c(E*A);return k===b&&x===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}=i,{X:S,Y:y,Z:A}=this,R=c(S*S),E=c(y*y),C=c(oa*c(A*A)),k=c(w*R),b=S+y,x=c(c(b*b)-R-E),T=k+E,L=T-C,I=k-E,P=c(x*L),B=c(T*I),D=c(x*I),F=c(L*T);return new g(P,B,F,D)}add(w){u(w);const{a:S,d:y}=i,{X:A,Y:R,Z:E,T:C}=this,{X:k,Y:b,Z:x,T}=w,L=c(A*k),I=c(R*b),P=c(C*y*T),B=c(E*x),D=c((A+R)*(k+b)-L-I),F=B-P,j=B+P,M=c(I-S*L),U=c(D*F),_=c(j*M),O=c(D*M),H=c(F*j);return new g(U,_,H,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:S,f:y}=m.cached(this,w,A=>Cn(g,A));return Cn(g,[S,y])[0]}multiplyUnsafe(w,S=g.ZERO){if(!o.isValid(w))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return w===sn?g.ZERO:this.is0()||w===Fe?this:m.unsafe(this,w,y=>Cn(g,y),S)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return m.unsafe(this,i.n).is0()}toAffine(w){return f(this,w)}clearCofactor(){return s===Fe?this:this.multiplyUnsafe(s)}toBytes(){const{x:w,y:S}=this.toAffine(),y=r.toBytes(S);return y[y.length-1]|=w&Fe?128:0,y}toHex(){return Tn(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 Cn(g,w)}static msm(w,S){return lp(g,o,w,S)}_setWindowSize(w){this.precompute(w)}toRawBytes(){return this.toBytes()}}g.BASE=new g(i.Gx,i.Gy,Fe,c(i.Gx*i.Gy)),g.ZERO=new g(sn,Fe,Fe,sn),g.Fp=r,g.Fn=o;const m=new cp(g,o.BITS);return g.BASE.precompute(8),g}function xv(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is required');Ko(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:o,Fp:i,Fn:s}=e,a=n.randomBytes||El,c=n.adjustScalarBytes||(b=>b),l=n.domain||((b,x,T)=>{if(On(T,"phflag"),x.length||T)throw new Error("Contexts/pre-hash are not supported");return b});function d(b){return s.create(Io(b))}function u(b){const x=y.secretKey;b=Ie("private key",b,x);const T=Ie("hashed private key",t(b),2*x),L=c(T.slice(0,x)),I=T.slice(x,2*x),P=d(L);return{head:L,prefix:I,scalar:P}}function f(b){const{head:x,prefix:T,scalar:L}=u(b),I=o.multiply(L),P=I.toBytes();return{head:x,prefix:T,scalar:L,point:I,pointBytes:P}}function h(b){return f(b).pointBytes}function g(b=Uint8Array.of(),...x){const T=Lt(...x);return d(t(l(T,Ie("context",b),!!r)))}function m(b,x,T={}){b=Ie("message",b),r&&(b=r(b));const{prefix:L,scalar:I,pointBytes:P}=f(x),B=g(T.context,L,b),D=o.multiply(B).toBytes(),F=g(T.context,D,P,b),j=s.create(B+F*I);if(!s.isValid(j))throw new Error("sign failed: invalid s");const M=Lt(D,s.toBytes(j));return vt(M,y.signature,"result")}const v={zip215:!0};function w(b,x,T,L=v){const{context:I,zip215:P}=L,B=y.signature;b=Ie("signature",b,B),x=Ie("message",x),T=Ie("publicKey",T,y.publicKey),P!==void 0&&On(P,"zip215"),r&&(x=r(x));const D=B/2,F=b.subarray(0,D),j=Io(b.subarray(D,B));let M,U,_;try{M=e.fromBytes(T,P),U=e.fromBytes(F,P),_=o.multiplyUnsafe(j)}catch{return!1}if(!P&&M.isSmallOrder())return!1;const O=g(I,U.toBytes(),M.toBytes(),x);return U.add(M.multiplyUnsafe(O)).subtract(_).clearCofactor().is0()}const S=i.BYTES,y={secretKey:S,publicKey:S,signature:2*S,seed:S};function A(b=a(y.seed)){return vt(b,y.seed,"seed")}function R(b){const x=k.randomSecretKey(b);return{secretKey:x,publicKey:h(x)}}function E(b){return $o(b)&&b.length===s.BYTES}function C(b,x){try{return!!e.fromBytes(b,x)}catch{return!1}}const k={getExtendedPublicKey:f,randomSecretKey:A,isValidSecretKey:E,isValidPublicKey:C,toMontgomery(b){const{y:x}=e.fromBytes(b),T=y.publicKey,L=T===32;if(!L&&T!==57)throw new Error("only defined for 25519 and 448");const I=L?i.div(Fe+x,Fe-x):i.div(x-Fe,x+Fe);return i.toBytes(I)},toMontgomerySecret(b){const x=y.secretKey;vt(b,x);const T=t(b.subarray(0,x));return c(T).subarray(0,x)},randomPrivateKey:A,precompute(b=8,x=e.BASE){return x.precompute(b,!1)}};return Object.freeze({keygen:R,getPublicKey:h,sign:m,verify:w,utils:k,Point:e,lengths:y})}function Ev(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp,r=$n(t.n,e.nBitLength,!0),o={Fp:n,Fn:r,uvRatio:e.uvRatio},i={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:o,hash:e.hash,eddsaOpts:i}}function Av(e,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function Cv(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:o}=Ev(e),i=Sv(t,n),s=xv(i,r,o);return Av(e,s)}const kv=BigInt(1),Qd=BigInt(2);BigInt(3);const Iv=BigInt(5),Rv=BigInt(8),Il=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),up={p:Il,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Rv,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Tv(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=Il,a=e*e%i*e%i,c=ke(a,Qd,i)*a%i,l=ke(c,kv,i)*e%i,d=ke(l,Iv,i)*l%i,u=ke(d,t,i)*d%i,f=ke(u,n,i)*u%i,h=ke(f,r,i)*f%i,g=ke(h,o,i)*h%i,m=ke(g,o,i)*h%i,v=ke(m,t,i)*d%i;return{pow_p_5_8:ke(v,Qd,i)*e%i,b2:a}}function Pv(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const eu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Nv(e,t){const n=Il,r=Be(t*t*t,n),o=Be(r*r*t,n),i=Tv(e*o).pow_p_5_8;let s=Be(e*r*i,n);const a=Be(t*s*s,n),c=s,l=Be(s*eu,n),d=a===e,u=a===Be(-e,n),f=a===Be(-e*eu,n);return d&&(s=c),(u||f)&&(s=l),uv(s,n)&&(s=Be(-s,n)),{isValid:d||u,value:s}}const Lv=$n(up.p,{isLE:!0}),Bv={...up,Fp:Lv,hash:rv,adjustScalarBytes:Pv,uvRatio:Nv},qi=Cv(Bv);class tu extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}}class nu extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}}class Dv extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}}const Jt={get(e=globalThis){const t=e.crypto;if(t?.subtle==null)throw new Dv("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 t}},Ki=32,$t=64,mc=32;let pr;const fp=(async()=>{try{return await Jt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function _v(){const e=qi.utils.randomPrivateKey(),t=qi.getPublicKey(e);return{privateKey:$v(e,t),publicKey:t}}async function Ov(e,t){let n;e.length===$t?n=e.subarray(0,32):n=e;const r={crv:"Ed25519",kty:"OKP",x:ue(e.subarray(32),"base64url"),d:ue(n,"base64url"),ext:!0,key_ops:["sign"]},o=await Jt.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),i=await Jt.get().subtle.sign({name:"Ed25519"},o,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(i,0,i.byteLength)}function Fv(e,t){const n=e.subarray(0,mc);return qi.sign(t instanceof Uint8Array?t:t.subarray(),n)}async function Mv(e,t){return pr==null&&(pr=await fp),pr?Ov(e,t):Fv(e,t)}async function jv(e,t,n){if(e.buffer instanceof ArrayBuffer){const r=await Jt.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Jt.get().subtle.verify({name:"Ed25519"},r,t,n instanceof Uint8Array?n:n.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Uv(e,t,n){return qi.verify(t,n instanceof Uint8Array?n:n.subarray(),e)}async function Hv(e,t,n){return pr==null&&(pr=await fp),pr?jv(e,t,n):Uv(e,t,n)}function $v(e,t){const n=new Uint8Array($t);for(let r=0;r<mc;r++)n[r]=e[r],n[mc+r]=t[r];return n}function ks(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}class hp{type="Ed25519";raw;constructor(t){this.raw=Ro(t,Ki)}toMultihash(){return Uo.digest(Ps(this))}toCID(){return Ae.createV1(114,this.toMultihash())}toString(){return Ze.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,n,r){r?.signal?.throwIfAborted();const o=Hv(this.raw,n,t);return ks(o)?o.then(i=>(r?.signal?.throwIfAborted(),i)):o}}class wc{type="Ed25519";raw;publicKey;constructor(t,n){this.raw=Ro(t,$t),this.publicKey=new hp(n)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}sign(t,n){n?.signal?.throwIfAborted();const r=Mv(this.raw,t);return ks(r)?r.then(o=>(n?.signal?.throwIfAborted(),o)):(n?.signal?.throwIfAborted(),r)}}function qv(e){if(e.length>$t){e=Ro(e,$t+Ki);const r=e.subarray(0,$t),o=e.subarray($t,e.length);return new wc(r,o)}e=Ro(e,$t);const t=e.subarray(0,$t),n=e.subarray(Ki);return new wc(t,n)}function pp(e){return e=Ro(e,Ki),new hp(e)}async function Kv(){const{privateKey:e,publicKey:t}=_v();return new wc(e,t)}function Ro(e,t){if(e=Uint8Array.from(e??[]),e.length!==t)throw new xt(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}const zv=Math.pow(2,7),Vv=Math.pow(2,14),Wv=Math.pow(2,21),Rl=Math.pow(2,28),Tl=Math.pow(2,35),Pl=Math.pow(2,42),Nl=Math.pow(2,49),we=128,We=127;function qn(e){if(e<zv)return 1;if(e<Vv)return 2;if(e<Wv)return 3;if(e<Rl)return 4;if(e<Tl)return 5;if(e<Pl)return 6;if(e<Nl)return 7;if(Number.MAX_SAFE_INTEGER!=null&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function gp(e,t,n=0){switch(qn(e)){case 8:t[n++]=e&255|we,e/=128;case 7:t[n++]=e&255|we,e/=128;case 6:t[n++]=e&255|we,e/=128;case 5:t[n++]=e&255|we,e/=128;case 4:t[n++]=e&255|we,e>>>=7;case 3:t[n++]=e&255|we,e>>>=7;case 2:t[n++]=e&255|we,e>>>=7;case 1:{t[n++]=e&255,e>>>=7;break}default:throw new Error("unreachable")}return t}function Gv(e,t,n=0){switch(qn(e)){case 8:t.set(n++,e&255|we),e/=128;case 7:t.set(n++,e&255|we),e/=128;case 6:t.set(n++,e&255|we),e/=128;case 5:t.set(n++,e&255|we),e/=128;case 4:t.set(n++,e&255|we),e>>>=7;case 3:t.set(n++,e&255|we),e>>>=7;case 2:t.set(n++,e&255|we),e>>>=7;case 1:{t.set(n++,e&255),e>>>=7;break}default:throw new Error("unreachable")}return t}function mp(e,t){let n=e[t],r=0;if(r+=n&We,n<we||(n=e[t+1],r+=(n&We)<<7,n<we)||(n=e[t+2],r+=(n&We)<<14,n<we)||(n=e[t+3],r+=(n&We)<<21,n<we)||(n=e[t+4],r+=(n&We)*Rl,n<we)||(n=e[t+5],r+=(n&We)*Tl,n<we)||(n=e[t+6],r+=(n&We)*Pl,n<we)||(n=e[t+7],r+=(n&We)*Nl,n<we))return r;throw new RangeError("Could not decode varint")}function Xv(e,t){let n=e.get(t),r=0;if(r+=n&We,n<we||(n=e.get(t+1),r+=(n&We)<<7,n<we)||(n=e.get(t+2),r+=(n&We)<<14,n<we)||(n=e.get(t+3),r+=(n&We)<<21,n<we)||(n=e.get(t+4),r+=(n&We)*Rl,n<we)||(n=e.get(t+5),r+=(n&We)*Tl,n<we)||(n=e.get(t+6),r+=(n&We)*Pl,n<we)||(n=e.get(t+7),r+=(n&We)*Nl,n<we))return r;throw new RangeError("Could not decode varint")}function Yv(e,t,n=0){return t==null&&(t=Zt(qn(e))),t instanceof Uint8Array?gp(e,t,n):Gv(e,t,n)}function wp(e,t=0){return e instanceof Uint8Array?mp(e,t):Xv(e,t)}const Ll=new Float32Array([-0]),pn=new Uint8Array(Ll.buffer);function Zv(e,t,n){Ll[0]=e,t[n]=pn[0],t[n+1]=pn[1],t[n+2]=pn[2],t[n+3]=pn[3]}function Jv(e,t){return pn[0]=e[t],pn[1]=e[t+1],pn[2]=e[t+2],pn[3]=e[t+3],Ll[0]}const Bl=new Float64Array([-0]),Ge=new Uint8Array(Bl.buffer);function Qv(e,t,n){Bl[0]=e,t[n]=Ge[0],t[n+1]=Ge[1],t[n+2]=Ge[2],t[n+3]=Ge[3],t[n+4]=Ge[4],t[n+5]=Ge[5],t[n+6]=Ge[6],t[n+7]=Ge[7]}function e0(e,t){return Ge[0]=e[t],Ge[1]=e[t+1],Ge[2]=e[t+2],Ge[3]=e[t+3],Ge[4]=e[t+4],Ge[5]=e[t+5],Ge[6]=e[t+6],Ge[7]=e[t+7],Bl[0]}const t0=BigInt(Number.MAX_SAFE_INTEGER),n0=BigInt(Number.MIN_SAFE_INTEGER);class Xe{lo;hi;constructor(t,n){this.lo=t|0,this.hi=n|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){const n=~this.lo+1>>>0;let r=~this.hi>>>0;return n===0&&(r=r+1>>>0),-(n+r*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){const n=~this.lo+1>>>0;let r=~this.hi>>>0;return n===0&&(r=r+1>>>0),-(BigInt(n)+(BigInt(r)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){const t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){const t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){const t=this.lo,n=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?n===0?t<16384?t<128?1:2:t<2097152?3:4:n<16384?n<128?5:6:n<2097152?7:8:r<128?9:10}static fromBigInt(t){if(t===0n)return Pn;if(t<t0&&t>n0)return this.fromNumber(Number(t));const n=t<0n;n&&(t=-t);let r=t>>32n,o=t-(r<<32n);return n&&(r=~r|0n,o=~o|0n,++o>ru&&(o=0n,++r>ru&&(r=0n))),new Xe(Number(o),Number(r))}static fromNumber(t){if(t===0)return Pn;const n=t<0;n&&(t=-t);let r=t>>>0,o=(t-r)/4294967296>>>0;return n&&(o=~o>>>0,r=~r>>>0,++r>4294967295&&(r=0,++o>4294967295&&(o=0))),new Xe(r,o)}static from(t){return typeof t=="number"?Xe.fromNumber(t):typeof t=="bigint"?Xe.fromBigInt(t):typeof t=="string"?Xe.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new Xe(t.low>>>0,t.high>>>0):Pn}}const Pn=new Xe(0,0);Pn.toBigInt=function(){return 0n};Pn.zzEncode=Pn.zzDecode=function(){return this};Pn.length=function(){return 1};const ru=4294967296n;function r0(e){let t=0,n=0;for(let r=0;r<e.length;++r)n=e.charCodeAt(r),n<128?t+=1:n<2048?t+=2:(n&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320?(++r,t+=4):t+=3;return t}function o0(e,t,n){if(n-t<1)return"";let o;const i=[];let s=0,a;for(;t<n;)a=e[t++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(e[t++]&63)<<6|e[t++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function yp(e,t,n){const r=n;let o,i;for(let s=0;s<e.length;++s)o=e.charCodeAt(s),o<128?t[n++]=o:o<2048?(t[n++]=o>>6|192,t[n++]=o&63|128):(o&64512)===55296&&((i=e.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=o&63|128):(t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=o&63|128);return n-r}function mt(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function ei(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class i0{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,mt(this,10);return t}int32(){return this.uint32()|0}sint32(){const t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw mt(this,4);return ei(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw mt(this,4);return ei(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw mt(this,4);const t=Jv(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw mt(this,4);const t=e0(this.buf,this.pos);return this.pos+=8,t}bytes(){const t=this.uint32(),n=this.pos,r=this.pos+t;if(r>this.len)throw mt(this,t);return this.pos+=t,n===r?new Uint8Array(0):this.buf.subarray(n,r)}string(){const t=this.bytes();return o0(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw mt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw mt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){const t=new Xe(0,0);let n=0;if(this.len-this.pos>4){for(;n<4;++n)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<n*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;n=0}else{for(;n<3;++n){if(this.pos>=this.len)throw mt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<n*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<n*7)>>>0,t}if(this.len-this.pos>4){for(;n<5;++n)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<n*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;n<5;++n){if(this.pos>=this.len)throw mt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<n*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw mt(this,8);const t=ei(this.buf,this.pos+=4),n=ei(this.buf,this.pos+=4);return new Xe(t,n)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const t=mp(this.buf,this.pos);return this.pos+=qn(t),t}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 s0(e){return new i0(e instanceof Uint8Array?e:e.subarray())}function Is(e,t,n){const r=s0(e);return t.decode(r,void 0,n)}function a0(e){let r,o=8192;return function(s){if(s<1||s>4096)return Zt(s);o+s>8192&&(r=Zt(8192),o=0);const a=r.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}class co{fn;len;next;val;constructor(t,n,r){this.fn=t,this.len=n,this.next=void 0,this.val=r}}function ia(){}class c0{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}}const l0=a0();function d0(e){return globalThis.Buffer!=null?Zt(e):l0(e)}class yc{len;head;tail;states;constructor(){this.len=0,this.head=new co(ia,0,0),this.tail=this.head,this.states=null}_push(t,n,r){return this.tail=this.tail.next=new co(t,n,r),this.len+=n,this}uint32(t){return this.len+=(this.tail=this.tail.next=new f0((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(ti,10,Xe.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){const n=Xe.fromBigInt(t);return this._push(ti,n.length(),n)}uint64Number(t){return this._push(gp,qn(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){const n=Xe.fromBigInt(t).zzEncode();return this._push(ti,n.length(),n)}sint64Number(t){const n=Xe.fromNumber(t).zzEncode();return this._push(ti,n.length(),n)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(sa,1,t?1:0)}fixed32(t){return this._push(zr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){const n=Xe.fromBigInt(t);return this._push(zr,4,n.lo)._push(zr,4,n.hi)}fixed64Number(t){const n=Xe.fromNumber(t);return this._push(zr,4,n.lo)._push(zr,4,n.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Zv,4,t)}double(t){return this._push(Qv,8,t)}bytes(t){const n=t.length>>>0;return n===0?this._push(sa,1,0):this.uint32(n)._push(h0,n,t)}string(t){const n=r0(t);return n!==0?this.uint32(n)._push(yp,n,t):this._push(sa,1,0)}fork(){return this.states=new c0(this),this.head=this.tail=new co(ia,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 co(ia,0,0),this.len=0),this}ldelim(){const t=this.head,n=this.tail,r=this.len;return this.reset().uint32(r),r!==0&&(this.tail.next=t.next,this.tail=n,this.len+=r),this}finish(){let t=this.head.next;const n=d0(this.len);let r=0;for(;t!=null;)t.fn(t.val,n,r),r+=t.len,t=t.next;return n}}function sa(e,t,n){t[n]=e&255}function u0(e,t,n){for(;e>127;)t[n++]=e&127|128,e>>>=7;t[n]=e}class f0 extends co{next;constructor(t,n){super(u0,t,n),this.next=void 0}}function ti(e,t,n){for(;e.hi!==0;)t[n++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=e.lo&127|128,e.lo=e.lo>>>7;t[n++]=e.lo}function zr(e,t,n){t[n]=e&255,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function h0(e,t,n){t.set(e,n)}globalThis.Buffer!=null&&(yc.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(p0,t,e),this},yc.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(g0,t,e),this});function p0(e,t,n){t.set(e,n)}function g0(e,t,n){e.length<40?yp(e,t,n):t.utf8Write!=null?t.utf8Write(e,n):t.set(Le(e),n)}function m0(){return new yc}function Rs(e,t){const n=m0();return t.encode(e,n,{lengthDelimited:!1}),n.finish()}var zi;(function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(zi||(zi={}));function bp(e,t,n,r){return{name:e,type:t,encode:n,decode:r}}function w0(e){function t(o){if(e[o.toString()]==null)throw new Error("Invalid enum value");return e[o]}const n=function(i,s){const a=t(i);s.int32(a)},r=function(i){const s=i.int32();return t(s)};return bp("enum",zi.VARINT,n,r)}function Ts(e,t){return bp("message",zi.LENGTH_DELIMITED,e,t)}class ou extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var Ce;(function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(Ce||(Ce={}));var bc;(function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(bc||(bc={}));(function(e){e.codec=()=>w0(bc)})(Ce||(Ce={}));var Fn;(function(e){let t;e.codec=()=>(t==null&&(t=Ts((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),Ce.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const i={},s=r==null?n.len:n.pos+r;for(;n.pos<s;){const a=n.uint32();switch(a>>>3){case 1:{i.Type=Ce.codec().decode(n);break}case 2:{i.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),t),e.encode=n=>Rs(n,e.codec()),e.decode=(n,r)=>Is(n,e.codec(),r)})(Fn||(Fn={}));var Vi;(function(e){let t;e.codec=()=>(t==null&&(t=Ts((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),Ce.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const i={},s=r==null?n.len:n.pos+r;for(;n.pos<s;){const a=n.uint32();switch(a>>>3){case 1:{i.Type=Ce.codec().decode(n);break}case 2:{i.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),t),e.encode=n=>Rs(n,e.codec()),e.decode=(n,r)=>Is(n,e.codec(),r)})(Vi||(Vi={}));const vp=zh;class Sp{type="RSA";jwk;_raw;_multihash;constructor(t,n){this.jwk=t,this._multihash=n}get raw(){return this._raw==null&&(this._raw=Ep(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Ae.createV1(114,this._multihash)}toString(){return Ze.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,n,r){return L0(this.jwk,n,t,r)}}class y0{type="RSA";jwk;_raw;publicKey;constructor(t,n){this.jwk=t,this.publicKey=n}get raw(){return this._raw==null&&(this._raw=E0(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}sign(t,n){return N0(this.jwk,t,n)}}const b0=8192,xp=18,v0=1062,S0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function x0(e){return{n:ue(e[1],"base64url"),e:ue(e[2],"base64url"),d:ue(e[3],"base64url"),p:ue(e[4],"base64url"),q:ue(e[5],"base64url"),dp:ue(e[6],"base64url"),dq:ue(e[7],"base64url"),qi:ue(e[8],"base64url"),kty:"RSA"}}function E0(e){if(e.n==null||e.e==null||e.d==null||e.p==null||e.q==null||e.dp==null||e.dq==null||e.qi==null)throw new xt("JWK was missing components");return Gt([ct(Uint8Array.from([0])),ct(Le(e.n,"base64url")),ct(Le(e.e,"base64url")),ct(Le(e.d,"base64url")),ct(Le(e.p,"base64url")),ct(Le(e.q,"base64url")),ct(Le(e.dp,"base64url")),ct(Le(e.dq,"base64url")),ct(Le(e.qi,"base64url"))]).subarray()}function A0(e){const t=Or(e[1],{offset:0});return{kty:"RSA",n:ue(t[0],"base64url"),e:ue(t[1],"base64url")}}function Ep(e){if(e.n==null||e.e==null)throw new xt("JWK was missing components");return Gt([S0,Sl(Gt([ct(Le(e.n,"base64url")),ct(Le(e.e,"base64url"))]))]).subarray()}function C0(e){const t=Or(e);return k0(t)}function k0(e){const t=x0(e);return T0(t)}function I0(e,t){if(e.byteLength>=v0)throw new xh("Key size is too large");const n=Or(e,{offset:0});return R0(n,e,t)}function R0(e,t,n){const r=A0(e);if(n==null){const o=vp(Fn.encode({Type:Ce.RSA,Data:t}));n=jo(xp,o)}return new Sp(r,n)}function T0(e){if(B0(e)>b0)throw new xt("Key size is too large");const t=P0(e),n=vp(Fn.encode({Type:Ce.RSA,Data:Ep(t.publicKey)})),r=jo(xp,n);return new y0(t.privateKey,new Sp(t.publicKey,r))}function P0(e){if(e==null)throw new xt("Missing key parameter");return{privateKey:e,publicKey:{kty:e.kty,n:e.n,e:e.e}}}async function N0(e,t,n){const r=await Jt.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);n?.signal?.throwIfAborted();const o=await Jt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function L0(e,t,n,r){const o=await Jt.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const i=await Jt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,n instanceof Uint8Array?n:n.subarray());return r?.signal?.throwIfAborted(),i}function B0(e){if(e.kty!=="RSA")throw new xt("invalid key type");if(e.n==null)throw new xt("invalid key modulus");return Le(e.n,"base64url").length*8}class Ap extends Hh{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,jh(t);const r=xl(n);if(this.iHash=t.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,i=new Uint8Array(o);i.set(r.length>o?t.create().update(r).digest():r);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=t.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),kr(i)}update(t){return ji(this),this.iHash.update(t),this}digestInto(t){ji(this),Hn(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Cp=(e,t,n)=>new Ap(e,t).update(n).digest();Cp.create=(e,t)=>new Ap(e,t);const iu=(e,t)=>(e+(e>=0?t:-t)/kp)/t;function D0(e,t,n){const[[r,o],[i,s]]=t,a=iu(s*e,n),c=iu(-o*e,n);let l=e-a*r-c*i,d=-a*o-c*s;const u=l<zt,f=d<zt;u&&(l=-l),f&&(d=-d);const h=qo(Math.ceil(Gh(n)/2))+gr;if(l<zt||l>=h||d<zt||d>=h)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:u,k1:l,k2neg:f,k2:d}}function vc(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function aa(e,t){const n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return On(n.lowS,"lowS"),On(n.prehash,"prehash"),n.format!==void 0&&vc(n.format),n}class _0 extends Error{constructor(t=""){super(t)}}const qt={Err:_0,_tlv:{encode:(e,t)=>{const{Err:n}=qt;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length&1)throw new n("tlv.encode: unpadded data");const r=t.length/2,o=Qo(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?Qo(o.length/2|128):"";return Qo(e)+i+o+t},decode(e,t){const{Err:n}=qt;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const o=t[r++],i=!!(o&128);let s=0;if(!i)s=o;else{const c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const l=t.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const d of l)s=s<<8|d;if(r+=c,s<128)throw new n("tlv.decode(long): not minimal encoding")}const a=t.subarray(r,r+s);if(a.length!==s)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+s)}}},_int:{encode(e){const{Err:t}=qt;if(e<zt)throw new t("integer: negative integers are not allowed");let n=Qo(e);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=qt;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Cs(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=qt,o=Ie("signature",e),{v:i,l:s}=r.decode(48,o);if(s.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,i),{v:l,l:d}=r.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(e){const{_tlv:t,_int:n}=qt,r=t.encode(2,n.encode(e.r)),o=t.encode(2,n.encode(e.s)),i=r+o;return t.encode(48,i)}},zt=BigInt(0),gr=BigInt(1),kp=BigInt(2),ni=BigInt(3),O0=BigInt(4);function ar(e,t){const{BYTES:n}=e;let r;if(typeof t=="bigint")r=t;else{let o=Ie("private key",t);try{r=e.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function F0(e,t={}){const n=dp("weierstrass",e,t),{Fp:r,Fn:o}=n;let i=n.CURVE;const{h:s,n:a}=i;Ko(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Rp(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(L,I,P){const{x:B,y:D}=I.toAffine(),F=r.toBytes(B);if(On(P,"isCompressed"),P){d();const j=!r.isOdd(D);return Lt(Ip(j),F)}else return Lt(Uint8Array.of(4),F,r.toBytes(D))}function f(L){vt(L,void 0,"Point");const{publicKey:I,publicKeyUncompressed:P}=l,B=L.length,D=L[0],F=L.subarray(1);if(B===I&&(D===2||D===3)){const j=r.fromBytes(F);if(!r.isValid(j))throw new Error("bad point: is not on curve, wrong x");const M=m(j);let U;try{U=r.sqrt(M)}catch(H){const V=H instanceof Error?": "+H.message:"";throw new Error("bad point: is not on curve, sqrt error"+V)}d();const _=r.isOdd(U);return(D&1)===1!==_&&(U=r.neg(U)),{x:j,y:U}}else if(B===P&&D===4){const j=r.BYTES,M=r.fromBytes(F.subarray(0,j)),U=r.fromBytes(F.subarray(j,j*2));if(!v(M,U))throw new Error("bad point: is not on curve");return{x:M,y:U}}else throw new Error(`bad point: got length ${B}, expected compressed=${I} or uncompressed=${P}`)}const h=t.toBytes||u,g=t.fromBytes||f;function m(L){const I=r.sqr(L),P=r.mul(I,L);return r.add(r.add(P,r.mul(L,i.a)),i.b)}function v(L,I){const P=r.sqr(I),B=m(L);return r.eql(P,B)}if(!v(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const w=r.mul(r.pow(i.a,ni),O0),S=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(w,S)))throw new Error("bad curve params: a or b");function y(L,I,P=!1){if(!r.isValid(I)||P&&r.is0(I))throw new Error(`bad point coordinate ${L}`);return I}function A(L){if(!(L instanceof b))throw new Error("ProjectivePoint expected")}function R(L){if(!c||!c.basises)throw new Error("no endo");return D0(L,c.basises,o.ORDER)}const E=Hi((L,I)=>{const{X:P,Y:B,Z:D}=L;if(r.eql(D,r.ONE))return{x:P,y:B};const F=L.is0();I==null&&(I=F?r.ONE:r.inv(D));const j=r.mul(P,I),M=r.mul(B,I),U=r.mul(D,I);if(F)return{x:r.ZERO,y:r.ZERO};if(!r.eql(U,r.ONE))throw new Error("invZ was invalid");return{x:j,y:M}}),C=Hi(L=>{if(L.is0()){if(t.allowInfinityPoint&&!r.is0(L.Y))return;throw new Error("bad point: ZERO")}const{x:I,y:P}=L.toAffine();if(!r.isValid(I)||!r.isValid(P))throw new Error("bad point: x or y not field elements");if(!v(I,P))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function k(L,I,P,B,D){return P=new b(r.mul(P.X,L),P.Y,P.Z),I=$i(B,I),P=$i(D,P),I.add(P)}class b{constructor(I,P,B){this.X=y("x",I),this.Y=y("y",P,!0),this.Z=y("z",B),Object.freeze(this)}static CURVE(){return i}static fromAffine(I){const{x:P,y:B}=I||{};if(!I||!r.isValid(P)||!r.isValid(B))throw new Error("invalid affine point");if(I instanceof b)throw new Error("projective point not allowed");return r.is0(P)&&r.is0(B)?b.ZERO:new b(P,B,r.ONE)}static fromBytes(I){const P=b.fromAffine(g(vt(I,void 0,"point")));return P.assertValidity(),P}static fromHex(I){return b.fromBytes(Ie("pointHex",I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,P=!0){return T.createCache(this,I),P||this.multiply(ni),this}assertValidity(){C(this)}hasEvenY(){const{y:I}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(I)}equals(I){A(I);const{X:P,Y:B,Z:D}=this,{X:F,Y:j,Z:M}=I,U=r.eql(r.mul(P,M),r.mul(F,D)),_=r.eql(r.mul(B,M),r.mul(j,D));return U&&_}negate(){return new b(this.X,r.neg(this.Y),this.Z)}double(){const{a:I,b:P}=i,B=r.mul(P,ni),{X:D,Y:F,Z:j}=this;let M=r.ZERO,U=r.ZERO,_=r.ZERO,O=r.mul(D,D),H=r.mul(F,F),V=r.mul(j,j),z=r.mul(D,F);return z=r.add(z,z),_=r.mul(D,j),_=r.add(_,_),M=r.mul(I,_),U=r.mul(B,V),U=r.add(M,U),M=r.sub(H,U),U=r.add(H,U),U=r.mul(M,U),M=r.mul(z,M),_=r.mul(B,_),V=r.mul(I,V),z=r.sub(O,V),z=r.mul(I,z),z=r.add(z,_),_=r.add(O,O),O=r.add(_,O),O=r.add(O,V),O=r.mul(O,z),U=r.add(U,O),V=r.mul(F,j),V=r.add(V,V),O=r.mul(V,z),M=r.sub(M,O),_=r.mul(V,H),_=r.add(_,_),_=r.add(_,_),new b(M,U,_)}add(I){A(I);const{X:P,Y:B,Z:D}=this,{X:F,Y:j,Z:M}=I;let U=r.ZERO,_=r.ZERO,O=r.ZERO;const H=i.a,V=r.mul(i.b,ni);let z=r.mul(P,F),W=r.mul(B,j),X=r.mul(D,M),G=r.add(P,B),Y=r.add(F,j);G=r.mul(G,Y),Y=r.add(z,W),G=r.sub(G,Y),Y=r.add(P,D);let ie=r.add(F,M);return Y=r.mul(Y,ie),ie=r.add(z,X),Y=r.sub(Y,ie),ie=r.add(B,D),U=r.add(j,M),ie=r.mul(ie,U),U=r.add(W,X),ie=r.sub(ie,U),O=r.mul(H,Y),U=r.mul(V,X),O=r.add(U,O),U=r.sub(W,O),O=r.add(W,O),_=r.mul(U,O),W=r.add(z,z),W=r.add(W,z),X=r.mul(H,X),Y=r.mul(V,Y),W=r.add(W,X),X=r.sub(z,X),X=r.mul(H,X),Y=r.add(Y,X),z=r.mul(W,Y),_=r.add(_,z),z=r.mul(ie,Y),U=r.mul(G,U),U=r.sub(U,z),z=r.mul(G,W),O=r.mul(ie,O),O=r.add(O,z),new b(U,_,O)}subtract(I){return this.add(I.negate())}is0(){return this.equals(b.ZERO)}multiply(I){const{endo:P}=t;if(!o.isValidNot0(I))throw new Error("invalid scalar: out of range");let B,D;const F=j=>T.cached(this,j,M=>Cn(b,M));if(P){const{k1neg:j,k1:M,k2neg:U,k2:_}=R(I),{p:O,f:H}=F(M),{p:V,f:z}=F(_);D=H.add(z),B=k(P.beta,O,V,j,U)}else{const{p:j,f:M}=F(I);B=j,D=M}return Cn(b,[B,D])[0]}multiplyUnsafe(I){const{endo:P}=t,B=this;if(!o.isValid(I))throw new Error("invalid scalar: out of range");if(I===zt||B.is0())return b.ZERO;if(I===gr)return B;if(T.hasCache(this))return this.multiply(I);if(P){const{k1neg:D,k1:F,k2neg:j,k2:M}=R(I),{p1:U,p2:_}=yv(b,B,F,M);return k(P.beta,U,_,D,j)}else return T.unsafe(B,I)}multiplyAndAddUnsafe(I,P,B){const D=this.multiplyUnsafe(P).add(I.multiplyUnsafe(B));return D.is0()?void 0:D}toAffine(I){return E(this,I)}isTorsionFree(){const{isTorsionFree:I}=t;return s===gr?!0:I?I(b,this):T.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:I}=t;return s===gr?this:I?I(b,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(I=!0){return On(I,"isCompressed"),this.assertValidity(),h(b,this,I)}toHex(I=!0){return Tn(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(I=!0){return this.toBytes(I)}_setWindowSize(I){this.precompute(I)}static normalizeZ(I){return Cn(b,I)}static msm(I,P){return lp(b,o,I,P)}static fromPrivateKey(I){return b.BASE.multiply(ar(o,I))}}b.BASE=new b(i.Gx,i.Gy,r.ONE),b.ZERO=new b(r.ZERO,r.ONE,r.ZERO),b.Fp=r,b.Fn=o;const x=o.BITS,T=new cp(b,t.endo?Math.ceil(x/2):x);return b.BASE.precompute(8),b}function Ip(e){return Uint8Array.of(e?2:3)}function Rp(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function M0(e,t={}){const{Fn:n}=e,r=t.randomBytes||El,o=Object.assign(Rp(e.Fp,n),{seed:ip(n.ORDER)});function i(h){try{return!!ar(n,h)}catch{return!1}}function s(h,g){const{publicKey:m,publicKeyUncompressed:v}=o;try{const w=h.length;return g===!0&&w!==m||g===!1&&w!==v?!1:!!e.fromBytes(h)}catch{return!1}}function a(h=r(o.seed)){return gv(vt(h,o.seed,"seed"),n.ORDER)}function c(h,g=!0){return e.BASE.multiply(ar(n,h)).toBytes(g)}function l(h){const g=a(h);return{secretKey:g,publicKey:c(g)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof e)return!0;const{secretKey:g,publicKey:m,publicKeyUncompressed:v}=o;if(n.allowedLengths||g===m)return;const w=Ie("key",h).length;return w===m||w===v}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 v=ar(n,h);return e.fromHex(g).multiply(v).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:e,utils:{isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:h=>ar(n,h),precompute(h=8,g=e.BASE){return g.precompute(h,!1)}},lengths:o})}function j0(e,t,n={}){jh(t),Ko(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||El,o=n.hmac||((P,...B)=>Cp(t,P,Lt(...B))),{Fp:i,Fn:s}=e,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h}=M0(e,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function v(P){const B=a>>gr;return P>B}function w(P,B){if(!s.isValidNot0(B))throw new Error(`invalid signature ${P}: out of range 1..Point.Fn.ORDER`);return B}function S(P,B){vc(B);const D=h.signature,F=B==="compact"?D:B==="recovered"?D+1:void 0;return vt(P,F,`${B} signature`)}class y{constructor(B,D,F){this.r=w("r",B),this.s=w("s",D),F!=null&&(this.recovery=F),Object.freeze(this)}static fromBytes(B,D=m){S(B,D);let F;if(D==="der"){const{r:_,s:O}=qt.toSig(vt(B));return new y(_,O)}D==="recovered"&&(F=B[0],D="compact",B=B.subarray(1));const j=s.BYTES,M=B.subarray(0,j),U=B.subarray(j,j*2);return new y(s.fromBytes(M),s.fromBytes(U),F)}static fromHex(B,D){return this.fromBytes(Ui(B),D)}addRecoveryBit(B){return new y(this.r,this.s,B)}recoverPublicKey(B){const D=i.ORDER,{r:F,s:j,recovery:M}=this;if(M==null||![0,1,2,3].includes(M))throw new Error("recovery id invalid");if(a*kp<D&&M>1)throw new Error("recovery id is ambiguous for h>1 curve");const _=M===2||M===3?F+a:F;if(!i.isValid(_))throw new Error("recovery id 2 or 3 invalid");const O=i.toBytes(_),H=e.fromBytes(Lt(Ip((M&1)===0),O)),V=s.inv(_),z=R(Ie("msgHash",B)),W=s.create(-z*V),X=s.create(j*V),G=e.BASE.multiplyUnsafe(W).add(H.multiplyUnsafe(X));if(G.is0())throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return v(this.s)}toBytes(B=m){if(vc(B),B==="der")return Ui(qt.hexFromSig(this));const D=s.toBytes(this.r),F=s.toBytes(this.s);if(B==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Lt(Uint8Array.of(this.recovery),D,F)}return Lt(D,F)}toHex(B){return Tn(this.toBytes(B))}assertValidity(){}static fromCompact(B){return y.fromBytes(Ie("sig",B),"compact")}static fromDER(B){return y.fromBytes(Ie("sig",B),"der")}normalizeS(){return this.hasHighS()?new y(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Tn(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Tn(this.toBytes("compact"))}}const A=n.bits2int||function(B){if(B.length>8192)throw new Error("input is too large");const D=Cs(B),F=B.length*8-c;return F>0?D>>BigInt(F):D},R=n.bits2int_modN||function(B){return s.create(A(B))},E=qo(c);function C(P){return gc("num < 2^"+c,P,zt,E),s.toBytes(P)}function k(P,B){return vt(P,void 0,"message"),B?vt(t(P),void 0,"prehashed message"):P}function b(P,B,D){if(["recovered","canonical"].some(W=>W in D))throw new Error("sign() legacy options not supported");const{lowS:F,prehash:j,extraEntropy:M}=aa(D,g);P=k(P,j);const U=R(P),_=ar(s,B),O=[C(_),C(U)];if(M!=null&&M!==!1){const W=M===!0?r(h.secretKey):M;O.push(Ie("extraEntropy",W))}const H=Lt(...O),V=U;function z(W){const X=A(W);if(!s.isValidNot0(X))return;const G=s.inv(X),Y=e.BASE.multiply(X).toAffine(),ie=s.create(Y.x);if(ie===zt)return;const se=s.create(G*s.create(V+ie*_));if(se===zt)return;let K=(Y.x===ie?0:2)|Number(Y.y&gr),ne=se;return F&&v(se)&&(ne=s.neg(se),K^=1),new y(ie,ne,K)}return{seed:H,k2sig:z}}function x(P,B,D={}){P=Ie("message",P);const{seed:F,k2sig:j}=b(P,B,D);return iv(t.outputLen,s.BYTES,o)(F,j)}function T(P){let B;const D=typeof P=="string"||$o(P),F=!D&&P!==null&&typeof P=="object"&&typeof P.r=="bigint"&&typeof P.s=="bigint";if(!D&&!F)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(F)B=new y(P.r,P.s);else if(D){try{B=y.fromBytes(Ie("sig",P),"der")}catch(j){if(!(j instanceof qt.Err))throw j}if(!B)try{B=y.fromBytes(Ie("sig",P),"compact")}catch{return!1}}return B||!1}function L(P,B,D,F={}){const{lowS:j,prehash:M,format:U}=aa(F,g);if(D=Ie("publicKey",D),B=k(Ie("message",B),M),"strict"in F)throw new Error("options.strict was renamed to lowS");const _=U===void 0?T(P):y.fromBytes(Ie("sig",P),U);if(_===!1)return!1;try{const O=e.fromBytes(D);if(j&&_.hasHighS())return!1;const{r:H,s:V}=_,z=R(B),W=s.inv(V),X=s.create(z*W),G=s.create(H*W),Y=e.BASE.multiplyUnsafe(X).add(O.multiplyUnsafe(G));return Y.is0()?!1:s.create(Y.x)===H}catch{return!1}}function I(P,B,D={}){const{prehash:F}=aa(D,g);return B=k(B,F),y.fromBytes(P,"recovered").recoverPublicKey(B).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h,Point:e,sign:x,verify:L,recoverPublicKey:I,Signature:y,hash:t})}function U0(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp;let r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0;const o=$n(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),i={Fp:n,Fn:o,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:i}}function H0(e){const{CURVE:t,curveOpts:n}=U0(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function $0(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,rp(n.Fn.ORDER,n.Fn.BITS))})}function q0(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:o}=H0(e),i=F0(t,n),s=j0(i,r,o);return $0(e,s)}function K0(e,t){const n=r=>q0({...e,hash:r});return{...n(t),create:n}}const Dl={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},z0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},su=BigInt(2);function V0(e){const t=Dl.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,d=l*l*e%t,u=ke(d,n,t)*d%t,f=ke(u,n,t)*d%t,h=ke(f,su,t)*l%t,g=ke(h,o,t)*h%t,m=ke(g,i,t)*g%t,v=ke(m,a,t)*m%t,w=ke(v,c,t)*v%t,S=ke(w,a,t)*m%t,y=ke(S,n,t)*d%t,A=ke(y,s,t)*g%t,R=ke(A,r,t)*l%t,E=ke(R,su,t);if(!Sc.eql(Sc.sqr(E),e))throw new Error("Cannot find square root");return E}const Sc=$n(Dl.p,{sqrt:V0}),mn=K0({...Dl,Fp:Sc,lowS:!0,endo:z0},zh);function W0(e,t,n){const r=vl.digest(t instanceof Uint8Array?t:t.subarray());if(ks(r))return r.then(({digest:o})=>(n?.signal?.throwIfAborted(),mn.sign(o,e).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new tu(String(o))});try{return mn.sign(r.digest,e).toDERRawBytes()}catch(o){throw new tu(String(o))}}function G0(e,t,n,r){const o=vl.digest(n instanceof Uint8Array?n:n.subarray());if(ks(o))return o.then(({digest:i})=>(r?.signal?.throwIfAborted(),mn.verify(t,i,e))).catch(i=>{throw i.name==="AbortError"?i:new nu(String(i))});try{return r?.signal?.throwIfAborted(),mn.verify(t,o.digest,e)}catch(i){throw new nu(String(i))}}class Tp{type="secp256k1";raw;_key;constructor(t){this._key=Q0(t),this.raw=Z0(this._key)}toMultihash(){return Uo.digest(Ps(this))}toCID(){return Ae.createV1(114,this.toMultihash())}toString(){return Ze.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,n,r){return G0(this._key,n,t,r)}}class X0{type="secp256k1";raw;publicKey;constructor(t,n){this.raw=J0(t),this.publicKey=new Tp(n??eS(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}sign(t,n){return W0(this.raw,t,n)}}function Y0(e){return new X0(e)}function Pp(e){return new Tp(e)}function Z0(e){return mn.ProjectivePoint.fromHex(e).toRawBytes(!0)}function J0(e){try{return mn.getPublicKey(e,!0),e}catch(t){throw new Eh(String(t))}}function Q0(e){try{return mn.ProjectivePoint.fromHex(e),e}catch(t){throw new xh(String(t))}}function eS(e){try{return mn.getPublicKey(e,!0)}catch(t){throw new Eh(String(t))}}async function tS(e,t){return Kv()}function xc(e,t){const{Type:n,Data:r}=Fn.decode(e),o=r??new Uint8Array;switch(n){case Ce.RSA:return I0(o,t);case Ce.Ed25519:return pp(o);case Ce.secp256k1:return Pp(o);case Ce.ECDSA:return Fh(o);default:throw new Ss}}function nS(e){const{Type:t,Data:n}=Fn.decode(e.digest),r=n??new Uint8Array;switch(t){case Ce.Ed25519:return pp(r);case Ce.secp256k1:return Pp(r);case Ce.ECDSA:return Fh(r);default:throw new Ss}}function Ps(e){return Fn.encode({Type:Ce[e.type],Data:e.raw})}function rS(e){const t=Vi.decode(e),n=t.Data??new Uint8Array;switch(t.Type){case Ce.RSA:return C0(n);case Ce.Ed25519:return qv(n);case Ce.secp256k1:return Y0(n);case Ce.ECDSA:return Bb(n);default:throw new Ss}}function oS(e){return Vi.encode({Type:Ce[e.type],Data:e.raw})}const Np=Symbol.for("nodejs.util.inspect.custom"),iS=114;class _l{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ah]=!0;toString(){return this.string==null&&(this.string=Ze.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Ae.createV1(iS,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Et(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Et(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Np](){return`PeerId(${this.toString()})`}}class Lp extends _l{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}}class Bp extends _l{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}}class Dp extends _l{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}}const sS=2336;class _p{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Uo.digest(Le(this.url))}[Np](){return`PeerId(${this.url})`}[Ah]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Ae.createV1(sS,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=ue(t)),t.toString()===this.toString())}}const aS=114,au=2336;function cS(e,t){let n;if(e.charAt(0)==="1"||e.charAt(0)==="Q")n=Ih(Ze.decode(`z${e}`));else{if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return lS(Ae.parse(e));throw new xt('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return Op(n)}function Rr(e){if(e.type==="Ed25519")return new Bp({multihash:e.toCID().multihash,publicKey:e});if(e.type==="secp256k1")return new Dp({multihash:e.toCID().multihash,publicKey:e});if(e.type==="RSA")return new Lp({multihash:e.toCID().multihash,publicKey:e});throw new Ss}function Op(e){if(uS(e))return new Lp({multihash:e});if(dS(e))try{const t=nS(e);if(t.type==="Ed25519")return new Bp({multihash:e,publicKey:t});if(t.type==="secp256k1")return new Dp({multihash:e,publicKey:t})}catch{const n=ue(e.digest);return new _p(new URL(n))}throw new zw("Supplied PeerID Multihash is invalid")}function lS(e){if(e?.multihash==null||e.version==null||e.version===1&&e.code!==aS&&e.code!==au)throw new Kw("Supplied PeerID CID is invalid");if(e.code===au){const t=ue(e.multihash.digest);return new _p(new URL(t))}return Op(e.multihash)}function dS(e){return e.code===Uo.code}function uS(e){return e.code===vl.code}class Fp extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}}class fS extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}}class Vr extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}}class cu extends Error{static name="StreamBufferError";constructor(t="The stream buffer was full"){super(t),this.name="StreamBufferError"}}class hS extends Event{data;constructor(t,n){super("message",n),this.data=t}}class Ol extends Event{error;local;constructor(t,n,r){super("close",r),this.error=n,this.local=t}}class pS extends Ol{constructor(t,n){super(!0,t,n)}}class gS extends Ol{constructor(t,n){super(!1,t,n)}}const mS=e=>e/2**32|0,wS=e=>e>>>0;function yS(e,t,n,r){const o=mS(n),i=wS(n);e.setUint32(t,r?i:o,r),e.setUint32(t+4,r?o:i,r)}function Ec(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}const Ac=e=>e?`"${e}" `:"";function Qt(e,t=""){if(typeof e!="number")throw new TypeError(Ac(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Ac(t)+"expected integer >= 0, got "+e);return e}function en(e,t,n=""){if(Ec(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Qt(t,"length");const r=Ec(e),o=t!==void 0?` of length ${t}`:"",i=r?`length=${e.length}`:`type=${typeof e}`,s=Ac(n)+"expected Uint8Array"+o+", got "+i;throw r?new RangeError(s):new TypeError(s)}function Fl(e){if(typeof e!="function"||typeof e.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Qt(e.outputLen),Qt(e.blockLen),e.outputLen<1||e.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}const bS=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},lu=(e,t)=>{bS(e,t);const n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function Wi(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Mp(e,t){en(e,void 0,"output");const n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function VP(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Nn(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ca(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Tt(e,t){return e<<32-t|e>>>t}function WP(e,t){return e<<t|e>>>32-t>>>0}const vS=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function SS(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function xS(e){for(let t=0;t<e.length;t++)e[t]=SS(e[t]);return e}const GP=vS?e=>e:xS,jp=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ES=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ml(e){if(en(e),jp)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=ES[e[n]];return t}function du(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Up(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(jp)try{return Uint8Array.fromHex(e)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}const t=e.length,n=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){const s=du(e.charCodeAt(i)),a=du(e.charCodeAt(i+1));if(s===void 0||a===void 0){const c=e[i]+e[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a}return r}function AS(e){const t=globalThis;if(typeof t.scheduler?.yield=="function"){const n=t.scheduler.yield();return e&&n.catch(e),n}return new Promise(n=>t.setTimeout(n,0))}async function XP(e,t,n,r){if(Qt(e,"iters"),Qt(t,"tick"),typeof n!="function")throw new TypeError("callback must be a function");let o=Date.now();for(let i=0;i<e;i++){n(i);const s=Date.now()-o;s>=0&&s<t||(await AS(r),o=Date.now())}}function CS(e){if(typeof e!="string")throw new TypeError("string expected");const t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{Nn(t)}}function YP(e,t=""){return typeof e=="string"?CS(e):en(e,void 0,t)}function kS(e,t,n="opts"){return lu(e,"defaults"),t!==void 0&&lu(t,n),Object.assign(Object.create(null),e,t)}function IS(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=kS({},t,"info");const n=(o,i)=>e(i).update(o).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>e(o),Object.assign(n,t),Object.freeze(n)}function RS(e=32){Qt(e,"bytesLength");const t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}const TS=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function PS(e,t,n){return e&t^~e&n}function NS(e,t,n){return e&t^e&n^t&n}class LS{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,n,r,o){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(t),this.view=ca(this.buffer)}update(t){Wi(this),en(t);const{view:n,buffer:r,blockLen:o}=this,i=t.length;let s=!1;for(let a=0;a<i;){const c=Math.min(o-this.pos,i-a);if(c===o){const l=ca(t);for(;o<=i-a;a+=o)this.process(l,a);s=!0;continue}r.set(a===0&&c===i?t:t.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(n,0),this.pos=0,s=!0)}return this.length+=t.length,s&&this.roundClean(),this}digestInto(t){Wi(this),Mp(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:o,isLE:i}=this;let{pos:s}=this;n[s++]=128,n.fill(0,s),this.padOffset>o-s&&(this.process(r,0),n.fill(0)),yS(r,o-8,this.length*8,i),this.process(r,0),this.roundClean();const a=t===n?r:ca(t),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],i)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){const{buffer:n,length:r,finished:o,destroyed:i,pos:s}=this;return t.destroyed=i,t.finished=o,t.length=r,t.pos=s,s&&t.buffer.set(n),t}clone(){return this._cloneInto()}}const BS=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),DS=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]),an=new Uint32Array(64);class _S extends LS{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(t,n){super(64,t,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){const{A:t,B:n,C:r,D:o,E:i,F:s,G:a,H:c}=this;return[t,n,r,o,i,s,a,c]}set(t,n,r,o,i,s,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let u=0;u<16;u++,n+=4)an[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const f=an[u-15],h=an[u-2],g=Tt(f,7)^Tt(f,18)^f>>>3,m=Tt(h,17)^Tt(h,19)^h>>>10;an[u]=m+an[u-7]+g+an[u-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=Tt(a,6)^Tt(a,11)^Tt(a,25),h=d+f+PS(a,c,l)+DS[u]+an[u]|0,m=(Tt(r,2)^Tt(r,13)^Tt(r,22))+NS(r,o,i)|0;d=l,l=c,c=a,a=s+h|0,s=i,i=o,o=r,r=h+m|0}r=r+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,i,s,a,c,l,d)}roundClean(){Nn(an)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Nn(this.buffer)}}class OS extends _S{constructor(){super(32,BS)}}const la=IS(()=>new OS,TS(1));function Hp(e,t,n=()=>{}){if(!Array.isArray(e))throw new TypeError(`"${t}" expected array, got type=${typeof e}`);for(let r=0;r<e.length;r++)n(e[r],`${t}[${r}]`);return e}const mr=(e,t,n)=>en(e,t,n),$p=Qt;function wr(e,t="object"){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`);return e}function bo(e,t){if(typeof e!="function")throw new TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}const FS=Ml,MS=e=>Up(e),qp=Ec,Kp=e=>RS(e),Gi=BigInt(0),uu=BigInt(1),jS=e=>e?`"${e}" `:"";function Ns(e,t=""){if(typeof e!="boolean")throw new TypeError(jS(t)+"expected boolean, got type="+typeof e);return e}function US(e){if(typeof e=="bigint"){if(!Ln(e))throw new RangeError("positive bigint expected, got "+e)}else $p(e);return e}function Cc(e,t=""){if(typeof e!="number"){const n=t&&`"${t}" `;throw new TypeError(n+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){const n=t&&`"${t}" `;throw new RangeError(n+"expected safe integer, got "+e)}}function zp(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?Gi:BigInt("0x"+e)}function Vp(e){return zp(Ml(e))}function Xi(e){return zp(Ml(To(en(e)).reverse()))}function Wp(e,t){if(Qt(t),t===0)throw new Error("zero output length is invalid");e=US(e);const n=t*2,r=e.toString(16);if(r.length>n)throw new RangeError("number is too large");return Up(r.padStart(n,"0"))}function Gp(e,t){return Wp(e,t).reverse()}function To(e){return Uint8Array.from(mr(e))}function Ln(e){return typeof e=="bigint"&&Gi<=e}function Xp(e,t,n){return Ln(e)&&Ln(t)&&Ln(n)&&t<=e&&e<n}function vo(e,t,n,r){if(!Xp(t,n,r))throw new RangeError("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function HS(e){if(e<Gi)throw new Error("expected non-negative bigint, got "+e);return e===Gi?0:e.toString(2).length}const $S=e=>(Cc(e,"n"),(uu<<BigInt(e))-uu);function Yi(e,t={},n={},r="object"){wr(e,r),wr(t,"fields"),wr(n,"optFields");function o(s,a,c){const l=r==="object"?`param "${String(s)}"`:`"${r}.${String(s)}"`,d=e[s];if(!Object.hasOwn(e,s)&&(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 i=(s,a)=>Object.entries(s).forEach(([c,l])=>o(c,l,a));i(t,!1),i(n,!0)}const je=BigInt(0),Ee=BigInt(1),kn=BigInt(2),Yp=BigInt(3),jl=BigInt(4),Zp=BigInt(5),qS=BigInt(7),Jp=BigInt(8),KS=BigInt(9),zS=BigInt(15),Qp=BigInt(16),VS=BigInt("0x10000000000000000");function xe(e,t){if(t<=je)throw new Error("mod: expected positive modulus, got "+t);const n=e%t;return n>=je?n:t+n}function WS(e,t,n){if(n<=Ee)throw new Error("pow: expected modulus > 1, got "+n);if(typeof t!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof t);if(t<je)throw new Error("invalid exponent, negatives unsupported");if(t===je)return Ee;if(t===Ee)return e;let r=e%n;if(r<je&&(r+=n),t<VS){let a=Ee;for(;t>je;)t&Ee&&(a=a*r%n),r=r*r%n,t>>=Ee;return a}const o=[];for(;t>je;)o.push(Number(t&zS)),t>>=jl;const i=new Array(16);i[0]=Ee,i[1]=r;for(let a=2;a<16;a++)i[a]=i[a-1]*r%n;let s=i[o[o.length-1]];for(let a=o.length-2;a>=0;a--){s=s*s%n,s=s*s%n,s=s*s%n,s=s*s%n;const c=o[a];c!==0&&(s=s*i[c]%n)}return s}function wt(e,t,n){if(n<=Ee)throw new Error("pow2: expected modulus > 1, got "+n);if(t<je)throw new Error("pow2: expected non-negative exponent, got "+t);let r=e;for(;t-- >je;)r*=r,r%=n;return r}function fu(e,t){if(e===je)throw new Error("invert: expected non-zero number");if(t<=Ee)throw new Error("invert: expected modulus > 1, got "+t);let n=xe(e,t),r=t,o=je,i=Ee;for(;n!==je;){const a=r/n,c=r-n*a,l=o-i*a;r=n,n=c,o=i,i=l}if(r!==Ee)throw new Error("invert: does not exist");return xe(o,t)}function Ul(e,t,n){const r=e;if(!r.eql(r.sqr(t),n))throw new Error("Cannot find square root")}function Hl(e,t){if((e&Ee)===je)throw new Error(t+": expected odd modulus, got "+e)}function eg(e,t){const n=e,r=(n.ORDER+Ee)/jl,o=n.pow(t,r);return Ul(n,o,t),o}function GS(e,t){const n=e,r=(n.ORDER-Zp)/Jp,o=n.mul(t,kn),i=n.pow(o,r),s=n.mul(t,i),a=n.mul(n.mul(s,kn),i),c=n.mul(s,n.sub(a,n.ONE));return Ul(n,c,t),c}function XS(e){const t=$l(e),n=tg(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+qS)/Qp;return((a,c)=>{const l=a;let d=l.pow(c,s),u=l.mul(d,r);const f=l.mul(d,o),h=l.mul(d,i),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 v=l.eql(l.sqr(u),c),w=l.cmov(d,u,v);return Ul(l,w,c),w})}function tg(e){if(e<Yp)throw new Error("sqrt is not defined for small field");Hl(e,"tonelliShanks");let t=e-Ee,n=0;for(;t%kn===je;)t/=kn,n++;let r=kn;const o=$l(e);for(;Zi(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return eg;let i=o.pow(r,t);const s=(t+Ee)/kn;return function(c,l){const d=c;if(d.is0(l))return l;if(Zi(d,l)!==1)throw new Error("Cannot find square root");let u=n,f=d.mul(d.ONE,i),h=d.pow(l,t),g=d.pow(l,s);for(;!d.eql(h,d.ONE);){if(d.is0(h))throw new Error("Cannot find square root: probably non-prime P");let m=1,v=d.sqr(h);for(;!d.eql(v,d.ONE);)if(m++,v=d.sqr(v),m===u)throw new Error("Cannot find square root");const w=Ee<<BigInt(u-m-1),S=d.pow(f,w);u=m,f=d.sqr(S),h=d.mul(h,f),g=d.mul(g,S)}return g}}function YS(e){return Hl(e,"Fp.sqrt"),e%jl===Yp?eg:e%Jp===Zp?GS:e%Qp===KS?XS(e):tg(e)}const ZS=(e,t)=>(xe(e,t)&Ee)===Ee,JS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Po(e){if(wr(e,"field"),typeof e.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof e.ORDER);Cc(e.BYTES,"BYTES"),Cc(e.BITS,"BITS");for(const t of JS)bo(e[t],"field."+t);if(e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=Ee)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function ng(e,t,n=!1){Po(e),Hp(t,"nums"),Ns(n,"passZero");const r=e,o=new Array(t.length).fill(n?r.ZERO:void 0),i=t.reduce((a,c,l)=>r.is0(c)?a:(o[l]=a,r.mul(a,c)),r.ONE),s=r.inv(i);return t.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),s),o}function Zi(e,t){Po(e);const n=e;Hl(n.ORDER,"FpLegendre");const r=(n.ORDER-Ee)/kn,o=n.pow(t,r),i=n.eql(o,n.ONE),s=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function QS(e,t){if(t!==void 0&&$p(t),e<=je)throw new Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);const n=HS(e);if(t!==void 0&&t<n)throw new Error(`invalid n length: expected nBitLength (${t}) >= bitLen(n) (${n})`);const r=t!==void 0?t:n,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}const hu=new WeakMap;class pu{ORDER;BITS;BYTES;isLE;ZERO=je;ONE=Ee;_lengths;_mod;constructor(t,n={}){if(t<=Ee)throw new Error("invalid field: expected ORDER > 1, got "+t);let r;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:!0}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));const{nBitLength:o,nByteLength:i}=QS(t,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=i,Object.freeze(this)}create(t){return xe(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return je<=t&&t<this.ORDER}is0(t){return t===je}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&Ee)===Ee}neg(t){return xe(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){return xe(t*t,this.ORDER)}add(t,n){return xe(t+n,this.ORDER)}sub(t,n){return xe(t-n,this.ORDER)}mul(t,n){return xe(t*n,this.ORDER)}pow(t,n){return WS(t,n,this.ORDER)}div(t,n){return xe(t*fu(n,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,n){return t+n}subN(t,n){return t-n}mulN(t,n){return t*n}inv(t){return fu(t,this.ORDER)}sqrt(t){let n=hu.get(this);return n||hu.set(this,n=YS(this.ORDER)),n(this,t)}toBytes(t){return this.isLE?Gp(t,this.BYTES):Wp(t,this.BYTES)}fromBytes(t,n=!1){mr(t);const{_lengths:r,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(r){if(t.length<1||!r.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+t.length);const l=new Uint8Array(o);l.set(t,i?0:l.length-t.length),t=l}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=i?Xi(t):Vp(t);if(a&&(c=xe(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return ng(this,t,!0)}cmov(t,n,r){return Ns(r,"condition"),r?n:t}}function $l(e,t={}){return Object.freeze(pu.prototype),new pu(e,t)}const ql=BigInt(0),No=BigInt(1),ex=BigInt(4),da=16,gu=128,tx=5,mu=2**31;function Kl(e){const t=e;if(typeof t!="function")throw new TypeError('"Point" expected constructor, got type='+typeof e);bo(t.fromAffine,"Point.fromAffine"),bo(t.fromBytes,"Point.fromBytes"),bo(t.fromHex,"Point.fromHex"),wr(t.BASE,"Point.BASE"),wr(t.ZERO,"Point.ZERO"),Po(t.Fp),Po(t.Fn)}function nx(e,t){Kl(e),rg(t,e);const n=ng(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function rx(e,t,n=1){if(!Number.isSafeInteger(e)||e<n||e>t)throw new Error("invalid window size, expected ["+n+".."+t+"], got W="+e)}function ox(e,t){const n=e*(4*t+128);if(n>mu)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+mu/2**20+" MiB")}function ix(e,t){if(e!==void 0){bo(e,"randomBytes");try{const n=e(t);if(!qp(n)||n.length!==t)return}catch{return}return e}}function rg(e,t){Hp(e,"points"),e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function sx(e,t,n){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,o)=>{if(!(n===void 0?t.isValid(r):Ln(r)&&r<n))throw new Error("invalid scalar at index "+o)})}const og=new WeakMap;function ua(e){return og.get(e)||1}function ax(e,t){const n=e.double(),r=[e];for(let o=1;o<t;o++)r.push(r[o-1].add(n));return r}function cx(e,t){const n=2**t,r=n/2,o=BigInt(n-1),i=[];for(;e>ql;){let s=0;e&No&&(s=Number(e&o),s>=r&&(s-=n),e-=BigInt(s)),i.push(s),e>>=No}return i}function lx(e,t,n){const r=2**t,o=r/2,i=BigInt(r-1),s=BigInt(t),a=[];for(let c=0;c<n;c++){let l=Number(e&i);e>>=s,l>o&&(l-=r,e+=No),a.push(l)}if(e!==ql)throw new Error("invalid wnaf");return a}function dx(e,t,n){let r=0;for(const i of n)r=Math.max(r,i.length);let o=e;for(let i=r-1;i>=0;i--){i!==r-1&&(o=o.double());for(let s=0;s<n.length;s++){const a=n[s][i];if(a){const c=t[s][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}class ux{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(t,n){Kl(t),this.randomBytes=ix(n,da),this.Point=t,this.BASE=t.BASE,this.ZERO=t.ZERO,this.bits=t.Fn.BITS}buildWnafTable(t,n,r){const o=Math.ceil(r/n)+1,i=2**(n-1),s=[];let a=t;for(let c=0;c<o;c++){let l=a;for(let d=0;d<i;d++)s.push(l),l=l.add(a);a=s[s.length-1].double()}return{W:n,bits:r,windows:o,comp:s}}wnafCachedCT(t,n){const{W:r,windows:o,comp:i}=t,s=2**(r-1),a=lx(n,r,o);let c=this.ZERO,l=this.BASE;for(let d=0;d<o;d++){const u=a[d],f=d*s,h=Math.abs(u)-1;let g=i[f];for(let v=1;v<s;v++)g=v===h?i[f+v]:g;const m=g.negate();u===0?l=l.add(i[f]):c=c.add(u<0?m:g)}return{p:c,f:l}}getWnafPrecomputes(t,n,r,o){let i=this.wnafPrecomputes.get(n),s=i?.find(a=>a.W===t&&a.bits===r);return s||(s=this.buildWnafTable(n,t,r),typeof o=="function"&&(s={...s,comp:o(s.comp)}),i||(i=[],this.wnafPrecomputes.set(n,i)),i.push(s)),s}assertPoint(t){if(!(t instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof t)}validateMulInput(t,n){if(this.assertPoint(t),!Xp(n,No,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(t,n,r,o){const i=ua(t);return i===1?this.fixedWindowCT(t,n,r):this.wnafCachedCT(this.getWnafPrecomputes(i,t,r,o),n)}mulCT(t,n,r){return this.validateMulInput(t,n),this.runCT(t,n,this.bits,r)}mulCTBlinded(t,n,r){if(this.validateMulInput(t,n),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");const o=this.Point.Fn.BITS+gu,i=this.randomBytes(da);if(!qp(i)||i.length!==da)throw new Error("randomBytes returned invalid byte array");i[0]=i[0]&63|128;const s=n+Vp(i)*this.Point.Fn.ORDER;return this.runCT(t,s,o,r)}fixedWindowCT(t,n,r){const o=tx,i=1<<o,s=$S(o),a=new Array(i);a[0]=this.ZERO;for(let d=1;d<i;d++)a[d]=a[d-1].add(t);const c=Math.ceil(r/o);let l=this.ZERO;for(let d=c-1;d>=0;d--){if(d!==c-1)for(let h=0;h<o;h++)l=l.double();const u=Number(n>>BigInt(d*o)&s);let f=a[0];for(let h=1;h<i;h++)f=h===u?a[h]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(t,n){return this.randomBytes===void 0?!1:n===No?!0:t!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(t,n,r,o){return this.shouldBlind(t,r)?this.mulCTBlinded(t,n,o):this.mulCT(t,n,o)}mulUnsafe(t,n,r){if(this.assertPoint(t),!Ln(n))throw new Error("invalid scalar");const o=ua(t);if(o===1||n>=this.Point.Fn.ORDER)return fx(this.Point,[t],[n],!0);const i=this.getWnafPrecomputes(o,t,this.bits,r);return this.wnafCachedCT(i,n).p}setWindowSize(t,n){this.assertPoint(t),rx(n,this.bits);const r=Math.ceil((this.bits+gu)/n)+1;ox(r*2**(n-1),this.Point.Fp.BYTES),og.set(t,n),this.wnafPrecomputes.delete(t)}hasWindowSize(t){return ua(t)!==1}}function fx(e,t,n,r=!1){if(Kl(e),rg(t,e),Ns(r,"allowOversized"),sx(n,e.Fn,r?e.Fn.ORDER**ex:void 0),t.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const o=t.map(s=>ax(s,4)),i=n.map(s=>cx(s,4));return dx(e.ZERO,o,i)}function wu(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Po(t),t}else return $l(e,{isLE:n})}function hx(e,t,n={},r){if(r===void 0&&(r=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);Yi(n);for(const c of["p","n","h"]){const l=t[c];if(!(Ln(l)&&l!==ql))throw new Error(`CURVE.${c} must be positive bigint`)}const o=wu(t.p,n.Fp,r),i=wu(t.n,n.Fn,r),a=["Gx","Gy","a","d"];for(const c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}function px(e,t){return function(r){const o=e(r);return{secretKey:o,publicKey:t(o)}}}const ri=BigInt(0),oi=BigInt(1),ii=BigInt(2),gx=BigInt(4),yu=BigInt(8);function mx(e,t,n,r){const o=e.sqr(n),i=e.sqr(r),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function wx(e,t={}){Yi(t,{},{},"extraOpts");const n=t,r=hx("edwards",e,n,n.FpFnLE),{Fp:o,Fn:i}=r;let s=r.CURVE;const{h:a}=s;if(Zi(o,s.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Zi(o,s.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Yi(n,{},{uvRatio:"function",randomBytes:"function"});const c=n.randomBytes===void 0?Kp:n.randomBytes,l=ii<<BigInt(o.BYTES*8)-oi;function d(S){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(S)}const u=n.uvRatio===void 0?(S,y)=>{try{return{isValid:!0,value:o.sqrt(o.div(S,y))}}catch{return{isValid:!1,value:ri}}}:n.uvRatio;if(!mx(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");const f=o.eql(s.a,o.neg(o.ONE))?S=>o.neg(S):o.eql(s.a,o.ONE)?S=>S:S=>o.mul(s.a,S);function h(S,y,A=!1){const R=A?oi:ri;return vo("coordinate "+S,y,R,l),y}function g(S){if(!(S instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(s.Gx,s.Gy,o.ONE,o.mul(s.Gx,s.Gy));static ZERO=new m(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=i;X;Y;Z;T;constructor(y,A,R,E){this.X=h("x",y),this.Y=h("y",A),this.Z=h("z",R,!0),this.T=h("t",E),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof m)throw new Error("extended point not allowed");const{x:A,y:R}=y||{};return h("x",A),h("y",R),new m(A,R,o.ONE,o.mul(A,R))}static fromBytes(y,A=!1){const R=o.BYTES,{a:E,d:C}=s;y=To(mr(y,R,"point")),Ns(A,"zip215");const k=To(y),b=y[R-1];k[R-1]=b&-129;const x=Xi(k),T=A?l:o.ORDER;vo("point.y",x,ri,T);const L=o.sqr(x),I=o.sub(L,o.ONE),P=o.sub(o.mulN(C,L),E);let{isValid:B,value:D}=u(I,P);if(!B)throw new Error("bad point: invalid y coordinate");const F=d(D),j=(b&128)!==0;if(!A&&o.is0(D)&&j)throw new Error("bad point: x=0 and x_0=1");return j!==F&&(D=o.neg(D)),m.fromAffine({x:D,y:x})}static fromHex(y,A=!1){return m.fromBytes(MS(y),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=6,A=!0){return w.setWindowSize(this,y),A||this.multiply(ii),this}assertValidity(){const y=this,{a:A,d:R}=s;if(y.is0())throw new Error("bad point: ZERO");const{X:E,Y:C,Z:k,T:b}=y,x=o.sqr(E),T=o.sqr(C),L=o.sqr(k),I=o.sqr(L),P=o.mul(x,A),B=o.mul(o.add(P,T),L),D=o.add(I,o.mul(R,o.mul(x,T)));if(!o.eql(B,D))throw new Error("bad point: equation left != right (1)");const F=o.mul(E,C),j=o.mul(k,b);if(!o.eql(F,j))throw new Error("bad point: equation left != right (2)")}equals(y){g(y);const{X:A,Y:R,Z:E}=this,{X:C,Y:k,Z:b}=y,x=o.mul(A,b),T=o.mul(C,E),L=o.mul(R,b),I=o.mul(k,E);return o.eql(x,T)&&o.eql(L,I)}is0(){return this.equals(m.ZERO)}negate(){return new m(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){const{X:y,Y:A,Z:R}=this,E=o.sqr(y),C=o.sqr(A),k=o.mul(o.sqr(R),ii),b=f(E),x=o.addN(y,A),T=o.sub(o.subN(o.sqr(x),E),C),L=o.addN(b,C),I=o.subN(L,k),P=o.subN(b,C),B=o.mul(T,I),D=o.mul(L,P),F=o.mul(T,P),j=o.mul(I,L);return new m(B,D,j,F)}add(y){g(y);const{d:A}=s,{X:R,Y:E,Z:C,T:k}=this,{X:b,Y:x,Z:T,T:L}=y,I=o.mul(R,b),P=o.mul(E,x),B=o.mul(o.mulN(k,A),L),D=o.mul(C,T),F=o.sub(o.subN(o.mulN(o.addN(R,E),o.addN(b,x)),I),P),j=o.subN(D,B),M=o.addN(D,B),U=o.sub(P,f(I)),_=o.mul(F,j),O=o.mul(M,U),H=o.mul(F,U),V=o.mul(j,M);return new m(_,O,V,H)}subtract(y){return g(y),this.add(y.negate())}multiply(y){if(!i.isValidNot0(y))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");const{p:A,f:R}=w.mulSecret(this,y,a,v);return v([A,R])[0]}multiplyUnsafe(y){if(!i.isValid(y))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return y===ri?m.ZERO:this.is0()||y===oi?this:w.mulUnsafe(this,y,v)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.mulUnsafe(this,s.n).is0()}toAffine(y){const A=this;let R=y;if(R!=null&&typeof R!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof R);const{X:E,Y:C,Z:k}=A,b=A.is0();R==null&&(R=b?o.create(yu):o.inv(k));const x=o.mul(E,R),T=o.mul(C,R),L=o.mul(k,R);if(b)return{x:o.ZERO,y:o.ONE};if(!o.eql(L,o.ONE))throw new Error("invZ was invalid");return{x,y:T}}clearCofactor(){return a===oi?this:a===ii?this.double():a===gx?this.double().double():a===yu?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){const{x:y,y:A}=this.toAffine(),R=o.toBytes(A);return R[R.length-1]|=d(y)?128:0,R}toHex(){return FS(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const v=S=>nx(m,S),w=new ux(m,c);return w.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}const vn=BigInt(0),pt=BigInt(1),si=BigInt(2);function bu(e,t){return e+t-(t>>pt<<pt)}function yx(e){const t=BigInt(6)*e;return(n,r,o)=>{const i=r+o,a=((t+o-r)*n+r)%e;return{x_2:a,x_3:i-a}}}function bx(e){return Yi(e,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...e})}function vx(e){const t=bx(e),{P:n,type:r,adjustScalarBytes:o,powPminus2:i,randomBytes:s}=t,a=t.scalarMultBase,c=r==="x25519";if(!c&&r!=="x448")throw new Error("invalid type");const l=s===void 0?Kp:s,d=c?255:448,u=yx(n),f=c?32:56,h=BigInt(c?9:5),g=BigInt(c?121665:39081),m=c?si**BigInt(254):si**BigInt(447),v=c?BigInt(8)*(si**BigInt(251)-pt):BigInt(4)*(si**BigInt(445)-pt),w=m+v+pt,S=D=>xe(D,n),y=A(h);function A(D){return Gp(S(D),f)}function R(D){const F=To(mr(D,f,"uCoordinate"));return c&&(F[31]&=127),S(Xi(F))}function E(D){return Xi(o(To(mr(D,f,"scalar"))))}const C=new Set(c?[vn,pt,n-pt,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[vn,pt,n-pt]);function k(D,F){const j=R(F);if(C.has(j))throw new Error("invalid private or public key received");const M=L(j,E(D));if(M===vn)throw new Error("invalid private or public key received");return A(M)}function b(D){if(a===void 0)return k(D,y);const F=E(D);vo("scalar",F,m,w);const j=S(a(F));if(j===vn)throw new Error("invalid private or public key received");return A(j)}const x=b,T=k;function L(D,F){vo("u",D,vn,n),vo("scalar",F,m,w);const j=F,M=D;let U=pt,_=vn,O=D,H=pt;const V=j^j>>pt;for(let X=BigInt(d-1);X>=vn;X--){const G=bu(n,V>>X);({x_2:U,x_3:O}=u(G,U,O)),{x_2:_,x_3:H}=u(G,_,H);const Y=U+_,ie=S(Y*Y),se=U-_,K=S(se*se),ne=ie-K,q=O+H,Z=O-H,oe=S(Z*Y),Q=S(q*se),ee=oe+Q,te=oe-Q;O=S(ee*ee),H=S(M*S(te*te)),U=S(ie*K),_=S(ne*(ie+S(g*ne)))}const z=bu(n,j);({x_2:U,x_3:O}=u(z,U,O)),{x_2:_,x_3:H}=u(z,_,H);const W=i(_);return S(U*W)}const I={secretKey:f,publicKey:f,seed:f},P=D=>(D=D===void 0?l(f):D,mr(D,I.seed,"seed"),D),B={randomSecretKey:P};return Object.freeze(I),Object.freeze(B),Object.freeze({keygen:px(P,x),getSharedSecret:T,getPublicKey:x,scalarMult:k,scalarMultBase:b,utils:B,GuBytes:y.slice(),lengths:I})}const vu=BigInt(0),Sx=BigInt(1),Su=BigInt(2),xx=BigInt(3),Ex=BigInt(5),Ax=BigInt(8),Ls=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Cx={p:Ls,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ax,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ig(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=Ls,a=e*e%i*e%i,c=wt(a,Su,i)*a%i,l=wt(c,Sx,i)*e%i,d=wt(l,Ex,i)*l%i,u=wt(d,t,i)*d%i,f=wt(u,n,i)*u%i,h=wt(f,r,i)*f%i,g=wt(h,o,i)*h%i,m=wt(g,o,i)*h%i,v=wt(m,t,i)*d%i;return{pow_p_5_8:wt(v,Su,i)*e%i,b2:a}}function kx(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const xu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ix(e,t){const n=Ls,r=xe(t*t*t,n),o=xe(r*r*t,n),i=ig(e*o).pow_p_5_8;let s=xe(e*r*i,n);const a=xe(t*s*s,n),c=s,l=xe(s*xu,n),d=a===e,u=a===xe(-e,n),f=a===xe(-e*xu,n);return d&&(s=c),(u||f)&&(s=l),ZS(s,n)&&(s=xe(-s,n)),{isValid:d||u,value:s}}const Eu=wx(Cx,{uvRatio:Ix}),ai=(()=>{const e=Ls,t=n=>{const{pow_p_5_8:r,b2:o}=ig(n);return xe(wt(r,xx,e)*o,e)};return vx({P:e,type:"x25519",powPminus2:t,adjustScalarBytes:kx,scalarMultBase:n=>{const r=xe(n,Eu.Fn.ORDER);if(r===vu)return vu;const o=Eu.BASE.multiply(r);return xe((o.Z+o.Y)*t(xe(o.Z-o.Y,e)),e)}})})();class Au{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,n){if(Fl(t),en(n,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?t.create().update(n).digest():n);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=t.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Nn(o)}update(t){return Wi(this),this.iHash.update(t),this}digestInto(t){Wi(this),Mp(t,this),this.finished=!0;const n=t.subarray(0,this.outputLen);this.iHash.digestInto(n),this.oHash.update(n),this.oHash.digestInto(n),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});const{oHash:n,iHash:r,finished:o,destroyed:i,blockLen:s,outputLen:a,canXOF:c}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.canXOF=c,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const sg=(()=>{const e=((t,n,r)=>new Au(t,n).update(r).digest());return e.create=(t,n)=>new Au(t,n),e})();function Cu(){const e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}class ku{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){const t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}}class fa{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new ku(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){const n=this.head;this.head=n.next=new ku(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){const n=this.tail.next;this.tail.next=null,this.tail=n,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}}class Rx extends Error{type;code;constructor(t,n){super(t??"The operation was aborted"),this.type="aborted",this.code=n??"ABORT_ERR"}}function Tx(e={}){return Px(n=>{const r=n.shift();if(r==null)return{done:!0};if(r.error!=null)throw r.error;return{done:r.done===!0,value:r.value}},e)}function Px(e,t){t=t??{};let n=t.onEnd,r=new fa,o,i,s,a=Cu();const c=async()=>{try{return r.isEmpty()?s?{done:!0}:await new Promise((v,w)=>{i=S=>{i=null,r.push(S);try{v(e(r))}catch(y){w(y)}return o}}):e(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Cu()})}},l=v=>i!=null?i(v):(r.push(v),o),d=v=>(r=new fa,i!=null?i({error:v}):(r.push({error:v}),o)),u=v=>{if(s)return o;if(t?.objectMode!==!0&&v?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:v})},f=v=>s?o:(s=!0,v!=null?d(v):l({done:!0})),h=()=>(r=new fa,f(),{done:!0}),g=v=>(f(v),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:g,push:u,end:f,get readableLength(){return r.size},onEmpty:async v=>{const w=v?.signal;if(w?.throwIfAborted(),r.isEmpty())return;let S,y;w!=null&&(S=new Promise((A,R)=>{y=()=>{R(new Rx)},w.addEventListener("abort",y)}));try{await Promise.race([a.promise,S])}finally{y!=null&&w!=null&&w?.removeEventListener("abort",y)}}},n==null)return o;const m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(v){return m.throw(v),n!=null&&(n(v),n=void 0),{done:!0}},return(){return m.return(),n!=null&&(n(),n=void 0),{done:!0}},push:u,end(v){return m.end(v),n!=null&&(n(v),n=void 0),o},get readableLength(){return m.readableLength},onEmpty:v=>m.onEmpty(v)},o}class zl extends Error{name="TimeoutError";constructor(t,n){super(t,n),Error.captureStackTrace?.(this,zl)}}const Iu=e=>e.reason??new DOMException("This operation was aborted.","AbortError");function Nx(e,t){const{milliseconds:n,fallback:r,message:o,customTimers:i={setTimeout,clearTimeout},signal:s}=t;let a,c;const d=new Promise((u,f)=>{if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(s?.aborted){f(Iu(s));return}if(s&&(c=()=>{f(Iu(s))},s.addEventListener("abort",c,{once:!0})),e.then(u,f),n===Number.POSITIVE_INFINITY)return;const h=new zl;a=i.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){f(g)}return}typeof e.cancel=="function"&&e.cancel(),o===!1?u():o instanceof Error?f(o):(h.message=o??`Promise timed out after ${n} milliseconds`,f(h))},n)}).finally(()=>{d.clear(),c&&s&&s.removeEventListener("abort",c)});return d.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},d}const Lx=e=>{const t=e.addEventListener||e.on||e.addListener,n=e.removeEventListener||e.off||e.removeListener;if(!t||!n)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:n.bind(e)}};function Bx(e,t,n){let r;const o=new Promise((i,s)=>{if(n={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...n},!(n.count>=0&&(n.count===Number.POSITIVE_INFINITY||Number.isInteger(n.count))))throw new TypeError("The `count` option should be at least 0 or more");n.signal?.throwIfAborted();const a=[t].flat(),c=[],{addListener:l,removeListener:d}=Lx(e),u=async(...h)=>{const g=n.multiArgs?h:h[0];if(n.filter)try{if(!await n.filter(g))return}catch(m){r(),s(m);return}c.push(g),n.count===c.length&&(r(),i(c))},f=(...h)=>{r(),s(n.rejectionMultiArgs?h:h[0])};r=()=>{for(const h of a)d(h,u);for(const h of n.rejectionEvents)a.includes(h)||d(h,f)};for(const h of a)l(h,u);for(const h of n.rejectionEvents)a.includes(h)||l(h,f);n.signal&&n.signal.addEventListener("abort",()=>{f(n.signal.reason)},{once:!0}),n.resolveImmediately&&i(c)});if(o.cancel=r,typeof n.timeout=="number"){const i=Nx(o,{milliseconds:n.timeout});return i.cancel=()=>{r(),i.clear()},i}return o}function Dx(e,t,n){typeof n=="function"&&(n={filter:n}),n={...n,count:1,resolveImmediately:!1};const r=Bx(e,t,n),o=r.then(i=>i[0]);return o.cancel=r.cancel,o}class Ji extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class _x extends Error{static name="StreamClosedError";name="StreamClosedError"}function Ox(e){return e.reason}function ag(e,t,n){if(t==null||e==null)return e;const r=Ox;if(t.aborted)return e.catch(()=>{}),Promise.reject(r(t));let o;return Promise.race([e,new Promise((i,s)=>{o=()=>{s(r(t))},t.addEventListener("abort",o)})]).finally(()=>{o!=null&&t.removeEventListener("abort",o)})}const Fx=Math.pow(2,20)*4;class cg extends Xw{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(t){super(),this.status="open",this.log=t.log,this.direction=t.direction??"outbound",this.inactivityTimeout=t.inactivityTimeout??12e4,this.maxReadBufferLength=t.maxReadBufferLength??Fx,this.maxWriteBufferLength=t.maxWriteBufferLength,this.maxMessageSize=t.maxMessageSize,this.readBuffer=new ye,this.writeBuffer=new ye,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);const n=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",n);const r=o=>{this.onDrainPromise?.reject(o.error??new _x)};this.addEventListener("close",r)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(t){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),ag(this.onDrainPromise.promise,t?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;const t=Tx(),n=i=>{t.push(i.data)};this.addEventListener("message",n);const r=i=>{t.end(i.error)};this.addEventListener("close",r);const o=()=>{t.end()};this.addEventListener("remoteCloseWrite",o);try{yield*t}finally{this.removeEventListener("message",n),this.removeEventListener("close",r),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(t){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Vr(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",t.byteLength),this.writeBuffer.append(t),this.processSendQueue()}abort(t){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",t),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(t)}catch(n){this.log("failed to send reset to remote - %e",n)}this.dispatchEvent(new pS(t))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Vr("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 Vr("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Vr(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.append(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Vr(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.prepend(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(t){if(t.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(t),this.dispatchReadBuffer()}}addEventListener(...t){super.addEventListener.apply(this,t),t[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 t=new fS;this.dispatchEvent(new gS(t))}onTransportClosed(t){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"),t!=null?this.abort(t):(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 Ol))}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 t=!0;const n=this.writeBuffer.byteLength;let r=0;for(;this.writeBuffer.byteLength>0;){const o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){t=!1;break}const i=this.writeBuffer.sublist(0,o),s=new ye(i);this.writeBuffer.consume(i.byteLength);const a=this.sendData(i);if(t=a.canSendMore,r+=a.sentBytes,a.sentBytes!==s.byteLength&&(s.consume(a.sentBytes),this.writeBuffer.prepend(s)),!t)break}return t||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",r,n,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),t}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 t=this.readBuffer.sublist();this.readBuffer.consume(t.byteLength),this.dispatchEvent(new hS(t))}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 cu(`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 cu(`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 Mx=4194304;class Ru extends Error{static name="UnwrappedError";name="UnwrappedError"}class lg extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class jx extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class Ux extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function Hx(e){return typeof e?.closeRead=="function"}function $x(e){return typeof e?.close=="function"}function ha(e){return Hx(e)?e.remoteWriteStatus!=="writable"&&e.readBufferLength===0:$x(e)?e.status!=="open":!1}function qx(e){return e?.addEventListener!=null&&e?.removeEventListener!=null&&e?.send!=null&&e?.push!=null&&e?.log!=null}function Kx(e,t){const n=t?.maxBufferSize??Mx,r=new ye;let o,i=!1;if(!qx(e))throw new Fp("Argument should be a Stream or a Multiaddr");const s=d=>{if(r.append(d.data),r.byteLength>n){const u=r.byteLength;r.consume(r.byteLength),o?.reject(new Error(`Read buffer overflow - ${u} > ${n}`))}o?.resolve()};e.addEventListener("message",s);const a=d=>{d.error!=null?o?.reject(d.error):o?.resolve()};e.addEventListener("close",a);const c=()=>{o?.resolve()};e.addEventListener("remoteCloseWrite",c);const l={readBuffer:r,async read(d){if(i===!0)throw new Ru("Stream was unwrapped");if(ha(e)){if(d?.bytes==null)return null;if(r.byteLength<d.bytes)throw e.log.error("closed after reading %d/%d bytes",r.byteLength,d.bytes),new Ji(`Unexpected EOF - stream closed after reading ${r.byteLength}/${d.bytes} bytes`)}const u=d?.bytes??1;for(o=Promise.withResolvers();;){if(r.byteLength>=u){o.resolve();break}if(await ag(o.promise,d?.signal),ha(e)){if(r.byteLength===0&&d?.bytes==null)return null;break}o=Promise.withResolvers()}const f=d?.bytes??r.byteLength;if(r.byteLength<f){if(ha(e))throw e.log.error("closed while reading %d/%d bytes",r.byteLength,f),new Ji(`Unexpected EOF - stream closed while reading ${r.byteLength}/${f} bytes`);return l.read(d)}const h=r.sublist(0,f);return r.consume(f),h},async write(d,u){if(i===!0)throw new Ru("Stream was unwrapped");e.send(d)||await Dx(e,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return i||(i=!0,e.removeEventListener("message",s),e.removeEventListener("close",a),e.removeEventListener("remoteCloseWrite",c),r.byteLength>0&&(e.log("stream unwrapped with %d unread bytes",r.byteLength),e.push(r))),e}};return l}function Tu(e,t={}){const n=Kx(e,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=qn(t.maxDataLength));const r=t?.lengthDecoder??wp,o=t?.lengthEncoder??Yv;return{async read(s){let a=-1;const c=new ye;for(;;){const d=await n.read({...s,bytes:1});if(d==null)break;c.append(d);try{a=r(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new lg("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ux(`Message length length too long - ${c.byteLength} > ${t.maxLengthLength}`);if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new jx(`Message length too long - ${a} > ${t.maxDataLength}`);const l=await n.read({...s,bytes:a});if(l==null)throw e.log.error("tried to read %d bytes but the stream closed",a),new Ji(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw e.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Ji(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(s,a){await n.write(new ye(o(s.byteLength),s),a)},async writeV(s,a){const c=new ye(...s.flatMap(l=>[o(l.byteLength),l]));await n.write(c,a)},unwrap(){return n.unwrap()}}}const zx=1024*1024*4,Vx=1024*1024*4;class Wx{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(t={}){this.buffer=new ye,this.maxBufferSize=t.maxBufferSize??zx,this.maxDataLength=t.maxDataLength??Vx,this.lengthDecoder=t.lengthDecoder??wp,this.encodingLength=t.encodingLength??qn}*decode(t){if(this.buffer.append(t),this.buffer.byteLength>this.maxBufferSize)throw new Fp(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let n;try{n=this.lengthDecoder(this.buffer)}catch(i){if(i instanceof RangeError)break;throw i}if(n<0||n>this.maxDataLength)throw new lg("Invalid message length");const r=this.encodingLength(n),o=r+n;if(this.buffer.byteLength>=o){const i=this.buffer.sublist(r,o);this.buffer.consume(o),i.byteLength>0&&(yield i)}else break}}}var Gx={};const Lo=65535,Pu=Lo-16,zo=!!Gx?.DUMP_SESSION_KEYS,Nu=16;function kc(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}const Qi=e=>e?`"${e}" `:"";function Ic(e,t=""){if(typeof e!="boolean")throw new TypeError(Qi(t)+"expected boolean, got type="+typeof e);return e}function yr(e,t=""){if(typeof e!="number")throw new TypeError(Qi(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Qi(t)+"expected integer >= 0, got "+e);return e}function Me(e,t,n=""){if(kc(e)&&(t===void 0||e.length===t))return e;t!==void 0&&yr(t,"length");const r=kc(e),o=t!==void 0?` of length ${t}`:"",i=r?`length=${e.length}`:`type=${typeof e}`,s=Qi(n)+"expected Uint8Array"+o+", got "+i;throw r?new RangeError(s):new TypeError(s)}const Lu=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`)};function Bu(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Xx(e,t){Me(e,void 0,"output");const n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function Vt(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function gn(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Yx(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}const br=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Zx(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Jx(e){for(let t=0;t<e.length;t++)e[t]=Zx(e[t]);return e}const In=br?e=>e:Jx;function Qx(e,t){return!e.byteLength||!t.byteLength?!1:e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function eE(e,t){if(Qx(e,t)&&e.byteOffset<t.byteOffset)throw new Error("complex overlap of input and output is not supported")}function tE(e,t){return Lu(e,"defaults"),Lu(t,"opts"),Object.assign(e,t)}function nE(e,t){if(e=Me(e),t=Me(t),e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function rE(e,t,n){const r=t,o=(()=>[]),i=(a,c)=>r(c,...o(a)).update(a).digest(),s=r(new Uint8Array(e),...o(new Uint8Array(0)));return i.outputLen=s.outputLen,i.blockLen=s.blockLen,i.create=(a,...c)=>r(a,...c),i}const oE=(e,t)=>{function n(r,...o){if(Me(r,void 0,"key"),e.nonceLength!==void 0){const u=o[0];Me(u,e.varSizeNonce?void 0:e.nonceLength,"nonce")}const i=e.tagLength,s=e.nonceLength!==void 0?1:0;if(!e.withAAD){for(let u=s;u<o.length;u++)if(kc(o[u]))throw new Error("AAD not supported")}e.withAAD&&o[s]!==void 0&&Me(o[s],void 0,"AAD");const a=t(r,...o),c=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");Me(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,Me(u,void 0,"data"),c(a.encrypt.length,f),a.encrypt(u,f)},decrypt(u,f){if(Me(u,void 0,"data"),i&&u.length<i)throw new Error('"ciphertext" expected length >= tagLength='+i);return c(a.decrypt.length,f),a.decrypt(u,f)}}}return Object.assign(n,e),n};function Rc(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(Me(t,e,"output"),n&&!es(t))throw new Error("invalid output, must be aligned");return t}function iE(e,t,n){yr(e),yr(t),Ic(n);const r=new Uint8Array(16),o=Yx(r);return o.setBigUint64(0,BigInt(t),n),o.setBigUint64(8,BigInt(e),n),r}function es(e){return e.byteOffset%4===0}function ts(e){return Uint8Array.from(Me(e))}const dg=e=>Uint8Array.from(e.split(""),t=>t.charCodeAt(0)),sE=In(Vt(dg("expand 16-byte k"))),aE=In(Vt(dg("expand 32-byte k")));function fe(e,t){return e<<t|e>>>32-t}const Wr=64,cE=16,Tc=2**32-1,Du=Uint32Array.of();function lE(e,t,n,r,o,i,s,a){const c=o.length,l=new Uint8Array(Wr),d=Vt(l),u=br&&es(o)&&es(i),f=u?Vt(o):Du,h=u?Vt(i):Du;if(!br){for(let g=0;g<c;s++){if(e(t,n,r,d,s,a),In(d),s>=Tc)throw new Error("arx: counter overflow");const m=Math.min(Wr,c-g);for(let v=0,w;v<m;v++)w=g+v,i[w]=o[w]^l[v];g+=m}return}for(let g=0;g<c;s++){if(e(t,n,r,d,s,a),s>=Tc)throw new Error("arx: counter overflow");const m=Math.min(Wr,c-g);if(u&&m===Wr){const v=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,S;w<cE;w++)S=v+w,h[S]=f[S]^d[w];g+=Wr;continue}for(let v=0,w;v<m;v++)w=g+v,i[w]=o[w]^l[v];g+=m}}function dE(e,t){const{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:i,rounds:s}=tE({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return yr(o),yr(s),Ic(i),Ic(n),(a,c,l,d,u=0)=>{Me(a,void 0,"key"),Me(c,void 0,"nonce"),Me(l,void 0,"data");const f=l.length,h=d!==void 0;if(d=Rc(f,d,!1),h&&eE(l,d),yr(u),u<0||u>=Tc)throw new Error("arx: counter overflow");const g=[];let m=a.length,v,w;if(m===32)g.push(v=ts(a)),w=aE;else if(m===16&&n)v=new Uint8Array(32),v.set(a),v.set(a,16),w=sE,g.push(v);else throw Me(a,32,"arx key"),new Error("invalid key size");(!br||!es(c))&&g.push(c=ts(c));let S=Vt(v);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");const R=c.subarray(0,16);if(br)r(w,S,Vt(R),S);else{const E=In(Uint32Array.from(w));r(E,S,Vt(R),S),gn(E),In(S)}c=c.subarray(16)}else br||In(S);const y=16-o;if(y!==c.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){const R=new Uint8Array(12);R.set(c,i?0:12-c.length),c=R,g.push(c)}const A=In(Vt(c));try{return lE(e,w,S,A,l,d,u,s),d}finally{gn(...g)}}}function Ue(e,t){return e[t++]&255|(e[t++]&255)<<8}class uE{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(t){t=ts(Me(t,32,"key"));const n=Ue(t,0),r=Ue(t,2),o=Ue(t,4),i=Ue(t,6),s=Ue(t,8),a=Ue(t,10),c=Ue(t,12),l=Ue(t,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|i<<9)&8191,this.r[4]=(i>>>4|s<<12)&255,this.r[5]=s>>>1&8190,this.r[6]=(s>>>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]=Ue(t,16+2*d)}process(t,n,r=!1){const o=r?0:2048,{h:i,r:s}=this,a=s[0],c=s[1],l=s[2],d=s[3],u=s[4],f=s[5],h=s[6],g=s[7],m=s[8],v=s[9],w=Ue(t,n+0),S=Ue(t,n+2),y=Ue(t,n+4),A=Ue(t,n+6),R=Ue(t,n+8),E=Ue(t,n+10),C=Ue(t,n+12),k=Ue(t,n+14);let b=i[0]+(w&8191),x=i[1]+((w>>>13|S<<3)&8191),T=i[2]+((S>>>10|y<<6)&8191),L=i[3]+((y>>>7|A<<9)&8191),I=i[4]+((A>>>4|R<<12)&8191),P=i[5]+(R>>>1&8191),B=i[6]+((R>>>14|E<<2)&8191),D=i[7]+((E>>>11|C<<5)&8191),F=i[8]+((C>>>8|k<<8)&8191),j=i[9]+(k>>>5|o),M=0,U=M+b*a+x*(5*v)+T*(5*m)+L*(5*g)+I*(5*h);M=U>>>13,U&=8191,U+=P*(5*f)+B*(5*u)+D*(5*d)+F*(5*l)+j*(5*c),M+=U>>>13,U&=8191;let _=M+b*c+x*a+T*(5*v)+L*(5*m)+I*(5*g);M=_>>>13,_&=8191,_+=P*(5*h)+B*(5*f)+D*(5*u)+F*(5*d)+j*(5*l),M+=_>>>13,_&=8191;let O=M+b*l+x*c+T*a+L*(5*v)+I*(5*m);M=O>>>13,O&=8191,O+=P*(5*g)+B*(5*h)+D*(5*f)+F*(5*u)+j*(5*d),M+=O>>>13,O&=8191;let H=M+b*d+x*l+T*c+L*a+I*(5*v);M=H>>>13,H&=8191,H+=P*(5*m)+B*(5*g)+D*(5*h)+F*(5*f)+j*(5*u),M+=H>>>13,H&=8191;let V=M+b*u+x*d+T*l+L*c+I*a;M=V>>>13,V&=8191,V+=P*(5*v)+B*(5*m)+D*(5*g)+F*(5*h)+j*(5*f),M+=V>>>13,V&=8191;let z=M+b*f+x*u+T*d+L*l+I*c;M=z>>>13,z&=8191,z+=P*a+B*(5*v)+D*(5*m)+F*(5*g)+j*(5*h),M+=z>>>13,z&=8191;let W=M+b*h+x*f+T*u+L*d+I*l;M=W>>>13,W&=8191,W+=P*c+B*a+D*(5*v)+F*(5*m)+j*(5*g),M+=W>>>13,W&=8191;let X=M+b*g+x*h+T*f+L*u+I*d;M=X>>>13,X&=8191,X+=P*l+B*c+D*a+F*(5*v)+j*(5*m),M+=X>>>13,X&=8191;let G=M+b*m+x*g+T*h+L*f+I*u;M=G>>>13,G&=8191,G+=P*d+B*l+D*c+F*a+j*(5*v),M+=G>>>13,G&=8191;let Y=M+b*v+x*m+T*g+L*h+I*f;M=Y>>>13,Y&=8191,Y+=P*u+B*d+D*l+F*c+j*a,M+=Y>>>13,Y&=8191,M=(M<<2)+M|0,M=M+U|0,U=M&8191,M=M>>>13,_+=M,i[0]=U,i[1]=_,i[2]=O,i[3]=H,i[4]=V,i[5]=z,i[6]=W,i[7]=X,i[8]=G,i[9]=Y}finalize(){const{h:t,pad:n}=this,r=new Uint16Array(10);let o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,r[0]=t[0]+5,o=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=t[a]+o,o=r[a]>>>13,r[a]&=8191;r[9]-=8192;let i=(o^1)-1;for(let a=0;a<10;a++)r[a]&=i;i=~i;for(let a=0;a<10;a++)t[a]=t[a]&i|r[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let s=t[0]+n[0];t[0]=s&65535;for(let a=1;a<8;a++)s=(t[a]+n[a]|0)+(s>>>16)|0,t[a]=s&65535;gn(r)}update(t){Bu(this),Me(t),t=ts(t);const{buffer:n,blockLen:r}=this,o=t.length;for(let i=0;i<o;){const s=Math.min(r-this.pos,o-i);if(s===r){for(;r<=o-i;i+=r)this.process(t,i);continue}n.set(t.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,gn(this.h,this.r,this.buffer,this.pad)}digestInto(t){Bu(this),Xx(t,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:o}=this;if(o){for(n[o++]=1;o<16;o++)n[o]=0;this.process(n,0,!0)}this.finalize();let i=0;for(let s=0;s<8;s++)t[i++]=r[s]>>>0,t[i++]=r[s]>>>8}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}}const fE=rE(32,e=>new uE(e));function hE(e,t,n,r,o,i=20){let s=e[0],a=e[1],c=e[2],l=e[3],d=t[0],u=t[1],f=t[2],h=t[3],g=t[4],m=t[5],v=t[6],w=t[7],S=o,y=n[0],A=n[1],R=n[2],E=s,C=a,k=c,b=l,x=d,T=u,L=f,I=h,P=g,B=m,D=v,F=w,j=S,M=y,U=A,_=R;for(let H=0;H<i;H+=2)E=E+x|0,j=fe(j^E,16),P=P+j|0,x=fe(x^P,12),E=E+x|0,j=fe(j^E,8),P=P+j|0,x=fe(x^P,7),C=C+T|0,M=fe(M^C,16),B=B+M|0,T=fe(T^B,12),C=C+T|0,M=fe(M^C,8),B=B+M|0,T=fe(T^B,7),k=k+L|0,U=fe(U^k,16),D=D+U|0,L=fe(L^D,12),k=k+L|0,U=fe(U^k,8),D=D+U|0,L=fe(L^D,7),b=b+I|0,_=fe(_^b,16),F=F+_|0,I=fe(I^F,12),b=b+I|0,_=fe(_^b,8),F=F+_|0,I=fe(I^F,7),E=E+T|0,_=fe(_^E,16),D=D+_|0,T=fe(T^D,12),E=E+T|0,_=fe(_^E,8),D=D+_|0,T=fe(T^D,7),C=C+L|0,j=fe(j^C,16),F=F+j|0,L=fe(L^F,12),C=C+L|0,j=fe(j^C,8),F=F+j|0,L=fe(L^F,7),k=k+I|0,M=fe(M^k,16),P=P+M|0,I=fe(I^P,12),k=k+I|0,M=fe(M^k,8),P=P+M|0,I=fe(I^P,7),b=b+x|0,U=fe(U^b,16),B=B+U|0,x=fe(x^B,12),b=b+x|0,U=fe(U^b,8),B=B+U|0,x=fe(x^B,7);let O=0;r[O++]=s+E|0,r[O++]=a+C|0,r[O++]=c+k|0,r[O++]=l+b|0,r[O++]=d+x|0,r[O++]=u+T|0,r[O++]=f+L|0,r[O++]=h+I|0,r[O++]=g+P|0,r[O++]=m+B|0,r[O++]=v+D|0,r[O++]=w+F|0,r[O++]=S+j|0,r[O++]=y+M|0,r[O++]=A+U|0,r[O++]=R+_|0}const pE=dE(hE,{counterRight:!1,counterLength:4,allowShortKeys:!1}),gE=new Uint8Array(16),_u=(e,t)=>{e.update(t);const n=t.length%16;n&&e.update(gE.subarray(n))},mE=new Uint8Array(32);function Ou(e,t,n,r,o){o!==void 0&&Me(o,void 0,"AAD");const i=e(t,n,mE),s=iE(r.length,o?o.length:0,!0),a=fE.create(i);o&&_u(a,o),_u(a,r),a.update(s);const c=a.digest();return gn(i,s),c}const wE=e=>(t,n,r)=>({encrypt(i,s){const a=i.length;s=Rc(a+16,s,!1),s.set(i);const c=s.subarray(0,-16);e(t,n,c,c,1);const l=Ou(e,t,n,c,r);return s.set(l,a),gn(l),s},decrypt(i,s){s=Rc(i.length-16,s,!1);const a=i.subarray(0,-16),c=i.subarray(-16),l=Ou(e,t,n,a,r);if(!nE(c,l))throw gn(l),new Error("invalid tag");return s.set(i.subarray(0,-16)),e(t,n,s,s,1),gn(l),s}}),Fu=oE({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},wE(pE));function yE(e,t,n){return Fl(e),n===void 0&&(n=new Uint8Array(e.outputLen)),sg(e,n,t)}const Gr=Uint8Array.of(0),bE=Uint8Array.of();function vE(e,t,n,r=32,o){Fl(e),Qt(r,"length"),en(t,void 0,"prk");const i=e.outputLen;if(t.length<i)throw new Error('"prk" must be at least HashLen octets');if(r>255*i)throw new Error("Length must be <= 255*HashLen");const s=Math.ceil(r/i);if(n===void 0?n=bE:en(n,void 0,"info"),!s)return new Uint8Array;const a=new Uint8Array(s*i),{iHash:c,oHash:l}=sg.create(e,t),d=new Uint8Array(i),u=s>1?e.create():void 0;for(let h=0;h<s-1;h++){Gr[0]=h+1;const g=c._cloneInto(u);h&&g.update(d),g.update(n).update(Gr).digestInto(d),l._cloneInto(u).update(d).digestInto(d),a.set(d,i*h)}if(Gr[0]=s,s>1&&c.update(d),c.update(n).update(Gr).digestInto(d),l.update(d).digestInto(d),a.set(d,i*(s-1)),c.destroy(),l.destroy(),u?.destroy(),d!==a&&Nn(d),Nn(Gr),r===a.length)return a;const f=a.slice(0,r);return Nn(a),f}const ug={hashSHA256(e){return la(e.subarray())},getHKDF(e,t){const n=yE(la,t,e),o=vE(la,n,void 0,96),i=o.subarray(0,32),s=o.subarray(32,64),a=o.subarray(64,96);return[i,s,a]},generateX25519KeyPair(){const e=ai.utils.randomSecretKey();return{publicKey:ai.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed(e){return{publicKey:ai.getPublicKey(e),privateKey:e}},generateX25519SharedKey(e,t){return ai.getSharedSecret(e.subarray(),t.subarray())},chaCha20Poly1305Encrypt(e,t,n,r){return Fu(r,t,n).encrypt(e.subarray())},chaCha20Poly1305Decrypt(e,t,n,r,o){return Fu(r,t,n).decrypt(e.subarray(),o)}},SE=ug;function xE(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,n)=>e.generateX25519SharedKey(t.privateKey,n).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}const ns=e=>{const t=Zt(2);return t[0]=e>>8,t[1]=e,t};ns.bytes=2;const rs=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};rs.bytes=2;function EE(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function fg(e,t){!t.enabled||!zo||(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${ue(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${ue(e.privateKey,"hex")}`)):t("Missing local static keys."))}function hg(e,t){!t.enabled||!zo||(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${ue(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${ue(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function AE(e,t){!t.enabled||!zo||t(e?`REMOTE_STATIC_PUBLIC_KEY ${ue(e.subarray(),"hex")}`:"Missing remote static public key.")}function pg(e,t){!t.enabled||!zo||t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${ue(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function gg(e,t,n){!n.enabled||!zo||(n(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&ue(e.k,"hex")}`),n(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&ue(t.k,"hex")}`))}class So extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=So.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}const CE=0,kE=4294967295,IE="Cipherstate has reached maximum n, a new handshake must be performed";class RE{n;bytes;view;constructor(t=CE){this.n=t,this.bytes=nt(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>kE)throw new Error(IE)}}const vr=nt(0);class ci{k;n;crypto;constructor(t,n=void 0,r=0){this.crypto=t,this.k=n,this.n=new RE(r)}hasKey(){return!!this.k}encryptWithAd(t,n){if(!this.hasKey())return n;this.n.assertValue();const r=this.crypto.encrypt(n,this.n.getBytes(),t,this.k);return this.n.increment(),r}decryptWithAd(t,n,r){if(!this.hasKey())return n;this.n.assertValue();const o=this.crypto.decrypt(n,this.n.getBytes(),t,this.k,r);return this.n.increment(),o}}class TE{cs;ck;h;crypto;constructor(t,n){this.crypto=t;const r=Le(n,"utf-8");this.h=NE(t,r),this.ck=this.h,this.cs=new ci(t)}mixKey(t){const[n,r]=this.crypto.hkdf(this.ck,t);this.ck=n,this.cs=new ci(this.crypto,r)}mixHash(t){this.h=this.crypto.hash(new ye(this.h,t))}encryptAndHash(t){const n=this.cs.encryptWithAd(this.h,t);return this.mixHash(n),n}decryptAndHash(t){const n=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),n}split(){const[t,n]=this.crypto.hkdf(this.ck,vr);return[new ci(this.crypto,t),new ci(this.crypto,n)]}}class PE{ss;s;e;rs;re;initiator;crypto;constructor(t){const{crypto:n,protocolName:r,prologue:o,initiator:i,s,e:a,rs:c,re:l}=t;this.crypto=n,this.ss=new TE(n,r),this.ss.mixHash(o),this.initiator=i,this.s=s,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.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(t,n=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<n+32)throw new Error("message is not long enough");this.re=t.sublist(n,n+32),this.ss.mixHash(this.re)}readS(t,n=0){if(this.rs)throw new Error("remote static public key is already set");const r=32+(this.ss.cs.hasKey()?16:0);if(t.byteLength<n+r)throw new Error("message is not long enough");const o=t.sublist(n,n+r);return this.rs=this.ss.decryptAndHash(o),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class mg extends PE{writeMessageA(t){return new ye(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){const n=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new ye(n,r,this.ss.encryptAndHash(t))}writeMessageC(t){const n=this.writeS();return this.writeSE(),new ye(n,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(n){throw new So(`handshake stage 0 validation fail: ${n.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();const n=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+n))}catch(n){throw new So(`handshake stage 1 validation fail: ${n.message}`)}}readMessageC(t){try{const n=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(n))}catch(n){throw new So(`handshake stage 2 validation fail: ${n.message}`)}}}function NE(e,t){if(t.length<=32){const n=nt(32);return n.set(t),n}else return e.hash(t)}var os;(function(e){let t;e.codec=()=>(t==null&&(t=Ts((n,r,o={})=>{if(o.lengthDelimited!==!1&&r.fork(),n.webtransportCerthashes!=null)for(const i of n.webtransportCerthashes)r.uint32(10),r.bytes(i);if(n.streamMuxers!=null)for(const i of n.streamMuxers)r.uint32(18),r.string(i);o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const i={webtransportCerthashes:[],streamMuxers:[]},s=r==null?n.len:n.pos+r;for(;n.pos<s;){const a=n.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&i.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new ou('Decode error - map field "webtransportCerthashes" had too many elements');i.webtransportCerthashes.push(n.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&i.streamMuxers.length===o.limits.streamMuxers)throw new ou('Decode error - map field "streamMuxers" had too many elements');i.streamMuxers.push(n.string());break}default:{n.skipType(a&7);break}}}return i})),t),e.encode=n=>Rs(n,e.codec()),e.decode=(n,r)=>Is(n,e.codec(),r)})(os||(os={}));var is;(function(e){let t;e.codec=()=>(t==null&&(t=Ts((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.identityKey!=null&&n.identityKey.byteLength>0&&(r.uint32(10),r.bytes(n.identityKey)),n.identitySig!=null&&n.identitySig.byteLength>0&&(r.uint32(18),r.bytes(n.identitySig)),n.extensions!=null&&(r.uint32(34),os.codec().encode(n.extensions,r)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const i={identityKey:nt(0),identitySig:nt(0)},s=r==null?n.len:n.pos+r;for(;n.pos<s;){const a=n.uint32();switch(a>>>3){case 1:{i.identityKey=n.bytes();break}case 2:{i.identitySig=n.bytes();break}case 4:{i.extensions=os.codec().decode(n,n.uint32(),{limits:o.limits?.extensions});break}default:{n.skipType(a&7);break}}}return i})),t),e.encode=n=>Rs(n,e.codec()),e.decode=(n,r)=>Is(n,e.codec(),r)})(is||(is={}));async function wg(e,t,n){const r=await e.sign(bg(t));return is.encode({identityKey:Ps(e.publicKey),identitySig:r,extensions:n})}async function yg(e,t,n){try{const r=is.decode(e),o=xc(r.identityKey);if(n?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${n}`);if(!t)throw new Error("Remote static does not exist");const i=bg(t);if(!await o.verify(i,r.identitySig))throw new Error("Invalid payload signature");return r}catch(r){throw new $w(r.message)}}function bg(e){const t=Le("noise-libp2p-static-key:");return e instanceof Uint8Array?uc([t,e],t.length+e.length):(e.prepend(t),e)}class LE extends cg{stream;handshake;metrics;decoder;constructor(t,n,r){super({log:t.log,inactivityTimeout:t.inactivityTimeout,maxReadBufferLength:t.maxReadBufferLength,direction:t.direction}),this.stream=t,this.handshake=n,this.metrics=r,this.decoder=new Wx({lengthDecoder:rs,maxBufferSize:16*1024*1024,encodingLength:()=>2});const o=c=>{try{for(const l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);const i=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",i);const s=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",s);const a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(t){const n=new ye;for(let r=0;r<t.byteLength;r+=Pu){let o=r+Pu;o>t.byteLength&&(o=t.byteLength);let i;t instanceof Uint8Array?i=this.handshake.encrypt(t.subarray(r,o)):i=this.handshake.encrypt(t.sublist(r,o)),this.metrics?.encryptedPackets.increment(),n.append(ns(i.byteLength)),n.append(i)}return n}decrypt(t){const n=new ye;for(let r=0;r<t.byteLength;r+=Lo){let o=r+Lo;if(o>t.byteLength&&(o=t.byteLength),o-Nu<r)throw new Error("Invalid chunk");let i;t instanceof Uint8Array?i=t.subarray(r,o):i=t.sublist(r,o);const s=t.subarray(r,o-Nu);try{const a=this.handshake.decrypt(i,s);this.metrics?.decryptedPackets.increment(),n.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return n}close(t){return this.stream.close(t)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(t){this.stream.abort(t)}sendData(t){return{sentBytes:t.byteLength,canSendMore:this.stream.send(this.encrypt(t))}}}function Mu(e,t,n){return new LE(e,t,n)}async function BE(e,t){const{log:n,connection:r,crypto:o,privateKey:i,prologue:s,s:a,remoteIdentityKey:c,extensions:l}=e,d=await wg(i,a.publicKey,l),u=new mg({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:s,s:a});fg(u.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(u.writeMessageA(vr),t),n.trace("Stage 0 - Initiator finished sending first message."),hg(u.e,n),n.trace("Stage 1 - Initiator waiting to receive first message from responder...");const f=u.readMessageB(await r.read(t));n.trace("Stage 1 - Initiator received the message."),pg(u.re,n),AE(u.rs,n),n.trace("Initiator going to check remote's signature...");const h=await yg(f,u.rs,c);n.trace("All good with the signature!"),n.trace("Stage 2 - Initiator sending third handshake message."),await r.write(u.writeMessageC(d),t),n.trace("Stage 2 - Initiator sent message with signed payload.");const[g,m]=u.ss.split();return gg(g,m,n),{payload:h,encrypt:v=>g.encryptWithAd(vr,v),decrypt:(v,w)=>m.decryptWithAd(vr,v,w)}}async function DE(e,t){const{log:n,connection:r,crypto:o,privateKey:i,prologue:s,s:a,remoteIdentityKey:c,extensions:l}=e,d=await wg(i,a.publicKey,l),u=new mg({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:s,s:a});fg(u.s,n),n.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await r.read(t)),n.trace("Stage 0 - Responder received first message."),pg(u.re,n),n.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await r.write(u.writeMessageB(d),t),n.trace("Stage 1 - Responder sent the second handshake message with signed payload."),hg(u.e,n),n.trace("Stage 2 - Responder waiting for third handshake message...");const f=u.readMessageC(await r.read(t));n.trace("Stage 2 - Responder received the message, finished handshake.");const h=await yg(f,u.rs,c),[g,m]=u.ss.split();return gg(g,m,n),{payload:h,encrypt:v=>m.encryptWithAd(vr,v),decrypt:(v,w)=>g.decryptWithAd(vr,v,w)}}class _E{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(t,n={}){const{staticNoiseKey:r,extensions:o,crypto:i,prologueBytes:s}=n,{metrics:a}=t;this.components=t,this.log=t.logger.forComponent("libp2p:noise");const c=i??SE;this.crypto=xE(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?EE(a):void 0,r?this.staticKey=c.generateX25519KeyPairFromSeed(r):this.staticKey=c.generateX25519KeyPair(),this.prologue=s??nt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Yw]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,n){const r=t.log?.newScope("noise")??this.log,o=Tu(t,{lengthEncoder:ns,lengthDecoder:rs,maxDataLength:Lo}),i=await this.performHandshakeInitiator(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),s=xc(i.payload.identityKey);return{connection:Mu(o.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:Rr(s),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(i.payload.extensions?.streamMuxers)}}getStreamMuxer(t){if(t==null||t.length===0)return;const n=this.components.upgrader.getStreamMuxers();if(n!=null)for(const r of t){const o=n.get(r);if(o!=null)return o}if(t.length)throw new qw("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(t,n){const r=t.log?.newScope("noise")??this.log,o=Tu(t,{lengthEncoder:ns,lengthDecoder:rs,maxDataLength:Lo}),i=await this.performHandshakeResponder(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),s=xc(i.payload.identityKey);return{connection:Mu(o.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:Rr(s),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(i.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(t,n,r,o,i){let s;const a=i?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await BE({connection:t,privateKey:n,remoteIdentityKey:o,log:r.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},i),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return s}async performHandshakeResponder(t,n,r,o,i){let s;const a=i?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await DE({connection:t,privateKey:n,remoteIdentityKey:o,log:r.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},i),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return s}}function OE(e={}){return t=>new _E(t,e)}const FE="termdock-e2ee-v1",Pc=3600*1e3,ju=512*1024*1024,Nc=4*1024*1024,Si=()=>{},Bs=Object.assign(Si,{enabled:!1,error:Si,trace:Si,newScope:()=>Bs});Object.freeze(Bs);async function vg(){const e=await tS();return{privateKey:e,peerId:Rr(e.publicKey).toString()}}function ME(e){return btoa(String.fromCharCode(...oS(e.privateKey)))}function Uu(e){if(e.length>512||!/^[A-Za-z0-9+/]+={0,2}$/.test(e))throw new Error("Invalid identity encoding");const t=rS(Uint8Array.from(atob(e),n=>n.charCodeAt(0)));if(t.type!=="Ed25519")throw new Error("Only Ed25519 device identities are supported");return{privateKey:t,peerId:Rr(t.publicKey).toString()}}class Sg{constructor(t=Si){this.consumed=t}consumed;chunks=[];size=0;ended=!1;error;wake;push(t){if(this.ended)throw this.error??new Error("Byte stream closed");if(this.size+t.byteLength>Nc)throw new Error("Secure stream buffer limit exceeded");this.chunks.push(t.slice()),this.size+=t.byteLength,this.wake?.()}end(t){this.ended=!0,this.error??=t,this.wake?.()}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const t=this.chunks.shift();if(t)this.size-=t.byteLength,yield t,this.consumed();else{if(this.ended)return;await new Promise(n=>{this.wake=n})}}}}class jE extends cg{constructor(t,n){super({log:Bs,direction:n?"outbound":"inbound",maxReadBufferLength:Nc,maxWriteBufferLength:Nc}),this.duplex=t,this.finished=t.sink(this.outgoing).catch(r=>{this.abort(Tr(r))}),this.readTransport()}duplex;outgoing=new Sg(()=>this.onMuxerDrain());finished;async readTransport(){try{for await(const t of this.duplex.source)this.onData(t.slice());this.onTransportClosed()}catch(t){this.onTransportClosed(Tr(t))}}sendData(t){return this.outgoing.push(t.subarray()),{sentBytes:t.byteLength,canSendMore:!1}}sendReset(t){this.outgoing.end(t),this.duplex.close?.(t)}sendPause(){}sendResume(){}async close(){this.outgoing.end(),this.duplex.close?.(),this.onTransportClosed(),await this.finished}}function Tr(e){return e instanceof Error?e:new Error("Secure transport failed")}class UE extends Error{code="E2EE_REHANDSHAKE_REQUIRED";constructor(){super("Encrypted connection lifetime reached; establish a new handshake without replaying pending input")}}function HE(e){const t=e?.maxAgeMs??Pc,n=e?.maxBytesPerDirection??ju;if(!Number.isSafeInteger(t)||t<=0||t>Pc||!Number.isSafeInteger(n)||n<=0||n>ju)throw new Error("Encrypted connection limits cannot exceed the production maximum");return{maxAgeMs:t,maxBytesPerDirection:n}}async function $E(e){const{identity:t,duplex:n,initiator:r,targetPinnedPeerId:o,signal:i}=e,s=HE(e.limits);if(typeof Reflect.get(Promise,"withResolvers")!="function"||typeof globalThis.crypto?.getRandomValues!="function")throw new Error("End-to-end encryption requires Node.js 22+ or a modern browser with Promise.withResolvers and secure random support");if(r&&!o)throw new Error("A pinned target identity is required");const a=o?cS(o):void 0;if(a&&a.type!=="Ed25519")throw new Error("Only Ed25519 target identities are supported");if(t.peerId!==Rr(t.privateKey.publicKey).toString())throw new Error("Local identity mismatch");if(i?.aborted)throw i.reason??new Error("Connection aborted");const c=new jE(n,r),l=new AbortController,d=setTimeout(()=>{const h=new Error("Encrypted handshake timed out");l.abort(h),c.abort(h)},15e3),u=()=>{l.abort(i?.reason),c.abort(Tr(i?.reason))};i?.addEventListener("abort",u,{once:!0}),c.addEventListener("close",()=>i?.removeEventListener("abort",u),{once:!0});const f=OE({crypto:ug,prologueBytes:new TextEncoder().encode(FE)})({privateKey:t.privateKey,peerId:Rr(t.privateKey.publicKey),logger:{forComponent:()=>Bs},upgrader:{getStreamMuxers:()=>new Map}});try{const h=await(r?f.secureOutbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}):f.secureInbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}));if(h.remotePeer.type!=="Ed25519")throw new Error("Unsupported remote identity");return{authenticatedPeerId:h.remotePeer.toString(),duplex:qE(h.connection,s)}}catch(h){throw c.abort(Tr(h)),h}finally{clearTimeout(d),i?.removeEventListener("abort",u)}}function qE(e,t){const n=new Sg,r=performance.now(),o=Date.now();let i=0,s=0,a;const c=()=>(a??=new UE,n.end(a),e.abort(a),a),l=setTimeout(c,t.maxAgeMs);typeof l=="object"&&l.unref?.();const d=(f,h)=>{if(a)throw a;if(Math.max(performance.now()-r,Date.now()-o)>=t.maxAgeMs||f+h>=t.maxBytesPerDirection)throw c()};e.addEventListener("message",f=>{try{d(s,f.data.byteLength),s+=f.data.byteLength,n.push(f.data.subarray())}catch(h){e.abort(Tr(h))}}),e.addEventListener("close",f=>{clearTimeout(l),n.end(f.error)},{once:!0});let u=!1;return{source:n,async sink(f){if(u)throw new Error("Secure sink already consumed");u=!0;try{for await(const h of f)d(i,h.byteLength),i+=h.byteLength,e.send(h)||await e.onDrain()}catch(h){throw e.abort(Tr(h)),h}},close(f){f?e.abort(f):e.close()}}}const xg=1012,Eg="Encrypted transport renewed";class Vl{constructor(t=64){this.limit=t}limit;items=[];wake;ended=!1;error;tryPush(t){if(this.ended)throw new Error("Channel closed");return this.items.length>=this.limit?!1:(this.items.push(t),this.wake?.(),!0)}push(t){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(t),this.wake?.()}get size(){return this.items.length}end(t){this.ended=!0,this.error??=t,this.wake?.()}clear(){this.items.length=0}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const t=this.items.shift();if(t!==void 0){yield t;continue}if(this.ended)return;await new Promise(n=>{this.wake=n}),this.wake=void 0}}}class pa extends Error{code="PACKET_QUEUE_BACKPRESSURE";constructor(t="Record queue capacity exceeded"){super(t),this.name="PacketQueueBackpressureError"}}const xi=2*1024*1024,KE=xi*2+8,Hu=64*1024,zE=new TextEncoder,VE=new TextDecoder("utf-8",{fatal:!0});class WE{constructor(t){this.duplex=t;const n=this;this.done=t.sink((async function*(){for await(const r of n.outgoing)try{yield r.bytes}finally{n.releaseQueuedPacket(r)}})()),this.done.then(()=>this.discardPending(),r=>this.discardPending(r instanceof Error?r:new Error("Transport failed")))}duplex;outgoing=new Vl(256);outgoingBytes=0;queuedBytesById=new Map;closed=!1;get hasPendingWrites(){return this.outgoingBytes>0}queuedBytesFor(t){return this.queuedBytesById.get(t)??0}done;send(t){if(this.outgoing.size>=256)throw new pa("Record queue item limit exceeded");const n=zE.encode(JSON.stringify(t));if(n.length>xi)throw new Error("Record too large");const r=new Uint8Array(n.length+4);if(new DataView(r.buffer).setUint32(0,n.length),r.set(n,4),this.outgoingBytes+r.byteLength>4*1024*1024)throw new pa("Record queue byte budget exceeded");const o={id:t.id,bytes:r};if(!this.outgoing.tryPush(o))throw new pa("Record queue item limit exceeded");this.outgoingBytes+=r.byteLength,this.queuedBytesById.set(t.id,this.queuedBytesFor(t.id)+r.byteLength)}releaseQueuedPacket(t){this.outgoingBytes=Math.max(0,this.outgoingBytes-t.bytes.byteLength);const n=this.queuedBytesById.get(t.id);if(n===void 0)return;const r=n-t.bytes.byteLength;r>0?this.queuedBytesById.set(t.id,r):this.queuedBytesById.delete(t.id)}close(t){this.discardPending(t)}abort(t){this.discardPending(t)}discardPending(t){this.closed||(this.closed=!0,this.outgoing.clear(),this.outgoing.end(t),this.outgoingBytes=0,this.queuedBytesById.clear(),this.duplex.close?.(t))}async*read(){const t=[];let n=0,r=0,o;const i=d=>{const u=JSON.parse(VE.decode(d.subarray(4)));if(!u||typeof u!="object"||typeof u.id!="string"||typeof u.type!="string")throw new Error("Invalid record");return u},s=d=>{let u=0;for(;u<d.byteLength;){let f=t[t.length-1];(!f||f.end===f.bytes.byteLength)&&(f={bytes:o??new Uint8Array(Hu),start:0,end:0},o=void 0,t.push(f));const h=Math.min(d.byteLength-u,f.bytes.byteLength-f.end);f.bytes.set(d.subarray(u,u+h),f.end),f.end+=h,u+=h}r+=d.byteLength},a=d=>{let u=n,f=d;for(;u<t.length;){const h=t[u];if(!h){u++;continue}const g=h.end-h.start;if(f<g)return h.bytes[h.start+f];f-=g,u++}throw new Error("Incomplete record header")},c=d=>{for(r-=d;d>0;){const u=t[n];if(!u){n++;continue}const f=Math.min(d,u.end-u.start);u.start+=f,d-=f,u.start===u.end&&(!o&&u.bytes.byteLength===Hu&&(o=u.bytes),t[n]=void 0,n++)}r===0?(t.length=0,n=0,o=void 0):n>=64&&n*2>=t.length&&(t.splice(0,n),n=0)},l=d=>{const u=t[n];if(!u)throw new Error("Incomplete record body");if(u.end-u.start>=d){const v=u.bytes.subarray(u.start,u.start+d);return c(d),v}const h=new Uint8Array(d);let g=n,m=0;for(;m<d;){const v=t[g];if(!v){g++;continue}const w=Math.min(d-m,v.end-v.start);h.set(v.bytes.subarray(v.start,v.start+w),m),m+=w,g++}return c(d),h};for await(const d of this.duplex.source){if(r+d.byteLength>KE)throw new Error("Record buffer exceeded");if(r===0&&d.byteLength>=5){const u=d[0]*16777216+(d[1]<<16)+(d[2]<<8)+d[3]>>>0;if(u>xi||u===0)throw new Error("Invalid record size");if(d.byteLength===u+4){yield i(d);continue}}for(d.byteLength&&s(d);r>=4;){const u=a(0)*16777216+(a(1)<<16)+(a(2)<<8)+a(3)>>>0;if(u>xi||u===0)throw new Error("Invalid record size");if(r<u+4)break;const f=l(u+4);yield i(f)}}if(r)throw new Error("Truncated record")}}function Ag(e){let t="";for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return btoa(t)}function Cg(e){const t=atob(e);return Uint8Array.from(t,n=>n.charCodeAt(0))}function GE(e){const t=new Vl(64);e.binaryType="arraybuffer";const n=r=>{t.end(r),e.close(1e3)};return e.addEventListener("message",r=>{try{if(!(r.data instanceof ArrayBuffer)||r.data.byteLength>1024*1024)throw new Error("Invalid encrypted frame");t.push(new Uint8Array(r.data))}catch{n(new Error("Encrypted transport rejected frame"))}}),e.addEventListener("close",()=>t.end()),e.addEventListener("error",()=>t.end(new Error("Encrypted transport disconnected"))),{source:t,close:n,async sink(r){try{for await(const o of r)for(let i=0;i<o.length;i+=64*1024){const s=Date.now();for(;e.bufferedAmount>256*1024;){if(e.readyState!==1||Date.now()-s>15e3)throw new Error("Encrypted transport congested");await new Promise(a=>setTimeout(a,10))}if(e.readyState!==1)throw new Error("Encrypted transport closed");e.send(o.subarray(i,i+64*1024))}}catch(o){throw n(o instanceof Error?o:new Error("Encrypted transport failed")),o}}}}const XE=5*1024*1024,YE=bh+yh+8,ZE=256,li=3e4,Xr=64*1024;function dn(e){return e instanceof Error?e:new Error(String(e??"Secure connection closed"))}function $u(e){if(!e.startsWith("/")||e.startsWith("//")||e.includes("#"))throw new Error("A local API path is required");return e}class kg extends EventTarget{constructor(t,n,r){super(),this.url=t,this.transmit=n,this.disconnect=r}url;transmit;disconnect;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;binaryType="arraybuffer";bufferedAmount=0;protocol="termdock-e2ee-v1";extensions="";getConnectionDiagnostics;createdAt=performance.now();openedAfterMs;readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;send(t){if(this.readyState!==1)throw new Error("Secure socket is not open");if(typeof t!="string"||new TextEncoder().encode(t).length>1024*1024)throw new Error("Unsupported socket payload");this.transmit(t)}close(t=1e3,n=""){this.readyState!==3&&(this.disconnect(),this.finish(t,n))}accept(t){if(this.readyState!==3)if(t.type==="ws-ready"){this.openedAfterMs=performance.now()-this.createdAt,this.readyState=1;const n=new Event("open");this.dispatchEvent(n),this.onopen?.(n)}else if(t.type==="ws-data"&&typeof t.data=="string"){const n=new MessageEvent("message",{data:t.data});this.dispatchEvent(n),this.onmessage?.(n)}else t.type==="ws-close"?this.finish(typeof t.code=="number"?t.code:1e3,typeof t.reason=="string"?t.reason:""):t.type==="error"&&this.fail(dn(t.error))}fail(t){if(this.readyState===3)return;const n=new Event("error");this.dispatchEvent(n),this.onerror?.(n),this.finish(1006,t.message)}finish(t,n){if(this.readyState===3)return;this.readyState=3;const r=new CloseEvent("close",{code:t,reason:n,wasClean:t===1e3});this.dispatchEvent(r),this.onclose?.(r)}}class JE{constructor(t,n,r){this.channel=t,this.identity=n,this.targetPeerId=r,this.read().catch(o=>this.close(dn(o))),t.done.catch(o=>this.close(dn(o)))}channel;identity;targetPeerId;transportDiagnostics;establishedAt=performance.now();establishedWallTime=Date.now();lastInputAt=-1/0;pending=new Map;waiting=[];stopped=!1;closeReason;get canSwitchTransport(){return!this.channel.hasPendingWrites&&performance.now()-this.lastInputAt>=2e3&&![...this.pending.values()].some(t=>t.kind!=="socket")&&!this.waiting.some(t=>t.kind!=="socket")}get renewalDue(){return!this.stopped&&Math.max(performance.now()-this.establishedAt,Date.now()-this.establishedWallTime)>=Pc-5*6e4}get closed(){return this.stopped}hasCapacity(t){if(this.pending.size>=YE)return!1;const n=[...this.pending.values()].filter(r=>r.kind===t).length;return t==="http"?n<yh:t==="socket"?n<bh:!0}allocate(t){if(this.stopped)throw this.closeReason??new Error("Secure connection closed");const n=crypto.randomUUID(),r=new Vl(4);return this.pending.set(n,{queue:r,kind:t}),{id:n,queue:r}}reserve(t,n){return n?.aborted?Promise.reject(n.reason):this.stopped?Promise.reject(this.closeReason??new Error("Secure connection closed")):this.hasCapacity(t)?Promise.resolve(this.allocate(t)):this.waiting.length>=ZE?Promise.reject(new Error("连接繁忙,请稍后重试。")):new Promise((r,o)=>{const i=l=>{this.waiting=this.waiting.filter(d=>d!==c),c.cleanup(),o(l)},s=()=>i(n?.reason??new Error("Request aborted")),a=setTimeout(()=>i(new Error("连接等待超时,请重试。")),li),c={kind:t,resolve:r,reject:o,cleanup:()=>{clearTimeout(a),n?.removeEventListener("abort",s)}};this.waiting.push(c),n?.addEventListener("abort",s,{once:!0})})}dispatchWaiting(){if(!this.stopped)for(let t=0;t<this.waiting.length;){const n=this.waiting[t];if(!this.hasCapacity(n.kind)){t++;continue}this.waiting.splice(t,1),n.cleanup(),n.resolve(this.allocate(n.kind))}}async read(){try{for await(const t of this.channel.read()){const n=this.pending.get(t.id);n&&(n.socket?(n.socket.accept(t),(t.type==="ws-close"||t.type==="error")&&this.release(t.id)):(n.queue.push(t),(t.type==="end"||t.type==="error")&&(n.cancelUpload?.(),this.release(t.id))))}}finally{this.close(new Error("Secure connection closed"))}}release(t){this.pending.get(t)?.queue.end(),this.pending.delete(t),this.dispatchWaiting()}async request(t,n){const{id:r,queue:o}=await this.reserve("request"),i=setTimeout(()=>this.close(new Error("Secure connection timed out")),Math.max(1e3,Math.min(li,n?.timeoutMs??li)));try{if(this.stopped)throw this.closeReason;this.channel.send({...t,id:r});const s=(await o[Symbol.asyncIterator]().next()).value;if(!s)throw new Error("Secure request closed");if(s.type==="error")throw dn(s.error);return s}finally{clearTimeout(i),this.release(r)}}openSocket(t){$u(t);let n;const r=new AbortController,o=new kg(t,s=>{if(n){try{JSON.parse(s)?.type==="input"&&(this.lastInputAt=performance.now())}catch{}this.channel.send({id:n,type:"ws-data",data:s})}},()=>{if(r.abort(),n)try{this.channel.send({id:n,type:"ws-close"})}finally{this.release(n)}});let i;return o.getConnectionDiagnostics=()=>{const s=this.transportDiagnostics?.();return s?{...s,socketOpenMs:o.openedAfterMs,socketQueueMs:i,pendingWrites:this.channel.hasPendingWrites,activeRequests:[...this.pending.values()].filter(a=>a.kind!=="socket").length,waitingRequests:this.waiting.length}:void 0},this.reserve("socket",r.signal).then(s=>{if(i=performance.now()-o.createdAt,n=s.id,o.readyState===3){this.release(n);return}const a=this.pending.get(n);if(!a)throw new Error("Secure connection closed");a.socket=o,this.channel.send({id:n,type:"ws-open",path:t})}).catch(s=>{n&&this.release(n),o.fail(dn(s))}),o}async fetch(t,n){const r=typeof location>"u"?"https://termdock.invalid":location.origin,o=t instanceof Request?t:null,i=new URL(o?.url??String(t),r);if(i.origin!==r)throw new Error("Only current-service API requests are supported");const s=new Request(i,o?new Request(o,n):n),a=s.method.toUpperCase(),c=$u(i.pathname+i.search),l=i.pathname==="/api/terminal/fs/upload"?110*1024*1024:XE;if(s.signal.aborted)throw s.signal.reason;const d={};s.headers.forEach((A,R)=>{["cookie","authorization","host","connection","content-length"].includes(R)||(d[R]=A)});const{id:u,queue:f}=await this.reserve("http",s.signal),h=f[Symbol.asyncIterator]();let g;const m=()=>{g?.cancel().catch(()=>{})},v=this.pending.get(u);if(!v)throw new Error("Secure connection closed");v.cancelUpload=m;const w=()=>{m();try{this.channel.send({id:u,type:"cancel"})}catch{}f.end(dn(s.signal.reason??"Request aborted")),this.release(u)};s.signal.addEventListener("abort",w,{once:!0});const S=()=>{s.signal.removeEventListener("abort",w),this.release(u)},y=async()=>{let A;try{const R=(await Promise.race([h.next(),new Promise((E,C)=>{A=setTimeout(()=>C(new Error("服务响应超时,请重试。")),li)})])).value;if(!R)throw new Error("Secure response ended unexpectedly");if(R.type==="error")throw dn(R.error);return R}finally{clearTimeout(A)}};try{if(s.signal.aborted)throw s.signal.reason;if(this.channel.send({id:u,type:"http",method:a,path:c,headers:d}),s.body){const k=s.body.getReader();g=k;let b=0,x=0;try{for(;;){const{done:T,value:L}=await k.read();if(T)break;if(b+=L.byteLength,b>l)throw new Error("Request body exceeds upload limit");for(let I=0;I<L.byteLength;I+=Xr){if(this.channel.send({id:u,type:"upload",data:Ag(L.subarray(I,I+Xr))}),(await y()).type!=="upload-ack")throw new Error("Invalid upload acknowledgement");x+=Math.min(Xr,L.byteLength-I),n?.onUploadProgress?.(x)}}}catch(T){throw await k.cancel(T).catch(()=>{}),T}finally{g=void 0,k.releaseLock()}}if(s.signal.aborted||this.stopped)throw new Error("Request aborted");this.channel.send({id:u,type:"upload-end"});const A=await y();if(A.type!=="head"||typeof A.status!="number")throw new Error("Invalid response header");const R=new Headers(A.headers);if(a==="HEAD"||[204,205,304].includes(A.status)){if((await y()).type!=="end")throw new Error("Unexpected response body");return S(),new Response(null,{status:A.status,headers:R})}let E=!1;const C=new ReadableStream({pull:async k=>{try{E&&(this.channel.send({id:u,type:"ack"}),E=!1);const b=await y();if(b.type==="end"){k.close(),S();return}if(b.type!=="chunk"||typeof b.data!="string")throw new Error("Invalid response chunk");const x=Cg(b.data);if(x.length>Xr)throw new Error("Response chunk exceeds budget");k.enqueue(x),E=!0}catch(b){k.error(b),w(),S()}},cancel:()=>{w(),S()}},{highWaterMark:Xr,size:k=>k.byteLength});return new Response(C,{status:A.status,headers:R})}catch(A){throw w(),S(),A}}retire(){for(const t of this.pending.values())t.socket?.accept({id:"",type:"ws-close",code:xg,reason:Eg});this.close()}close(t=new Error("Secure connection closed")){if(!this.stopped){this.stopped=!0,this.closeReason=t;for(const n of this.waiting.splice(0))n.cleanup(),n.reject(t);for(const n of this.pending.values())n.queue.end(t),n.cancelUpload?.(),n.socket?.fail(t);this.pending.clear(),this.channel.close(t)}}}async function Mn(e){const t=new URL(e.url);if(!["wss:","ws:"].includes(t.protocol))throw new Error("A WebSocket endpoint is required");if(t.protocol==="ws:"&&!["127.0.0.1","localhost","[::1]"].includes(t.hostname))throw new Error("Remote secure channels require WSS");const n=e.identity??await vg(),r=performance.now(),o=(e.socketFactory??(l=>new WebSocket(l)))(t.href),i=GE(o),s=new AbortController,a=setTimeout(()=>s.abort(new Error("Secure handshake timed out")),2e4),c=e.signal?AbortSignal.any([e.signal,s.signal]):s.signal;try{await new Promise((m,v)=>{if(c.aborted){v(c.reason);return}const w=()=>{c.removeEventListener("abort",A),o.removeEventListener("open",S),o.removeEventListener("error",y),o.removeEventListener("close",y)},S=()=>{w(),m()},y=()=>{w(),v(new Error("Secure transport unavailable"))},A=()=>{w(),v(c.reason)};c.addEventListener("abort",A,{once:!0}),o.addEventListener("open",S),o.addEventListener("error",y),o.addEventListener("close",y),o.readyState===1&&S()});const l=performance.now(),d=await $E({identity:n,duplex:i,initiator:!0,targetPinnedPeerId:e.targetPeerId,signal:c}),u=new JE(new WE(d.duplex),n,d.authenticatedPeerId),f=performance.now(),h=Date.now(),g=o.connectionTimings;if(u.transportDiagnostics=()=>({endpoint:t.host,path:g?"relay":"direct",targetPeerId:d.authenticatedPeerId,transportOpenMs:l-r,handshakeMs:f-l,establishedAt:h,relay:g?{...g}:void 0,bufferedBytes:o.bufferedAmount,pendingWrites:!1,activeRequests:0,waitingRequests:0}),e.pairingCode)try{await u.request({type:"pair",code:e.pairingCode})}catch(m){throw u.close(dn(m)),m}return u}catch(l){throw o.close(),l}finally{clearTimeout(a)}}const qu=256*1024,QE=1024*1024;class e1 extends EventTarget{constructor(t,n,r=o=>new WebSocket(o)){if(super(),this.url=t,!/^[a-zA-Z0-9_.:-]{1,160}$/.test(n))throw new Error("Invalid target identity");const o=performance.now();let i;this.upstream=r(t),this.upstream.addEventListener("open",()=>{this.connectionTimings.entryOpenMs=performance.now()-o}),this.deadline=setTimeout(()=>this.fail("Relay connection timed out"),ml),this.upstream.addEventListener("message",s=>{if(this.readyState!==3)try{if(typeof s.data!="string"||new TextEncoder().encode(s.data).length>qu)throw new Error("Invalid relay envelope");const a=JSON.parse(s.data);if(a.type==="ready"&&!this.requested){i=performance.now(),this.requested=!0,this.transmit({type:"open",streamId:this.streamId,serviceId:n});return}if(a.streamId!==this.streamId)return;if(a.type==="opened"&&this.readyState===0){this.connectionTimings.routeOpenMs=i===void 0?null:performance.now()-i,clearTimeout(this.deadline),this.readyState=1;const u=new Event("open");this.dispatchEvent(u),this.onopen?.(u);return}if(a.type==="close"){this.finish(1001,"Relay route closed"),this.upstream.close();return}if(a.type!=="data"||this.readyState!==1||a.encoding!=="base64"||typeof a.payload!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(a.payload))throw new Error("Invalid ciphertext relay frame");const c=Cg(a.payload),l=this.binaryType==="blob"?new Blob([c]):c.buffer,d=new MessageEvent("message",{data:l});this.dispatchEvent(d),this.onmessage?.(d)}catch{this.fail("Relay protocol rejected frame")}}),this.upstream.addEventListener("close",s=>this.finish(s.code||1006,"Relay disconnected")),this.upstream.addEventListener("error",()=>this.fail("Relay transport unavailable"))}url;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;protocol="";extensions="";binaryType="arraybuffer";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;connectionTimings={entryOpenMs:null,routeOpenMs:null};upstream;streamId=crypto.randomUUID();requested=!1;deadline;get bufferedAmount(){return this.upstream.bufferedAmount}transmit(t){const n=JSON.stringify(t);if(this.upstream.readyState!==1||this.upstream.bufferedAmount+n.length>QE||n.length>qu)throw new Error("Relay unavailable or congested");this.upstream.send(n)}send(t){if(this.readyState!==1)throw new Error("Relay socket is not open");let n;if(ArrayBuffer.isView(t))n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);else if(t instanceof ArrayBuffer)n=new Uint8Array(t);else throw new Error("Relay secure transport requires binary bytes");try{this.transmit({type:"data",streamId:this.streamId,encoding:"base64",payload:Ag(n)})}catch(r){throw this.fail("Relay transport congested"),r}}close(t=1e3,n=""){if(this.readyState!==3){try{this.requested&&this.transmit({type:"close",streamId:this.streamId})}catch{}this.finish(t,n),this.upstream.close()}}fail(t){if(this.readyState===3)return;const n=new Event("error");this.dispatchEvent(n),this.onerror?.(n),this.finish(1006,t),this.upstream.close()}finish(t,n){if(this.readyState===3)return;clearTimeout(this.deadline),this.readyState=3;const r=new CloseEvent("close",{code:t,reason:n,wasClean:t===1e3});this.dispatchEvent(r),this.onclose?.(r)}}function Ig(e){return t=>new e1(t,e)}function t1(e){if(typeof e!="string"||!e.startsWith("/api/")||/[\\\x00-\x20\x7f#]/.test(e))return null;const t=e.split("?")[0];if(t.includes("//"))return null;try{const r=t.split("/").map((o,i)=>{if(i===0||o===""&&i===t.split("/").length-1)return o;const s=decodeURIComponent(o);if(!s||s==="."||s===".."||/[\\/\x00-\x1f\x7f]/.test(s)||/%[a-f0-9]{2}/i.test(s))throw new Error("Ambiguous API path");return s}).join("/");return r.endsWith("/")&&!r.startsWith("/api/terminal/fs/preview/")?null:r}catch{return null}}function n1(e){if(!("serviceWorker"in navigator))return()=>{};const t=new Set,n=r=>{if(r.source!==navigator.serviceWorker.controller||r.data?.type!=="termdock-secure-fetch"||r.ports.length!==1)return;const o=r.ports[0],{path:i,method:s,headers:a,body:c,expectedTargetPeerId:l,previewPrefix:d}=r.data;let u;try{u=new URL(i,location.origin)}catch{o.close();return}if(u.origin!==location.origin||!u.pathname.startsWith("/api/")||t.size>=32||typeof s!="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(s)||!t1(u.pathname)?.startsWith(d))){o.postMessage({type:"error"}),o.close();return}const f=new AbortController;let h,g,m=!1,v=!1;const w=()=>{v||(v=!0,t.delete(w),f.abort(),h?.cancel().catch(()=>{}),o.close())};t.add(w),o.onmessage=S=>{if(S.data?.type==="cancel"){w();return}S.data?.type!=="pull"||m||v||(m=!0,(async()=>{if(!h){o.postMessage({type:"end"}),w();return}if(!g?.length){const A=await h.read();if(A.done){o.postMessage({type:"end"}),w();return}g=A.value}const y=g.slice(0,64*1024);g=g.subarray(y.length),o.postMessage({type:"chunk",data:y.buffer},[y.buffer])})().catch(()=>{o.postMessage({type:"error"}),w()}).finally(()=>{m=!1}))},o.onmessageerror=w,o.start(),(async()=>{const S=await e();if(v)return;if(l&&l!==S.targetPeerId)throw new Error("Preview target changed");const y=await S.fetch(u.pathname+u.search,{method:s,headers:a,body:["GET","HEAD"].includes(s)?void 0:c,signal:f.signal});if(v){await y.body?.cancel();return}h=y.body?.getReader();const A={};y.headers.forEach((R,E)=>{A[E]=R}),o.postMessage({type:"head",status:y.status,headers:A,bodyless:!h,targetPeerId:S.targetPeerId})})().catch(()=>{v||(o.postMessage({type:"error"}),w())})};return navigator.serviceWorker.addEventListener("message",n),()=>{navigator.serviceWorker.removeEventListener("message",n);for(const r of[...t])r()}}class ut extends Error{constructor(){super("Device authorization expired or revoked")}}const di=new WeakMap;function Fr(e,t={}){const n=di.get(e);if(!e.closed&&n&&(!n.settled||Date.now()-n.at<(t.maxAgeMs??1e3)))return n.pending;const r={at:Date.now(),settled:!1,pending:void 0},o=r1(e,t.timeoutMs??5e3).then(i=>(r.at=Date.now(),r.settled=!0,i),i=>{throw di.get(e)===r&&di.delete(e),i});return r.pending=o,di.set(e,r),o}async function r1(e,t){const n=await e.request({type:"permissions"},{timeoutMs:t});if(n.type!=="result"||typeof n.fullService!="boolean"||!Array.isArray(n.grants))throw new Error("Invalid permission response");const r=n.grants,o=n.fullService===!0;if(!o&&r.length===0)throw new ut;return{fullService:o,grants:r,canManage:o&&r.length>0||r.some(i=>i.actions.includes("authorization.manage"))}}const Rg="termdock-secure-last-path:",o1=10*6e4;function Tg(e){try{const t=JSON.parse(sessionStorage.getItem(Rg+e)||"null");return t&&typeof t.key=="string"&&Date.now()-t.at<o1?t.key:void 0}catch{return}}function Lc(e,t){try{sessionStorage.setItem(Rg+e,JSON.stringify({key:t,at:Date.now()}))}catch{}}function Pg(e,t,n=!1){return new Promise((r,o)=>{let i=0,s=0,a=!1,c,l,d;const u=new Set,f=()=>{clearTimeout(d);for(const g of u)g.abort();u.clear()},h=()=>{if(a)return;if(i>=e.length){s||(a=!0,f(),o(l||c||new Error("没有可用的连接路线。")));return}if(s>=(n?1:2))return;const g=e[i++],m=performance.now(),v=S=>{performance.getEntriesByName("termdock:connection-path").length>64&&performance.clearMeasures("termdock:connection-path"),performance.measure("termdock:connection-path",{start:m,end:performance.now(),detail:{path:g.key.startsWith("relay:")?"relay":"direct",ok:S}})},w=new AbortController;u.add(w),s++,g.run(w.signal).then(S=>{if(v(!0),u.delete(w),a){t(S);return}a=!0,f(),r({value:S,key:g.key})},S=>{if(v(!1),u.delete(w),s--,!a){if(c=S,S instanceof Error&&S.name==="UnexpectedPeerError"&&(l=S),S instanceof ut){a=!0,f(),o(S);return}h()}}),clearTimeout(d),!n&&i<e.length&&(d=setTimeout(h,400))};h()})}const i1=3,s1=1/0,a1=10,Ng="termdock-secure-workspace-limit";function Lg(e){return e===1/0||Number.isInteger(e)&&e>=3&&e<=a1}function c1(){try{const e=localStorage.getItem(Ng),t=e==="unlimited"?1/0:Number(e);if(Lg(t))return t}catch{}return navigator.maxTouchPoints>0?i1:s1}function l1(e,t,n,r){if(e.length<=r)return e;const o=new Set(["root",t,...n?[n]:[]]),i=[...e].reverse().sort((s,a)=>a.touchedAt-s.touchedAt);for(const s of i){if(o.size>=r)break;o.add(s.key)}return e.filter(s=>o.has(s.key))}const Bg="termdock-workspace",Bo="termdock:workspace-visibility",Bc="termdock:workspace-activate";function Ds(){return window.parent!==window&&location.pathname==="/workspace.html"&&new URLSearchParams(location.search).get(Bg)||"root"}let Ku,zu;function Bt(){try{if(window.parent===window)return window.__termdockWorkspaceHost;const e=window.parent.__termdockWorkspaceHost;return e&&e!==Ku&&(Ku=e,zu={...e,subscribe(t){const n=e.subscribe(t,Ds()),r=o=>{o.persisted||n()};return window.addEventListener("pagehide",r),()=>{n(),window.removeEventListener("pagehide",r)}}}),e?zu:void 0}catch{return}}function Ei(){const e=Bt();return!e||e.snapshot().activeKey===Ds()}function ss(e,t=!0){return Bt()?.activate(e,t)??!1}function or(e){Bt()?.report(Ds(),e)}const Dc="termdock-secure-workspace-session:",Dg="termdock-secure-last-workspace";function d1(){for(const e of["sessionStorage","localStorage"])try{const t=window[e].getItem(Dg);if(t)return t}catch{}return null}function u1(e){for(const t of["sessionStorage","localStorage"])try{window[t].setItem(Dg,e)}catch{}}function ZP(e){if(e)try{const t=JSON.parse(localStorage.getItem(Dc+e)||"null");return localStorage.removeItem(Dc+e),t&&typeof t.sessionId=="string"&&Date.now()-t.at<6e4?t.sessionId:void 0}catch{return}}function f1(e){if(window.parent!==window||window.termdockDesktop)return;if(window.__termdockWorkspaceHost)return window.__termdockWorkspaceHost;let t={activeKey:"root",items:[{key:"root",service:e,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]};try{const u=d1(),f=e&&u!==e.targetPeerId?_n().find(h=>h.targetPeerId===u):void 0;f?.targetPeerId&&(t={activeKey:f.targetPeerId,items:[...t.items,{key:f.targetPeerId,service:f,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]})}catch{}let n=c1(),r=t.activeKey==="root"?"root":null;const o=new Map,i=new Map([["root",window]]),s=new Set,a=()=>{for(const u of[...o.keys()])u()},c=()=>{const u=l1(t.items,t.activeKey,r,n),f=new Set(u.map(h=>h.key));t={...t,items:u};for(const[h,g]of o)g&&!f.has(g)&&o.delete(h);for(const h of i.keys())f.has(h)||i.delete(h);for(const h of s)f.has(h)||s.delete(h)},l=(u,f)=>{try{const h=f.document.createEvent("CustomEvent");if(h.initCustomEvent(Bo,!1,!1,{active:t.activeKey===u}),f.dispatchEvent(h),t.activeKey===u){const g=f.document.createEvent("Event");if(g.initEvent("resize",!1,!1),f.dispatchEvent(g),s.delete(u)){const m=f.document.createEvent("Event");m.initEvent(Bc,!1,!1),f.dispatchEvent(m)}}else f.document.activeElement?.blur?.()}catch{}},d={snapshot:()=>t,subscribe:(u,f)=>(o.set(u,f),()=>{o.delete(u)}),present(u){r=u},retentionLimit:()=>n,setRetentionLimit(u){if(Lg(u)){n=u;try{localStorage.setItem(Ng,u===1/0?"unlimited":String(u))}catch{}c(),a()}},activate(u,f=!0){const h=bs(u);if(!h?.targetPeerId)return!1;const g=t.items.find(w=>w.service?.targetPeerId===h.targetPeerId),m=g?.key||h.targetPeerId,v=g?{...g,service:h,touchedAt:Date.now()}:{key:m,service:h,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()};t={activeKey:m,items:g?t.items.map(w=>w===g?v:w):[...t.items,v]},c(),u1(h.targetPeerId),f&&s.add(m),a();for(const[w,S]of i)l(w,S);return!0},report(u,f){const h=t.items.find(m=>m.key===u);if(!h||f.service&&h.service?.targetPeerId&&f.service.targetPeerId!==h.service.targetPeerId)return;const g={...h,...f};JSON.stringify(g)!==JSON.stringify(h)&&(t={...t,items:t.items.map(m=>m===h?g:m)},a())},attach(u,f){f&&t.items.some(h=>h.key===u)?(i.set(u,f),l(u,f)):i.delete(u)},focusSession(u,f){const h=_n().find(m=>m.targetPeerId===u);if(!h)return!1;try{localStorage.setItem(Dc+u,JSON.stringify({sessionId:f,at:Date.now()}))}catch{return!1}d.activate(h,!1);const g=i.get(t.activeKey);if(g){const m=g.document.createEvent("CustomEvent");m.initCustomEvent("termdock:workspace-session",!1,!1,null),g.dispatchEvent(m)}return!0}};return window.__termdockWorkspaceHost=d,d}let ga;async function ft(){return ga||(ga=(async()=>{const e=await new Promise((t,n)=>{const r=indexedDB.open("termdock-device-identity",1);r.onupgradeneeded=()=>r.result.createObjectStore("keys"),r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)});try{const t=await new Promise((o,i)=>{const s=e.transaction("keys").objectStore("keys").get("identity");s.onsuccess=()=>o(s.result),s.onerror=()=>i(s.error)});if(t)return Uu(t);const n=await vg();let r=n;return await new Promise((o,i)=>{const s=e.transaction("keys","readwrite"),a=s.objectStore("keys"),c=a.get("identity");c.onsuccess=()=>{typeof c.result=="string"?r=Uu(c.result):a.put(ME(n),"identity")},s.oncomplete=()=>o(),s.onerror=()=>i(s.error)}),r}finally{e.close()}})()),ga}const h1="termdock:secure-ready";let _c="ready";const Oc=new Set;function cr(e){if(e!==_c){_c=e;for(const t of Oc)t();e==="ready"&&window.dispatchEvent(new Event(h1))}}function JP(){return N.useSyncExternalStore(e=>(Oc.add(e),()=>{Oc.delete(e)}),()=>_c)}function _g(e){const t=e instanceof Error?e.message:String(e);return/^(Secure connection closed|Secure connection timed out|Secure request closed|Secure response ended unexpectedly|Encrypted connection unavailable|Encrypted transport disconnected|Secure transport unavailable|Secure handshake timed out|WebSocket closed|WebSocket connection failed)$/.test(t)}const as={CONNECTION_FAILED:{reason:"connectionFailed",status:503,message:"暂时连不上这台服务,请检查地址和网络后重试。"},INVALID_PASSWORD:{reason:"invalidPassword",status:401,message:"密码不正确,或服务身份无法验证。请检查后重试。"},IDENTITY_MISMATCH:{reason:"identityMismatch",status:409,message:"服务身份与已保存的记录不一致,请确认目标服务。"},RATE_LIMITED:{reason:"rateLimited",status:429,message:"尝试次数较多,请稍后再试。"},LOGIN_UNAVAILABLE:{reason:"unavailable",status:503,message:"暂时无法登录这台服务,请稍后重试。"},DEVICE_AUTHORIZATION_REQUIRED:{reason:"authorizationRequired",status:403,message:"请检查目标服务与入口的设备授权后重试。"}};function Vu(e){return typeof e=="string"&&Object.hasOwn(as,e)?as[e].reason:void 0}class yt extends Error{constructor(t,n){super(as[t].message),this.code=t,this.retryAfterMs=n,this.status=as[t].status}code;retryAfterMs;status}function _s(e){if(e instanceof yt)return e;if(e instanceof ut)return new yt("DEVICE_AUTHORIZATION_REQUIRED");if(e instanceof Error){if(e.name==="UnexpectedPeerError"||e.message==="PEER_IDENTITY_MISMATCH")return new yt("IDENTITY_MISMATCH");if(e.message==="LOGIN_RATE_LIMIT"||e.message==="Too many password login attempts")return new yt("RATE_LIMITED");if(e.message==="AUTHORIZATION_DENIED")return new yt("DEVICE_AUTHORIZATION_REQUIRED");if(e instanceof TypeError||["TimeoutError","AbortError"].includes(e.name)||_g(e)||e.message==="Encrypted handshake timed out"||e.message==="Encrypted transport failed")return new yt("CONNECTION_FAILED");if(e.message==="Password authentication failed"||e.message==="Password login expired"||e.message==="INVALID_LOGIN")return new yt("INVALID_PASSWORD")}return new yt("LOGIN_UNAVAILABLE")}const dt="termdock:secure-state";let ae,ir,Je,Pr="direct",Ai=!1,Wu=0,Ci=!1,Gu=-1/0;const Nr=globalThis.fetch.bind(globalThis);function ce(){return Qe()}function bt(){return ae}function p1(){return Je}function Wl(){ae?.close(),Je?.close(),ae=void 0,Je=void 0}class ma extends Error{constructor(){super("Secure read target changed"),this.name="SecureReadTargetChanged"}}function g1(e){if(_g(e))return!0;if(!e||typeof e!="object")return!1;const t=e;return t.name==="UnexpectedEOFError"&&typeof t.message=="string"&&/^Unexpected EOF - stream closed while reading \d+\/\d+ bytes$/.test(t.message)}async function m1(e,t){const n=ce(),r=n?.targetPeerId,o=JSON.stringify(n),i=()=>JSON.stringify(ce())===o,s=bt(),a=c=>{if(!i())throw new ma;if(t?.aborted)throw new DOMException("The operation was aborted","AbortError");return c};try{return a(await e())}catch(c){if(c instanceof ma||t?.aborted||c instanceof Error&&c.name==="AbortError"||c&&typeof c=="object"&&"status"in c||!r||!i()||!s?.closed&&!g1(c))throw c;if(cr(navigator.onLine===!1?"offline":"reconnecting"),s&&bt()===s&&Wl(),window.dispatchEvent(new Event(dt)),await jg(t),!i())throw new ma;const l=a(await e());return cr("ready"),l}}async function Og(){const e=await Nr("/api/auth/status",{signal:AbortSignal.timeout(5e3)});if(!e.ok)throw new Error("Failed to query auth status");return e.json()}async function w1(){if(ce()){await gt();return}if((await Og()).enabled)return;const e=await Nr("/api/auth/open/parameters",{cache:"no-store"});if(!e.ok)throw new Error("Open service unavailable");const{serviceIdentity:t}=await e.json();if(typeof t!="string"||!t)throw new Error("Invalid service identity");await St({url:location.origin,targetPeerId:t,serviceName:location.hostname})}async function y1(e,t){const{startPasswordBootstrap:n,finishPasswordBootstrap:r}=await wn(async()=>{const{startPasswordBootstrap:u,finishPasswordBootstrap:f}=await import("./passwordBootstrap-Co17Xh3M.js");return{startPasswordBootstrap:u,finishPasswordBootstrap:f}},__vite__mapDeps([0,1,2,3])),o=typeof window<"u"?window.termdockDesktop:void 0;let i=location.origin;if(o?.previewCapabilities&&o.passwordBootstrapOrigin){const u=o.passwordBootstrapOrigin(e),f=new URL(u);if(f.origin!==u||e!==location.origin&&f.origin!==e||!["http:","https:"].includes(f.protocol)||f.username||f.password)throw new yt("LOGIN_UNAVAILABLE");i=u}const s=u=>e===location.origin?u:new URL(u,e).href,a=async(u,f)=>{const h=await Nr(s(u),{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(15e3),...f?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)}:{}});if(!h.ok){const g=await h.json().catch(()=>null),m=typeof g?.retryAfterMs=="number"&&Number.isFinite(g.retryAfterMs)&&g.retryAfterMs>=0?g.retryAfterMs:void 0;throw new yt(h.status===429?"RATE_LIMITED":h.status===401?"INVALID_PASSWORD":"LOGIN_UNAVAILABLE",m)}return h.json()},{saltHex:c}=await a("/api/auth/password/parameters"),l=await ft(),d=await n(t,c);try{const u=await a("/api/auth/password/start",{startLoginRequest:d.startLoginRequest,clientIdentity:l.peerId}),f=await r(d,u,{clientIdentity:l.peerId,origin:i});await a("/api/auth/password/finish",{attemptId:f.attemptId,finishLoginRequest:f.finishLoginRequest});const h=i===location.origin?e:i;return{url:h,targetPeerId:f.serverIdentity,serviceName:new URL(h).host,serviceOrigin:h}}finally{d.passwordKey=""}}async function Gl(e,t){const n=ce();if(n&&(n.serviceOrigin||n.url)===e)return await Fc(n,t),n;try{return await y1(e,t)}catch(r){if(!(r instanceof TypeError)&&!(r instanceof DOMException))throw r;const o=(await Ye()).find(s=>s.targetPeerId&&(s.serviceOrigin||s.url)===e);if(!o?.targetPeerId)throw _s(r);const i={...o,targetPeerId:o.targetPeerId,serviceName:o.label};return await Fc(i,t),i}}async function Fc(e,t){const n=await Xl(e),{startPasswordBootstrap:r,finishPasswordBootstrap:o}=await wn(async()=>{const{startPasswordBootstrap:s,finishPasswordBootstrap:a}=await import("./passwordBootstrap-Co17Xh3M.js");return{startPasswordBootstrap:s,finishPasswordBootstrap:a}},__vite__mapDeps([0,1,2,3]));let i;try{const s=await n.request({type:"password-parameters"},{timeoutMs:5e3});i=await r(t,String(s.saltHex));const a=await n.request({type:"password-start",startLoginRequest:i.startLoginRequest,origin:location.origin}),c=await o(i,a,{clientIdentity:(await ft()).peerId,origin:location.origin});if(c.serverIdentity!==e.targetPeerId)throw new yt("IDENTITY_MISMATCH");await n.request({type:"password-finish",attemptId:c.attemptId,finishLoginRequest:c.finishLoginRequest})}catch(s){throw _s(s)}finally{i&&(i.passwordKey=""),n.close()}}async function b1(e){try{const t=ce(),n=t?.serviceOrigin||location.origin,r=await Gl(n,e);return await St({...r,routes:t?.routes,serviceName:t?.serviceName||r.serviceName}),Response.json({ok:!0})}catch(t){const n=_s(t);return Response.json({error:n.message,code:n.code,retryAfterMs:n.retryAfterMs},{status:n.status})}}async function Xu(e,t){const n=Re(e),r=(await Ye()).find(s=>(s.serviceOrigin||s.url)===n&&s.targetPeerId);if(t===void 0&&r?.targetPeerId)try{return await St({...r,targetPeerId:r.targetPeerId,serviceName:r.label}),{}}catch(s){if(!(s instanceof ut))throw s}if(t!==void 0){const s=await Gl(n,t);if(r?.targetPeerId&&r.targetPeerId!==s.targetPeerId)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await St({...s,routes:r?.routes,serviceName:r?.label||s.serviceName}),{}}const o=await Nr(new URL("/api/auth/open/parameters",n).href,{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(1e4)}).catch(()=>{throw new Error("暂时连不上这台服务,请检查地址和网络后重试。")});if(o.status===403)return{passwordRequired:!0};if(!o.ok)throw new Error("这台服务暂时不可用,请稍后重试。");const{serviceIdentity:i}=await o.json();if(typeof i!="string"||!i)throw new Error("这不是可连接的 Termdock 服务。");if(r?.targetPeerId&&r.targetPeerId!==i)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await St({url:n,targetPeerId:i,serviceName:r?.label||new URL(n).host,serviceOrigin:n}),{}}function At(e){const t=[...e.routes||[]];if(e.entryServiceId&&e.entryServiceId!==e.targetPeerId&&t.unshift({url:e.url,targetPeerId:e.entryServiceId}),!t.length&&e.routes===void 0)try{const r=JSON.parse(localStorage.getItem(gl)||"null");r&&r.targetPeerId!==e.targetPeerId&&new URL(r.url).host===new URL(e.url).host&&t.push(r)}catch{}const n=new Set;return t.flatMap(r=>{try{if(!r.targetPeerId||r.targetPeerId===e.targetPeerId)return[];const o=Re(r.url),i=JSON.stringify([r.targetPeerId,o]);return n.has(i)?[]:(n.add(i),[{url:o,targetPeerId:r.targetPeerId}])}catch{return[]}}).slice(0,4)}const xo=e=>`relay:${e.targetPeerId}:${e.url}`;async function Fg(e){const t=At(e),n=new Set(t.map(xo)),r=[],o=await Ye(),i=o.some(s=>s.targetPeerId===e.targetPeerId);for(const s of o)if(!(!s.targetPeerId||s.targetPeerId===e.targetPeerId||!i&&!At({...s,targetPeerId:s.targetPeerId}).some(a=>a.targetPeerId===e.targetPeerId)))for(const a of yn({...s,targetPeerId:s.targetPeerId})){const c={url:a,targetPeerId:s.targetPeerId};n.has(xo(c))||(n.add(xo(c)),r.push(c))}return r.slice(0,Math.max(0,4-Math.max(e.routes?.length??0,t.length)))}async function Mg(e,t,n){n.throwIfAborted();const r=await e.request({type:"route-targets"},{timeoutMs:5e3}),o=(Array.isArray(r.items)?r.items:[]).find(c=>c.serviceId===t);if(!o?.available)throw new Error("反向中转通道尚未建立。");if(n.throwIfAborted(),o.authorized===!0)return;if(r.canManage!==!0)throw new Error("反向中转尚未授权。");const i=await e.request({type:"route-access"},{timeoutMs:5e3}),s=(await ft()).peerId;if(n.throwIfAborted(),!Array.isArray(i.grants))throw new Error("入口未返回有效的路由授权记录。");if(i.grants.some(c=>c.subjectId===s&&c.targetServiceId===t&&c.revokedAt!==void 0))throw new Error("反向中转授权已撤销。");await e.request({type:"route-grant",serviceId:t,subjectId:s})}function yn(e){const t=At(e),n=[e.serviceOrigin||e.url,...(e.routes||[]).slice(0,4).filter(o=>o.targetPeerId===e.targetPeerId).map(o=>o.url)],r=new Set;for(const o of n)try{const i=Re(o);t.some(s=>s.url===i)||r.add(i)}catch{}return[...r]}function jn(e){const t=new URL("/api/federation/secure",Re(e));return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.href}async function bn(e,t){return Mn({url:jn(e.url),targetPeerId:e.targetPeerId,identity:await ft(),signal:t?AbortSignal.any([t,AbortSignal.timeout(5e3)]):AbortSignal.timeout(5e3)})}async function Xl(e,t){const n=await ft(),r=yn(e).map(a=>({key:`direct:${a}`,run:c=>Mn({url:jn(a),targetPeerId:e.targetPeerId,identity:n,signal:AbortSignal.any([c,AbortSignal.timeout(8e3),...t?[t]:[]])})})),o=await Fg(e);for(const a of[...At(e),...o])r.push({key:xo(a),run:async c=>{t&&(c=AbortSignal.any([c,t]));const l=[ae,Je].find(u=>u&&!u.closed&&u.targetPeerId===a.targetPeerId),d=l||await bn(a,c);try{if(c.aborted)throw c.reason;o.includes(a)&&await Mg(d,e.targetPeerId,c);const u=await d.request({type:"route-ticket",serviceId:e.targetPeerId},{timeoutMs:5e3});if(c.aborted)throw c.reason;if(typeof u.routeToken!="string")throw new Error("入口未允许此设备连接该服务。");const f=new URL(jn(a.url));return f.pathname="/api/federation/relay",f.searchParams.set("routeToken",u.routeToken),await Mn({url:f.href,targetPeerId:e.targetPeerId,identity:n,socketFactory:Ig(e.targetPeerId),signal:AbortSignal.any([c,AbortSignal.timeout(ml)])})}finally{l||d.close()}}});const i=Tg(e.targetPeerId);r.sort((a,c)=>+(c.key===i)-+(a.key===i));const s=await Pg(r,a=>a.close());return Lc(e.targetPeerId,s.key),s.value}async function v1(e,t){const n=await Xl(e,t);try{const o=(await n.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node;if(o?.serviceId!==e.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");return{...o,serviceId:e.targetPeerId}}finally{n.close()}}async function S1(e,t){const n=await Xl(e,t),r=()=>n.close();t.addEventListener("abort",r,{once:!0});try{if(t.aborted||(await Fr(n,{timeoutMs:3e3}),t.aborted))throw t.reason;return n}catch(o){throw n.close(),o}finally{t.removeEventListener("abort",r)}}async function St(e,t={}){const n=ae,r=Je,o=await ft(),i=Re(e.serviceOrigin||e.url),s=(await Ye()).find(S=>S.targetPeerId===e.targetPeerId),a={...e,routes:e.routes??s?.routes},c=await Fg(a),l=[...At(a),...c],d=yn(a);let u,f,h=e.pairingCode,g="direct";const m=new Set,v=new Map,w=async(S,y)=>{if(n&&!n.closed&&n.targetPeerId===S.targetPeerId)return n;if(r&&!r.closed&&r.targetPeerId===S.targetPeerId)return r;const A=JSON.stringify([S.targetPeerId,S.url]),R=v.get(A);if(R&&!R.closed)return R;const E=await bn(S,y);return m.add(E),v.set(A,E),E};try{if(e.routeCode&&e.entryServiceId){const T=l.find(P=>P.targetPeerId===e.entryServiceId);if(!T)throw new Error("邀请缺少入口信息。");if((await(await w(T)).request({type:"route-pair",code:e.routeCode})).serviceId!==e.targetPeerId)throw new Error("邀请的目标服务不一致。");e.routeOnly&&await Yt({id:e.targetPeerId,url:i,label:e.serviceName||new URL(i).host,targetPeerId:e.targetPeerId,serviceOrigin:i,routes:l})}const S=[],y=async(T,L)=>{const I=()=>T.close();L.addEventListener("abort",I,{once:!0});try{if(L.aborted||(await Fr(T),L.aborted))throw L.reason}catch(P){throw T.close(),P}finally{L.removeEventListener("abort",I)}};for(const T of d)S.push({key:`direct:${T}`,run:async L=>{const I=await Mn({url:jn(T),targetPeerId:e.targetPeerId,pairingCode:h,identity:o,signal:AbortSignal.any([L,AbortSignal.timeout(8e3)])});return h=void 0,await y(I,L),{client:I,path:"direct"}}});for(const T of l)S.push({key:`relay:${T.targetPeerId}:${T.url}`,run:async L=>{let I,P;try{if(I=await w(T,L),L.aborted)throw L.reason;c.includes(T)&&await Mg(I,e.targetPeerId,L);const B=await I.request({type:"route-ticket",serviceId:e.targetPeerId},{timeoutMs:5e3});if(L.aborted)throw L.reason;if(typeof B.routeToken!="string"||!B.routeToken)throw new Error("入口未允许此设备连接该服务。");const D=new URL(jn(T.url));return D.pathname="/api/federation/relay",D.searchParams.set("routeToken",B.routeToken),P=await Mn({url:D.href,targetPeerId:e.targetPeerId,pairingCode:h,identity:o,socketFactory:Ig(e.targetPeerId),signal:AbortSignal.any([L,AbortSignal.timeout(ml)])}),h=void 0,await y(P,L),{client:P,entry:I,path:"relay"}}catch(B){throw P?.close(),I&&I!==r&&I!==n&&I.close(),B}}});const A=Tg(e.targetPeerId);S.sort((T,L)=>+(L.key===A)-+(T.key===A));const R=await Pg(S,T=>{T.client.close(),T.entry&&T.entry!==n&&T.entry!==r&&T.entry.close()},!!h);if(u=R.value.client,f=R.value.entry,g=R.value.path,t.renewIfCurrent){if(ae!==t.renewIfCurrent||n!==t.renewIfCurrent||n.closed||!n.canSwitchTransport||ce()?.targetPeerId!==e.targetPeerId){u.close();for(const T of m)T!==Je&&T!==ae&&T.close();return ae??n}ae=u,Pr=g,Je=f,Lc(e.targetPeerId,R.key),n.retire();for(const T of new Set([r,...m]))T&&T!==n&&T!==u&&T!==f&&T.close();return window.dispatchEvent(new Event(dt)),u}if(Lc(e.targetPeerId,R.key),ae!==n&&ae&&!ae.closed&&ae.targetPeerId===e.targetPeerId){u.close();for(const T of m)T!==Je&&T.close();return ae}g==="direct"&&new URL(i).host===location.host&&Mw(e.targetPeerId);const E=(await Ye()).find(T=>T.targetPeerId===e.targetPeerId||!T.targetPeerId&&(T.serviceOrigin||T.url)===i),C=E?.label||e.serviceName||new URL(i).host,k=c.find(T=>xo(T)===R.key),b=a.routes??At(a),x={url:i,targetPeerId:e.targetPeerId,serviceName:C,serviceOrigin:i,routes:k?[...b,k]:b};if(await(t.rememberOnly?Uw:Yt)({id:E?.id||e.targetPeerId,...x,label:C}),dr!=="unpaired"&&dr!==e.targetPeerId&&Bt()&&ss({id:E?.id||e.targetPeerId,...x,label:C})){u.close();for(const T of m)T!==n&&T!==r&&T.close();return n||u}wh(x),ae=u,Pr=g,Je=f;for(const T of new Set([n,r,...m]))T&&T!==u&&T!==f&&T.close();return dr!==e.targetPeerId?(location.reload(),new Promise(()=>{})):(window.dispatchEvent(new Event(dt)),u)}catch(S){u?.close();for(const y of m)y!==r&&y.close();throw S}}async function x1(){const e=ae,t=ce();if(!(Ci||Ai||ir||!e?.renewalDue||!e.canSwitchTransport||!t||performance.now()-Gu<3e4)){Gu=performance.now(),Ci=!0;try{await St(t,{renewIfCurrent:e})}catch(n){console.debug("[connection] renewal deferred",{reason:n instanceof Error?n.message:"unknown"})}finally{Ci=!1}}}async function E1(){const e=ae,t=ce();if(Date.now()-Wu<6e4||Ci||Ai||Pr!=="relay"||!e||e.closed||!e.canSwitchTransport||!t?.serviceOrigin)return;Ai=!0,Wu=Date.now();let n;try{for(const o of yn(t))try{n=await Mn({url:jn(o),targetPeerId:t.targetPeerId,identity:await ft(),signal:AbortSignal.timeout(3e3)}),await Fr(n);break}catch(i){if(n?.close(),n=void 0,i instanceof ut)throw i}if(!n||ae!==e||!e.canSwitchTransport)return;const r=Je;ae=n,n=void 0,Je=void 0,Pr="direct",e.close(),r?.close(),window.dispatchEvent(new Event(dt))}catch(r){r instanceof ut&&ae===e&&(Wl(),window.dispatchEvent(new Event("auth:unauthorized")))}finally{n?.close(),Ai=!1}}function A1(){return Pr}async function jg(e){return e?(e.throwIfAborted(),new Promise((t,n)=>{const r=()=>n(e.reason);e.addEventListener("abort",r,{once:!0}),gt().then(o=>{e.removeEventListener("abort",r),e.aborted?n(e.reason):t(o)},o=>{e.removeEventListener("abort",r),n(o)})})):gt()}async function gt(){if(ae&&!ae.closed){const t=ae;return x1(),t}if(ae=void 0,ir)return ir;const e=ce();if(!e)throw new Error("DEVICE_PAIRING_REQUIRED");return ir=St(e,{rememberOnly:!0}).catch(t=>{if(ae&&!ae.closed&&ae.targetPeerId===e.targetPeerId)return ae;throw t}).finally(()=>{ir=void 0}),ir}function Ug(e){const t=new URL(e,location.href);if(ae&&!ae.closed)return ae.openSocket(t.pathname+t.search);let n;const r=new kg(e,o=>n?.send(o),()=>n?.close());return gt().then(o=>{r.readyState!==3&&(n=o.openSocket(t.pathname+t.search),r.getConnectionDiagnostics=()=>{const i=n?.getConnectionDiagnostics?.();return i?{...i,socketOpenMs:r.openedAfterMs}:void 0},n.onopen=()=>r.accept({type:"ws-ready",id:""}),n.onmessage=i=>r.accept({type:"ws-data",id:"",data:i.data}),n.onclose=i=>r.accept({type:"ws-close",id:"",code:i.code,reason:i.reason}),n.onerror=()=>r.fail(new Error("Encrypted connection unavailable")))}).catch(o=>r.fail(o)),r}function C1(){n1(gt),window.fetch=async(e,t)=>{const n=new URL(e instanceof Request?e.url:String(e),location.href);if(!n.pathname.startsWith("/api/"))return Nr(e,t);if(n.origin!==location.origin)throw new Error("Remote business API requires a paired encrypted service");if(n.pathname==="/api/meta")return Nr(e,t);if(n.pathname==="/api/auth/status"){if(!ce()){const i=await Og();return Response.json({enabled:i.enabled,authenticated:!1})}try{const i=await Fr(await gt());return Response.json({enabled:i.grants.length>0,authenticated:!0})}catch(i){if(i instanceof ut)return Response.json({enabled:!0,authenticated:!1});throw i}}if(n.pathname==="/api/auth/login"){const s=await new Request(e instanceof Request?e:n.href,t).json();return b1(typeof s.password=="string"?s.password:"")}if(n.pathname==="/api/csrf-token")return Response.json({csrfToken:"encrypted-device-channel"});if(n.pathname==="/api/auth/logout")return ae&&!ae.closed&&await ae.request({type:"logout"}),ae?.close(),Je?.close(),ae=void 0,Je=void 0,Fw(),location.reload(),Response.json({ok:!0});const r=t?.signal!==void 0?t.signal:e instanceof Request?e.signal:void 0,o=await jg(r);return e instanceof Request?o.fetch(e,t):o.fetch(n.pathname+n.search,t)}}async function k1(e){if(!e.targetPeerId)throw new Error("请先连接这台服务,再查看可中转的服务。");for(const t of yn({...e,targetPeerId:e.targetPeerId})){let n;const r={url:t,targetPeerId:e.targetPeerId};try{n=await bn(r)}catch{continue}try{const o=await n.request({type:"route-targets"},{timeoutMs:5e3});if(!Array.isArray(o.items))throw new Error("入口服务需要更新后才能查看中转列表。");return{route:r,canManage:o.canManage===!0,items:o.items}}catch(o){throw o instanceof Error&&/UNKNOWN|UNSUPPORTED/i.test(o.message)?new Error("入口服务需要更新后才能查看中转列表。"):o}finally{n.close()}}throw new Error("暂时连不上中转入口,请检查地址和网络后重试。")}async function I1(e,t){const n=await bn(e);try{const r=await n.request({type:"route-targets"},{timeoutMs:5e3}),o=(Array.isArray(r.items)?r.items:[]).find(c=>c.serviceId===t);if(!o)throw new Error("该服务已不可见,请刷新列表或请入口管理员授权。");if(!o.available)throw new Error("入口暂时无法中转到这台服务,请稍后重试。");const i=(await Ye()).find(c=>c.targetPeerId===o.serviceId),s=[e,...(i?.routes||[]).filter(c=>c.targetPeerId!==e.targetPeerId||Re(c.url)!==Re(e.url))];if(s.length>4)throw new Error("这台服务已保存 4 个备用连接,请先移除一个后重试。");if(!o.authorized){if(!r.canManage)throw new Error("请先让入口管理员授权此设备。");await n.request({type:"route-grant",serviceId:o.serviceId,subjectId:(await ft()).peerId})}const a=i?.serviceOrigin||i?.url||o.url||e.url;return{url:a,serviceOrigin:a,targetPeerId:o.serviceId,serviceName:i?.label||o.label||(o.url?new URL(o.url).host:`中转服务 ${o.serviceId.slice(0,8)}`),routes:s}}finally{n.close()}}async function R1(e,t){const n=await bn(e);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),o=(await ft()).peerId;return{canManage:r.canManage===!0,grants:(Array.isArray(r.grants)?r.grants:[]).filter(i=>i.subjectId===o&&i.targetServiceId===t)}}finally{n.close()}}async function T1(e,t,n){if(n!==void 0&&(await Gl(Re(t.url),n)).targetPeerId!==t.targetPeerId)throw new Error("入口服务的身份已改变,请重新连接并确认。");const r=await bn(t);try{await r.request({type:"route-grant",serviceId:e.targetPeerId,subjectId:(await ft()).peerId,url:Re(e.serviceOrigin||e.url)})}finally{r.close()}}async function P1(e,t){const n=await bn(t);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),o=(await ft()).peerId,i=(Array.isArray(r.grants)?r.grants:[]).filter(s=>s.subjectId===o&&s.targetServiceId===e&&s.active);for(const s of i)await n.request({type:"route-revoke",grantId:s.id})}finally{n.close()}}async function Hg(e,t){const n=await bn(t);try{const r=await n.request({type:"route-invite-create",serviceId:e.targetPeerId});if(typeof r.routeCode!="string"||typeof r.expiresAt!="number")throw new Error("暂时无法生成备用连接邀请。");return{routeCode:r.routeCode,expiresAt:r.expiresAt}}finally{n.close()}}async function ki(e,t){const n=(await Ye()).find(o=>o.id===e.id||e.targetPeerId&&o.targetPeerId===e.targetPeerId)||e;await Yt({...n,url:n.serviceOrigin||n.url,entryServiceId:void 0,routes:t});const r=ce();r&&r.targetPeerId===e.targetPeerId&&wh({...r,url:r.serviceOrigin||r.url,entryServiceId:void 0,routes:t})}async function N1(e,t){const n=e.targetPeerId;if(!n)throw new Error("请先连接这台服务,再添加备用地址。");let r;try{r=Re(t)}catch{throw new Error("请输入有效的 HTTPS 地址,例如 https://电脑地址:9834。")}const o=async()=>(await Ye()).find(a=>a.targetPeerId===n)||e,i=a=>{const c=a.routes??At({...a,targetPeerId:n});if(Re(a.serviceOrigin||a.url)===r||c.some(l=>Re(l.url)===r))throw new Error("这个地址已经在连接列表中。");if(c.length>=4)throw new Error("最多保存 4 个备用地址或入口,请先移除不再使用的连接。");return[...c,{url:r,targetPeerId:n}]};i(await o());let s;try{try{s=await Mn({url:jn(r),targetPeerId:n,identity:await ft(),signal:AbortSignal.timeout(5e3)}),await Fr(s)}catch(l){throw l instanceof ut?new Error("这台服务尚未授权当前设备,请先恢复设备授权。"):new Error("无法验证这个地址。请确认能访问该地址、HTTPS 证书受信任,且运行的是同一台 Termdock 服务。")}const a=await o(),c=i(a);if(await ki(a,c),ce()?.targetPeerId===n&&dr===n&&(!ae||ae.closed)){const l=ae,d=Je;ae=s,s=void 0,Je=void 0,Pr="direct",l?.close(),d?.close(),window.dispatchEvent(new Event(dt))}return c}finally{s?.close()}}async function Yu(e,t){await Fc(e,t),await St({...e,pairingCode:void 0,routeCode:void 0})}function L1(){let e=!1,t=!1,n=!1,r;const o=new Map,i=new Set,s=new Map,a=async(f,h,g)=>{const m=JSON.stringify(g);if(o.get(h.serviceId)===m)return;const v=AbortSignal.timeout(1e4),w=await f.fetch("/api/csrf-token",{signal:v});if(!w.ok)throw new Error("CONNECTION_AUTHORIZATION_REQUIRED");const S=await w.json();if(typeof S.csrfToken!="string")throw new Error("INVALID_CSRF_TOKEN");const y=await f.fetch("/api/terminal/operations/collaboration-connections",{method:"POST",signal:v,headers:{"Content-Type":"application/json","X-XSRF-TOKEN":S.csrfToken},body:JSON.stringify({origin:h.origin,nodes:g})});if(!y.ok){const A=await y.json().catch(()=>({}));throw new Error(A.error||`HTTP_${y.status}`)}o.set(h.serviceId,m)},c=async()=>{if(e){n=!0;return}const f=ce(),h=bt();if(!(t||!f||!h||h.closed)){e=!0,n=!1;try{let g;const m=await Promise.race([Ye(),new Promise((R,E)=>{g=setTimeout(()=>E(new Error("SERVICE_DIRECTORY_TIMEOUT")),8e3)})]).finally(()=>clearTimeout(g));m.some(R=>R.targetPeerId===f.targetPeerId)||m.push({...f,id:f.targetPeerId,label:f.serviceName||f.url});const v=[...new Map(m.filter(R=>!!R.targetPeerId).map(R=>[R.targetPeerId,R])).values()].slice(0,64);if(v.length<2)return;const w=[];for(const R of v)try{const E=`${R.targetPeerId}:${R.serviceOrigin||R.url}`;let C=s.get(E);if(!C){const k=R.targetPeerId===f.targetPeerId?(await h.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node:await v1({...R,targetPeerId:R.targetPeerId},AbortSignal.timeout(8e3));if(k?.serviceId!==R.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");const b=k.origin||R.serviceOrigin||R.url,x=new URL(b);if(x.protocol!=="https:"||x.origin!==b)throw new Error("INVALID_SERVICE_ORIGIN");C={serviceId:k.serviceId,origin:b,...k.caFingerprint256?{caFingerprint256:k.caFingerprint256}:{}},s.set(E,C)}w.push({service:R,node:C})}catch{}if(t||bt()!==h||ce()?.targetPeerId!==f.targetPeerId)return;const S=w.find(R=>R.node.serviceId===f.targetPeerId);if(!S||w.length<2){l(3e4);return}const y=w.map(R=>R.node).sort((R,E)=>R.serviceId.localeCompare(E.serviceId));await a(h,S.node,y);let A=w.length<v.length;for(const R of w){if(R===S||o.get(R.node.serviceId)===JSON.stringify(y))continue;let E;try{E=await S1({...R.service,targetPeerId:R.node.serviceId},AbortSignal.timeout(8e3)),await a(E,R.node,y)}catch{let C=i.has(R.node.serviceId);if(!C&&E)try{(await E.request({type:"collaboration-scoped-peer",origin:R.node.origin,node:S.node},{timeoutMs:8e3})).type==="result"&&(i.add(R.node.serviceId),C=!0)}catch{}C||(A=!0)}finally{E?.close()}}window.dispatchEvent(new CustomEvent("termdock:collaboration-enrollment",{detail:{ok:!0}})),A&&l(3e4)}catch(g){window.dispatchEvent(new CustomEvent("termdock:collaboration-enrollment",{detail:{ok:!1,error:g instanceof Error?g.message:"CONNECTION_ENROLLMENT_FAILED"}})),l(3e4)}finally{e=!1,n&&l(100)}}};function l(f=100){t||(clearTimeout(r),r=setTimeout(()=>{c()},f))}const d=()=>{l()},u=vs(d);window.addEventListener(dt,d),window.addEventListener("termdock:collaboration-enroll",d),window.addEventListener("online",d),window.addEventListener("pageshow",d),window.addEventListener("pagehide",f=>{f.persisted||(t=!0,clearTimeout(r),u(),window.removeEventListener("termdock:collaboration-enroll",d),window.removeEventListener(dt,d),window.removeEventListener("online",d),window.removeEventListener("pageshow",d))}),l()}var ui={},Zu;function B1(){if(Zu)return ui;Zu=1;var e=Rw();return ui.createRoot=e.createRoot,ui.hydrateRoot=e.hydrateRoot,ui}var D1=B1();const _1=gh(D1);function et({size:e=16,className:t="",...n}){const r=!!(n["aria-label"]||n["aria-labelledby"]);return p.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none","aria-hidden":r?void 0:!0,role:r?"img":void 0,focusable:"false",...n,className:`td-loading-spinner animate-spin ${t.replace(/\b(?:animate-spin|service-spinning)\b/g,"")}`,children:p.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2.5",strokeDasharray:"18 44.8",strokeLinecap:"round"})})}function O1(){return p.jsx("span",{className:"td-loading-dots","aria-hidden":"true",children:[0,1,2].map(e=>p.jsx("span",{style:{animationDelay:`${(e-3)*400}ms`}},e))})}function QP({label:e,className:t="",dots:n=!1}){return p.jsxs("div",{role:"status","aria-live":"polite","aria-atomic":"true",className:`flex items-center justify-center gap-2 text-sm text-muted-foreground ${t}`,children:[n?p.jsx(O1,{}):p.jsx(et,{size:18}),p.jsx("span",{children:e})]})}const $g=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();const F1=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const M1=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());const Ju=e=>{const t=M1(e);return t.charAt(0).toUpperCase()+t.slice(1)};var wa={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 j1=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},U1=N.createContext({}),H1=()=>N.useContext(U1),$1=N.forwardRef(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:o="",children:i,iconNode:s,...a},c)=>{const{size:l=24,strokeWidth:d=2,absoluteStrokeWidth:u=!1,color:f="currentColor",className:h=""}=H1()??{},g=r??u?Number(n??d)*24/Number(t??l):n??d;return N.createElement("svg",{ref:c,...wa,width:t??l??wa.width,height:t??l??wa.height,stroke:e??f,strokeWidth:g,className:$g("lucide",h,o),...!i&&!j1(a)&&{"aria-hidden":"true"},...a},[...s.map(([m,v])=>N.createElement(m,v)),...Array.isArray(i)?i:[i]])});const qe=(e,t)=>{const n=N.forwardRef(({className:r,...o},i)=>N.createElement($1,{ref:i,iconNode:t,className:$g(`lucide-${F1(Ju(e))}`,`lucide-${e}`,r),...o}));return n.displayName=Ju(e),n};const q1=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],qg=qe("arrow-left",q1);const K1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],z1=qe("arrow-right",K1);const V1=[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]],W1=qe("arrow-up-right",V1);const G1=[["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"}]],Kg=qe("bell-dot",G1);const X1=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],cs=qe("check",X1);const Y1=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],zg=qe("chevron-down",Y1);const Z1=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Un=qe("chevron-right",Z1);const J1=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Q1=qe("chevron-up",J1);const eA=[["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"}]],Vg=qe("copy",eA);const tA=[["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"}]],Wg=qe("ellipsis",tA);const nA=[["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"}]],rA=qe("monitor",nA);const oA=[["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"}]],iA=qe("pencil",oA);const sA=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Gg=qe("plus",sA);const aA=[["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"}]],Os=qe("server",aA);const cA=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],Xg=qe("smartphone",cA);const lA=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],dA=qe("terminal",lA);const uA=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Yg=qe("x",uA),fA={},Qu=e=>{let t;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(t):d;if(!Object.is(f,t)){const h=t;t=u??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(g=>g(t,h))}},o=()=>t,c={setState:r,getState:o,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(fA?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},l=t=e(r,o,c);return c},hA=e=>e?Qu(e):Qu;var ya={exports:{}},ba={},va={exports:{}},Sa={};var ef;function pA(){if(ef)return Sa;ef=1;var e=pl();function t(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,i=e.useLayoutEffect,s=e.useDebugValue;function a(u,f){var h=f(),g=r({inst:{value:h,getSnapshot:f}}),m=g[0].inst,v=g[1];return i(function(){m.value=h,m.getSnapshot=f,c(m)&&v({inst:m})},[u,h,f]),o(function(){return c(m)&&v({inst:m}),u(function(){c(m)&&v({inst:m})})},[u]),s(h),h}function c(u){var f=u.getSnapshot;u=u.value;try{var h=f();return!n(u,h)}catch{return!0}}function l(u,f){return f()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?l:a;return Sa.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:d,Sa}var tf;function gA(){return tf||(tf=1,va.exports=pA()),va.exports}var nf;function mA(){if(nf)return ba;nf=1;var e=pl(),t=gA();function n(l,d){return l===d&&(l!==0||1/l===1/d)||l!==l&&d!==d}var r=typeof Object.is=="function"?Object.is:n,o=t.useSyncExternalStore,i=e.useRef,s=e.useEffect,a=e.useMemo,c=e.useDebugValue;return ba.useSyncExternalStoreWithSelector=function(l,d,u,f,h){var g=i(null);if(g.current===null){var m={hasValue:!1,value:null};g.current=m}else m=g.current;g=a(function(){function w(E){if(!S){if(S=!0,y=E,E=f(E),h!==void 0&&m.hasValue){var C=m.value;if(h(C,E))return A=C}return A=E}if(C=A,r(y,E))return C;var k=f(E);return h!==void 0&&h(C,k)?(y=E,C):(y=E,A=k)}var S=!1,y,A,R=u===void 0?null:u;return[function(){return w(d())},R===null?void 0:function(){return w(R())}]},[d,u,f,h]);var v=o(l,g[0],g[1]);return s(function(){m.hasValue=!0,m.value=v},[v]),c(v),v},ba}var rf;function wA(){return rf||(rf=1,ya.exports=mA()),ya.exports}var yA=wA();const bA=gh(yA),Zg={},{useDebugValue:vA}=lt,{useSyncExternalStoreWithSelector:SA}=bA;let of=!1;const xA=e=>e;function EA(e,t=xA,n){(Zg?"production":void 0)!=="production"&&n&&!of&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),of=!0);const r=SA(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return vA(r),r}const sf=e=>{(Zg?"production":void 0)!=="production"&&typeof e!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const t=typeof e=="function"?hA(e):e,n=(r,o)=>EA(t,r,o);return Object.assign(n,t),n},Fs=e=>e?sf(e):sf,ls=e=>`@collaboration:${e}`,Jg=Fs(e=>({activePaneId:null,setActivePane:t=>e({activePaneId:t}),docks:{},hosts:{},setDock:(t,n)=>e(r=>{const o={...r.docks};return n?o[t]=n:delete o[t],{docks:o,...!n&&r.activePaneId===ls(t)?{activePaneId:r.docks[t]?.sessionId??null}:{}}}),setHost:(t,n)=>e(r=>{const o={...r.hosts};return n?o[t]=n:delete o[t],{hosts:o}})})),Rn=new Map;let ds;function Qg(){const e=Jg.getState().activePaneId,t=Rn.get(ds??"");if(t?.requiresFocus&&e===ls(t.paneKey))return t.receive;for(const n of Rn.values())if(n.requiresFocus&&e===ls(n.paneKey))return n.receive;return t&&!t.requiresFocus?t.receive:void 0}function AA(e){const t=Rn.get(e);t&&(ds=e,Jg.getState().setActivePane(t.requiresFocus?ls(t.paneKey):null))}function CA(e){const t=Qg();return!t||!e?!1:(t(e),!0)}function e2(e,t="default",n=!1,r=t){Rn.set(t,{receive:e,requiresFocus:n,paneKey:r}),n||AA(t);const o=i=>{const{text:s,nonce:a}=i.detail??{};!s||Qg()!==e||(e(s),i.stopImmediatePropagation(),a&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:a,ok:!0}})))};return window.addEventListener("termdock-insert-reference",o,!0),()=>{Rn.get(t)?.receive===e&&(Rn.delete(t),ds===t&&(ds=[...Rn.keys()].at(-1))),window.removeEventListener("termdock-insert-reference",o,!0)}}const kA=/^[A-Za-z0-9_@%+=:,./-]$/;function IA(e){return Array.from(e,t=>(t.codePointAt(0)??0)>127||kA.test(t)?t:`\\${t}`).join("")}let RA=0;function TA(e,t){if(!t)return!1;try{const n=new URL(t.serviceOrigin||t.url);return n.origin===e&&/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})$/.test(n.hostname)&&!(t.routes??[]).some(r=>r.targetPeerId!==t.targetPeerId)}catch{return!1}}function PA(e,t=!0){const n=new Set,r=new Set,o=new WeakMap,i=l=>l.target instanceof Element?l.target.closest("[data-termdock-terminal-dropzone]"):null,s=()=>!t||!TA(location.origin,Qe()),a=l=>{const d=i(l);!d||!s()||!l.dataTransfer?.types.includes("Files")||(l.preventDefault(),l.stopImmediatePropagation(),l.dataTransfer.dropEffect="copy",d.dataset.nativeFileDrag="true",d.dataset.nativeFileDropState="remote")},c=l=>{const d=i(l),u=Array.from(l.dataTransfer?.files??[]);if(!d||!u.length||!s())return;l.preventDefault(),l.stopImmediatePropagation(),o.get(d)?.abort();const f=new AbortController;o.set(d,f);const h=d.dataset.termdockTerminalDropzone??"",g=Qe(),m=d.dataset.termdockTerminalOwner,v=g?.targetPeerId??null,w=String(++RA),S=()=>!f.signal.aborted&&d.isConnected&&d.dataset.termdockTerminalDropzone===h&&d.dataset.nativeFileDropOperation===w&&Qe()===g&&Qe()?.targetPeerId===v&&d.dataset.termdockTerminalOwner===m,y=()=>S()?!1:(d.dataset.nativeFileDropOperation===w&&(delete d.dataset.nativeFileDrag,delete d.dataset.nativeFileDropState,delete d.dataset.nativeFileDropOperation,delete d.dataset.nativeFileDropProgress,delete d.dataset.nativeFileDropCancellable),!0);d.dataset.nativeFileDropOperation=w,d.dataset.nativeFileDrag="true",d.dataset.nativeFileDropState="uploading",d.dataset.nativeFileDropCancellable="true",delete d.dataset.nativeFileDropProgress;const A=b=>{(b?.type==="auth:unauthorized"||b?.type==="pagehide"||!S())&&(f.abort(),y())},R=new MutationObserver(()=>A());R.observe(d,{attributes:!0,attributeFilter:["data-termdock-terminal-dropzone","data-termdock-terminal-owner","data-native-file-drop-operation"]});const E=()=>{f.abort(),y(),k()},C=b=>{if(!(b.target instanceof Element)||b.target.closest("[data-termdock-terminal-dropzone]")!==d||!S())return;E(),d.dataset.nativeFileDrag="true",d.dataset.nativeFileDropOperation=w,d.dataset.nativeFileDropState="cancelled";const x=window.setTimeout(()=>{r.delete(x),d.dataset.nativeFileDropOperation===w&&d.dataset.nativeFileDropState==="cancelled"&&(delete d.dataset.nativeFileDrag,delete d.dataset.nativeFileDropState,delete d.dataset.nativeFileDropOperation)},3e3);r.add(x)};window.addEventListener("termdock:file-drop-cancel",C);const k=()=>{window.removeEventListener("termdock:file-drop-cancel",C),R.disconnect();for(const b of["termdock:secure-state","auth:unauthorized","pagehide"])window.removeEventListener(b,A);n.delete(E)};n.add(E);for(const b of["termdock:secure-state","auth:unauthorized","pagehide"])window.addEventListener(b,A);wn(async()=>{const{uploadFiles:b}=await Promise.resolve().then(()=>qI);return{uploadFiles:b}},void 0).then(({uploadFiles:b})=>{if(!S())throw new DOMException("Drop target changed","AbortError");return b("/tmp",u,f.signal,x=>{S()&&(d.dataset.nativeFileDropProgress=String(Math.round(x)))},S)}).then(b=>{if(b.files.length!==u.length||b.files.some(T=>!T.path))throw new Error("Upload did not return every file path");if(y())return;delete d.dataset.nativeFileDropCancellable,delete d.dataset.nativeFileDropProgress,e({sessionKey:h,paths:b.files.map(T=>T.path)}),d.dataset.nativeFileDropState="uploaded";const x=window.setTimeout(()=>{r.delete(x),S()&&d.dataset.nativeFileDropState==="uploaded"&&(delete d.dataset.nativeFileDrag,delete d.dataset.nativeFileDropState,delete d.dataset.nativeFileDropOperation)},3e3);r.add(x)}).catch(b=>{if(y())return;delete d.dataset.nativeFileDropCancellable,delete d.dataset.nativeFileDropProgress,d.dataset.nativeFileDropState="error",d.dispatchEvent(new CustomEvent("termdock:file-drop-error",{bubbles:!0,detail:b instanceof Error?b.message:"File upload failed"}));const x=window.setTimeout(()=>{r.delete(x),S()&&d.dataset.nativeFileDropState==="error"&&(delete d.dataset.nativeFileDrag,delete d.dataset.nativeFileDropState,delete d.dataset.nativeFileDropOperation)},3e3);r.add(x)}).finally(k)};return window.addEventListener("dragover",a,!0),window.addEventListener("drop",c,!0),()=>{window.removeEventListener("dragover",a,!0),window.removeEventListener("drop",c,!0);for(const l of n)l();for(const l of r)clearTimeout(l);r.clear()}}function it(){return typeof window>"u"?null:window.termdockDesktop??null}const xa=new Set;let af=!1;function t2(e){const t=it();if(xa.add(e),!af){const n=r=>{if(!CA(r.paths.map(IA).join(" ")+" "))for(const o of xa)o(r)};PA(n,!!t),t?.onNativeFileDrop(n),af=!0}return()=>{xa.delete(e)}}function em(e=navigator.userAgent,t=navigator.maxTouchPoints){const n=/iPad/.test(e)||/Macintosh/.test(e)&&t>1?"iPad":/iPhone/.test(e)?"iPhone":/Android/.test(e)?"Android":/Windows/.test(e)?"Windows":/Macintosh|Mac OS X/.test(e)?"Mac":/Linux/.test(e)?"Linux":"设备",r=/Electron/.test(e)?"Termdock":/Edg\//.test(e)?"Edge":/Firefox|FxiOS/.test(e)?"Firefox":/Chrome|CriOS/.test(e)?"Chrome":/Safari/.test(e)?"Safari":"浏览器";return`${n} · ${r}`}let NA;function LA(){return NA??=(async()=>{const e=navigator.userAgent,[t,n]=em().split(" · "),r=/(?:Edg|Firefox|FxiOS|Chrome|CriOS|Version)\/([\d.]+)/g,o=[...e.matchAll(r)],i=/(?:CPU (?:iPhone )?OS |Mac OS X |Android )([\d._]+)/.exec(e)?.[1]?.replaceAll("_","."),s={system:`${t}${i?` ${i}`:""}`,client:`${n}${o.length?` ${o.at(-1)[1]}`:""}`,mode:matchMedia("(display-mode: standalone)").matches||navigator.standalone?"已安装的网页应用":"网页"},a=it();if(a){s.mode="桌面客户端";const l=/Electron\/([\d.]+)/.exec(e)?.[1];s.client=l?`Termdock(Electron ${l})`:"Termdock";try{Object.assign(s,await a.deviceInfo?.())}catch{}return s}const c=navigator.userAgentData;try{const l=await c?.getHighEntropyValues(["model","architecture","bitness","platformVersion"]);typeof l?.model=="string"&&l.model&&(s.model=l.model),typeof l?.architecture=="string"&&l.architecture&&(s.arch=`${l.architecture}${l.bitness?` ${l.bitness} 位`:""}`)}catch{}return s})()}const tt=[],Mc=new Set,cf=()=>Mc.forEach(e=>e()),BA=()=>tt.length>0,DA=()=>tt[tt.length-1]??null;function n2(e){const t=DA(),n=t?Yl(t.element):[document.body];return e.isConnected&&!e.closest('[hidden], [inert], [aria-hidden="true"]')&&(!t||n.some(r=>r.contains(e)))&&tm(e,n)}function r2(){return N.useSyncExternalStore(e=>(Mc.add(e),()=>{Mc.delete(e)}),BA,()=>!1)}function Yl(e){const t=Array.from(document.querySelectorAll("[data-sidebar-composer-popover]")).filter(n=>e.id&&n.dataset.sidebarComposerPopover===e.id);return[e,...t]}function tm(e,t){for(let n=e;n;n=n.parentElement){const r=getComputedStyle(n);if(r.display==="none"||r.visibility==="hidden")return!1;if(t.includes(n))break}return!0}function lf(e){const t=Yl(e);return t.flatMap(n=>Array.from(n.querySelectorAll("button:not(:disabled), input:not(:disabled), textarea:not(:disabled), select:not(:disabled), a[href], summary, [tabindex]"))).filter(n=>{const r=n.closest("details:not([open])"),o=r?.querySelector("summary");return n.tabIndex>=0&&!n.matches(":disabled")&&!n.closest('[hidden], [inert], [aria-hidden="true"]')&&(!r||!!o?.contains(n))&&tm(n,t)})}function _A(e,t,n,r){const o=N.useRef(n);o.current=n;const i=N.useRef(r);i.current=r,N.useLayoutEffect(()=>{const s=e.current;if(!t||!s)return;const a=document.activeElement instanceof HTMLElement?document.activeElement:null,c={element:s},l=tt.findIndex(v=>s.contains(v.element));l<0?tt.push(c):tt.splice(l,0,c),cf();const d=()=>tt[tt.length-1]===c,u=v=>v instanceof Node&&Yl(s).some(w=>w.contains(v)),f=()=>(lf(s)[0]??s).focus({preventScroll:!0});d()&&f();const h=v=>{d()&&!u(v.target)&&f()},g=v=>{if(!d()||v.key!=="Tab"||v.defaultPrevented)return;const w=lf(s),S=w[0],y=w[w.length-1];(!S||!u(document.activeElement)||(v.shiftKey?document.activeElement===S:document.activeElement===y))&&(v.preventDefault(),(v.shiftKey?y:S)?.focus({preventScroll:!0}))},m=v=>{!d()||v.key!=="Escape"||v.defaultPrevented||v.isComposing||(v.preventDefault(),v.stopImmediatePropagation(),o.current())};return document.addEventListener("focusin",h,!0),document.addEventListener("keydown",g,!0),document.addEventListener("keydown",m),()=>{const v=d();if(tt.splice(tt.indexOf(c),1),cf(),document.removeEventListener("focusin",h,!0),document.removeEventListener("keydown",g,!0),document.removeEventListener("keydown",m),v){const w=tt[tt.length-1];queueMicrotask(()=>{if(tt[tt.length-1]!==w)return;(a?.isConnected&&a!==document.body?a:i.current?.())?.focus({preventScroll:!0})})}}},[t,e])}function OA({service:e,onBusyChange:t,onConnect:n,onConnectWithPassword:r}){const[o,i]=N.useState(),[s,a]=N.useState(!0),[c,l]=N.useState(!1),[d,u]=N.useState(""),[f,h]=N.useState(0),[g,m]=N.useState(),[v,w]=N.useState("");N.useEffect(()=>{let A=!1,R=!1,E;a(!0),u(""),i(void 0);const C=async k=>{try{const b=await k1(e);if(A)return;R=!0,i(b),u("")}catch(b){!A&&(!R||k)&&u(b instanceof Error?b.message:"暂时无法读取中转列表,请重试。")}finally{A||(a(!1),E=setTimeout(()=>{C(!1)},2e3))}};return C(!0),()=>{A=!0,clearTimeout(E)}},[e.id,e.url,f]);const S=async A=>{if(!c){l(!0),t(!0),u("");try{await A()}catch(R){u(R instanceof Error?R.message:"暂时无法连接,请重试。")}finally{l(!1),t(!1)}}},y=async A=>{const R=await I1(o.route,A.serviceId);try{await n(R)}catch(E){if(!(E instanceof ut))throw E;m(R)}};return p.jsxs("div",{className:"service-form",children:[g?p.jsxs("form",{className:"service-form",onSubmit:A=>{A.preventDefault(),S(async()=>{try{await r?.(g,v)}finally{w("")}})},children:[p.jsxs("p",{className:"service-help",children:["已通过“",e.label,"”连接到“",g.serviceName,"”。请登录目标服务,完成此设备的访问授权。"]}),r?p.jsxs(p.Fragment,{children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"目标服务密码"}),p.jsx("input",{type:"password",autoFocus:!0,required:!0,autoComplete:"current-password",value:v,disabled:c,onChange:A=>w(A.target.value)})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:c||!v,children:c?"正在登录…":"登录并连接"})]}):p.jsx("p",{className:"service-help",children:"请让目标服务管理员邀请此设备后再连接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>{m(void 0),w(""),u(""),h(A=>A+1)},children:"返回中转列表"})]}):p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["通过“",e.label,"”连接下方服务。",o?.canManage?"选择未授权的服务会授权此设备使用该中转。":"这里只显示已授权给此设备的中转。","目标服务会单独验证访问权限。"]}),s?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(et,{size:16,className:"service-spinning"}),"正在读取可中转的服务…"]}):o&&p.jsxs("div",{className:"service-list",children:[o.items.map(A=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:c||!A.available,onClick:()=>{S(()=>y(A))},children:[p.jsx("span",{className:"service-icon",children:p.jsx(Os,{size:19})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:A.label||(A.url?new URL(A.url).host:`中转服务 ${A.serviceId.slice(0,8)}`)}),p.jsx("span",{className:"service-description",children:A.available?A.authorized?"已获中转授权 · 连接":"授权此设备并连接":"中转暂不可用"})]}),p.jsx(Un,{size:16})]},A.serviceId)),o.items.length===0&&p.jsx("p",{className:"service-empty",children:o.canManage?"暂无可中转的服务。可在本机 Mac 客户端连接目标服务,或在目标服务的“备用连接”中启用本入口。":"暂无已授权的中转服务,请让入口管理员分享备用连接邀请。"})]}),c&&p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(et,{size:16,className:"service-spinning"}),"正在授权并连接目标服务…"]}),!s&&p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>h(A=>A+1),children:"刷新列表"})]}),d&&p.jsx("p",{className:"service-error",role:"alert",children:d})]})}const jc="#termdock-invite=";function nm(e){const t=new URL(e.entryUrl);t.hash="",t.search="",t.pathname="/";const n=new TextEncoder().encode(JSON.stringify(e));return t.hash=jc.slice(1)+btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),t.href}function Bn(e){const t=new URL(e);if(!["https:","http:"].includes(t.protocol)||!t.hash.startsWith(jc))throw new Error("这不是有效的 Termdock 邀请链接");const n=t.hash.slice(jc.length);if(n.length>8192)throw new Error("邀请链接过长");let r;try{const s=n.replace(/-/g,"+").replace(/_/g,"/");r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(atob(s),a=>a.charCodeAt(0))))}catch{throw new Error("邀请链接不完整,请重新复制")}if(r.v!==1||typeof r.serviceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(r.serviceId)||r.routeOnly!==!0&&(typeof r.code!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(r.code)))throw new Error("邀请信息无效或版本不兼容");const o=new URL(r.entryUrl);if(o.origin!==t.origin||o.username||o.password||!["https:","http:"].includes(o.protocol))throw new Error("邀请地址与服务不一致");if(o.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(o.hostname))throw new Error("远程邀请需要 HTTPS");if(r.entryServiceId!==void 0&&(typeof r.entryServiceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(r.entryServiceId)))throw new Error("邀请入口身份无效");if(r.routeCode!==void 0&&(typeof r.routeCode!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(r.routeCode)||!r.entryServiceId))throw new Error("邀请入口权限无效");if(r.routeOnly===!0&&(!r.entryServiceId||!r.routeCode||r.code!==void 0))throw new Error("备用连接邀请不完整");let i=o.origin;if(r.serviceUrl!==void 0){const s=new URL(r.serviceUrl);if(!["https:","http:"].includes(s.protocol)||s.username||s.password)throw new Error("目标服务地址无效");i=r.entryServiceId&&r.entryServiceId!==r.serviceId?s.origin:o.origin}return{url:o.origin,targetPeerId:r.serviceId,pairingCode:r.code,...r.routeOnly===!0?{routeOnly:!0}:{},serviceOrigin:i,serviceName:typeof r.name=="string"?r.name.slice(0,120):void 0,entryServiceId:r.entryServiceId,routeCode:r.routeCode}}function FA({service:e,onBusyChange:t}){const n={...e,targetPeerId:e.targetPeerId,serviceName:e.label},[r,o]=N.useState(()=>e.routes??At(n)),[i,s]=N.useState([]),[a,c]=N.useState(!0),[l,d]=N.useState(!1),[u,f]=N.useState(""),h=_=>{d(_),t(_)},[g,m]=N.useState(),[v,w]=N.useState(""),[S,y]=N.useState(""),[A,R]=N.useState(""),[E,C]=N.useState(!1),[k,b]=N.useState(),[x,T]=N.useState(),[L,I]=N.useState(!1);N.useEffect(()=>{let _=!1;return Ye().then(O=>{_||s(O.filter(H=>H.targetPeerId&&H.targetPeerId!==e.targetPeerId))}).catch(()=>{_||f("暂时无法读取可用服务。")}).finally(()=>{_||c(!1)}),()=>{_=!0}},[e.targetPeerId]);const P=_=>i.find(O=>O.targetPeerId===_.targetPeerId)?.label||new URL(_.url).host,B=async _=>{h(!0),f(""),R("");try{await _()}catch(O){const H=O instanceof Error?O.message:"";f(/AUTHORIZATION|DENIED/.test(H)?"当前设备没有入口管理权限。请让管理员分享备用连接邀请,或使用入口密码授权。":"暂时无法完成。请确认入口能连接目标服务,且目标地址、证书和授权有效。")}finally{h(!1)}},D=async(_,O)=>{const H={url:_.serviceOrigin||_.url,targetPeerId:_.targetPeerId};await B(async()=>{const V=await R1(H,n.targetPeerId);if(!V.grants.some(W=>W.active)){if(!V.canManage&&O===void 0){m(_);return}await T1(n,H,O)}const z=[...r.filter(W=>W.targetPeerId!==H.targetPeerId||W.url!==H.url),H];await ki(e,z),o(z),m(void 0),w("")})};if(x)return p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["把链接发给需要使用此备用连接的人。它只允许通过入口连接“",e.label,"”,对方仍需获得目标服务的访问权限。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用连接邀请"}),p.jsx("input",{readOnly:!0,value:x,onFocus:_=>_.target.select()})]}),p.jsxs("button",{type:"button",className:"service-button service-primary",onClick:()=>{navigator.clipboard.writeText(x).then(()=>I(!0)).catch(()=>f("无法自动复制,请长按链接复制。"))},children:[p.jsx(Vg,{size:16}),L?"已复制":"复制邀请链接"]}),p.jsx("button",{type:"button",className:"service-button service-secondary",onClick:()=>{T(void 0),I(!1)},children:"返回备用连接"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});if(g)return p.jsxs("form",{className:"service-form",onSubmit:_=>{_.preventDefault(),D(g,v).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:v,onChange:_=>w(_.target.value),autoComplete:"current-password",disabled:l,autoFocus:!0})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||!v,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 F=r.filter(_=>_.targetPeerId===n.targetPeerId),j=r.filter(_=>_.targetPeerId!==n.targetPeerId),M=i.flatMap(_=>yn({..._,targetPeerId:_.targetPeerId}).map(O=>({..._,id:JSON.stringify([_.id,O]),url:O,serviceOrigin:O}))),U=async()=>{if(!l){h(!0),C(!0),f(""),R("");try{o(await N1({...e,routes:r},S)),y(""),R("备用地址已验证并保存。")}catch(_){f(_ instanceof Error?_.message:"暂时无法添加地址,请重试。")}finally{h(!1),C(!1)}}};return p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"电脑换了网络?添加它在新网络下的地址,原地址连不上时会自动尝试。只接受同一台服务。"}),p.jsxs("form",{className:"service-form",onSubmit:_=>{_.preventDefault(),U()},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用地址"}),p.jsx("input",{value:S,onChange:_=>{y(_.target.value),f(""),R("")},required:!0,disabled:l||r.length>=4,inputMode:"url",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:192.168.10.20:9834"})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||r.length>=4||!S.trim(),children:E?p.jsxs(p.Fragment,{children:[p.jsx(et,{size:16,className:"service-spinning"}),"正在验证…"]}):"验证并添加"})]}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u}),A&&p.jsx("p",{role:"status",className:"service-help",children:A}),r.length>=4&&p.jsx("p",{className:"service-help",children:"已保存 4 个备用连接。移除不再使用的地址或入口后,可以继续添加。"}),p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"首选地址"}),p.jsx("p",{className:"service-address",children:e.serviceOrigin||e.url})]}),F.length>0&&p.jsx("div",{className:"service-list",children:F.map(_=>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:_.url}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`移除地址 ${_.url}`,disabled:l,onClick:()=>b(_),children:"移除"})]}),k?.targetPeerId===_.targetPeerId&&k.url===_.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:()=>b(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{B(async()=>{const O=r.filter(H=>H.targetPeerId!==_.targetPeerId||H.url!==_.url);await ki(e,O),o(O),b(void 0)})},children:"确认移除"})]})]})]},_.url))}),p.jsxs("details",{className:"service-relay-options",children:[p.jsxs("summary",{children:["通过其他服务中转",j.length?`(${j.length})`:""]}),p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"所有直连地址都不可用时,尝试下方已授权入口;直连恢复后自动切回。"}),j.length>0&&p.jsx("div",{className:"service-list",children:j.map(_=>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(Os,{size:18})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:P(_)}),p.jsx("span",{className:"service-description",children:_.url})]}),p.jsx(cs,{size:16,className:"service-selected"})]}),k?.targetPeerId===_.targetPeerId&&k.url===_.url?p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["撤销此设备经“",P(_),"”所有地址连接目标的权限?如当前无法直连,目标服务将断开。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>b(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{B(async()=>{await P1(n.targetPeerId,_);const O=r.filter(H=>H.targetPeerId!==_.targetPeerId);await ki(e,O),o(O),b(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:()=>{B(async()=>{const O=await Hg(n,_);T(nm({v:1,routeOnly:!0,serviceId:n.targetPeerId,name:e.label,serviceUrl:e.serviceOrigin||e.url,entryUrl:_.url,entryServiceId:_.targetPeerId,routeCode:O.routeCode}))})},children:"分享备用连接"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>b(_),children:"撤销授权"})]})]},JSON.stringify([_.targetPeerId,_.url])))}),a?p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(et,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"添加中转入口"}),M.filter(_=>!r.some(O=>O.targetPeerId===_.targetPeerId&&O.url===_.url)).map(_=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:l||r.length>=4,onClick:()=>{D(_)},children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:_.label}),p.jsx("span",{className:"service-description",children:_.url})]}),p.jsx(Un,{size:16})]},_.id)),i.length===0&&p.jsx("p",{className:"service-empty",children:"添加并登录另一台服务后,可以将它设为中转入口。"})]})]})]}),l&&!E&&p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(et,{size:16,className:"service-spinning"}),"正在验证连接与授权…"]})]})}const MA={architecture:{choosePaths:"Choose folders or files",browsePaths:"Browse",addScopeReference:"Add to analysis scope",searchScopePaths:"Search files or folders",useCurrentFile:"Use current file",useCurrentDirectory:"Use current folder",browsePathsHint:"Expand folders to browse. Use the reference button on a row to add it to the analysis scope.",correctPathsFirst:"Correct the entered paths before adding more scope.",pathsHint:"Choose scope or paste file/line references. Paths are relative to this project.",featureScopeHint:"Locate this feature within the selected scope first",removePath:"Remove path",chooseThisDirectory:"Select this folder",filterDirectory:"Filter this folder",loadingPaths:"Loading folder…",pathsLoadFailed:"Could not read this folder. Check connection or access, then retry.",noPaths:"No matching files or folders here.",pathsTruncated:"This folder has too many entries to show at once. Open a subfolder or paste its path directly.",selectedPaths:"Selected paths",usePaths:"Use selected scope",expandDetail:"Read module details",collapseDetail:"Collapse module details",backToMap:"Back to map",backToModule:"Back to module",previousModule:"Previous module",parentModule:"Back to parent",viewPrepared:"View this analysis",closeDetail:"Close module details",connections:"Connections",outgoing:"To",incoming:"From",browseMode:"Browse mode",outlineMode:"Module details",graphMode:"Relationship diagram",analysisNotes:"Analysis notes",limitations:"Scope and limitations",analyzedPaths:"Analyzed sources",fitGraph:"Fit entire diagram",fullscreen:"Open fullscreen diagram",closeFullscreen:"Close fullscreen diagram",panHint:"Drag to pan, pinch to zoom; select a module for details",newAnalysis:"New analysis",updateAnalysis:"Update current analysis",closePreparation:"Close analysis settings",analysisRange:"Analysis scope",projectRange:"Entire project",moduleRange:"Directory / module",featureRange:"Feature flow",modulePaths:"Module paths (one per line)",modulePlaceholder:"Choose folders/files or paste existing references, one per line",featureTarget:"Feature to understand",featurePlaceholder:"For example: file upload from selecting a file to storage",invalidPaths:"Choose up to 20 project folders/files or paste their references; outside paths and .. are not allowed.",requiredFeature:"Describe a specific feature and check that optional starting paths are project-relative.",independentHint:"Scoped analyses are saved separately. Repeating the same scope updates its map; the entire project uses the project overview.",updateOnly:"Only this analysis will be updated. Other maps are preserved.",analysisOptions:"Dependencies and other options",dependencyDepth:"Dependency tracing",boundaryDepth:"Scope boundary (faster)",followDepth:"Follow relevant calls and dependencies",startPaths:"Feature scope (optional)",focus:"Analysis request and constraints (optional)",focusPlaceholder:"For example: explain permission checks and retries; skip styling.",savedAnalyses:"Saved analyses",libraryFailed:"Could not list analyses. The current map is still available. Refresh to retry.",awaitingFile:"This analysis has not been saved yet. Send the prepared prompt to your Agent; the result will appear after the file is saved.",analyzeModule:"Analyze this module in detail",scopeUnavailable:"This scoped map is missing analysis metadata. Create a new analysis to specify its boundaries.",tab:"Map",title:"Code architecture",generate:"Generate",update:"Update",refresh:"Refresh architecture",prepare:"Prepare architecture analysis",promptHint:"Use the Agent in this project's terminal to analyze the code. The prompt goes into the current input or context draft for you to review and send. This view refreshes when the architecture is saved. Open an Agent first; analysis uses its time and allowance.",insertPrompt:"Insert prompt",copyPrompt:"Copy prompt",previewPrompt:"Review analysis prompt",inserting:"Adding to the current input…",insertFailed:"Could not add the prompt. Check the current session, or copy it below.",inserted:"Review the current input or context draft, then send it to your Agent.",copied:"Prompt copied.",failed:"Copy failed. Copy manually from the prompt below.",loading:"Reading project architecture…",invalid:"The architecture file is invalid. Analyze the project again to repair it.",loadFailed:"Could not read project architecture. Check connection and access, then retry.",previous:"The last successfully loaded architecture remains below.",retry:"Retry",empty:"Understand this project's architecture",emptyHint:"Start with the project, selected paths or one feature. A full project map is not required.",savedAt:"Saved",perspective:"Perspective",breadcrumb:"Architecture hierarchy",modules:"Modules",explore:"Explore submodules",sourceFiles:"Related source",diagram:"Architecture diagram",diagramHint:"Select a module for details",zoomOut:"Zoom out diagram",zoomIn:"Zoom in diagram",resetZoom:"Reset diagram zoom",download:"Download architecture SVG",downloadFailed:"Download failed. Please retry.",diagramFailed:"The diagram could not render. You can still explore the modules below.",rendering:"Drawing architecture…"},computer:{returnToDesktop:"Return to desktop",tools:"Control settings",closeTools:"Close control settings",keyboard:"Keyboard",keyboardInput:"Type directly on the computer",keyboardPlaceholder:"Tap to type directly on the computer",hideKeyboard:"Hide keyboard",keyboardNavigation:"Keyboard navigation",desktopZoom:"Desktop zoom",zoomIn:"Zoom in desktop",zoomOut:"Zoom out desktop",resetZoom:"Fit desktop to screen",pinchHint:"Pinch to zoom",keyEscape:"Send Esc",keyLeft:"Move left",keyDown:"Move down",keyUp:"Move up",keyRight:"Move right",keySelectAll:"Select all",clipboardTool:"Clipboard",zoom:"Zoom in",expand:"Full screen",switchTouchMode:"Switch touch mode",touchMode:"Touch mode",trackpadMode:"Trackpad",directTouchMode:"Direct touch",trackpadHint:"Slide to move, tap to click, hold to drag. Use two fingers to scroll or tap for right-click.",directTouchHint:"Tap a position on the screen to click. Drag your finger to interact with the desktop.",trustCertificateHere:"Trust this computer’s certificate",rememberLogin:"Remember login",autoConnect:"Connect automatically next time",forgetLogin:"Forget login",savedPassword:"Saved — leave empty to connect",loginExpired:"Saved login expired. Enter your password again.",loginSaveFailed:"Could not save or retrieve login details. Please retry.",title:"Computer control",host:"Computer address",hostPlaceholder:"192.168.1.20 or computer.local",username:"Username (optional)",password:"Password",passwordHint:"Enter the target computer’s VNC password. Include a username if the server requires account sign-in. Remember login encrypts credentials on the service after a successful connection.",connect:"Connect",disconnect:"Disconnect",cancel:"Cancel",connecting:"Connecting…",connected:"Connected",disconnected:"Disconnected. You can reconnect.",viewOnly:"View only",control:"Allow control",fit:"Fit to panel",actualSize:"Actual size",fullscreen:"Expand desktop",exitFullscreen:"Collapse desktop",setup:"How to connect a computer",step1:"On your Mac, open System Settings → General → Sharing → Screen Sharing.",step2:"Allow your user in Screen Sharing settings. For a VNC password, enable “VNC viewers may control screen with password”.",step3:"Enter a private computer address reachable from this service. To control the computer running this service, choose “This computer”.",networkHint:"Uses VNC port 5900. Browser-to-Termdock traffic is encrypted; use a trusted LAN or VPN for the VNC connection from the service to the target computer.",service:"Current service: {name}",remoteTitle:"Remote computer desktop",startHint:"Connect to view the desktop and control the computer with mouse, touch, and keyboard.",credentials:"Enter login credentials",authenticate:"Sign in",authFailed:"Sign-in failed. Check the username, password, and remote desktop permissions.",sharingOff:"VNC connection refused. Start desktop sharing and check port 5900.",unreachable:"Cannot reach the computer. Check the address, network, and firewall.",timeout:"Connection timed out. Make sure the target computer is awake and reachable from this service.",invalidHost:"Enter a private IP or hostname without a protocol or port.",privateOnly:"Only private or local addresses are supported. For remote access, switch to the Termdock service on the target computer.",permission:"Computer control requires full access to the current service.",failed:"Connection failed. Please reconnect.",clipboard:"Send clipboard",clipboardPlaceholder:"Send text to the computer clipboard",clipboardHint:"Enter text and press {shortcut} to paste, or send it to the clipboard only. Character support depends on the target computer.",remoteClipboard:"Text copied on the computer",copyToDevice:"Copy to this device",clipboardCopied:"Copied to this device",clipboardAccessFailed:"System clipboard is unavailable. Enter text here to send, or select the received text and copy it manually.",clipboardSent:"Sent to computer clipboard",shortcuts:"Shortcuts",switchApps:"Switch apps",spotlight:"Spotlight search",desktop:"Show desktop",loading:"Loading computer control…",platform:"Target system",thisComputer:"This computer",otherComputer:"Another computer",target:"Computer to connect",localService:"Computer running the current Termdock service · {name}",advanced:"Advanced settings",rdpLoginHint:"Use the credentials from Remote Desktop settings.",vncLoginHint:"Use your screen sharing VNC password.",checkSettings:"Check connection settings",localHint:"Local means the computer running the current Termdock service. Enable the selected remote desktop protocol on the target first.",linuxStep1:"Ubuntu / Linux needs a VNC server. To share the current desktop with x11vnc, use an X11 session; select “Ubuntu on Xorg” at the Ubuntu login screen.",linuxStep2:"Set a VNC password and listen on port 5900. RDP-only desktop sharing cannot connect here.",linuxCommandHint:"Run these commands in a desktop terminal on the target, then enter the VNC password you set. This example only accepts connections from the service computer. Commands are not run automatically:",linuxProtocolHint:"Ubuntu 24.04’s built-in Remote Desktop uses RDP; this panel uses VNC. Wayland needs a VNC server compatible with the desktop. TigerVNC virtual desktops are separate sessions, not the current screen.",windowsStep1:"Install and start a compatible VNC server on Windows. Windows RDP Remote Desktop cannot connect here.",windowsStep2:"Set a VNC password, enable keyboard and mouse control, and allow this service to reach port 5900 through the firewall.",systemSearch:"System search",protocol:"Connection protocol",port:"RDP port",rdpUsername:"RDP username",domain:"Domain (optional)",rdpPasswordHint:"Use the RDP username and password configured in Remote Desktop settings. Ubuntu remote login credentials may differ from your system account. Remember login encrypts credentials on the service after a successful connection.",rdpBackendUnavailable:"RDP support is unavailable on this service. Complete the server-side RDP setup first.",rdpBackendRecovery:"Start the RDP backend (guacd) on the computer running this Termdock service, then refresh this page to check again. Connection settings are kept; you can also switch to VNC in advanced settings.",rdpFailed:"RDP connection failed. Check Remote Desktop, the port, and credentials. For a self-signed certificate, verify the computer’s identity before enabling certificate trust.",rdpLinuxStep1:"On Ubuntu, open Settings → System → Remote Desktop. Enable Desktop Sharing or Remote Login and configure RDP credentials.",rdpStep1:"Enable RDP on the target computer. On Windows, use Settings → System → Remote Desktop. Use VNC for built-in Mac Screen Sharing.",rdpStep2:"Enter the username, password, and port from Remote Desktop settings. The default RDP port is 3389; Ubuntu Desktop Sharing may use 3390. Verify the target before trusting a self-signed certificate.",rdpNetworkHint:"Display and input use the encrypted browser-to-Termdock channel. The current service connects to the target over RDP. Desktop Sharing and Remote Login may use different sessions; showing the current screen depends on the target service’s settings.",trustCertificate:"Trust this computer’s RDP certificate (skip verification)",settingsLoading:"Loading connection settings…",settingsSaving:"Saving settings…",settingsSaved:"Connection settings saved on this service.",settingsSaveFailed:"Settings could not be saved. Your edits are still on this page.",settingsLoadFailed:"Connection settings could not be loaded. Please retry.",retry:"Retry",retryConnect:"Retry connection",rdpCertificate:"The target computer’s RDP certificate could not be verified. After confirming the computer’s identity, trust its certificate below and retry.",clipboardFailed:"Failed to send clipboard. Try again."},app:{name:"Termdock"},android:{device:"Device",selectDevice:"Select device",noDevices:"No device found",closeTab:"Close device tab",refresh:"Refresh devices",connect:"Connect",disconnect:"Stop mirroring",addDevice:"Connect over network",addressPlaceholder:"ip:port, e.g. 192.168.1.20:5555",adbUnavailable:"adb (Android platform-tools) not found; mirroring is unavailable. macOS: brew install android-platform-tools; Ubuntu: sudo apt install adb; or set TERMDOCK_ADB_BIN in ~/.termdock/.env.",scrcpyUnavailable:"scrcpy / scrcpy-server not found; mirroring is unavailable. macOS: brew install scrcpy; Ubuntu: sudo apt install scrcpy; or set TERMDOCK_SCRCPY_BIN in ~/.termdock/.env.",connecting:"Connecting to device…",reconnecting:"Connection lost, reconnecting…",retrySchedule:"Retry {attempt} starts in {seconds} seconds",lastError:"Last error (retained while reconnecting)",retry:"Retry",idleHint:"Pick a device to start mirroring",noDevicesHint:"Connect a phone over USB with debugging enabled, or add a network device",back:"Back",home:"Home",recents:"Recents",notifications:"Notifications",rotate:"Rotate",volumeUp:"Volume up",volumeDown:"Volume down",power:"Power",zoomIn:"Zoom in",zoomOut:"Zoom out",zoomPanHint:"Two-finger drag to move the view",inputText:"Type text",inputPlaceholder:"Text to send to the phone",send:"Send",splitOpen:"Open in split view",splitClose:"Exit split view",splitDockedHint:"Mirroring is shown in the split area.",splitDrag:"Drag to reposition",insertFixPrompt:"Insert fix prompt",screenshot:"Screenshot and insert",recordingStart:"Start recording",recordingStop:"Stop recording",recording:"Recording…",recordingLimit:"Reached the 5-minute limit, recording stopped",recordingStopped:"Mirroring stopped, recording ended",captureInserted:"Screenshot inserted",recordingInserted:"Recording inserted",recordingConfirm:"Recording finished. What next?",recordingInsert:"Insert directly",recordingSave:"Save to a folder",recordingSaveHint:"Recorded on the server. Insert a file reference, or save to a server folder.",recordingDiscard:"Discard recording",captureInserting:"Inserting…",recordingSaving:"Saving recording…",captureFailed:"Insert failed",captureUnavailable:"Cannot insert into the terminal right now",more:"More",fullscreen:"Fullscreen",fillSidebar:"Fill sidebar",exitFullscreen:"Exit fullscreen",fullscreenHint:"Mirroring is shown in fullscreen.",quality:"Quality",qualityAutoHint:"Adapts bitrate to connection and decoding performance without reconnecting. Resolution stays stable; controls and server recording are unaffected.",qualityAutoUnavailable:"Automatic bitrate adjustment paused; video stays connected.",qualityAutoVersionError:"Server scrcpy version is not supported (details).",qualityAutoBuildError:"Server scrcpy build has not been verified (details).",qualityAutoExtensionError:"Bitrate extension could not be read, verified or transferred (details).",qualityAutoTimeoutError:"Bitrate confirmation timed out; encoder support is unknown (details).",qualityAutoEncoderError:"Device encoder rejected this adjustment (details).",qualityAutoChannelError:"Bitrate control channel failed (details).",qualityAutoUnknownError:"Server did not provide a reason; update that server and retry (details).",qualityLow:"Smooth",qualityMedium:"Standard",qualityHigh:"HD",qualityCustom:"Custom",qualityResolution:"Resolution",qualityBitRate:"Bitrate",qualityFrameRate:"Frame rate",qualityAuto:"Auto",qualityApply:"Apply",presetNamePlaceholder:"Preset name",presetSave:"Save preset",presetDelete:"Delete preset",stateUnauthorized:"unauthorized",stateOffline:"offline",stateUnknown:"unknown state",unauthorizedHint:"Confirm the USB debugging prompt on the phone.",offlineHint:"Device is offline; reconnect the cable or network device."},common:{cancel:"Cancel",close:"Close",save:"Save",reset:"Reset",loading:"Loading…",error:"Error",retry:"Retry",refresh:"Refresh",search:"Search",clear:"Clear",delete:"Delete",on:"On",off:"Off",back:"Back",copy:"Copy",decrease:"Decrease",increase:"Increase",use:"Use",previous:"Previous",next:"Next"},login:{prompt:"termdock login",placeholder:"Enter password",placeholderBlocked:({s:e})=>`Please wait ${e}s`,submit:"Sign in",invalidPassword:"The password is incorrect, or the service identity could not be verified. Check and try again.",identityMismatch:"The service identity has changed. Check the address with its owner before trying again.",unavailable:"Password sign-in is temporarily unavailable. Check the connection and try again.",authorizationRequired:"This device needs authorization. Ask the service owner for a new invitation.",currentTarget:({address:e})=>`Signing in to ${e}`,manageServices:"Manage services / use another address",failed:"Could not sign in. Check the connection and try again.",rateLimited:"Too many attempts. Please wait and try again.",continueAfterReconnect:"You can continue signing in when the network returns.",savedConnectionRetained:"Saved service retained. Access will be checked after reconnecting.",invalidAddress:"Enter a valid HTTPS service address, for example computer.example:9834 or https://computer.example:9834.",invalidInvitation:"This invitation is incomplete or invalid. Copy the full invitation link and try again."},sidebar:{sessionCreating:"Starting…",sessionCreateDirectoryUnavailable:"The working directory is unavailable. Choose another folder and try again.",sessionCreatePermissionDenied:"You do not have permission to start here. Choose another folder.",sessionCreateConnectionFailed:"Could not connect. Check the connection and try again.",sessionCreateFailed:"Could not start the session. Please try again.",sessions:"Sessions",noSessions:"No open sessions yet.",noMatchingSessions:"No matching sessions.",toggleSearch:"Toggle search",settings:"Settings",moreActions:"More actions",subscriptionQuota:"Subscription quota",pinSidebar:"Keep sidebar open",unpinSidebar:"Stop keeping sidebar open",runningSessionButton:"Running sessions button",runningSessionButtonHint:"Tap to cycle, swipe sideways to select, hold to drag",attentionButton:"Attention button",attentionButtonHint:"Show the yellow floating bell for unread or pending sessions",updateAvailable:({version:e})=>`Termdock ${e} is available`,updateInstalling:"Installing in the background without interrupting this service.",updateReady:"The update is installed and ready for a confirmed restart.",updateRestart:"Restart and finish update",updateRestartConfirm:({version:e})=>`Restart Termdock and switch to ${e}? This page will reconnect briefly and sessions will stay open.`,updateRestarting:"Restarting; this page will reconnect automatically…",updateFailed:"Automatic installation failed. This reminder will remain.",updateRetry:"Try again",serverAttention:"The service had a problem",filterSessions:"Filter sessions",clearSearch:"Clear search",groupByFolder:"Group by folder",groupByFolderTitle:"Collapse sessions into groups by working directory. Mutually exclusive with drag sorting.",ungrouped:"Other",needsAttention:"Needs attention",waitingForYou:"Waiting for you",completedUnread:"Completed · unread",closeSession:({name:e})=>`Close ${e}`,newShell:"Shell",newTmux:"Tmux",newTmuxDisabled:"tmux not available on server",confirmNewShell:"Create Shell?",confirmNewTmux:"Create Tmux?",newSession:"New terminal",newSessionWithAgent:({agent:e})=>`New ${e}`,moreLaunchOptions:"More launch options",recoverableSessions:"Recoverable sessions",confirmCloseRecoverableSession:({name:e})=>`End ${e}? This stops all processes in the session.`,endRecoverableSession:"End session",closeRecoverableSessionFailed:"Could not end the session. Please retry.",refreshRecoverableSessions:"Refresh recoverable sessions",restoreRecoverableSession:({name:e})=>`Restore ${e}`,restoringRecoverableSession:"Restoring…",restore:"Restore",newSessionAdvanced:"Quick-launch agent",newSessionComposerTitle:"Start a session",newSessionHint:"Choose how and where it starts",launchSessionWith:({name:e})=>`Start ${e}`,setNewSessionDefault:({name:e})=>`Set ${e} as default`,currentNewSessionDefault:({name:e})=>`${e} is the current default`,currentDefaultAgent:({name:e})=>`Current default: ${e}`,defaultAgent:"Default",makeDefault:"Make default",sessionMode:"Run mode",tmuxKeepsRunning:"Keeps running after disconnect",resumeHistory:"Recent conversations",resumeHistoryCount:({n:e})=>`${e} saved`,resumeHistoryLoading:"Loading recent Agent conversations…",resumeHistoryAction:({title:e})=>`Resume ${e}`,resumeHistoryRemove:({title:e})=>`Remove ${e} from recent conversations`,resumeHistoryLoadFailed:"Could not load recent Agent conversations.",resumeHistoryFailed:"Could not prepare this Agent conversation for resume.",resumeHistoryRemoveFailed:"Could not remove the conversation from history.",customStartupCommand:"Custom command",changeStartupCommand:"Change startup command",saveStartupCommand:"Save command",startupCommandSaved:"Saved",saveStartupCommandFailed:"Could not save. Check browser storage permissions.",addStartupCommand:"Add custom command…",deleteStartupCommand:"Delete command",startupCommand:"Startup command",resetStartupCommand:"Reset",startupCommandPlaceholder:"e.g. vim, htop or npm run dev",agentStartupCommandHint:"Edit the full command; leave blank for the Agent default. Saved in this browser.",terminalStartupCommandHint:"Run a program in the selected directory, e.g. vim README.md. Saved in this browser.",workingDirectory:"Working directory",directoryPlaceholder:"Enter a directory path",browseDirectories:"Browse",hideDirectoryBrowser:"Hide browser",chooseDirectory:"Choose working directory",directoryPickerHint:"Open a folder, then confirm the current location.",useThisFolder:"Use folder",recentDirectories:"Recent directories",startCommand:"Start command",customCommand:"Other command",commandPlaceholder:"Optional, e.g. codex",detectAgents:"Detect agents again",savePreset:"Save as preset",createAndRun:"Create and run",createSession:"Create terminal",openLeftSidebar:"Open left sidebar",openRightSidebar:"Open right sidebar",closeSidebar:"Close sidebar"},rightSidebar:{workspace:"Workspace",currentProject:"Project",browsingLocation:"Browsing",parentFolder:"Parent folder",backToProjectRoot:"Back to project",refreshFiles:"Refresh current folder",resizeFileTree:"Drag to resize file browser",pinCurrentFolder:"Pin current folder to this project",unpinCurrentFolder:"Unpin current folder",showHiddenFiles:"Show hidden files",hideHiddenFiles:"Hide hidden files",hideGitIgnoredFiles:"Hide Git-ignored files",showGitIgnoredFiles:"Show Git-ignored files",gitIgnoreSaveFailed:"Could not save Git ignore visibility. Please retry.",gitIgnoreConfigureHint:"Long-press or right-click to configure exceptions",gitIgnoreExceptionsTitle:"Git ignore filter exceptions",gitIgnoreExceptionsHint:"Select files or folders to keep visible while filtering is enabled. Use the arrow beside a folder to browse inside it. Selected folders include all descendants; parent folders of selected files stay visible. Save to apply.",gitIgnoreExceptionsPaths:"Select files or folders",gitIgnoreExceptionsInvalid:"Select up to 200 files or folders.",gitIgnoreExceptionsLoadFailed:"Could not load this folder. Please retry.",gitIgnoreExceptionsEmptyDirectory:"This folder is empty",gitIgnoreExceptionsOpenDirectory:({name:e})=>`Open folder ${e}`,gitIgnoreExceptionsSelected:({count:e})=>`${e} selected`,gitIgnoreExceptionsClear:"Clear selection",gitIgnoreExceptionsRemove:({path:e})=>`Remove ${e}`,gitIgnoreExceptionsTruncated:"This folder has too many entries; only some are shown.",gitIgnoreExceptionsSaveFailed:"Could not save. Check that all paths are inside the current folder (up to 200), then retry.",insertCurrentFolder:"Insert current folder reference",insertCurrentFolderShort:"Insert",pinnedFolders:"Pinned",unpinFolder:({name:e})=>`Unpin ${e}`,fileWatchUnavailable:({message:e})=>`File watcher unavailable: ${e}. Click to refresh manually.`,browsingOutsideProject:"Browsing outside current project",browsingOutsideProjectHint:"Git and Changes still use the current project. File references from here are inserted as external paths.",toggleSearch:"Toggle search",refreshGit:"Refresh Git status",gitLastUpdated:({time:e})=>`Last updated: ${e}`,close:"Close",filterChanges:"Filter changes or files",searchPlaceholderContent:"Search text in files…",searchModeName:"File",searchModeContent:"Content",clearSearch:"Clear search",searchScope:"Scope",searchScopePlaceholder:"Relative folder or absolute path",resetSearchScope:"Reset to current folder",searchOptions:"Search options",searchExclude:"Exclude",searchExcludePlaceholder:"dist/**, *.lock",clearSearchExclude:"Clear exclusions",contentSearchOptions:"Content search options",matchCase:"Match case",matchWholeWord:"Whole word",useRegex:"Regex",insertGitContext:"Insert current Git context into terminal",copyGitContext:"Copy Git context",insertChangeAuditPrompt:"Explain changes",insertChangeAuditPromptTitle:"Insert the change audit prompt into the current session",changeAuditShort:"Explain changes",changeAuditLoading:"Loading hunk explanations…",changeAuditLoaded:({count:e})=>`${e} hunk explanation${e===1?"":"s"} loaded`,changeAuditLoadedAt:({time:e})=>`Generated ${e}`,changeAuditRegenerate:"Regenerate",changeAuditRefreshStale:"Fill stale",changeAuditRefreshStaleTitle:"Insert a prompt to refresh stale hunk explanations",clearChangeAudit:"Clear change explanations",clearChangeAuditTitle:"Clear hunk explanations for the current repository",changeAuditClearFailed:({message:e})=>`Failed to clear hunk explanations: ${e}`,changeAuditScopeAll:"All repositories",changeAuditScopeLabel:"Explain scope",branchAuditTitle:"Branch explanation",branchAuditShort:"Explain branch changes",branchAuditBaseLabel:"Base branch",branchAuditBasePlaceholder:"Base branch, e.g. master",branchAuditBaseSearchPlaceholder:"Search base branch",branchAuditBaseEmpty:"No branch options. Type a branch name directly.",branchAuditGenerate:"Generate",branchAuditRegenerate:"Regenerate",branchAuditGenerateTitle:"Insert a prompt to explain this branch against the base branch",branchAuditViewDiff:"View diff",branchAuditViewDiffTitle:"View target branch changes against the base branch",branchAuditDiffLoading:"Loading branch diff...",branchAuditDiffEmpty:"No changes between this branch and the base branch.",branchAuditMissingBase:({repo:e})=>`${e} has no base branch set`,branchAuditRefreshDiff:"Refresh diff",branchAuditRefreshStale:"Fill stale",branchAuditRefreshStaleTitle:"Insert a prompt to refresh stale branch explanations",branchAuditClearTitle:"Clear current branch explanation",branchAuditClearFailed:({message:e})=>`Failed to clear branch explanation: ${e}`,branchAuditCommitCount:({count:e})=>`${e} commit${e===1?"":"s"}`,branchAuditFileCount:({count:e})=>`${e} file${e===1?"":"s"}`,branchAuditTruncated:"diff truncated",branchAuditCurrent:"Saved explanation",branchAuditStale:"Explanation is stale",branchAuditEmpty:"No branch explanation yet. Generate one to persist it here for later review.",branchAuditView:"View explanations",branchAuditSaved:({count:e})=>`${e} hunk explanation${e===1?"":"s"} saved`,branchAuditGeneratedAt:({time:e})=>`Generated ${e}`,insertPreset:({label:e})=>`Insert: ${e}`,tabChanges:"Changes",tabGit:"Git",tabFiles:"Files",tabAndroid:"Device",tabComputer:"Mac",showAndroidTab:"Show device tab",showArchitectureTab:"Show architecture tab",showComputerTab:"Show computer tab",inserted:"Inserted",copied:"Copied",toggleContextDraft:"Toggle context draft",contextDraftTitle:"Context draft",contextDraftHint:"References are added here while enabled. Keep browsing, add instructions, then insert once.",contextDraftPlaceholder:"Compose a longer prompt here. Keep using sidebar references to add context…",contextDraftCollapse:"Collapse context draft",contextDraftExpand:"Expand context draft",contextDraftDisable:"Disable context draft",contextDraftClear:"Clear draft",contextDraftInsert:"Insert",contextDraftInsertAndSend:"Insert & send",contextDraftInserted:"Inserted",contextDraftSent:"Sent",contextDraftSend:"Send draft",contextDraftAppended:"Reference added",contextDraftResize:"Drag to resize, double-click for default height",contextDraftAutoCollapseAfterSend:"Collapse after insert/send",contextDraftInsertFailed:"Input not accepted — draft kept. Close the active form or return to the terminal and retry.",contextDraftPending:"Waiting…",contextDraftCharacterCount:({count:e})=>`${e} chars`,selectFilePrompt:"Select a file to preview its contents",backToFileList:"Back to file list",backToPreviousPreview:"Back to source document",insertLineRef:({lineLabel:e})=>`Insert ${e}`,insertFileRef:"Insert",copyFileRef:"Copy file reference",findInFile:"Find in file",findInFilePlaceholder:"Find in this file…",previousSearchMatch:"Previous match",nextSearchMatch:"Next match",closeFileSearch:"Close file search",downloadFile:"Download file",downloadFailed:"Download failed",downloadCanceled:"Download canceled",downloadSaved:"File saved",downloadStarted:"Browser download started",uploadPending:"Uploading…",uploadInserting:"File uploaded · waiting for input acceptance…",uploadDone:({count:e})=>`${e} files uploaded`,uploadReferenceDone:"File uploaded · reference added",uploadReferenceRejected:"File uploaded; reference not added. Close the active form or return to the original terminal and retry.",uploadLimit:"Choose up to 50 files. None were uploaded; select a smaller batch.",uploadCanceled:"Upload stopped. Check the target directory before uploading again.",uploadFileCount:({count:e})=>`${e} selected files`,uploadFile:"Upload file",uploadFiles:"Upload files",insertLocalFile:"Insert local file",insertLocalImage:"Insert local image",layoutMode:"Display mode",layoutModeAuto:"Auto",layoutModeNarrow:"Narrow",layoutModeWide:"Wide",dropToUpload:"Drop files to upload",uploading:"Uploading…",uploadSuccess:({count:e})=>`${e} file${e===1?"":"s"} uploaded`,uploadFailed:"Upload failed",binaryPreviewHint:"Binary files cannot be previewed. Use the download button above to save it.",selectedLineHint:({lineLabel:e})=>`Selected ${e} · tap "Insert" below to add to terminal`,multiLineHint:"Multi-line select: tap start line, then end line",loadingImage:"Loading image…",imagePreviewHint:"Pinch or ⌘/Ctrl + scroll to zoom · double-tap to reset",imageLoadFailed:"Failed to load image preview",loadingVideo:"Loading video…",videoPreviewHint:"Click to play · hold 2× and drag forward to speed up · arrows seek/volume · space pauses",videoLoadFailed:"Failed to load video preview",videoUnsupported:"Your browser does not support this video format",videoPlay:"Play",videoPause:"Pause",videoLongPressSpeed:({rate:e})=>`Playing at ${e}×`,videoVolume:({percent:e})=>`Volume ${e}%`,videoRotate:"Rotate 90° clockwise",videoFullscreenEnter:"Enter fullscreen",videoFullscreenExit:"Exit fullscreen",model3dLoading:"Loading 3D model…",model3dExplode:"Exploded view",model3dExplodeAxis:"Explosion axis (viewer coordinates)",model3dExplodeAmount:"Explosion amount",model3dHome:"Reset view",model3dFit:"Fit visible parts",model3dFront:"Front view",model3dTop:"Top view",model3dRight:"Right view",model3dAssemble:"Restore assembly",model3dExplodedNotice:"Exploded · dimensions and references remain assembled",model3dLoadFailed:"Failed to load 3D model preview",model3dTimeout:"3D model transfer timed out. Check your connection and retry.",model3dDimensions:({dims:e})=>`Dimensions: ${e}`,model3dHintMouse:"Drag to orbit · two-finger pan · pinch or scroll to zoom",model3dHintTouch:"One finger to orbit · two fingers to zoom & pan",model3dFullscreenEnter:"Fullscreen",model3dFullscreenExit:"Exit fullscreen",model3dBgToLight:"Light background",model3dBgToDark:"Dark background",model3dRefresh:"Reload model",model3dClipToggle:"Section view",model3dClipPosition:"Section position",model3dClipFlip:"Flip section direction",model3dFeatureToggle:"Features",model3dFeatureStatus:({total:e,positioned:t})=>`Features: ${e} · positioned ${t}`,model3dFeatureInsert:"Insert reference",model3dGlossaryToggle:"Modeling terms",model3dPickToggle:"Select part / reference",model3dPickHint:"Select a part to hide it or insert a point reference",model3dHidePart:"Hide part",model3dShowAllParts:({count:e})=>`Show all (${e})`,model3dParts:"Parts",model3dCloseParts:"Close parts",model3dSearchParts:"Find a part",model3dClearPartSearch:"Clear part search",model3dHiddenParts:({count:e})=>`${e} hidden`,model3dShowNamedPart:({name:e})=>`Show ${e}`,model3dHideNamedPart:({name:e})=>`Hide ${e}`,model3dIsolateNamedPart:({name:e})=>`Only show ${e}`,model3dIsolatePart:"Only this part",model3dShowPart:"Show part",model3dNoParts:"No matching parts",model3dUndoVisibility:"Undo",model3dClearSelection:"Clear selection",model3dAllPartsVisible:"All parts visible",model3dInspectHint:"Drag to orbit · double-tap to zoom · double-tap empty space to fit",model3dUnnamedPart:({index:e})=>`Part ${e}`,model3dCanvas:"3D model",model3dMore:"More model options",edaLoading:"Rendering KiCad file…",reviewTargetChanged:"The active session changed. Return to the original session before inserting this reference.",reviewReference:"Review reference",reviewReferenceHint:"Add context, then insert. Nothing is sent automatically.",reviewSnapshot:"Snapshot of the selected viewer",reviewCapturing:"Capturing this view…",reviewIncludeImage:"Include snapshot (stored temporarily on this server)",reviewCaptureFailed:"Snapshot unavailable; location can still be inserted.",reviewNote:"Your comment (optional)",reviewNotePlaceholder:"What should change here?",reviewDetails:"View location and quoted content",reviewUploading:"Preparing reference…",reviewAddToDraft:"Add to context draft",reviewInsert:"Insert reference",reviewUploadFailed:"Could not prepare the reference. Your comment is kept. Retry, or uncheck the snapshot to insert text only.",edaLoadFailed:"Failed to render KiCad preview",edaTimeout:"KiCad preview rendering or transfer timed out. Please retry.",edaRefresh:"Render again",edaPickHint:"Click a schematic or PCB location to create an electronics annotation",edaPickedPosition:({x:e,y:t})=>`Selected ${e}%, ${t}%`,edaPickedBoardPosition:({x:e,y:t,object:n})=>`Board ${e}, ${t} mm · ${n}`,edaInspecting:"Reading board coordinates and nearby object…",edaNoNearbyObject:"No nearby object",edaInsertAnnotation:"Insert electronics annotation",csvUnnamedColumn:({index:e})=>`Column ${e}`,csvSelectedCell:({row:e,column:t})=>`Row ${e} · ${t}`,csvPickHint:({rows:e,columns:t})=>`${e} records · ${t} columns; click a cell to reference`,csvInsertAnnotation:"Insert table annotation",csvTablePreview:"Table preview: select a cell to reference its record",kicadLocalStateNotice:"This is local UI state and is not part of schematic, PCB, or manufacturing review.",kicadShowRawJson:"Show raw JSON",kicadProjectPickHint:"Select a setting to insert a reference",kicadInsertSetting:"Insert setting",markdownPreview:"Preview",markdownSource:"Source",markdownParseFailed:"Markdown preview parsing failed or exceeded its limits. Showing the source text.",markdownPreviewHint:"Tap a line/section to reference, tap another to extend; drag the left rail to select a range",htmlPreview:"Preview",htmlSource:"Source",htmlPreviewHint:"Sandboxed iframe preview; scripts run sandboxed",htmlFullscreenEnter:"Enter fullscreen preview",htmlFullscreenExit:"Exit fullscreen preview",markdownOutline:"Markdown outline",markdownOutlineShort:"Outline",closeMarkdownOutline:"Close outline",changedFromPath:({path:e})=>`from ${e}`,selectedLineFooter:({lineLabel:e})=>`Selected ${e}`,clearSelection:"Clear",allChanges:"All changes",backToChangeList:"Back to list",allRepositories:"All repositories",allRepositoriesShort:"All",repositories:"Repositories",gitRepositorySectionTitle:"Repository",gitRepositoryLabel:"Repository",gitRepositoryPlaceholder:"Select repository",gitRepositorySearchPlaceholder:"Search repositories",gitRepositoryEmpty:"No available repositories",selectRepositoryForGitActions:"Select a repository before running Git actions",selectRepositoryForDiff:"Select a repository or file to view diff",repoNotLoaded:"Tap to load",repoChangedCount:({count:e})=>`${e} change${e===1?"":"s"}`,repoStagedCount:({count:e})=>`${e} staged`,noChanges:"No changes",noMatchingChanges:"No matching changes",loadingGitChanges:"Loading Git changes…",loadingGitChangesSlow:"Large repositories can take a few seconds.",refreshingGitChanges:"Refreshing Git changes…",gitChangesLoadFailed:"Unable to load Git changes",retryGitChanges:"Retry",insertThisFile:"Insert this file reference into terminal",viewDiff:"View diff",diffViewMode:"Change file display mode",diffViewModeList:"Flat list",diffViewModeTree:"Folder tree",diffViewModeAi:"AI walkthrough",changeWalkthroughEmpty:"No AI walkthrough yet. Generate explanations to show the overview, flow, and checks here.",gitInfo:"Git context",wrapLongLines:"Wrap long lines",wrapOn:"Wrapped",wrapOff:"Raw",multiRepoScan:"Scan sub-repos",multiRepoScanTitle:"Scan this workspace for nested Git repositories. Off keeps a single-repo view, which opens much faster on large repos.",horizontalScrollHint:"Swipe left/right to see the full diff",stageFile:"Stage",stageAll:"Stage all",unstageFile:"Unstage",stashFile:"Stash",stashAll:"Stash all",restoreFile:"Restore",gitQuickActions:"Git Actions",gitUnavailable:"Current directory is not a Git repository",branchSectionTitle:"Current branch",currentBranchLabel:"Branch",switchBranchPlaceholder:"Select branch",switchBranchSearchPlaceholder:"Search local branch",switchNoBranches:"No local branches",switchBranch:"Switch",noStagedChangesShort:"no staged",stagedCount:({count:e})=>`${e} staged`,stagedCountShort:({count:e})=>`${e} staged`,commitSectionTitle:"Commit",commitReadyHint:({count:e})=>`${e} file${e===1?"":"s"} ready`,commitMessagePlaceholder:"Commit message",commitChanges:"Commit",commitNeedsStaged:"Stage changes before committing",commitAhead:"↑ Unpushed",commitBehind:"↓ Incoming",commitSynced:"Synced",recentCommitsTitle:"Recent commits",recentCommitsSearchPlaceholder:"Search commit hash or message",recentCommitsLoadMore:"Load more commits",recentCommitsEmpty:"No commit history",pushSectionTitle:"Remote sync",pushRemoteLabel:"Remote",pushRemotePlaceholder:"origin",pushRemoteSearchPlaceholder:"Search remote",pushNoRemotes:"No remotes",pushBranchLabel:"Target",pushBranchPlaceholder:({branch:e})=>`${e}`,pushBranchSearchPlaceholder:"Search branch",pushNoBranches:"No branches",pushUpstreamBadge:"upstream",pushCurrentBranchBadge:"current",pushNoUpstream:"No upstream configured",pushUpToDate:"Up to date with remote",pushAheadCount:({count:e})=>`${e} commit${e===1?"":"s"} to push`,pushBehindCount:({count:e})=>`${e} commit${e===1?"":"s"} to pull`,pushDivergedCount:({ahead:e,behind:t})=>`${e} ahead / ${t} behind`,pullChanges:"Pull",pushChanges:"Push",gitActionRunning:"Running…",gitActionFailed:({message:e})=>`Git action failed: ${e}`,confirmRestoreTitle:"Discard changes?",confirmRestoreDescription:({path:e})=>`This will discard unstaged changes in ${e}. Termdock cannot recover them.`,confirmRestorePhrase:"discard changes",confirmRestorePlaceholder:"Type “discard changes” to confirm",confirmStashAllTitle:"Stash all changes?",confirmStashAllDescription:"This moves current working tree changes, including untracked files, into a stash.",confirmAction:"Confirm",renderingHtml:"Rendering HTML…",footnotes:"Footnotes",backToFootnote:({index:e})=>`Back to footnote ${e}`,openMermaidDiagram:"Open Mermaid diagram",mermaidDiagram:"Mermaid diagram",renderingDiagram:"Rendering diagram…",markdownImage:"Markdown image",image:"Image",previousImage:"Previous image",nextImage:"Next image",closeImagePreview:"Close image preview",emptyFile:"Empty file.",insertReference:({reference:e})=>`Insert reference: ${e}`,copyReference:({reference:e})=>`Copy reference: ${e}`,byteCount:({count:e})=>`${e} bytes`,previewTruncated:"Preview truncated to 1 MB",branchCandidatesLoading:"Loading branch candidates…",includeUncommitted:"Include local uncommitted changes",includeUncommittedCurrentBranchOnly:"Available only when the compared branch is checked out",includeUncommittedHint:"Include working tree and untracked diffs when viewing or explaining changes",missingBaseReposSkipped:({repositories:e})=>`Repositories without a base branch will be skipped: ${e}`,localBranch:"local",remoteBranch:"remote"},fileTree:{insertRef:"Insert",insertRefTitle:"Insert file reference into active terminal",openDirRoot:"Open",openDirRootTitle:"Use this folder as the current browsing root",openInFileBrowser:"Reveal in Finder",openInFileBrowserTitle:"Open this item in the system file browser",openInFileBrowserFailed:"Failed to open file browser",moreDirActions:"More folder actions",searchFromDir:"Search from here",searchFromDirTitle:"Search only this folder and its descendants",pinDir:"Pin",pinDirTitle:"Pin this folder to the current project",unpinDir:"Pinned",unpinDirTitle:"Unpin this folder",pinFileTitle:"Pin this file to the current project",unpinFileTitle:"Unpin this file",pinFile:"Pin",unpinFile:"Unpin",moreFileActions:"More file actions",deleteFile:"Delete file",deleteFileConfirm:({name:e})=>`Delete “${e}”? This action cannot be undone.`,deleteFileFailed:({message:e})=>`Failed to delete file: ${e}`,noWorkingDir:"No working directory detected.",emptyDir:"Empty directory.",noMatchingFiles:"No matching files.",searching:"Searching files…",searchingWithCount:({count:e})=>`Searching… ${e} found`,searchResults:({count:e})=>`${e} results`,searchScope:"Search scope",searchTruncatedHint:({count:e})=>`Fallback search scanned a large directory and stopped after ${e} matches. Install ripgrep or refine the query for complete results.`,searchStillRunning:"Search is still running. More results will appear automatically.",showingSearchResults:({shown:e,total:t})=>`Showing ${e} of ${t}`,loadMoreSearchResults:({shown:e,total:t})=>`Show more (${e}/${t})`,contentMatchesCount:({count:e})=>`${e} file${e===1?"":"s"} with matches`,moreMatches:({count:e})=>`+${e} more match${e===1?"":"es"}`,noContentMatches:"No matches found in file contents.",contentSearchNeedsRipgrep:"Content search requires ripgrep (rg). Install it on the server to search inside files.",truncatedHint:"Showing first 1000 entries. Use search or open a smaller folder for better performance.",dropToUploadHere:"Upload here",symbolicLink:"Symbolic link",sortByModified:"Sort by recent changes",sortByName:"Sort by name",sortedByModified:"Sorted by recent changes"},diffViewer:{noFileChanges:"No changes in this file.",noUnstagedChanges:"No unstaged changes.",emptyHint:"Make some changes, or pull from a remote.",loading:"Loading diff…",insertAllDiff:"Insert current diff as context",insertFileDiff:"Insert this file's diff",insertHunkDiff:"Insert this hunk",insertLineDiff:"Insert the selected diff lines",insertHunkShort:"Insert",insertFileShort:"Insert",insertAllShort:"Insert all",stageHunk:"Stage",stageHunkTitle:"Stage only this hunk (git apply --cached)",revertHunk:"Revert",revertHunkTitle:"Revert this hunk in the worktree (cannot be undone)",revertHunkConfirm:"Confirm revert?",hunkActionReverted:"Reverted",hunkActionStaged:"Staged",hunkActionApplying:"Applying…",hunkActionUnavailable:"Cannot build a patch for this hunk",hunkActionFailed:({message:e})=>`Failed: ${e}. If the changes moved on, refresh and retry.`,auditExplanation:"Change meaning",auditStale:"Explanation stale",auditClear:"Clear explanation",auditGeneratedAt:({time:e})=>`Generated ${e}`,allDiffLabel:"all changes",allChangesLabel:"all changes",workingTree:"Working tree changes",allUnstaged:"All unstaged changes",binaryOrEmpty:"No textual changes to display.",noFinalNewline:"No newline at end of file",noHunks:"No hunks",hunkOutline:"Hunks",expandHunkRail:"Show hunk list",collapseHunkRail:"Hide hunk list",prevHunk:"Previous hunk",nextHunk:"Next hunk",prevFile:"Previous",nextFile:"Next",expandFile:"Expand file",collapseFile:"Collapse file",expandAll:"Expand all",collapseAll:"Collapse all",collapseHunk:"Collapse hunk",useBracketKeysHint:"Press [ / ] to jump between hunks",unified:"Unified",unifiedMode:"Unified view",split:"Split",splitMode:"Side-by-side view",moreActions:"More actions",view:"View",loadingPreviousFile:"Loading previous file…",loadingNextFile:"Loading next file…",resizeNavigation:"Resize diff navigation",focusPathHint:"Select a label to focus its path",whitespace:"Whitespace",whitespaceDefault:"Default",whitespaceTrim:"Ignore trailing",whitespaceIgnore:"Ignore all",whitespaceIgnoreBlankLines:"Ignore blank lines",context:"Context",expandAbove:({count:e})=>`Expand ${e} lines above`,expandBelow:({count:e})=>`Expand ${e} lines below`,contextLines:({count:e})=>`${e} lines`,contextAll:"All"},settings:{title:"Settings",font:"Font",render:"Render",workspaceLimit:"Keep service pages",workspaceUnlimited:"Unlimited",workspaceLimitHint:"Applies on this device, including the entry page. Lower limits save memory. Older background pages reconnect when revisited; terminal tasks keep running.",theme:"Theme",darkTheme:"Dark",lightTheme:"Light",newTab:"New tab",debug:"Debug",noSleep:"No sleep",noSleepUnavailable:"No network — disabled",updateTitle:"Termdock update",updateRuntimeTitle:"CLI and service runtime",updateHint:"A manual check downloads and installs a new version immediately. The service restarts only after you confirm.",updateCheck:"Check for updates",updateCheckAgain:"Check again",updateChecking:"Checking npm for the latest version…",updateCheckingShort:"Checking…",updateInstallingShort:"Installing…",updateCurrent:"Termdock is up to date.",desktopUpdateTitle:"macOS desktop app",desktopUpdateHint:"Manually check signed desktop releases published on GitHub.",desktopUpdateUnsupported:"In-app updates require an installed, signed macOS app.",desktopUpdateChecking:"Checking for a desktop update…",desktopUpdateCurrent:"The desktop app is up to date.",desktopUpdateDownloadingShort:"Downloading…",desktopUpdateDownloading:"A new version is downloading in the background…",desktopUpdateReady:"The desktop update is downloaded and ready to install.",desktopUpdateInstalling:"Restarting to install the desktop update…",desktopUpdateCheck:"Check desktop app",desktopUpdateCheckAgain:"Check again",desktopUpdateRestart:"Restart and install",desktopUpdateRestartConfirm:"Restart Termdock and install the downloaded desktop update? The terminal service and tmux sessions will remain running.",serverHealthTitle:"Service health",serverHealthHint:"What happened to the Termdock service recently.",serverHealthSupervised:"Automatic recovery is on: the service will attempt to restart if it crashes or stops responding.",serverHealthUnsupervised:"Built-in automatic recovery is off. A crash may require a manual restart.",serverHealthEnable:"Enable and restart",serverHealthEnableHint:"Enabling restarts the service and briefly disconnects clients. Plain terminals may close; tmux sessions can reconnect. Repeated startup failures stop automatic retries.",serverHealthEnabling:"Enabling…",serverHealthEnablePending:"Waiting for reconnection to confirm automatic recovery…",serverHealthEnableError:"Could not confirm automatic recovery. Reconnect to check its status. If the service is unreachable, check the startup logs on its host.",serverHealthEnableUnavailable:"This launch method cannot enable recovery here. Configure supervision on the service host; desktop and externally managed services remain managed by their launcher.",serverHealthClean:"No problems recorded.",serverHealthHistory:"Previous problem",serverHealthRunningNow:"The service is running now with automatic recovery enabled.",serverHealthLastIncident:"Last problem",serverHealthRestarted:({count:e})=>`Restarted automatically ${e}${e===1?" time":" times"}`,serverHealthGaveUp:({count:e})=>`This supervisor stopped retrying after ${e} consecutive failures.`,serverHealthSupervisorLost:"Automatic recovery is unavailable. The service is still running.",serverHealthOomNote:"Memory was near the limit before it died; the OOM killer may have taken it.",serverHealthUptime:({duration:e})=>`ran for ${e}`,serverHealthDismiss:"Got it",serverHealthDismissed:"Acknowledged",serverHealthUnknownEvent:"Something went wrong",serverHealthEventStartupFailure:"Failed to start",serverHealthEventCrash:"Crashed",serverHealthEventCrashNative:"Crashed in native code",serverHealthEventKilled:"Killed outright",serverHealthEventWedge:"Stopped responding and had to be killed",serverHealthEventPortConflict:"Could not start: the port is already in use",serverHealthEventGaveUp:"Repeated failures; retries stopped at that time",serverHealthEventExitZero:"Exited with code 0 without being asked to",serverHealthEventTerminated:"Terminated by another process",serverHealthEventSupervisorLost:"Lost contact with the supervisor",serverHealthEventUncaughtException:"Hit an uncaught exception",serverHealthEventUnhandledRejection:"Had an unhandled promise rejection",serverHealthEventExitNonzero:"Exited with an error code",notifications:"Notify",notificationsTitle:"Notification settings",notificationsHint:"Notify when an AI task finishes while Termdock is hidden.",notificationsPageHint:"Choose which Termdock events can send system notifications. The master switch controls browser permission and delivery; event switches decide what should notify you.",notificationsMaster:"System notifications",notificationsMasterHint:"Allow Termdock to send notifications when it is hidden or running as an installed PWA.",notificationsIOSInstallHint:"On iPhone and iPad, install Termdock to the Home Screen before enabling notifications.",notificationsPermission:"Permission",notificationsPermissionSystem:"Managed by macOS",notificationsTest:"Send test",notificationsTestChecking:"Waiting for macOS to confirm delivery…",notificationsTestDelivered:"Delivered to Notification Center. If no banner appeared, check the alert style and Focus.",notificationsTestFailed:"macOS did not deliver the notification. Allow Termdock in System Settings.",notificationsOpenSystemSettings:"Open system notification settings",notificationsAlertStyle:"Alert style",notificationsAlertStyleHint:"Browsers and Android still decide the final heads-up behavior. Termdock can only request quiet/default/sticky notification options.",notificationsStyleNormal:"Default",notificationsStyleNormalHint:"Sound/vibration if allowed",notificationsStyleQuiet:"Quiet",notificationsStyleQuietHint:"Status tray, no sound",notificationsStylePersistent:"Sticky",notificationsStylePersistentHint:"Stay until dismissed",notificationsEvents:"Events",notificationsAiFinished:"AI task finished",notificationsAiFinishedHint:"Notify when an AI agent stops while Termdock is in the background.",notificationsSessionExited:"Terminal exited",notificationsSessionExitedHint:"Notify when a terminal process exits on its own (closing it yourself does not trigger; delivered via Web Push).",notificationsFutureHint:"More notification types can be added here later without changing the top-level settings layout.",notificationsOffSummary:"System notifications disabled",notificationsAiOnSummary:"AI task finished enabled",notificationsExitOnSummary:"Terminal exit enabled",notificationsBothOnSummary:"AI task finished and terminal exit enabled",notificationsNoEventsSummary:"No notification events enabled",notificationsDenied:"Browser notification permission is blocked. Enable it in site settings.",notificationsUnsupported:"Notifications require a secure context and service worker support.",notificationsTestBody:"Notifications are enabled. You will be notified when an AI task finishes in the background.",shell:"Shell",tmux:"Tmux",auto:"Auto",webgl:"WebGL",canvas:"Built-in",tmuxServer:"Tmux server",tmuxUnavailable:"unavailable",noTmuxSessions:"No tmux sessions on the server.",installTmuxHint:"Install tmux on the server to enable.",refresh:"Refresh",attached:"Attached",restorable:"Restorable",attach:"Attach",attaching:"Attaching…",destroy:"Destroy",sessions:({n:e})=>`${e} session${e===1?"":"s"}`,windows:({n:e})=>`${e} window${e===1?"":"s"}`,keyboardToolbar:"Keyboard toolbar",aiAgentDetection:"AI agent detection",signOut:"Sign out",language:"Language",programNamePlaceholder:"Program name (e.g. claude)",patternPlaceholder:"Regex pattern (e.g. Thinking|Generating)",statusPlaceholder:"Status",addProgram:"Add program",addPattern:"Add pattern",resetDefaults:"Reset defaults",invalidRegex:"Invalid regex",removeProgram:"Remove program",removeRule:"Remove rule",keepLabel:"keep",customColor:"Custom color",tabIndicator:"Tab indicator style",toolbarPresets:"Toolbar presets",detectionRules:"Detection rules",agentHooksHint:"With hooks installed, agents report their own status: working (green), waiting for you (amber), turn done (check) — and you get a notification the moment one needs your input. Hooks install globally but only fire inside termdock terminals.",agentHooksInstall:"Install",agentHooksInstalled:"Installed",agentHooksOutdated:"Outdated",agentHooksNeedsApproval:"Needs approval",agentHooksApprovalHint:"Run /hooks in Codex and approve the Termdock hooks",agentHooksNotInstalled:"Not installed",agentHooksUninstall:"Uninstall",agentHooksReinstall:"Reinstall",agentHooksDevMode:"Dev mode: hooks point at TS sources and need a built install to fire",agentHooksTarget:"writes to",agentAutoRename:"Automatic session titles",agentAutoRenameHint:"Update the title from recent work when an agent finishes a turn. Off by default; manual titles are never overwritten. External plugin CLIs run only after their title feature is enabled.",agentAutoRenameToggle:"Toggle automatic titles for this agent",agentAutoRenameShort:"Auto title",agentAutoRenameNamer:"Title agent",agentAutoRenameFollow:"Follow current session",agentAutoRenameModelsFromCli:"Models discovered from local CLIs",agentAutoRenameRefreshModels:"Refresh CLI models",agentAutoRenameCliDefault:"CLI default model",agentAutoRenameAutomatic:"Automatic selection",agentAutoRenameNoCli:"No supported title CLI detected",agentAutoRenameAdvanced:"Advanced title preferences",agentAutoRenamePreference:"Additional preferences",agentAutoRenamePreferenceHint:"Optional. Add preferences for title style or emphasis; Termdock keeps its default naming rules. Saved when you leave the field.",agentAutoRenamePreferencePlaceholder:"For example: emphasize user value; use action phrases; avoid technical jargon",agentAutoRenamePayloadLimit:"User-message context limit (characters)",agentAutoRenamePayloadLimitHint:"Total raw prompt-submit payload characters retained. Default 12000; range 1000–64000.",agentPlugins:"Agent Plugins",agentPluginAdd:"Add Plugin",agentPluginHint:"Install from an HTTPS Git repository or local directory after reviewing the source. Hooks and executable title CLIs require separate user opt-in.",agentPluginCreate:"Create Plugin",agentPluginDelete:"Delete Plugin",agentPluginInvalid:"Invalid plugin manifest",agentPluginCopyAiPrompt:"Copy AI fix prompt",agentPluginCopied:"Copied",agentPluginSourcePlaceholder:"https://github.com/user/agent-plugin or local directory",agentPluginInstallPackage:"Install plugin",agentPluginAdvancedManifest:"Advanced: paste manifest.json",agentPluginUpdateAvailable:"Update available",agentPluginManualSource:"Manual manifest",agentPluginUpdate:"Update",agentPluginCheck:"Check",agentPluginDoctor:"Diagnose",agentPluginDoctorHint:"Explicitly probe plugin models without generating a title",agentPluginDoctorStatusOk:"Title and model capabilities are healthy",agentPluginDoctorStatusMissing:"titleNamer is not declared",agentPluginDoctorStatusCliDefault:"Titles are available using the CLI default model",agentPluginDoctorStatusNoModels:"No usable model data was returned",agentPluginDoctorStatusFailed:"Model probe failed",agentPluginDoctorModels:"usable models",agentPluginDoctorAutomatic:"automatic",agentPluginDoctorCliDefault:"When no model is specified, the Agent CLI default model is used",agentAutoRenameInterval:"Recheck interval",agentAutoRenameMinutes:"minutes",mobileKeyboard:"Mobile keyboard",saving:"Saving…",rulesHint:"Configure regex patterns to detect what an AI tool is doing in a terminal tab. Each rule can choose its label, color, icon style and how long the indicator is kept after output quiets down. When it stops and you haven't viewed the tab yet, the tab keeps a yellow review hint.",programsHelp:"Supports multiple programs in one config. Separate with commas.",programLabelResolution:"Program label resolution",rawCommandMapping:"Raw command mapping",rawCommandMappingHint:"Rules below map the raw command line to the tab display label. User rules run before built-ins.",genericProgramNames:"Generic program names",genericProgramNamesHint:"Trigger ps-based deep detection (e.g. node, python)",wrapperScriptNames:"Wrapper script names",wrapperScriptNamesHint:"CLI wrappers that launch another tool (e.g. aiden, npx)",shellNamesConfig:"Shell names",shellNamesHint:"Filtered out from tab display (e.g. bash, zsh)",addTag:"+ add",customRules:"Custom rules",addRule:"Add rule",localAccess:"Local access",localAccessHint:"Connection addresses and phone setup instructions",resetAutoName:"Reset auto",mobileSetupIntro:"Connect your phone to the same network as this service. If HTTPS is enabled, install and trust its CA certificate first, then open an address below.",mobileSetupDownload:"1. Scan to download the CA certificate",mobileSetupIos:"iPhone / iPad: scan with the Camera and open in Safari. Install the downloaded profile in Settings → General → VPN & Device Management, then enable full trust in Settings → General → About → Certificate Trust Settings.",mobileSetupAndroid:"Android: download the certificate and install it as a CA certificate in system security settings. Menu names vary by device.",mobileSetupConnect:"2. Open Termdock",mobileSetupConnectHint:"After trusting the certificate, scan an IP address QR code below or copy the local address to your phone browser. If the hostname does not resolve, use an IP address.",onboardingUrl:"Mobile setup",httpsActive:"HTTPS active",httpsInactive:"HTTPS inactive",caMissing:"CA download unavailable",closeSettings:"Close settings",desktopTitle:"Termdock Desktop",desktopStatusLoading:"Reading native macOS status…",desktopSwitchService:"Switch service",desktopOpenDataDirectory:"Open data directory"},toolbarPresets:{preview:"Preview",presets:"Presets",label:"Label",new:"New",reset:"Reset",presetLabelPlaceholder:"Preset label",deletePreset:({name:e})=>`Delete preset ${e}`,matchPrograms:"Match programs",typeEnterHint:"Type & Enter",programsPlaceholder:"vim, nvim, /^claude(-code)?$/i …",programsHelp:"Plain names match as case-insensitive substrings. Wrap in /…/flags for regex (tested against the lowercase program name).",altSlot:"Alt modifier slot",altSlotHint:"Reserve one preview slot for the Alt key.",desktopVisibility:"Show on desktop",desktopVisibilityHint:"Desktop shows only this preset’s custom actions, not the basic keyboard shortcuts.",rowLayout:"Row layout",rowLayoutHint:"Buttons per expanded row.",addRow:"Row",rowN:({n:e})=>`Row ${e}`,del:"Del",buttons:"Buttons",buttonsHint:"Tap to edit. Use ↑↓ to reorder.",addButton:"Add button",noCustomButtons:"No custom buttons yet. Add one to override the default toolbar.",moveUp:"Move up",moveDown:"Move down",removeRow:({n:e})=>`Remove row ${e}`,removeAction:({name:e})=>`Remove ${e}`,labelField:"Label",labelPlaceholder:"Label shown on the button",sequence:"Sequence",sequencePlaceholder:"e.g. /undo or \\t or /||undo",sequenceHint:"Double-tap sequence",doubleTap:"Double-tap sequence",doubleTapAdd:"+ Add",doubleTapPlaceholder:"e.g. /undo\\r or /||undo ||\\r",remove:"Remove",noSequence:"No sequence",preset:"Preset",overCapacityHint:"More buttons than slots. Extra rows will use the last row size."},agentRules:{ruleColors:{green:"Green",yellow:"Yellow",red:"Red",blue:"Blue",purple:"Purple",orange:"Orange",gray:"Gray"}},tab:{session:"Session",new:"New session",rename:"Rename",renameHint:"Change the tab display name",renamePlaceholder:"Leave empty to reset to default",copyCwd:"Copy cwd",copyCwdHint:"Copy the current working directory",fontSize:"Font size",fontSizeHint:"Only for this session",fontSizeReset:"Follow global",resumeAgent:"Resume agent session",resumeAgentHint:"Resume the last conversation by its native session id",resumeAgentAvailable:"Agent conversation available to resume",resumeAgentRecoveredTitle:({agent:e})=>`${e} conversation available`,resumeAgentRecoveredHint:"This terminal was rebuilt after an interruption. Continue where you left off.",resumeAgentNow:"Resume",resumeAgentLater:"Dismiss for now",resumeAgentSubmitting:"Submitting the native resume command…",resumeAgentWaiting:"Waiting for the Agent to confirm the restored conversation…",resumeAgentSuccess:({agent:e})=>`${e} conversation restored`,resumeAgentFailed:"Could not resume the Agent conversation. You can retry.",resumeAgentConflict:"This Agent conversation is already open in another terminal.",resumeAgentBusy:"Wait for the current Agent turn to finish before resuming.",resumeAgentTimeout:"The Agent did not confirm the restored conversation. Check the terminal or retry.",tmuxRecoveryTitle:({count:e})=>`tmux exited unexpectedly; ${e} Agent session(s) can be restored`,tmuxRecoveryHint:"Termdock kept the native session IDs. Restore continues each conversation in its original tab.",tmuxRecoveryRestoreAll:"Restore all",tmuxRecoveryRestoring:"Restoring…",tmuxRecoveryDismiss:"Not now",tmuxRecoveryPartial:({restored:e,failed:t})=>`Restored ${e}; ${t} still need attention.`,tmuxRecoveryFailed:"Recovery failed. Check the terminals and try again.",tmuxRecoveryDismissFailed:"Could not dismiss the recovery notice.",tmuxRecoveryProgress:({total:e,queued:t,paused:n,resourceWait:r,running:o,succeeded:i,failed:s})=>`Recovery: ${i}/${e} complete · ${t} queued · ${n} paused (${r} waiting for resources) · ${o} running · ${s} failed`,tmuxRecoveryPausedForResources:"Resources are below budget. New launches are paused and will resume automatically when capacity returns.",tmuxRecoveryPause:"Pause",tmuxRecoveryResume:"Resume",tmuxRecoveryInProgress:"Recovery in progress",copied:"Copied",close:"Close session",closeHint:"Remove this tab from the list",longPressTip:"Tip: hold a tab still for a moment to open actions; hold and drag to reorder.",sessionsTitle:"Sessions",explorerTitle:"Explorer",split:"Split",splitTitle:"Add to split workspace",closeFailed:({name:e})=>`Could not close ${e}. The session is still open. Try again.`,splitNew:"New session in workspace",splitNewHint:"Uses the current directory and default type; add as many panes as needed",splitExisting:"Choose a session or workspace",splitExistingHint:"Create multiple independent workspaces; choosing another workspace merges them",splitCurrent:"Current",splitClose:"Exit split",splitLayout:"Split layout",splitHorizontal:"Side by side",splitVertical:"Stacked",splitGrid:"Grid",splitWorkspace:"Split group",splitWorkspaces:"Split workspaces",splitRename:"Rename split group",splitRemovePane:"Remove from split",splitExistingGroups:"Existing split groups",splitAvailableSessions:"Available sessions",splitOccupied:"Grouped",splitUnavailableGrouped:"Grouped mode only supports sessions in the same directory",splitEndedGrouped:"Split ended: grouped mode does not support mixed directories",splitNoOtherSessions:"No other sessions are available",sessionCount:({count:e})=>`${e} session${e===1?"":"s"}`,closeChooserTitle:"Destroy tmux session?",closeChooserDescription:"This will stop the session and every process inside it. This cannot be undone.",destroySession:"Destroy session",confirmDestroySession:"Confirm destroy",destroySessionHint:"Stop the tmux session and every process inside it.",dragToClose:"Drag here to close",releaseToClose:"Release to confirm"},agent:{aiRunning:"AI running",needsReview:"Needs review",finishedReview:"AI finished — needs review",aiWaiting:"AI waiting",copyMode:"Copy mode",jumpToNext:"Jump to next session needing attention",jumpToNextRunning:"Jump to next running session",selectRunningSession:"Select a running session",runningSessionGestureHint:"Tap to cycle · swipe sideways to select · hold to drag",currentSession:"Current"},serviceAttention:{title:"Attention across services",summary:"{services} services · {count} sessions",currentService:"Current service",waiting:"Waiting for you",offline:"Offline · Last known status",login:"Sign-in required · Last known status",empty:"No sessions need attention",viewService:"Open service",scope:"Includes opened services. Select a session to go directly to it.",changed:"The pending sessions have changed. Please choose again.",unavailable:"Unable to open this service. Retry from the service list."},connection:{reconnecting:"Reconnecting…"},desktopServices:{switchService:"Switch Termdock service",openServices:"Open services",idle:"Idle",manageServices:"Manage services and names"},terminal:{input:"Terminal input",error:"Error",dropFilesToPastePaths:"Drop files to paste paths",loading:"Loading terminal…",initializing:"Initializing terminal engine…",failedToLoad:"Failed to load terminal",unknownError:"An unknown error occurred",componentFailed:"Terminal component failed to load",paste:"Paste",copied:"Copied",copyFailed:"Copy failed",longPressSelectsText:"Long press selects text",longPressSendsArrows:"Long press sends arrow keys",switchLongPressToArrows:"Switch long press to arrow keys",switchLongPressToCopy:"Switch long press to copy selection"},quota:{title:"Subscription Quota",noProviders:"No subscription providers detected.",noProvidersHint:"Quota tracking becomes available when you use AI coding agents with API keys or OAuth login.",exhausted:"Exhausted",left:({n:e})=>`${e} left`,updated:({time:e})=>`Updated ${e}`,refresh:"Refresh",close:"Close"},errorBoundary:{title:"Something went wrong",unexpected:"An unexpected error occurred",retry:"Try Again",copyDetails:"Copy error details",copied:"Copied",copyFailed:"Copy failed"},error:{type:{network:"Network error",session:"Session error",terminal:"Terminal error",auth:"Authentication error",validation:"Validation error",unknown:"Unknown error"},severity:{low:"Notice: ",medium:"Warning: ",high:"Error: ",critical:"Critical: "},suggestion:{networkCheck:"Check your network connection",networkRetry:"Try reconnecting",networkProxy:"Check proxy settings",networkWait:"Wait for the network to recover",sessionRecreate:"Recreate the session",sessionServer:"Check the server status",sessionCache:"Clear your browser cache",terminalRestart:"Restart the terminal",terminalConfig:"Check the terminal configuration",terminalClear:"Clear the terminal output",authRelogin:"Sign in again",authCredentials:"Check your credentials",authAdmin:"Contact the administrator",validationFormat:"Check the input format",validationParams:"Verify your parameters",validationDocs:"See the documentation",unknownReload:"Reload the page",unknownApp:"Restart the app",unknownSupport:"Contact support"}}},jA={architecture:{choosePaths:"选择目录或文件",browsePaths:"浏览目录",addScopeReference:"引用到分析范围",searchScopePaths:"搜索文件或目录",useCurrentFile:"引用当前文件",useCurrentDirectory:"引用当前目录",browsePathsHint:"展开目录浏览,点击右侧引用按钮加入分析范围。",correctPathsFirst:"请先修正已填写的路径,再添加范围。",pathsHint:"可选择范围或粘贴文件/行引用,路径相对当前项目。",featureScopeHint:"优先在所选范围内定位功能",removePath:"移除路径",chooseThisDirectory:"选择此目录",filterDirectory:"筛选当前目录",loadingPaths:"正在读取目录…",pathsLoadFailed:"无法读取目录,请检查连接或访问权限后重试。",noPaths:"当前目录没有匹配的文件或子目录。",pathsTruncated:"当前目录条目较多,仅显示部分结果;可进入子目录,或直接粘贴目标路径。",selectedPaths:"已选路径",usePaths:"使用所选范围",expandDetail:"查看详情",collapseDetail:"收起说明",backToMap:"返回架构",backToModule:"返回模块",previousModule:"上一模块",parentModule:"返回上一级",viewPrepared:"查看这份分析",closeDetail:"关闭模块详情",connections:"连接关系",outgoing:"连向",incoming:"来自",browseMode:"浏览方式",outlineMode:"模块说明",graphMode:"关系图",analysisNotes:"分析说明",limitations:"范围与限制",analyzedPaths:"已分析源码",fitGraph:"查看全图",fullscreen:"全屏看图",closeFullscreen:"关闭全屏图",panHint:"拖动浏览,双指缩放;点击模块查看说明",newAnalysis:"新建分析",updateAnalysis:"更新当前分析",closePreparation:"关闭分析设置",analysisRange:"分析范围",projectRange:"整个项目",moduleRange:"目录 / 模块",featureRange:"功能链路",modulePaths:"模块路径(每行一个)",modulePlaceholder:"选择目录或文件,或粘贴已有引用,每行一个",featureTarget:"想了解的功能",featurePlaceholder:"例如:文件上传从选择文件到写入存储的完整流程",invalidPaths:"请选择项目内的目录或文件,或粘贴其引用,最多 20 个;项目外路径和 .. 无法使用。",requiredFeature:"请描述一个具体功能,并检查可选起始路径是否为项目内相对路径。",independentHint:"局部分析单独保存,可随时切换。同一范围再次生成会更新对应的图;整个项目使用项目总览。",updateOnly:"只更新当前这份分析,其他架构图会保留。",analysisOptions:"依赖深度与其他选项",dependencyDepth:"依赖追踪",boundaryDepth:"范围边界(更快)",followDepth:"追踪相关调用与依赖",startPaths:"功能范围(可选)",focus:"分析诉求与限制(可选)",focusPlaceholder:"例如:重点解释权限检查和失败重试,忽略界面样式。",savedAnalyses:"已保存分析",libraryFailed:"无法读取分析列表,当前图仍可浏览。请点击刷新重试。",awaitingFile:"这份分析尚未保存。将准备好的指令发送给 Agent;文件保存后这里会自动显示结果。",analyzeModule:"细化分析这个模块",scopeUnavailable:"这份局部架构缺少范围信息,请新建分析以明确分析边界。",tab:"架构",title:"代码架构",generate:"生成",update:"更新",refresh:"刷新架构",prepare:"准备架构分析",promptHint:"使用当前项目的 Agent 分析代码。提示词会放入当前输入区或上下文草稿,检查后发送;架构保存后,这里会自动刷新。请先在终端打开 Agent,分析会消耗其时间和额度。",insertPrompt:"放入输入区",copyPrompt:"复制提示词",previewPrompt:"查看分析提示词",inserting:"正在添加到当前输入区…",insertFailed:"未能添加提示词,请检查当前会话,或从下方复制。",inserted:"请检查当前输入区或上下文草稿,并发送给 Agent。",copied:"提示词已复制。",failed:"复制失败,请从下方提示词中手动复制。",loading:"正在读取项目架构…",invalid:"架构文件格式有误。可以重新分析项目来修复。",loadFailed:"无法读取项目架构,请检查连接与访问权限后重试。",previous:"下面保留上次成功读取的架构。",retry:"重试",empty:"了解这个项目的代码架构",emptyHint:"可以从整个项目、指定目录或某个功能开始分析,无需先生成全项目架构。",savedAt:"保存于",perspective:"视角",breadcrumb:"架构层级",modules:"模块",explore:"展开子模块",sourceFiles:"相关源码",diagram:"架构关系图",diagramHint:"点击模块查看详情",zoomOut:"缩小架构图",zoomIn:"放大架构图",resetZoom:"重置架构图缩放",download:"下载架构图 SVG",downloadFailed:"下载失败,请重试。",diagramFailed:"图表暂时无法渲染,仍可通过下方模块查看架构。",rendering:"正在绘制架构图…"},computer:{returnToDesktop:"返回桌面",tools:"控制设置",closeTools:"关闭控制设置",keyboard:"键盘",keyboardInput:"直接输入到电脑",keyboardPlaceholder:"点这里打字,文字直接发送到电脑",hideKeyboard:"收起键盘",keyboardNavigation:"键盘导航",desktopZoom:"桌面缩放",zoomIn:"放大桌面",zoomOut:"缩小桌面",resetZoom:"恢复适应屏幕",pinchHint:"双指捏合缩放",keyEscape:"发送 Esc",keyLeft:"向左",keyDown:"向下",keyUp:"向上",keyRight:"向右",keySelectAll:"全选",clipboardTool:"剪贴板",zoom:"放大",expand:"全屏",switchTouchMode:"切换触摸方式",touchMode:"触控模式",trackpadMode:"触控板",directTouchMode:"直接触摸",trackpadHint:"单指滑动移动鼠标,轻点点击,长按拖动;双指滚动,双指轻点右键。",directTouchHint:"轻点屏幕上的位置即可点击,拖动手指操作桌面。",trustCertificateHere:"信任此电脑的证书",rememberLogin:"记住登录",autoConnect:"下次打开自动连接",forgetLogin:"清除登录",savedPassword:"已保存,留空直接连接",loginExpired:"登录信息已失效,请重新输入密码。",loginSaveFailed:"登录信息保存或读取失败,请重试。",title:"电脑控制",host:"电脑地址",hostPlaceholder:"192.168.1.20 或 computer.local",username:"用户名(可选)",password:"密码",passwordHint:"填写目标电脑的 VNC 密码;服务器要求账户登录时,同时填写用户名。勾选记住登录后,成功连接时在服务端加密保存。",connect:"连接",disconnect:"断开",cancel:"取消",connecting:"正在连接…",connected:"已连接",disconnected:"连接已断开,可以重新连接。",viewOnly:"仅查看",control:"允许控制",fit:"适应面板",actualSize:"原始尺寸",fullscreen:"展开桌面",exitFullscreen:"收起桌面",setup:"如何连接电脑",step1:"在 Mac 上打开「系统设置 → 通用 → 共享 → 屏幕共享」。",step2:"在屏幕共享设置中允许你的用户访问;使用 VNC 密码时,开启「VNC 查看器可以使用密码控制屏幕」。",step3:"填写当前服务能访问的电脑内网地址;控制服务所在电脑时,选择「当前电脑」。",networkHint:"使用 VNC 端口 5900。浏览器到 Termdock 全程加密;服务到目标电脑的 VNC 段请使用可信内网或 VPN。",service:"当前服务:{name}",remoteTitle:"远程电脑桌面",startHint:"连接后可在这里查看桌面,用鼠标、触摸和键盘操作电脑。",credentials:"请填写登录信息",authenticate:"登录",authFailed:"登录失败,请检查用户名、密码和目标电脑的远程桌面权限。",sharingOff:"电脑未接受 VNC 连接,请先启动桌面共享服务,并检查端口 5900。",unreachable:"无法连接电脑,请检查地址、网络以及防火墙。",timeout:"连接超时,请确认目标电脑已唤醒且能从当前服务访问。",invalidHost:"请填写电脑的内网 IP 或主机名,无需协议或端口。",privateOnly:"仅支持内网或本机地址;远程访问可切换到目标电脑上的 Termdock 服务。",permission:"电脑控制需要当前服务的全权授权。",failed:"电脑连接失败,请重新连接。",clipboard:"发送剪贴板",clipboardPlaceholder:"发送文字到电脑剪贴板",clipboardHint:"输入文字后点 {shortcut} 即可粘贴;也可以只发送到剪贴板。字符支持取决于目标电脑。",remoteClipboard:"电脑复制的文字",copyToDevice:"复制到本机",clipboardCopied:"已复制到本机",clipboardAccessFailed:"无法访问系统剪贴板。可在此输入文字发送,或选中电脑复制的文字手动复制。",clipboardSent:"已发送到电脑剪贴板",shortcuts:"快捷键",switchApps:"切换应用",spotlight:"Spotlight 搜索",desktop:"显示桌面",loading:"正在加载电脑控制…",platform:"目标系统",thisComputer:"当前电脑",otherComputer:"其他电脑",target:"连接哪台电脑",localService:"运行当前 Termdock 服务的电脑 · {name}",advanced:"高级设置",rdpLoginHint:"使用远程桌面设置中的账号和密码。",vncLoginHint:"使用屏幕共享的 VNC 密码。",checkSettings:"检查连接设置",localHint:"本机指运行当前 Termdock 服务的电脑;目标电脑需先启用所选协议的远程桌面服务。",linuxStep1:"Ubuntu / Linux 需要运行 VNC 服务。共享当前桌面时,x11vnc 需要 X11 会话;Ubuntu 登录界面可选择「Ubuntu on Xorg」。",linuxStep2:"设置 VNC 密码,并让服务监听 5900 端口;只有 RDP 的桌面共享无法在此连接。",linuxCommandHint:"在目标电脑的桌面终端执行以下命令,然后填写设置的 VNC 密码。此示例仅允许连接服务所在电脑,不会自动执行:",linuxProtocolHint:"Ubuntu 24.04 的内置远程桌面使用 RDP,此处使用 VNC。Wayland 需要兼容该桌面的 VNC 服务;TigerVNC 虚拟桌面是独立会话,不等同于当前屏幕。",windowsStep1:"在 Windows 上安装并启动兼容 VNC 的桌面共享服务器;Windows 的 RDP 远程桌面无法在此连接。",windowsStep2:"设置 VNC 密码,启用键盘和鼠标控制,并允许当前服务通过防火墙访问 5900 端口。",systemSearch:"系统搜索",protocol:"连接协议",port:"RDP 端口",rdpUsername:"RDP 用户名",domain:"域(可选)",rdpPasswordHint:"填写远程桌面设置中的 RDP 用户名和密码;Ubuntu 的远程登录凭据可能与系统账户不同。勾选记住登录后,成功连接时在服务端加密保存。",rdpBackendUnavailable:"当前服务的 RDP 支持不可用,请先完成服务端 RDP 配置。",rdpBackendRecovery:"请在运行 Termdock 服务的电脑上启动 RDP 后台(guacd),然后刷新此页面重新检查。连接设置会保留;也可在高级设置中切换为 VNC。",rdpFailed:"远程桌面连接失败。请检查目标地址、端口和电脑上的远程桌面设置。",rdpLinuxStep1:"在 Ubuntu 打开「设置 → 系统 → 远程桌面」,启用「桌面共享」或「远程登录」,并设置 RDP 登录凭据。",rdpStep1:"在目标电脑启用 RDP 远程桌面。Windows 可在「设置 → 系统 → 远程桌面」中开启;Mac 内置屏幕共享请使用 VNC。",rdpStep2:"填写远程桌面设置中的用户名、密码和实际端口。RDP 默认端口为 3389;Ubuntu 的桌面共享也可能使用 3390。目标使用自签名证书时,确认电脑身份后可勾选信任证书。",rdpNetworkHint:"浏览器到 Termdock 的画面和输入复用加密通道;RDP 由当前服务连接目标电脑。桌面共享与远程登录可能连接不同会话,是否显示当前屏幕取决于目标服务的设置。",trustCertificate:"信任此电脑的 RDP 证书(跳过校验)",settingsLoading:"正在读取连接设置…",settingsSaving:"正在保存设置…",settingsSaved:"连接设置已保存到当前服务。",settingsSaveFailed:"设置未能保存,当前修改仍在此页面。",settingsLoadFailed:"连接设置读取失败,请重试。",retry:"重试",retryConnect:"重试连接",rdpCertificate:"目标电脑的 RDP 证书未通过校验。确认是你的电脑后,可勾选信任证书并重试。",clipboardFailed:"剪贴板发送失败,请重试。"},app:{name:"Termdock"},android:{device:"设备",selectDevice:"选择设备",noDevices:"未发现设备",closeTab:"关闭设备 Tab",refresh:"刷新设备",connect:"连接",disconnect:"停止投屏",addDevice:"网络连接",addressPlaceholder:"ip:port,例如 192.168.1.20:5555",adbUnavailable:"本机未找到 adb(Android platform-tools),无法投屏。macOS: brew install android-platform-tools;Ubuntu: sudo apt install adb;或在 ~/.termdock/.env 设置 TERMDOCK_ADB_BIN。",scrcpyUnavailable:"本机未找到 scrcpy / scrcpy-server,无法投屏。macOS: brew install scrcpy;Ubuntu: sudo apt install scrcpy;或在 ~/.termdock/.env 设置 TERMDOCK_SCRCPY_BIN。",connecting:"正在连接设备…",reconnecting:"连接断开,正在自动重连…",retrySchedule:"第 {attempt} 次重试将在 {seconds} 秒后开始",lastError:"最近一次错误(重连期间保留)",retry:"重试",idleHint:"选择设备开始投屏",noDevicesHint:"用 USB 连接手机并开启 USB 调试,或在此添加网络设备",back:"返回",home:"主页",recents:"多任务",notifications:"通知栏",rotate:"旋转屏幕",volumeUp:"音量 +",volumeDown:"音量 -",power:"电源",zoomIn:"放大",zoomOut:"缩小",zoomPanHint:"双指拖动可移动画面",inputText:"输入文字",inputPlaceholder:"输入要发送到手机的文字",send:"发送",splitOpen:"在分屏中打开",splitClose:"退出分屏",splitDockedHint:"投屏已在分屏区域显示。",splitDrag:"按住拖动调整位置",insertFixPrompt:"插入修复提示词",screenshot:"截图并插入",recordingStart:"开始录屏",recordingStop:"停止录屏",recording:"正在录屏…",recordingLimit:"已达 5 分钟上限,录屏已停止",recordingStopped:"投屏已中断,录屏已停止",captureInserted:"截图已插入",recordingInserted:"录屏已插入",recordingConfirm:"录屏已结束,如何处理?",recordingInsert:"直接插入",recordingSave:"保存到指定目录",recordingSaveHint:"录像已保存在服务端。可插入终端引用,或另存到服务端目录。",recordingDiscard:"丢弃录屏",captureInserting:"正在插入…",recordingSaving:"正在保存录屏…",captureFailed:"插入失败",captureUnavailable:"当前无法插入到终端",more:"更多",fullscreen:"全屏",fillSidebar:"铺满侧栏",exitFullscreen:"退出全屏",fullscreenHint:"投屏正在全屏显示。",quality:"画质",qualityAutoHint:"根据连接与解码表现动态调码率,不断流、不重连。分辨率保持稳定,操作和服务端录屏不受影响。",qualityAutoUnavailable:"自动调码率已暂停,画面保持连接。",qualityAutoVersionError:"服务端 scrcpy 版本尚未适配(点击查看详情)。",qualityAutoBuildError:"服务端 scrcpy 文件尚未验证兼容(点击查看详情)。",qualityAutoExtensionError:"调码率扩展文件读取、校验或推送失败(点击查看详情)。",qualityAutoTimeoutError:"调码率确认超时,不能据此判断编码器不支持(点击查看详情)。",qualityAutoEncoderError:"设备编码器拒绝了这次调节(点击查看详情)。",qualityAutoChannelError:"调码率控制通道异常(点击查看详情)。",qualityAutoUnknownError:"服务端未提供具体原因,请更新该服务端后重试(点击查看详情)。",qualityLow:"流畅",qualityMedium:"标准",qualityHigh:"高清",qualityCustom:"自定义",qualityResolution:"分辨率",qualityBitRate:"码率",qualityFrameRate:"帧率",qualityAuto:"自动",qualityApply:"应用",presetNamePlaceholder:"预设名称",presetSave:"保存预设",presetDelete:"删除预设",stateUnauthorized:"未授权",stateOffline:"离线",stateUnknown:"状态未知",unauthorizedHint:"请在手机上确认 USB 调试授权。",offlineHint:"设备离线,请重新插拔或重连。"},common:{cancel:"取消",close:"关闭",save:"保存",reset:"重置",loading:"加载中…",error:"错误",retry:"重试",refresh:"刷新",search:"搜索",clear:"清除",delete:"删除",on:"开",off:"关",back:"返回",copy:"复制",decrease:"减少",increase:"增加",use:"使用",previous:"上一个",next:"下一个"},login:{prompt:"termdock login",placeholder:"请输入密码",placeholderBlocked:({s:e})=>`请稍候 ${e}s`,submit:"登录",invalidPassword:"密码不正确,或服务身份无法验证。请检查后重试。",identityMismatch:"服务身份已改变。请与服务所有者核对地址后再试。",unavailable:"暂时无法登录此服务,请检查连接后重试。",authorizationRequired:"此设备需要授权。请向服务所有者索取新的邀请。",currentTarget:({address:e})=>`正在登录 ${e}`,manageServices:"管理服务 / 使用其他地址",failed:"暂时无法登录,请检查连接后重试。",rateLimited:"尝试次数较多,请稍后再试。",continueAfterReconnect:"网络恢复后可继续登录。",savedConnectionRetained:"已保留服务记录,恢复连接后会重新检查访问权限。",invalidAddress:"请输入有效的 HTTPS 服务地址,例如 computer.example:9834 或 https://computer.example:9834。",invalidInvitation:"邀请链接不完整或无效,请重新复制完整链接后重试。"},sidebar:{sessionCreating:"正在启动…",sessionCreateDirectoryUnavailable:"工作目录已失效,请重新选择目录后重试。",sessionCreatePermissionDenied:"没有权限在此目录启动,请选择其他目录。",sessionCreateConnectionFailed:"连接失败,请检查连接后重试。",sessionCreateFailed:"无法启动会话,请重试。",sessions:"会话",noSessions:"暂无打开的会话。",noMatchingSessions:"没有匹配的会话。",toggleSearch:"切换搜索",settings:"设置",moreActions:"更多操作",subscriptionQuota:"订阅额度",pinSidebar:"常驻边栏",unpinSidebar:"取消常驻",runningSessionButton:"运行中会话按钮",runningSessionButtonHint:"轻点循环,横向滑动选择,长按拖动",attentionButton:"待处理提醒按钮",attentionButtonHint:"显示未读、等待处理的黄色悬浮铃铛",updateAvailable:({version:e})=>`Termdock ${e} 可用`,updateInstalling:"正在后台安装,不会中断当前服务。",updateReady:"更新已安装,确认后将重启服务。",updateRestart:"重启并完成更新",updateRestartConfirm:({version:e})=>`确认重启 Termdock 并切换到 ${e}?当前网页会短暂重连,会话不会被关闭。`,updateRestarting:"正在重启,网页将自动重连…",updateFailed:"自动安装失败,提醒会保留。",updateRetry:"重新尝试",serverAttention:"服务出过问题",filterSessions:"过滤会话",clearSearch:"清除搜索",groupByFolder:"按文件夹分组",groupByFolderTitle:"按工作目录把会话归组折叠;与拖拽排序互斥。",ungrouped:"其他",needsAttention:"待处理",waitingForYou:"等你操作",completedUnread:"完成待查看",closeSession:({name:e})=>`关闭 ${e}`,newShell:"Shell",newTmux:"Tmux",newTmuxDisabled:"服务端未安装 tmux",confirmNewShell:"创建 Shell?",confirmNewTmux:"创建 Tmux?",newSession:"新建 Terminal",newSessionWithAgent:({agent:e})=>`新建 ${e}`,moreLaunchOptions:"更多启动选项",recoverableSessions:"可恢复会话",confirmCloseRecoverableSession:({name:e})=>`结束 ${e}?这会停止该会话中的所有进程。`,endRecoverableSession:"结束会话",closeRecoverableSessionFailed:"结束会话失败,请重试。",refreshRecoverableSessions:"刷新可恢复会话",restoreRecoverableSession:({name:e})=>`恢复 ${e}`,restoringRecoverableSession:"恢复中…",restore:"恢复",newSessionAdvanced:"快速启动 Agent",newSessionComposerTitle:"开始新会话",newSessionHint:"选好运行方式和目录后再启动",launchSessionWith:({name:e})=>`启动 ${e}`,setNewSessionDefault:({name:e})=>`将 ${e} 设为默认`,currentNewSessionDefault:({name:e})=>`${e} 是当前默认`,currentDefaultAgent:({name:e})=>`当前默认:${e}`,defaultAgent:"默认",makeDefault:"设为默认",sessionMode:"运行方式",tmuxKeepsRunning:"断开后继续运行",resumeHistory:"最近会话",resumeHistoryCount:({n:e})=>`已保存 ${e} 条`,resumeHistoryLoading:"正在载入最近的 Agent 会话…",resumeHistoryAction:({title:e})=>`恢复 ${e}`,resumeHistoryRemove:({title:e})=>`从最近会话中移除 ${e}`,resumeHistoryLoadFailed:"无法载入最近的 Agent 会话。",resumeHistoryFailed:"无法准备恢复该 Agent 会话。",resumeHistoryRemoveFailed:"无法从历史中移除该会话。",customStartupCommand:"自定义命令",changeStartupCommand:"更改启动命令",saveStartupCommand:"保存命令",startupCommandSaved:"已保存",saveStartupCommandFailed:"保存失败,请检查浏览器存储权限",addStartupCommand:"新增自定义命令…",deleteStartupCommand:"删除命令",startupCommand:"启动命令",resetStartupCommand:"恢复默认",startupCommandPlaceholder:"例如 vim、htop 或 npm run dev",agentStartupCommandHint:"可修改完整命令;留空使用 Agent 默认命令。保存到当前浏览器。",terminalStartupCommandHint:"在所选目录启动程序,例如 vim README.md。保存到当前浏览器。",workingDirectory:"工作目录",directoryPlaceholder:"输入目录路径",browseDirectories:"浏览目录",hideDirectoryBrowser:"收起目录",chooseDirectory:"选择工作目录",directoryPickerHint:"进入文件夹,确认后才会更改工作目录。",useThisFolder:"使用此目录",recentDirectories:"最近使用的目录",startCommand:"启动命令",customCommand:"其他命令",commandPlaceholder:"可选,例如 codex",detectAgents:"重新检测 Agent",savePreset:"保存为预设",createAndRun:"创建并运行",createSession:"创建 Terminal",openLeftSidebar:"打开左侧边栏",openRightSidebar:"打开右侧边栏",closeSidebar:"关闭边栏"},rightSidebar:{workspace:"工作区",currentProject:"项目",browsingLocation:"浏览中",parentFolder:"上一级目录",backToProjectRoot:"回到当前项目",refreshFiles:"刷新当前目录",resizeFileTree:"拖动调整文件目录宽度",pinCurrentFolder:"固定当前目录到这个项目",unpinCurrentFolder:"取消固定当前目录",showHiddenFiles:"显示隐藏文件",hideHiddenFiles:"不显示隐藏文件",hideGitIgnoredFiles:"隐藏 Git 忽略文件",showGitIgnoredFiles:"显示 Git 忽略文件",gitIgnoreSaveFailed:"保存 Git 忽略文件显示设置失败,请重试",gitIgnoreConfigureHint:"长按或右键配置例外",gitIgnoreExceptionsTitle:"Git 忽略过滤例外",gitIgnoreExceptionsHint:"勾选过滤开启时仍需显示的文件或目录。点击目录右侧箭头可进入选择;选中目录会包含所有子项,文件的父目录会自动保留。保存后生效。",gitIgnoreExceptionsPaths:"选择文件或目录",gitIgnoreExceptionsInvalid:"最多选择 200 个文件或目录。",gitIgnoreExceptionsLoadFailed:"无法加载目录,请重试。",gitIgnoreExceptionsEmptyDirectory:"此目录为空",gitIgnoreExceptionsOpenDirectory:({name:e})=>`进入目录 ${e}`,gitIgnoreExceptionsSelected:({count:e})=>`已选 ${e} 项`,gitIgnoreExceptionsClear:"清空选择",gitIgnoreExceptionsRemove:({path:e})=>`移除 ${e}`,gitIgnoreExceptionsTruncated:"此目录项目过多,仅显示部分内容。",gitIgnoreExceptionsSaveFailed:"保存失败,请检查路径是否位于当前目录内(最多 200 个),然后重试。",insertCurrentFolder:"引用当前目录",insertCurrentFolderShort:"引用",pinnedFolders:"固定",unpinFolder:({name:e})=>`取消固定 ${e}`,fileWatchUnavailable:({message:e})=>`文件监听不可用:${e}。可点击手动刷新。`,browsingOutsideProject:"正在浏览当前项目外目录",browsingOutsideProjectHint:"Git 和改动仍使用当前项目;这里引用的文件会按外部路径插入。",toggleSearch:"切换搜索",refreshGit:"刷新 Git 状态",gitLastUpdated:({time:e})=>`上次更新:${e}`,close:"关闭",filterChanges:"过滤改动或文件",searchPlaceholderContent:"在文件内容中搜索…",searchModeName:"文件",searchModeContent:"内容",clearSearch:"清除搜索",searchScope:"范围",searchScopePlaceholder:"相对目录或绝对路径",resetSearchScope:"恢复搜索当前目录",searchOptions:"搜索选项",searchExclude:"排除",searchExcludePlaceholder:"dist/**, *.lock",clearSearchExclude:"清空排除规则",contentSearchOptions:"内容搜索选项",matchCase:"区分大小写",matchWholeWord:"全词",useRegex:"正则",insertGitContext:"把当前 Git 信息插入 Terminal",copyGitContext:"复制 Git 信息",insertChangeAuditPrompt:"解释当前改动",insertChangeAuditPromptTitle:"把更改审计提示词插入当前会话",changeAuditShort:"解释当前改动",changeAuditLoading:"正在加载 hunk 解释…",changeAuditLoaded:({count:e})=>`已加载 ${e} 条 hunk 解释`,changeAuditLoadedAt:({time:e})=>`最近生成 ${e}`,changeAuditRegenerate:"重新生成",changeAuditRefreshStale:"补充失效",changeAuditRefreshStaleTitle:"为已失效的 hunk 解释插入补充生成提示词",clearChangeAudit:"清理改动解释",clearChangeAuditTitle:"清理当前仓库的 hunk 解释",changeAuditClearFailed:({message:e})=>`清理 hunk 解释失败:${e}`,changeAuditScopeAll:"全部仓库",changeAuditScopeLabel:"解释范围",branchAuditTitle:"分支解释",branchAuditShort:"解释分支改动",branchAuditBaseLabel:"基线分支",branchAuditBasePlaceholder:"基线分支,例如 master",branchAuditBaseSearchPlaceholder:"搜索基线分支",branchAuditBaseEmpty:"没有可选分支,可直接输入分支名",branchAuditGenerate:"生成解释",branchAuditRegenerate:"重新生成",branchAuditGenerateTitle:"生成当前分支相对于基线分支的解释提示词",branchAuditViewDiff:"查看对比",branchAuditViewDiffTitle:"查看目标分支相对于基线分支的改动",branchAuditDiffLoading:"正在加载分支对比…",branchAuditDiffEmpty:"当前分支相对于基线分支暂无改动。",branchAuditMissingBase:({repo:e})=>`${e} 未设置基线分支`,branchAuditRefreshDiff:"刷新对比",branchAuditRefreshStale:"补充失效",branchAuditRefreshStaleTitle:"为已失效的分支解释插入补充生成提示词",branchAuditClearTitle:"清理当前分支解释",branchAuditClearFailed:({message:e})=>`清理分支解释失败:${e}`,branchAuditCommitCount:({count:e})=>`${e} 个提交`,branchAuditFileCount:({count:e})=>`${e} 个文件`,branchAuditTruncated:"diff 已截断",branchAuditCurrent:"已保存解释",branchAuditStale:"解释已失效",branchAuditEmpty:"暂无分支解释。生成后会持久化保存,可随时回来查看。",branchAuditView:"查看解释",branchAuditSaved:({count:e})=>`已保存 ${e} 条 hunk 解释`,branchAuditGeneratedAt:({time:e})=>`生成于 ${e}`,insertPreset:({label:e})=>`插入:${e}`,tabChanges:"改动",tabGit:"Git",tabFiles:"文件",tabAndroid:"设备",tabComputer:"电脑",showAndroidTab:"显示设备 Tab",showArchitectureTab:"显示架构 Tab",showComputerTab:"显示电脑 Tab",inserted:"已插入",copied:"已复制",toggleContextDraft:"切换上下文草稿",contextDraftTitle:"上下文草稿",contextDraftHint:"启用后,引用会追加到这里;可以继续浏览、补写描述,最后一次插入。",contextDraftPlaceholder:"在这里组织长提示词,继续点击侧栏中的引用来追加上下文…",contextDraftCollapse:"收起上下文草稿",contextDraftExpand:"展开上下文草稿",contextDraftDisable:"停用上下文草稿",contextDraftClear:"清空草稿",contextDraftInsert:"插入",contextDraftInsertAndSend:"插入并发送",contextDraftInserted:"已插入",contextDraftSent:"已发送",contextDraftSend:"发送草稿",contextDraftAppended:"已追加引用",contextDraftResize:"拖动调整高度,双击恢复默认",contextDraftAutoCollapseAfterSend:"插入/发送后收起",contextDraftInsertFailed:"输入未被接受,草稿已保留。关闭当前表单或返回终端后重试。",contextDraftPending:"等待接收…",contextDraftCharacterCount:({count:e})=>`${e} 字`,selectFilePrompt:"选择文件以预览内容",backToFileList:"返回文件列表",backToPreviousPreview:"返回来源文档",insertLineRef:({lineLabel:e})=>`引用${e}`,insertFileRef:"引用",copyFileRef:"复制文件引用",findInFile:"在文件内查找",findInFilePlaceholder:"在当前文件中查找…",previousSearchMatch:"上一个匹配项",nextSearchMatch:"下一个匹配项",closeFileSearch:"关闭文件搜索",downloadFile:"下载文件",downloadFailed:"下载失败",downloadCanceled:"下载已取消",downloadSaved:"文件已保存",downloadStarted:"浏览器已开始下载",uploadPending:"正在上传…",uploadInserting:"文件已上传,等待输入接收…",uploadDone:({count:e})=>`已上传 ${e} 个文件`,uploadReferenceDone:"文件已上传,引用已添加",uploadReferenceRejected:"文件已上传,引用尚未添加。关闭当前表单或返回原终端后重试。",uploadLimit:"每次最多上传 50 个文件。本次未上传,请重新选择较小批次。",uploadCanceled:"已停止上传。再次上传前请检查目标目录。",uploadFileCount:({count:e})=>`已选择 ${e} 个文件`,uploadFile:"上传文件",uploadFiles:"上传文件",insertLocalFile:"插入本地文件",insertLocalImage:"插入本地图片",layoutMode:"显示模式",layoutModeAuto:"自动",layoutModeNarrow:"窄版",layoutModeWide:"宽版",dropToUpload:"拖放文件以上传",uploading:"上传中…",uploadSuccess:({count:e})=>`已上传 ${e} 个文件`,uploadFailed:"上传失败",binaryPreviewHint:"二进制文件无法预览,请使用上方下载按钮保存到本地",selectedLineHint:({lineLabel:e})=>`已选 ${e} · 点下方「引用」按钮插入`,multiLineHint:"多行引用:先点起始行,再点结束行",loadingImage:"正在加载图片…",imagePreviewHint:"双指捏合或 ⌘/Ctrl + 滚动缩放 · 双击还原",imageLoadFailed:"图片预览加载失败",loadingVideo:"正在加载视频…",videoPreviewHint:"点击播放 · 长按 2× 并前拖提速 · 方向键调进度/音量 · 空格暂停",videoLoadFailed:"视频预览加载失败",videoUnsupported:"当前浏览器不支持该视频格式",videoPlay:"播放",videoPause:"暂停",videoLongPressSpeed:({rate:e})=>`正在 ${e}× 播放`,videoVolume:({percent:e})=>`音量 ${e}%`,videoRotate:"顺时针旋转 90°",videoFullscreenEnter:"全屏播放",videoFullscreenExit:"退出全屏",model3dLoading:"正在加载 3D 模型…",model3dExplode:"爆炸展开",model3dExplodeAxis:"展开方向(查看器坐标)",model3dExplodeAmount:"展开程度",model3dHome:"回正并看全",model3dFit:"看全可见零件",model3dFront:"正视图",model3dTop:"俯视图",model3dRight:"右视图",model3dAssemble:"恢复装配",model3dExplodedNotice:"爆炸展示 · 尺寸与引用仍为原始装配坐标",model3dLoadFailed:"3D 模型预览加载失败",model3dTimeout:"3D 模型传输超时,请检查连接后重试。",model3dDimensions:({dims:e})=>`尺寸: ${e}`,model3dHintMouse:"拖拽旋转 / 双指平移 / 捏合或滚轮缩放",model3dHintTouch:"单指旋转 / 双指缩放平移",model3dFullscreenEnter:"全屏查看",model3dFullscreenExit:"退出全屏",model3dBgToLight:"切换为白底",model3dBgToDark:"切换为黑底",model3dRefresh:"重新加载模型",model3dClipToggle:"切面查看",model3dClipPosition:"切面位置",model3dClipFlip:"反转切面方向",model3dFeatureToggle:"特征标注",model3dFeatureStatus:({total:e,positioned:t})=>`特征: ${e} 个 · 已定位 ${t}`,model3dFeatureInsert:"引用",model3dGlossaryToggle:"建模名词说明",model3dPickToggle:"选择零件 / 引用",model3dPickHint:"点选零件后可临时隐藏,或引用所选位置",model3dHidePart:"隐藏零件",model3dShowAllParts:({count:e})=>`显示全部(${e})`,model3dParts:"零件",model3dCloseParts:"关闭零件列表",model3dSearchParts:"查找零件",model3dClearPartSearch:"清空零件搜索",model3dHiddenParts:({count:e})=>`已隐藏 ${e}`,model3dShowNamedPart:({name:e})=>`显示 ${e}`,model3dHideNamedPart:({name:e})=>`隐藏 ${e}`,model3dIsolateNamedPart:({name:e})=>`只看 ${e}`,model3dIsolatePart:"只看此件",model3dShowPart:"显示零件",model3dNoParts:"没有匹配的零件",model3dUndoVisibility:"撤销",model3dClearSelection:"取消选择",model3dAllPartsVisible:"全部可见",model3dInspectHint:"单指旋转 · 双指缩放平移 · 双击局部放大,双击空白看全",model3dUnnamedPart:({index:e})=>`零件 ${e}`,model3dCanvas:"三维模型",model3dMore:"更多模型选项",edaLoading:"正在渲染 KiCad 文件…",reviewTargetChanged:"当前会话已切换,请回到创建这条引用的会话后再插入。",reviewReference:"审阅引用",reviewReferenceHint:"补充意见后插入,不会自动发送。",reviewSnapshot:"选中位置的视图快照",reviewCapturing:"正在截取当前视图…",reviewIncludeImage:"附带截图(临时保存在当前服务器)",reviewCaptureFailed:"截图未成功,仍可插入定位信息。",reviewNote:"你的意见(可选)",reviewNotePlaceholder:"例如:这里太厚了,能否减薄?",reviewDetails:"查看定位信息和引用原文",reviewUploading:"正在准备引用…",reviewAddToDraft:"加入引用草稿",reviewInsert:"插入引用",reviewUploadFailed:"引用准备失败,意见已保留。请重试,或取消附带截图后只插入文字。",edaLoadFailed:"KiCad 预览渲染失败",edaTimeout:"KiCad 预览生成或传输超时,请重试。",edaRefresh:"重新渲染",edaPickHint:"点击原理图或 PCB 上的问题位置,生成电子标注",edaPickedPosition:({x:e,y:t})=>`已选位置 ${e}%, ${t}%`,edaPickedBoardPosition:({x:e,y:t,object:n})=>`板坐标 ${e}, ${t} mm · ${n}`,edaInspecting:"正在读取板坐标和附近对象…",edaNoNearbyObject:"附近无对象",edaInsertAnnotation:"引用电子标注",csvUnnamedColumn:({index:e})=>`第 ${e} 列`,csvSelectedCell:({row:e,column:t})=>`已选第 ${e} 行 · ${t}`,csvPickHint:({rows:e,columns:t})=>`${e} 条记录 · ${t} 列,点击单元格引用`,csvInsertAnnotation:"引用表格标注",csvTablePreview:"表格预览:点击单元格后可引用完整记录",kicadLocalStateNotice:"这是本机界面状态文件,不参与原理图、PCB 或生产审查。",kicadShowRawJson:"查看原始 JSON",kicadProjectPickHint:"点击一项配置后可插入引用",kicadInsertSetting:"引用配置",markdownPreview:"预览",markdownSource:"源码",markdownParseFailed:"Markdown 预览解析失败或超过限制,已显示原文。",markdownPreviewHint:"点按行/段落引用,再点一行扩选;拖左侧竖条可连续框选",htmlPreview:"预览",htmlSource:"源码",htmlPreviewHint:"HTML 沙箱 iframe 预览,脚本受限",htmlFullscreenEnter:"全屏预览",htmlFullscreenExit:"退出全屏预览",markdownOutline:"Markdown 目录",markdownOutlineShort:"目录",closeMarkdownOutline:"关闭目录",changedFromPath:({path:e})=>`来自 ${e}`,selectedLineFooter:({lineLabel:e})=>`已选 ${e}`,clearSelection:"清除",allChanges:"全部改动",backToChangeList:"返回目录",allRepositories:"全部仓库",allRepositoriesShort:"全部",repositories:"仓库",gitRepositorySectionTitle:"操作仓库",gitRepositoryLabel:"仓库",gitRepositoryPlaceholder:"选择仓库",gitRepositorySearchPlaceholder:"搜索仓库",gitRepositoryEmpty:"没有可操作的仓库",selectRepositoryForGitActions:"请选择一个仓库后再执行 Git 操作",selectRepositoryForDiff:"选择一个仓库或文件查看 diff",repoNotLoaded:"点击加载",repoChangedCount:({count:e})=>`${e} 个改动`,repoStagedCount:({count:e})=>`${e} 已暂存`,noChanges:"没有改动",noMatchingChanges:"没有匹配的改动",loadingGitChanges:"正在加载 Git 改动…",loadingGitChangesSlow:"仓库较大时可能需要几秒。",refreshingGitChanges:"正在刷新 Git 改动…",gitChangesLoadFailed:"无法加载 Git 改动",retryGitChanges:"重试",insertThisFile:"把这个文件引用插入 Terminal",viewDiff:"查看 diff",diffViewMode:"改动文件展示方式",diffViewModeList:"平铺列表",diffViewModeTree:"目录结构",diffViewModeAi:"AI 导览",changeWalkthroughEmpty:"暂无 AI 导览。生成解释后会在这里展示总览、链路和验证点。",gitInfo:"Git 信息",wrapLongLines:"长行换行",wrapOn:"已换行",wrapOff:"原始",multiRepoScan:"扫描子仓库",multiRepoScanTitle:"扫描当前工作区下的嵌套 Git 仓库。关闭时只看单个仓库,大仓库打开更快。",horizontalScrollHint:"左右滑动查看完整 diff",stageFile:"暂存",stageAll:"全部暂存",unstageFile:"取消暂存",stashFile:"贮藏",stashAll:"全部贮藏",restoreFile:"丢弃",gitQuickActions:"Git 操作",gitUnavailable:"当前目录不是 Git 仓库",branchSectionTitle:"当前分支",currentBranchLabel:"分支",switchBranchPlaceholder:"选择分支",switchBranchSearchPlaceholder:"搜索本地分支",switchNoBranches:"没有本地分支",switchBranch:"切换",noStagedChangesShort:"无暂存",stagedCount:({count:e})=>`已暂存 ${e}`,stagedCountShort:({count:e})=>`已暂存 ${e}`,commitSectionTitle:"提交",commitReadyHint:({count:e})=>`${e} 个文件已准备提交`,commitMessagePlaceholder:"提交信息",commitChanges:"提交",commitNeedsStaged:"请先暂存要提交的改动",commitAhead:"↑ 待推送",commitBehind:"↓ 待拉取",commitSynced:"已同步",recentCommitsTitle:"近期提交",recentCommitsSearchPlaceholder:"搜索提交 hash 或信息",recentCommitsLoadMore:"加载更多提交",recentCommitsEmpty:"暂无提交历史",pushSectionTitle:"同步远端",pushRemoteLabel:"Remote",pushRemotePlaceholder:"origin",pushRemoteSearchPlaceholder:"搜索 Remote",pushNoRemotes:"没有 Remote",pushBranchLabel:"目标分支",pushBranchPlaceholder:({branch:e})=>`${e}`,pushBranchSearchPlaceholder:"搜索分支",pushNoBranches:"没有分支",pushUpstreamBadge:"upstream",pushCurrentBranchBadge:"当前",pushNoUpstream:"当前分支未设置 upstream",pushUpToDate:"与远端同步",pushAheadCount:({count:e})=>`领先远端 ${e} 个提交`,pushBehindCount:({count:e})=>`落后远端 ${e} 个提交`,pushDivergedCount:({ahead:e,behind:t})=>`领先 ${e} / 落后 ${t} 个提交`,pullChanges:"拉取",pushChanges:"推送",gitActionRunning:"执行中…",gitActionFailed:({message:e})=>`Git 操作失败:${e}`,confirmRestoreTitle:"确认丢弃改动",confirmRestoreDescription:({path:e})=>`将丢弃 ${e} 的未暂存改动,此操作不可从 Termdock 恢复。`,confirmRestorePhrase:"丢弃改动",confirmRestorePlaceholder:"输入“丢弃改动”确认",confirmStashAllTitle:"确认贮藏全部改动",confirmStashAllDescription:"会把当前工作区改动(包含未跟踪文件)移入贮藏。",confirmAction:"确认",renderingHtml:"正在渲染 HTML…",footnotes:"脚注",backToFootnote:({index:e})=>`返回脚注 ${e}`,openMermaidDiagram:"打开 Mermaid 图表",mermaidDiagram:"Mermaid 图表",renderingDiagram:"正在渲染图表…",markdownImage:"Markdown 图片",image:"图片",previousImage:"上一张图片",nextImage:"下一张图片",closeImagePreview:"关闭图片预览",emptyFile:"空文件。",insertReference:({reference:e})=>`插入引用:${e}`,copyReference:({reference:e})=>`复制引用:${e}`,byteCount:({count:e})=>`${e} 字节`,previewTruncated:"预览已截断至 1 MB",branchCandidatesLoading:"正在加载分支候选…",includeUncommitted:"包含本地未提交改动",includeUncommittedCurrentBranchOnly:"仅当对比分支是当前检出分支时可开启",includeUncommittedHint:"查看对比或生成解释时纳入工作区和未跟踪文件的 diff",missingBaseReposSkipped:({repositories:e})=>`未设置基线的仓库会跳过:${e}`,localBranch:"本地",remoteBranch:"远端"},fileTree:{insertRef:"引用",insertRefTitle:"Insert file reference into active terminal",openDirRoot:"进入",openDirRootTitle:"把这个目录作为当前浏览根目录",openInFileBrowser:"在 Finder 中显示",openInFileBrowserTitle:"在系统文件浏览器中打开这个项目",openInFileBrowserFailed:"打开文件浏览器失败",moreDirActions:"更多目录操作",searchFromDir:"从这里搜索",searchFromDirTitle:"只搜索这个目录及其子目录",pinDir:"固定",pinDirTitle:"固定这个目录到当前项目",unpinDir:"已固定",unpinDirTitle:"取消固定这个目录",pinFileTitle:"固定这个文件到当前项目",unpinFileTitle:"取消固定这个文件",pinFile:"固定",unpinFile:"已固定",moreFileActions:"更多文件操作",deleteFile:"删除文件",deleteFileConfirm:({name:e})=>`确认删除“${e}”?此操作无法撤销。`,deleteFileFailed:({message:e})=>`删除文件失败:${e}`,noWorkingDir:"未检测到工作目录。",emptyDir:"空目录。",noMatchingFiles:"没有匹配的文件。",searching:"正在搜索文件…",searchingWithCount:({count:e})=>`搜索中…已找到 ${e} 项`,searchResults:({count:e})=>`${e} 个结果`,searchScope:"搜索范围",searchTruncatedHint:({count:e})=>`降级搜索已扫描大量目录并在找到 ${e} 项后停止。安装 ripgrep 或输入更精确关键词可获得完整结果。`,searchStillRunning:"搜索仍在进行,更多结果会自动出现。",showingSearchResults:({shown:e,total:t})=>`正在展示 ${e}/${t}`,loadMoreSearchResults:({shown:e,total:t})=>`查看更多(${e}/${t})`,contentMatchesCount:({count:e})=>`${e} 个文件命中`,moreMatches:({count:e})=>`还有 ${e} 处匹配`,noContentMatches:"文件内容中没有匹配。",contentSearchNeedsRipgrep:"内容搜索需要 ripgrep(rg),请在服务端安装后再在文件内搜索。",truncatedHint:"仅展示前 1000 项。使用搜索或打开更小的文件夹以获得更好性能。",dropToUploadHere:"上传到这里",symbolicLink:"符号链接",sortByModified:"按最近修改排序",sortByName:"按名称排序",sortedByModified:"已按最近修改排序"},diffViewer:{noFileChanges:"此文件无改动。",noUnstagedChanges:"没有未暂存的改动。",emptyHint:"做一些改动,或从远程拉取。",loading:"正在加载 diff…",insertAllDiff:"把当前 diff 内容作为上下文插入 Terminal",insertFileDiff:"引用这个文件的 diff",insertHunkDiff:"引用这段 diff hunk",insertLineDiff:"引用选中的这几行 diff",insertHunkShort:"引用",insertFileShort:"引用",insertAllShort:"全部",stageHunk:"暂存",stageHunkTitle:"只把这个 hunk 加入暂存区 (git apply --cached)",revertHunk:"撤销",revertHunkTitle:"撤销这个 hunk 的工作区改动(不可恢复)",revertHunkConfirm:"确认撤销?",hunkActionReverted:"已撤销",hunkActionStaged:"已暂存",hunkActionApplying:"应用中…",hunkActionUnavailable:"无法为这个 hunk 构造补丁",hunkActionFailed:({message:e})=>`操作失败:${e}。如改动已变化,请刷新后重试。`,auditExplanation:"更改意义",auditStale:"解释已失效",auditClear:"清除解释",auditGeneratedAt:({time:e})=>`生成于 ${e}`,allDiffLabel:"全部 diff",allChangesLabel:"全部改动",workingTree:"工作区改动",allUnstaged:"所有未暂存改动",binaryOrEmpty:"没有可显示的文本改动。",noFinalNewline:"文件末尾没有换行符",noHunks:"没有 hunk",hunkOutline:"Hunk 列表",expandHunkRail:"显示 hunk 列表",collapseHunkRail:"隐藏 hunk 列表",prevHunk:"上一个 hunk",nextHunk:"下一个 hunk",prevFile:"上一个",nextFile:"下一个",expandFile:"展开文件",collapseFile:"折叠文件",expandAll:"全部展开",collapseAll:"全部折叠",collapseHunk:"折叠 hunk",useBracketKeysHint:"按 [ / ] 在 hunk 之间跳转",unified:"统一",unifiedMode:"统一视图",split:"分屏",splitMode:"左右分屏视图",moreActions:"更多操作",view:"视图",loadingPreviousFile:"正在加载上一个文件…",loadingNextFile:"正在加载下一个文件…",resizeNavigation:"调整 diff 导航宽度",focusPathHint:"点击标注聚焦路径",whitespace:"空白",whitespaceDefault:"默认",whitespaceTrim:"忽略行尾空白",whitespaceIgnore:"忽略所有空白",whitespaceIgnoreBlankLines:"忽略空行",context:"上下文",expandAbove:({count:e})=>`向上展开 ${e} 行`,expandBelow:({count:e})=>`向下展开 ${e} 行`,contextLines:({count:e})=>`${e} 行`,contextAll:"全部"},settings:{title:"设置",font:"字体",render:"渲染",workspaceLimit:"保留服务页面",workspaceUnlimited:"不限制",workspaceLimitHint:"在本机生效,包含入口页面。数量越少越省内存;超限释放最久未用的后台页面,切回时重新连接,终端任务继续运行。",theme:"主题",darkTheme:"深色",lightTheme:"浅色",newTab:"新标签",debug:"调试",noSleep:"常亮",noSleepUnavailable:"无网络 — 已禁用",updateTitle:"Termdock 更新",updateRuntimeTitle:"CLI 与服务 Runtime",updateHint:"手动检查会立即下载并安装新版本;服务只会在你确认后重启。",updateCheck:"检查更新",updateCheckAgain:"再次检查",updateChecking:"正在检查 npm 上的最新版本…",updateCheckingShort:"检查中…",updateInstallingShort:"安装中…",updateCurrent:"Termdock 已是最新版本。",desktopUpdateTitle:"macOS 桌面版",desktopUpdateHint:"手动检查 GitHub 发布的签名桌面版本。",desktopUpdateUnsupported:"仅签名安装的 macOS 桌面版支持应用内更新。",desktopUpdateChecking:"正在检查桌面版更新…",desktopUpdateCurrent:"桌面版已是最新版本。",desktopUpdateDownloadingShort:"下载中…",desktopUpdateDownloading:"发现新版本,正在后台下载…",desktopUpdateReady:"桌面版更新已下载,可以重启安装。",desktopUpdateInstalling:"正在重启并安装桌面版更新…",desktopUpdateCheck:"检查桌面版",desktopUpdateCheckAgain:"再次检查",desktopUpdateRestart:"重启并安装",desktopUpdateRestartConfirm:"重启 Termdock 并安装已下载的桌面版更新?终端服务和 tmux 会话不会被停止。",serverHealthTitle:"服务健康",serverHealthHint:"Termdock 服务最近出过什么事。",serverHealthSupervised:"自动恢复已开启:服务崩溃或无响应时会尝试自动重启。",serverHealthUnsupervised:"内置自动恢复未开启,服务异常退出后可能需要手动重启。",serverHealthEnable:"开启并重启",serverHealthEnableHint:"开启后会重启服务并短暂断连。普通终端可能中断,tmux 会话可在重连后恢复。连续多次启动失败时会停止重试。",serverHealthEnabling:"正在开启…",serverHealthEnablePending:"等待服务重连并确认自动恢复状态…",serverHealthEnableError:"未能确认自动恢复已开启。请重连后查看状态;若服务无法连接,请在服务所在设备检查启动日志。",serverHealthEnableUnavailable:"当前启动方式不支持在此开启。请在服务所在设备配置守护启动;桌面版或外部托管服务由原启动程序管理。",serverHealthClean:"没有异常记录。",serverHealthHistory:"历史异常",serverHealthRunningNow:"当前服务正在运行,自动恢复已开启。",serverHealthLastIncident:"最近一次异常",serverHealthRestarted:({count:e})=>`已自动重启 ${e} 次`,serverHealthGaveUp:({count:e})=>`连续失败 ${e} 次后,该守护进程已停止重试。`,serverHealthSupervisorLost:"自动恢复已失效,服务仍在运行。",serverHealthOomNote:"退出前内存接近上限,可能是被 OOM killer 杀掉的。",serverHealthUptime:({duration:e})=>`运行了 ${e}`,serverHealthDismiss:"知道了",serverHealthDismissed:"已确认",serverHealthUnknownEvent:"服务出过问题",serverHealthEventStartupFailure:"启动失败",serverHealthEventCrash:"崩溃退出",serverHealthEventCrashNative:"原生代码崩溃",serverHealthEventKilled:"被强制杀掉",serverHealthEventWedge:"卡死无响应,只能杀掉",serverHealthEventPortConflict:"起不来:端口已被占用",serverHealthEventGaveUp:"当时连续失败,停止重试",serverHealthEventExitZero:"未经要求地以 0 退出",serverHealthEventTerminated:"被其他进程终止",serverHealthEventSupervisorLost:"与监督者失联",serverHealthEventUncaughtException:"触发了未捕获异常",serverHealthEventUnhandledRejection:"有未处理的 Promise 拒绝",serverHealthEventExitNonzero:"以错误码退出",notifications:"通知",notificationsTitle:"通知设置",notificationsHint:"Termdock 在后台时,AI 任务结束后发送系统通知。",notificationsPageHint:"选择哪些 Termdock 事件可以发送系统通知。总开关负责浏览器权限和投递,事件开关决定具体哪些内容提醒你。",notificationsMaster:"系统通知",notificationsMasterHint:"允许 Termdock 在隐藏或作为 PWA 安装运行时发送通知。",notificationsIOSInstallHint:"在 iPhone 或 iPad 上,请先将 Termdock 添加到主屏幕,再开启通知。",notificationsPermission:"权限",notificationsPermissionSystem:"由 macOS 管理",notificationsTest:"发送测试",notificationsTestChecking:"正在等待 macOS 确认投递…",notificationsTestDelivered:"已投递到通知中心;若没有横幅,请检查提醒样式和专注模式。",notificationsTestFailed:"macOS 未投递通知,请在系统设置中允许 Termdock 通知。",notificationsOpenSystemSettings:"打开系统通知设置",notificationsAlertStyle:"提醒方式",notificationsAlertStyleHint:"最终是否横幅弹出仍由浏览器和 Android 系统决定。Termdock 只能请求静默、默认或持续显示等通知选项。",notificationsStyleNormal:"默认",notificationsStyleNormalHint:"允许时声音/震动",notificationsStyleQuiet:"静默",notificationsStyleQuietHint:"仅状态栏,无声音",notificationsStylePersistent:"持续",notificationsStylePersistentHint:"保留到手动关闭",notificationsEvents:"事件",notificationsAiFinished:"AI 任务结束",notificationsAiFinishedHint:"当 Termdock 在后台时,AI agent 停止后发送通知。",notificationsSessionExited:"终端退出",notificationsSessionExitedHint:"终端进程自行结束时发送通知(主动关闭不触发,经 Web Push 投递)。",notificationsFutureHint:"后续可以在这里继续增加更多通知类型,不需要改变顶层设置布局。",notificationsOffSummary:"系统通知已关闭",notificationsAiOnSummary:"AI 任务结束通知已开启",notificationsExitOnSummary:"终端退出通知已开启",notificationsBothOnSummary:"AI 任务结束、终端退出通知已开启",notificationsNoEventsSummary:"暂无开启的通知事件",notificationsDenied:"浏览器通知权限已被阻止,请在站点设置中开启。",notificationsUnsupported:"通知需要安全上下文和 Service Worker 支持。",notificationsTestBody:"通知已开启。后台 AI 任务结束后会提醒你。",shell:"Shell",tmux:"Tmux",auto:"自动",webgl:"WebGL",canvas:"内置",tmuxServer:"Tmux 服务",tmuxUnavailable:"不可用",noTmuxSessions:"服务端没有 tmux 会话。",installTmuxHint:"请在服务端安装 tmux 后启用。",refresh:"刷新",attached:"已连接",restorable:"可恢复",attach:"连接",attaching:"连接中…",destroy:"销毁",sessions:({n:e})=>`${e} 个会话`,windows:({n:e})=>`${e} 个窗口`,keyboardToolbar:"键盘工具栏",aiAgentDetection:"AI 代理检测",signOut:"退出登录",language:"语言",programNamePlaceholder:"程序名(如 claude)",patternPlaceholder:"正则表达式(如 Thinking|Generating)",statusPlaceholder:"状态",addProgram:"添加程序",addPattern:"添加规则",resetDefaults:"恢复默认",invalidRegex:"无效的正则",removeProgram:"移除程序",removeRule:"移除规则",keepLabel:"保持",customColor:"自定义颜色",tabIndicator:"标签指示器样式",toolbarPresets:"工具栏预设",detectionRules:"检测规则",agentHooksHint:"安装 hooks 后,agent 会主动上报状态:回合进行中(绿)、等你授权/回答(黄)、回合完成(对勾),并在等待你输入时推送通知。hooks 全局安装但只在 termdock 的终端里生效。",agentHooksInstall:"安装",agentHooksInstalled:"已安装",agentHooksOutdated:"需更新",agentHooksNeedsApproval:"待授权",agentHooksApprovalHint:"在 Codex 中输入 /hooks,批准 Termdock Hook 后生效",agentHooksNotInstalled:"未安装",agentHooksUninstall:"卸载",agentHooksReinstall:"重新安装",agentHooksDevMode:"开发模式:hooks 指向 TS 源码,需要构建后的版本才能生效",agentHooksTarget:"写入",agentAutoRename:"自动更新会话标题",agentAutoRenameHint:"Agent 完成一轮后,根据近期内容更新标题。默认全部关闭,手工命名的会话不会被覆盖;启用外部插件标题后才会执行其 CLI。",agentAutoRenameToggle:"切换此 Agent 的自动标题",agentAutoRenameShort:"自动标题",agentAutoRenameNamer:"起名 Agent",agentAutoRenameFollow:"跟随当前会话",agentAutoRenameModelsFromCli:"模型由本机 CLI 动态提供",agentAutoRenameRefreshModels:"重新查询 CLI 模型",agentAutoRenameCliDefault:"CLI 默认模型",agentAutoRenameAutomatic:"自动选择",agentAutoRenameNoCli:"未检测到可用于起名的 CLI",agentAutoRenameAdvanced:"高级标题偏好",agentAutoRenamePreference:"补充偏好",agentAutoRenamePreferenceHint:"可选。仅补充你对标题风格或重点的偏好;Termdock 的默认起名规则仍会保留。离开输入框时自动保存。",agentAutoRenamePreferencePlaceholder:"例如:突出用户收益;优先使用动宾结构;避免技术术语",agentAutoRenamePayloadLimit:"用户消息上下文上限(字符)",agentAutoRenamePayloadLimitHint:"保留 prompt-submit 原始 payload 的总字符数,默认 12000,可设置 1000–64000。",agentPlugins:"Agent 插件",agentPluginAdd:"添加插件",agentPluginHint:"从 HTTPS Git 仓库或本地目录安装;请先审查来源。Hooks 和可执行的标题 CLI 均需用户分别启用。",agentPluginCreate:"创建插件",agentPluginDelete:"删除插件",agentPluginInvalid:"插件配置无效",agentPluginCopyAiPrompt:"复制 AI 修复提示",agentPluginCopied:"已复制",agentPluginSourcePlaceholder:"https://github.com/user/agent-plugin 或本地目录",agentPluginInstallPackage:"安装插件",agentPluginAdvancedManifest:"高级:直接粘贴 manifest.json",agentPluginUpdateAvailable:"有更新",agentPluginManualSource:"手动 manifest",agentPluginUpdate:"更新",agentPluginCheck:"检查更新",agentPluginDoctor:"诊断",agentPluginDoctorHint:"显式运行插件模型探测,不会调用标题生成",agentPluginDoctorStatusOk:"标题与模型能力正常",agentPluginDoctorStatusMissing:"未声明 titleNamer",agentPluginDoctorStatusCliDefault:"标题可用,使用 CLI 默认模型",agentPluginDoctorStatusNoModels:"没有可用的模型数据",agentPluginDoctorStatusFailed:"模型探测失败",agentPluginDoctorModels:"个可用模型",agentPluginDoctorAutomatic:"自动选择",agentPluginDoctorCliDefault:"未指定模型时使用 Agent CLI 默认模型",agentAutoRenameInterval:"重新判断间隔",agentAutoRenameMinutes:"分钟",mobileKeyboard:"移动键盘",saving:"保存中…",rulesHint:"配置正则表达式来识别 AI 工具在终端标签中的状态。每条规则可独立设置标签、颜色、图标样式以及输出静默后指示器保留的时长。停止后若你未查看该标签,标签会保留一个黄色待查看提示。",programsHelp:"支持在一个配置中匹配多个程序,用英文逗号分隔。",programLabelResolution:"程序名识别",rawCommandMapping:"原始命令映射",rawCommandMappingHint:"以下规则将原始命令行映射为标签显示名。用户规则优先于内置规则。",genericProgramNames:"通用程序名",genericProgramNamesHint:"触发 ps 深度识别(如 node, python)",wrapperScriptNames:"包装脚本名",wrapperScriptNamesHint:"CLI 包装器,启动其他工具(如 aiden, npx)",shellNamesConfig:"Shell 名称",shellNamesHint:"从标签显示中过滤(如 bash, zsh)",addTag:"+ 添加",customRules:"自定义规则",addRule:"添加规则",localAccess:"本地访问",localAccessHint:"连接地址与手机访问引导",resetAutoName:"恢复自动",mobileSetupIntro:"手机与此服务需处于同一网络。启用 HTTPS 时,先安装并信任本地 CA 证书,再打开下方访问地址。",mobileSetupDownload:"1. 扫码下载 CA 证书",mobileSetupIos:"iPhone / iPad:用相机扫码后在 Safari 打开。在「设置 → 通用 → VPN 与设备管理」安装已下载的描述文件,再到「设置 → 通用 → 关于本机 → 证书信任设置」开启完全信任。",mobileSetupAndroid:"Android:下载证书后,在系统安全设置中将其安装为 CA 证书。不同品牌的菜单名称可能有所不同。",mobileSetupConnect:"2. 打开 Termdock",mobileSetupConnectHint:"信任证书后,扫描下方 IP 地址二维码,或将本地地址复制到手机浏览器。若域名无法解析,请使用 IP 地址。",onboardingUrl:"手机引导",httpsActive:"HTTPS 已启用",httpsInactive:"HTTPS 未启用",caMissing:"未配置 CA 下载",closeSettings:"关闭设置",desktopTitle:"Termdock 桌面端",desktopStatusLoading:"正在读取 macOS 原生状态…",desktopSwitchService:"切换服务",desktopOpenDataDirectory:"打开数据目录"},toolbarPresets:{preview:"预览",presets:"预设",label:"标签",new:"新建",reset:"重置",presetLabelPlaceholder:"预设名称",deletePreset:({name:e})=>`删除预设 ${e}`,matchPrograms:"匹配程序",typeEnterHint:"输入后回车",programsPlaceholder:"vim, nvim, /^claude(-code)?$/i …",programsHelp:"纯字符串按大小写不敏感子串匹配。用 /…/flags 包裹则为正则(针对小写程序名测试)。",altSlot:"Alt 修饰键槽",altSlotHint:"在预览中保留一个 Alt 键槽位。",desktopVisibility:"桌面端显示",desktopVisibilityHint:"桌面端只显示该预设的自定义按钮,不显示基础快捷键。",rowLayout:"行布局",rowLayoutHint:"每行按钮数。",addRow:"行",rowN:({n:e})=>`第 ${e} 行`,del:"删",buttons:"按钮",buttonsHint:"点击编辑,使用 ↑↓ 排序。",addButton:"添加按钮",noCustomButtons:"暂无自定义按钮。添加一个来覆盖默认工具栏。",moveUp:"上移",moveDown:"下移",removeRow:({n:e})=>`移除第 ${e} 行`,removeAction:({name:e})=>`移除 ${e}`,labelField:"标签",labelPlaceholder:"按钮上显示的文本",sequence:"序列",sequencePlaceholder:"例如 /undo 或 \\t 或 /||undo",sequenceHint:"双击序列",doubleTap:"双击序列",doubleTapAdd:"+ 添加",doubleTapPlaceholder:"例如 /undo\\r 或 /||undo ||\\r",remove:"移除",noSequence:"无序列",preset:"预设",overCapacityHint:"按钮数超过槽位,多余按钮将使用最后一行的尺寸。"},agentRules:{ruleColors:{green:"绿",yellow:"黄",red:"红",blue:"蓝",purple:"紫",orange:"橙",gray:"灰"}},tab:{session:"会话",new:"新建会话",rename:"重命名",renameHint:"修改标签的显示名称",renamePlaceholder:"留空则恢复默认名称",copyCwd:"复制当前目录",copyCwdHint:"复制当前工作目录",fontSize:"字体大小",fontSizeHint:"仅对这个会话生效",fontSizeReset:"跟随全局",resumeAgent:"恢复 Agent 会话",resumeAgentHint:"用原生 session id 恢复上次对话",resumeAgentAvailable:"有可恢复的 Agent 对话",resumeAgentRecoveredTitle:({agent:e})=>`可继续上次的 ${e} 对话`,resumeAgentRecoveredHint:"Terminal 曾异常中断,已重新创建;可以从上次对话继续。",resumeAgentNow:"恢复",resumeAgentLater:"暂不恢复",resumeAgentSubmitting:"正在提交原生恢复命令…",resumeAgentWaiting:"正在等待 Agent 确认已载入原会话…",resumeAgentSuccess:({agent:e})=>`${e} 会话已恢复`,resumeAgentFailed:"Agent 会话恢复失败,可以重试。",resumeAgentConflict:"该 Agent 会话已在另一个 Terminal 中打开。",resumeAgentBusy:"当前 Agent 回合尚未结束,暂时不能恢复。",resumeAgentTimeout:"Agent 未确认已载入原会话,请查看 Terminal 输出或重试。",tmuxRecoveryTitle:({count:e})=>`检测到 tmux 异常退出,${e} 个 Agent 可恢复`,tmuxRecoveryHint:"Termdock 保留了原生会话 ID。恢复操作会在原标签页中继续之前的对话。",tmuxRecoveryRestoreAll:"恢复全部",tmuxRecoveryRestoring:"正在恢复…",tmuxRecoveryDismiss:"暂不处理",tmuxRecoveryPartial:({restored:e,failed:t})=>`已恢复 ${e} 个,${t} 个需要重试。`,tmuxRecoveryFailed:"恢复失败,请检查终端状态后重试。",tmuxRecoveryDismissFailed:"暂时无法关闭该恢复提示。",tmuxRecoveryProgress:({total:e,queued:t,paused:n,resourceWait:r,running:o,succeeded:i,failed:s})=>`恢复进度:总计 ${e} · 排队 ${t} · 暂停 ${n}(资源等待 ${r}) · 执行中 ${o} · 完成 ${i} · 失败 ${s}`,tmuxRecoveryPausedForResources:"资源不足,已暂停启动;资源恢复后会自动继续。",tmuxRecoveryPause:"暂停",tmuxRecoveryResume:"继续",tmuxRecoveryInProgress:"恢复进行中",copied:"已复制",close:"关闭会话",closeHint:"从列表移除该标签",longPressTip:"提示:按住标签不动约半秒打开操作菜单,按住并拖动可排序。",sessionsTitle:"会话",explorerTitle:"资源管理器",split:"分屏",splitTitle:"添加到分屏工作区",closeFailed:({name:e})=>`未能关闭「${e}」。会话仍保留,请重试。`,splitNew:"新建会话并加入",splitNewHint:"沿用当前目录和默认会话类型;可连续加入多个会话",splitExisting:"选择已有会话或工作区",splitExistingHint:"会话可组成多个独立工作区;选择另一工作区会将两组合并",splitCurrent:"当前",splitClose:"退出分屏",splitLayout:"分屏布局",splitHorizontal:"左右",splitVertical:"上下",splitGrid:"网格",splitWorkspace:"分屏组",splitWorkspaces:"分屏工作区",splitRename:"重命名分屏组",splitRemovePane:"移出分屏",splitExistingGroups:"已有分屏组",splitAvailableSessions:"可加入的会话",splitOccupied:"已成组",splitUnavailableGrouped:"分组模式下只能分屏同一目录的会话",splitEndedGrouped:"已退出分屏:分组模式不支持跨目录组合",splitNoOtherSessions:"没有可组合的其他会话",sessionCount:({count:e})=>`${e} 个会话`,closeChooserTitle:"销毁 Tmux 会话?",closeChooserDescription:"确认后会终止该会话及其中的所有进程,此操作无法撤销。",destroySession:"销毁会话",confirmDestroySession:"确认销毁",destroySessionHint:"终止 tmux 会话及其中的所有进程。",dragToClose:"拖到此处关闭",releaseToClose:"松手后确认"},agent:{aiRunning:"AI 运行中",needsReview:"需要查看",finishedReview:"AI 已完成 — 需要查看",aiWaiting:"AI 等待中",copyMode:"Copy 模式",jumpToNext:"跳到下一个待处理",jumpToNextRunning:"跳到下一个运行中会话",selectRunningSession:"选择运行中的 Session",runningSessionGestureHint:"轻点循环 · 横向滑动选择 · 长按拖动",currentSession:"当前"},serviceAttention:{title:"所有服务的待处理",summary:"{services} 个服务 · {count} 个会话",currentService:"当前服务",waiting:"等待你处理",offline:"连接已断开 · 显示上次状态",login:"需要重新登录 · 显示上次状态",empty:"暂时没有待处理会话",viewService:"进入服务查看",scope:"汇总已打开的服务,点会话直接进入",changed:"待处理状态已更新,请重新选择。",unavailable:"暂时无法打开该服务,请从服务列表重试。"},connection:{reconnecting:"正在重连…"},desktopServices:{switchService:"切换 Termdock 服务",openServices:"已打开的服务",idle:"空闲",manageServices:"管理服务与名称"},terminal:{input:"终端输入",error:"错误",dropFilesToPastePaths:"拖放文件以输入路径",loading:"正在加载终端…",initializing:"正在初始化终端引擎…",failedToLoad:"终端加载失败",unknownError:"发生未知错误",componentFailed:"终端组件加载失败",paste:"粘贴",copied:"已复制",copyFailed:"复制失败",longPressSelectsText:"长按选择文本",longPressSendsArrows:"长按发送方向键",switchLongPressToArrows:"将长按切换为方向键",switchLongPressToCopy:"将长按切换为复制所选文本"},quota:{title:"订阅配额",noProviders:"未检测到订阅服务。",noProvidersHint:"使用 AI 编程工具并登录后,自动显示配额信息。",exhausted:"已用完",left:({n:e})=>`剩余 ${e}`,updated:({time:e})=>`${e} 更新`,refresh:"刷新",close:"关闭"},errorBoundary:{title:"出现了一些问题",unexpected:"发生意外错误",retry:"重试",copyDetails:"复制错误信息",copied:"已复制",copyFailed:"复制失败"},error:{type:{network:"网络连接错误",session:"会话错误",terminal:"终端错误",auth:"认证错误",validation:"验证错误",unknown:"未知错误"},severity:{low:"提示:",medium:"警告:",high:"错误:",critical:"严重错误:"},suggestion:{networkCheck:"检查网络连接",networkRetry:"尝试重新连接",networkProxy:"检查代理设置",networkWait:"等待网络恢复",sessionRecreate:"重新创建会话",sessionServer:"检查服务器状态",sessionCache:"清理浏览器缓存",terminalRestart:"重启终端",terminalConfig:"检查终端配置",terminalClear:"清除终端输出",authRelogin:"重新登录",authCredentials:"检查凭证",authAdmin:"联系管理员",validationFormat:"检查输入格式",validationParams:"验证参数",validationDocs:"参考文档",unknownReload:"刷新页面",unknownApp:"重启应用",unknownSupport:"联系技术支持"}}},UA=["en","zh"],Lr="en",Uc=new WeakMap;let HA=0;function $A(e,t,n){const r=Uc.get(e);if(!r?.pending||r.pending.id!==t)return;const o=performance.now();if(!document.hidden&&o-r.lastPoll<2500){const i=o-r.pending.sentAt;r.samples.push(i<8e3?i:null),r.samples=r.samples.slice(-20),i<8e3&&(r.lastReply=o,r.handlerMs=typeof n=="number"&&Number.isFinite(n)&&n>=0&&n<=i?n:void 0)}r.pending=void 0}function qA(e){const t={connected:!1,rtt:null,average:null,jitter:null,timeouts:0,samples:0,waiting:!1};if(!e||e.readyState!==WebSocket.OPEN)return t;const n=performance.now();let r=Uc.get(e);if(r||(r={lastPoll:n,lastSent:-1/0,lastReply:-1/0,samples:[]},Uc.set(e,r)),(document.hidden||n-r.lastPoll>=2500)&&(r.pending=void 0,r.lastSent=-1/0,r.lastReply=-1/0),r.lastPoll=n,!document.hidden&&(r.pending&&n-r.pending.sentAt>=8e3&&(r.samples.push(null),r.samples=r.samples.slice(-20),r.pending=void 0),!r.pending&&n-r.lastSent>=5e3)){const l=`quality-${++HA}`;r.pending={id:l,sentAt:n},r.lastSent=n;try{e.send(JSON.stringify({type:"ping",qualityProbeId:l}))}catch{return r.pending=void 0,t}}const o=r.samples.filter(l=>l!==null),i=r.samples[r.samples.length-1],s=n-r.lastReply<15e3,a=o.slice(1).map((l,d)=>Math.abs(l-o[d])),c=[...o].sort((l,d)=>l-d);return{diagnostics:e.getConnectionDiagnostics?.(),minimum:c[0],maximum:c[c.length-1],p95:c[Math.ceil(c.length*.95)-1],history:[...r.samples],handlerMs:s&&i!=null?r.handlerMs:void 0,lastReplyAgeMs:Number.isFinite(r.lastReply)?n-r.lastReply:void 0,connected:!0,rtt:s&&i!=null?Math.round(i):null,average:o.length?Math.round(o.reduce((l,d)=>l+d,0)/o.length):null,jitter:a.length?Math.round(a.reduce((l,d)=>l+d,0)/a.length):null,timeouts:r.samples.length-o.length,samples:r.samples.length,waiting:!!r.pending&&n-r.pending.sentAt>=1500}}function KA(e){const t=e.serviceLabel?.trim();if(!t||/^https?:\/\//i.test(t)||t===e.serviceOrigin)return"远端服务";try{const n=new URL(e.serviceOrigin??"");if(t===n.host||t===n.hostname)return"远端服务"}catch{}return t}function o2(e,t){const n=i=>{const s=i.name.trim();return!s||/^(?:tmux:|remote:|wt-)/i.test(s)||s===i.sessionId?i.agent?.displayName?.trim()||"成员":s},r=n(e),o=t.filter(i=>n(i)===r);return o.length>1?`${r} ${o.findIndex(i=>i.sessionId===e.sessionId)+1}`:r}function i2(e){return e.serviceConnected===!1||["offline","disconnected","service-unreachable","closed","exited"].includes(e.status??"")?"disconnected":e.serviceConnected===!0?"connected":"unknown"}function lo(e){if(!e.startsWith("remote:"))return null;const t=e.slice(7).split(":");if(t.length!==2)return null;try{const n=decodeURIComponent(t[0]),r=decodeURIComponent(t[1]);return!r||new URL(n).origin!==n||!/^https?:/.test(n)?null:{origin:n,id:r}}catch{return null}}class zA{constructor(t){this.source=t,this.peers={state:t.peerProtocol==="unsupported"?"unsupported":t.readPeers?"loading":"unavailable",checkedAt:null}}source;local=null;remote=[];peers;localInFlight=null;peerInFlight=null;listeners=new Set;disposed=!1;peerTimer;lastPeerAttempt=-1/0;generation=0;localHealthy=!1;subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}snapshot(){if(!this.local)return null;const t=new Map;for(const n of this.local.groups)for(const r of n.remoteSessions??[]){const o=lo(r.sessionId);o&&o.origin!==this.source.origin&&o.origin!==this.source.peerOrigin&&t.set(r.sessionId,{...r,status:"offline",serviceConnected:!1})}for(const n of this.remote)t.set(n.sessionId,n);for(const n of this.local.sessions){const r=lo(n.sessionId);t.set(n.sessionId,r&&r.origin!==this.source.origin&&r.origin!==this.source.peerOrigin?{...n,status:"offline",serviceConnected:!1}:n)}for(const n of this.remote){const r=this.peers.services?.find(o=>o.origin===n.serviceOrigin||o.origin===lo(n.sessionId)?.origin);t.set(n.sessionId,r?.connected===!1?{...n,status:"offline",serviceConnected:!1}:n)}return{groups:this.local.groups.map(n=>({...n,remoteSessions:n.remoteSessions?.map(r=>t.get(r.sessionId)??r)})),sessions:[...t.values()],peers:this.peers,capabilities:this.local.capabilities}}emit(){if(this.disposed||!this.localHealthy)return;const t=this.snapshot();if(t)for(const n of this.listeners)n(t)}load(){if(this.disposed)return Promise.reject(new Error("协作连接已切换,请重新加载"));if(this.localInFlight)return this.localInFlight;this.refreshPeers();const t=this.generation,n=Promise.resolve().then(()=>this.source.readLocal()).then(r=>{if(this.disposed)throw new Error("协作连接已切换,请重新加载");if(t!==this.generation)return this.load();if(!Array.isArray(r.groups)||!Array.isArray(r.sessions))throw new Error("协作会话响应无效,请更新服务后重试");return this.local=r,this.localHealthy=!0,this.emit(),this.snapshot()}).catch(r=>{throw t===this.generation&&(this.localHealthy=!1,this.remote=this.remote.map(o=>({...o,status:"offline",serviceConnected:!1}))),r}).finally(()=>{this.localInFlight===n&&(this.localInFlight=null)});return this.localInFlight=n,n}invalidate(){this.generation++,this.localInFlight=null,this.localHealthy=!1}refreshPeers(t=!1){if(this.disposed||!this.source.readPeers||this.peerInFlight||!t&&Date.now()-this.lastPeerAttempt<2e3)return;this.lastPeerAttempt=Date.now(),this.peers.checkedAt||(this.peers={state:"loading",checkedAt:null}),this.emit();const n=this.source.readPeers;this.peerInFlight=Promise.race([Promise.resolve().then(()=>n()),new Promise((r,o)=>{this.peerTimer=setTimeout(()=>o(new Error("服务端协作目录加载超时,请检查服务连接")),2e4)})]).then(r=>{if(this.disposed)return;const o=r.origin===this.source.origin||!!this.source.peerOrigin&&r.origin===this.source.peerOrigin;if(!Array.isArray(r.sessions)||this.source.peerProtocol==="v2"&&(r.protocolVersion!==2||!o)||r.origin&&!o||r.protocolVersion!==void 0&&r.protocolVersion!==2)throw new Error("协作目录响应与当前服务不匹配,请升级服务后重试");this.remote=r.sessions.filter(s=>{const a=lo(s.sessionId);return a&&a.origin!==this.source.origin&&a.origin!==this.source.peerOrigin});const i=r.services?.filter(s=>s.origin!==this.source.origin&&s.origin!==this.source.peerOrigin);this.peers={state:i?.some(s=>!s.connected)?"partial":"ready",checkedAt:Date.now(),services:i,removedServices:r.removedServices}}).catch(r=>{this.disposed||(this.remote=this.remote.map(o=>({...o,status:"offline",serviceConnected:!1})),this.peers={state:"error",checkedAt:Date.now(),error:r instanceof Error?r.message:"跨服务会话加载失败"})}).finally(()=>{clearTimeout(this.peerTimer),this.peerInFlight=null,this.emit()})}dispose(){this.disposed=!0,clearTimeout(this.peerTimer),this.listeners.clear(),this.local=null,this.remote=[]}}async function VA(e,t){const n=navigator.serviceWorker?.controller;if(!n)return null;const r=new MessageChannel;return new Promise(o=>{const i=a=>{clearTimeout(s),r.port1.close(),o(a)},s=setTimeout(()=>i(null),5e3);r.port1.onmessage=a=>{try{const c=new URL(a.data.url,location.origin);i(c.origin===location.origin&&/^\/__termdock-download\/[a-f0-9-]{36}$/.test(c.pathname)?c.href:null)}catch{i(null)}},r.port1.onmessageerror=()=>i(null);try{n.postMessage({type:"termdock:prepare-download",blob:e,filename:t},[r.port2])}catch{i(null)}})}const WA=4*1024*1024,GA=256*1024,XA=1440*6e4;let Sr=0,df;function Zl(){return typeof indexedDB>"u"?Promise.resolve(null):df??=new Promise(e=>{const t=indexedDB.open(`termdock-terminal-snapshots:${dr}`,1);t.onupgradeneeded=()=>t.result.createObjectStore("snapshots",{keyPath:"id"}),t.onerror=()=>e(null),t.onblocked=()=>e(null),t.onsuccess=()=>{t.result.onversionchange=()=>{t.result.close(),df=void 0},e(t.result)}})}function Hc(e){return!!e&&e.version===1&&typeof e.epoch=="string"&&e.epoch.length>0&&Number.isSafeInteger(e.cols)&&e.cols>0&&Number.isSafeInteger(e.rows)&&e.rows>0&&Number.isSafeInteger(e.seq)&&e.seq>0&&typeof e.data=="string"&&e.data.length*2<=GA&&e.savedAt<=Date.now()&&Date.now()-e.savedAt<XA}async function s2(e){const t=Sr;try{const n=await Zl();return!n||t!==Sr?null:await new Promise(r=>{const o=n.transaction("snapshots").objectStore("snapshots").get(e);o.onerror=()=>r(null),o.onsuccess=()=>r(t===Sr&&Hc(o.result)?o.result:null)})}catch{return null}}async function a2(e){const t=Sr;if(Hc(e))try{const n=await Zl();if(!n||t!==Sr)return;await new Promise(r=>{const o=n.transaction("snapshots","readwrite"),i=o.objectStore("snapshots");i.put(e);const s=i.getAll();s.onsuccess=()=>{let a=0,c=0;for(const l of s.result.sort((d,u)=>u.savedAt-d.savedAt))a+=l.data.length*2,(++c>32||a>WA||!Hc(l))&&i.delete(l.id)},o.oncomplete=()=>r(),o.onerror=o.onabort=()=>r()})}catch{}}async function rm(){Sr+=1;try{(await Zl())?.transaction("snapshots","readwrite").objectStore("snapshots").clear()}catch{}}typeof window<"u"&&window.addEventListener("auth:unauthorized",()=>{rm()});const Ut=new Map,un=new Map,YA=32*1024*1024,ZA=8*1024*1024,JA=48;let uo=0,$c=0;function Jl(){$c+=1,Ut.clear(),uo=0;for(const e of un.values())e.controller.abort();un.clear()}typeof window<"u"&&window.addEventListener("auth:unauthorized",Jl);function QA(e,t){const n=Ut.get(e);if(n&&(uo-=n.blob.size,Ut.delete(e)),!(t.blob.size>ZA))for(Ut.set(e,t),uo+=t.blob.size;Ut.size>JA||uo>YA;){const r=Ut.keys().next().value;uo-=Ut.get(r).blob.size,Ut.delete(r)}}async function om(e,t={}){const n=new URL(e,typeof location<"u"?location.origin:"http://localhost");if(!/^\/api\/terminal\/fs\/(read|blob)$/.test(n.pathname))return fetch(e,{signal:t.signal});if(t.signal?.aborted)throw t.signal.reason??new DOMException("Aborted","AbortError");n.searchParams.delete("requestSlotId"),n.searchParams.delete("action"),n.searchParams.sort();const r=n.href;let o=un.get(r);if(!o){const s=new AbortController,a=$c,c=Ut.get(r),l=new Headers,d=c?.headers.get("ETag");d&&l.set("If-None-Match",d);const u=setTimeout(()=>s.abort(new DOMException("File preview timed out. Please retry.","TimeoutError")),t.timeoutMs??15e3),f={controller:s,readers:0,promise:Promise.resolve(null)};f.promise=(async()=>{const h=await fetch(r,{headers:l,signal:s.signal,cache:"no-cache"});let g;return h.status===304&&c?g=c:g={blob:await h.blob(),headers:new Headers(h.headers),status:h.status},$c===a&&!s.signal.aborted&&g.status===200&&g.headers.has("ETag")&&QA(r,g),h.status===401&&Jl(),g})().finally(()=>{clearTimeout(u),un.get(r)===f&&un.delete(r)}),o=f,un.set(r,o)}const i=o;return i.readers+=1,new Promise((s,a)=>{let c=!1;const l=()=>c?!1:(c=!0,t.signal?.removeEventListener("abort",d),i.readers-=1,i.readers===0&&un.get(r)===i&&(un.delete(r),i.controller.abort()),!0),d=()=>{l()&&a(t.signal?.reason??new DOMException("Aborted","AbortError"))};if(t.signal?.addEventListener("abort",d,{once:!0}),t.signal?.aborted){d();return}i.promise.then(u=>{l()&&s(new Response(u.blob,{status:u.status,headers:u.headers}))},u=>{l()&&a(u)})})}const Ql="auth:unauthorized";let lr=null;class Se extends Error{constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="TerminalApiError"}status;code}class Br extends Error{code="TERMINAL_INPUT_REJECTED";constructor(t){super(t),this.name="TerminalInputError"}}async function eC(){const e=await fetch("/api/terminal/update");if(!e.ok)throw new Se("Failed to load update state",e.status);return e.json()}async function tC(){const e=await re(),t=await fetch("/api/terminal/update/check",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Se("Failed to check for updates",t.status);return t.json()}async function nC(e){if(e&&!e())throw new Se("Update confirmation expired");const t=await re();if(e&&!e())throw new Se("Update confirmation expired");const n=await fetch("/api/terminal/update/restart",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to restart Termdock"}));throw new Se(r.error||"Failed to restart Termdock",n.status)}return n.json()}async function rC(){const e=await re(),t=await fetch("/api/terminal/server-health/enable-supervision",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Se("Failed to enable automatic recovery",t.status)}async function oC(){const e=await fetch("/api/terminal/server-health");if(!e.ok)throw new Se("Failed to load server health",e.status);return e.json()}async function iC(){const e=await re(),t=await fetch("/api/terminal/server-health/dismiss",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Se("Failed to dismiss server health",t.status);return t.json()}async function sC(){const e=await fetch("/api/terminal/quota");if(!e.ok)throw new Se("Failed to fetch quota",e.status);return e.json()}async function aC(){const e=await re(),t=await fetch("/api/terminal/quota/refresh",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Se("Failed to refresh quota",t.status);return t.json()}const Kn=8e3,im=6e4,cC=32e3,sm=125e3,Xt=1e4,lC=65e3,xr=45e3,dC=18e4,am=8e3,cm=8e3,lm=15e3,uC=1e4,Dr=5e3;let fC=0;const Ii=[];let Ea=!1;function jt(e,t={}){if(typeof window>"u")return;const n=JSON.stringify({level:e==="error"||e==="timeout_or_abort"||e==="response_body_timeout"||e==="response_body_parse_error"?"warn":"info",message:`DIFF_API ${e}`,data:{seq:++fC,ts:Date.now(),...t}});Ii.push(n),hC()}async function hC(){if(!Ea){Ea=!0;try{for(;Ii.length>0;){const e=Ii[0];try{await fetch("/api/client-log",{method:"POST",headers:{"Content-Type":"application/json"},body:e,keepalive:!0}),Ii.shift()}catch{break}}}finally{Ea=!1}}}function ed(e,t,n){const r=new AbortController;let o=setTimeout(()=>{r.abort(new DOMException(n,"TimeoutError"))},t);const i=()=>r.abort(e?.reason);return e&&(e.aborted?i():e.addEventListener("abort",i,{once:!0})),{signal:r.signal,cleanup:()=>{o&&(clearTimeout(o),o=null),e?.removeEventListener("abort",i)}}}async function Te(e,t,n,r){const{signal:o,cleanup:i}=ed(t?.signal??void 0,n,r);try{return await fetch(e,{...t,signal:o})}catch(s){throw s instanceof DOMException&&s.name==="TimeoutError"?new Error(r):s}finally{i()}}async function dm(e,t,n){let r=null;const o=new Promise((i,s)=>{r=setTimeout(()=>s(new Error(n)),t)});try{return await Promise.race([e.text(),o])}finally{r&&clearTimeout(r)}}async function _r(e,t,n){const r=await dm(e,t,n);return JSON.parse(r)}if(typeof window<"u"&&!window.__termdockFetchPatched){window.__termdockFetchPatched=!0;const e=window.fetch.bind(window);window.fetch=async(...t)=>{const n=await e(...t);if(n.status===401){lr=null,Vo();try{window.dispatchEvent(new CustomEvent(Ql))}catch{}}return n}}async function re(){if(lr)return lr;const e=await Te("/api/csrf-token",void 0,am,"CSRF token request timed out");if(!e.ok)throw new Error("Failed to get CSRF token");const t=await _r(e,Dr,"CSRF token response timed out");if(!t.csrfToken)throw new Error("Invalid CSRF token response");return lr=t.csrfToken,lr}function td(){Vo(),lr=null}const pC=2e4,uf=8e3,um=1500,fm=um,Pe=new Map,nd=new Map;function gC(e){return qA(Pe.get(e)?.ws)}const mC=24,wC=40,yC=40,bC=1024*1024,vC=1024*1024,SC=2*1024*1024,xC=36,hm=50,EC=1e3,AC=20,pm=new TextEncoder;function gm(e){return e.items.length-e.head}function ff(e){e.head===e.items.length?(e.items.length=0,e.head=0):e.head>=64&&e.head*2>=e.items.length&&(e.items.splice(0,e.head),e.head=0)}function CC(e){const t=JSON.stringify({id:"0".repeat(xC),type:"ws-data",data:e});return pm.encode(t).byteLength<=SC}function kC(e){return typeof e=="object"&&e!==null&&e.code==="PACKET_QUEUE_BACKPRESSURE"}function hf(e,t){const n=t instanceof Br?t:new Br(t.message),r=e.pendingInputs;r.items.length=0,r.head=0,r.bytes=0,e.inputFlushTimer&&(clearTimeout(e.inputFlushTimer),e.inputFlushTimer=null);try{e.onError?.(n,!0)}finally{e.disconnect()}return n}function IC(e){const t=gm(e.pendingInputs);return e.retryState.retryCount>=2||t>=yC?"congested":e.retryState.retryCount>=1||t>=8?"degraded":"good"}function pf(e){const t=e.pendingInputs;if(!(gm(t)===0||e.ws.readyState!==WebSocket.OPEN))for(;t.head<t.items.length;){const n=t.items[t.head];if(!n){t.head++,ff(t);continue}try{e.ws.send(n.message)}catch(r){if(!kC(r))return hf(e,r instanceof Error?r:new Error(String(r)));if(e.inputRetryAttempts++,e.inputRetryAttempts>=AC)return hf(e,new Br("Terminal input was not accepted after repeated encrypted-channel backpressure"));const o=e.inputRetryDelayMs;e.inputRetryDelayMs=Math.min(EC,o*2),!e.inputFlushTimer&&!e.retryState.isClosed&&(e.inputFlushTimer=setTimeout(()=>{e.inputFlushTimer=null,rd(e)},o));return}t.bytes-=n.bytes,t.items[t.head]=void 0,t.head++,ff(t),e.inputRetryDelayMs=hm,e.inputRetryAttempts=0}}function rd(e){if(e.ws.readyState!==WebSocket.OPEN||e.inputFlushTimer)return;const t=IC(e);if(t==="good")return pf(e);const n=t==="congested"?wC:mC;e.inputFlushTimer=setTimeout(()=>{e.inputFlushTimer=null,pf(e)},n)}const Eo=new Map;function RC(e,t,n,r,o,i){const s=Eo.get(e);!s||s.connection!==i||(Eo.delete(e),t?s.resolve({success:!0,layout:n,selection:o}):s.reject(new Error(r||"Tmux action failed")))}const sr=new Map;function TC(e,t,n,r){const i=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/terminal/${e}/ws`,s=new URLSearchParams({flow:"2",transport:"tmux-client",active:nd.get(e)===!1?"0":"1"});t>0&&s.set("since",String(t)),n&&s.set("epoch",n);const a=r??sr.get(e);return a&&(s.set("cols",String(a.cols)),s.set("rows",String(a.rows))),`${i}?${s}`}const qc=new Map,Kc=new Map;function PC(e,t,n){qc.set(e,t),Kc.set(e,n)}function NC(e){const t=Pe.get(e);return t?.streamEpoch&&t.appliedSeq===t.lastSeq&&t.lastSeq>0?{seq:t.lastSeq,epoch:t.streamEpoch}:null}async function LC(e){const t=await re(),n=await fetch("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({cols:e.cols||80,rows:e.rows||24,mode:e.mode||"shell",tmuxSessionName:e.tmuxSessionName,cwd:e.cwd,termType:e.termType})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to create terminal"}));throw new Error(r.error||"Failed to create terminal session")}return n.json()}function BC(e,t,n,r={}){const{maxRetries:o=10,initialRetryDelay:i=1e3,maxRetryDelay:s=2e4,connectionTimeout:a=15e3}=r,c={maxRetries:o,initialDelayMs:i,maxDelayMs:s,connectionTimeoutMs:a,retryCount:0,retryTimeout:null,connectionTimeoutId:null,isClosed:!1,isSuspended:!1};let l=null,d=qc.get(e)??0,u=Kc.get(e);Kc.delete(e),qc.delete(e);const f={items:[],head:0,bytes:0};let h=!1,g=null;const m=new WeakSet,v=()=>{c.retryTimeout&&(clearTimeout(c.retryTimeout),c.retryTimeout=null),c.connectionTimeoutId&&(clearTimeout(c.connectionTimeoutId),c.connectionTimeoutId=null),g&&(clearTimeout(g),g=null)},w=E=>{E.wakeProbe&&(clearTimeout(E.wakeProbe.timer),E.wakeProbe=void 0),E.heartbeatTimer&&(clearInterval(E.heartbeatTimer),E.heartbeatTimer=null),E.pongTimer&&(clearTimeout(E.pongTimer),E.pongTimer=null),E.inputFlushTimer&&(clearTimeout(E.inputFlushTimer),E.inputFlushTimer=null)},S=E=>{w(E),E.heartbeatTimer=setInterval(()=>{if(E.ws.readyState===WebSocket.OPEN){try{E.ws.send(JSON.stringify({type:"ping"}))}catch{}E.pongTimer&&clearTimeout(E.pongTimer),E.pongTimer=setTimeout(()=>{if(Date.now()-E.lastInboundAt>=uf){h=!0,w(E);try{E.ws.close()}catch{}R(new Error("WebSocket heartbeat timeout"),!1)}},uf)}},pC)},y=()=>{if(c.isClosed=!0,v(),f.items.length=0,f.head=0,f.bytes=0,l){w(l),Pe.delete(e);try{l.ws.close()}catch{}l=null}},A=()=>{if(c.isClosed)return;if(l){m.add(l.ws),w(l);try{l.ws.close()}catch{}}const E=TC(e,d,u,r.getDimensions?.()),C=Ug(E);h=!1,c.connectionTimeoutId=setTimeout(()=>{C.readyState!==WebSocket.OPEN&&(h=!0,C.close(),R(new Error("WebSocket connection timeout"),!1))},a);const k={ws:C,onEvent:t,onError:n,disconnect:y,reconnectNow:b=>{if(!c.isClosed&&(c.isSuspended=!1,!g)){if(v(),l){m.add(l.ws),w(l);try{l.ws.close()}catch{}}b?.silent||t({type:"reconnecting",attempt:Math.min(c.retryCount+1,o),maxAttempts:o}),c.retryCount=Math.min(c.retryCount+1,o),h=!0,g=setTimeout(()=>{g=null,h=!1,A()},0)}},suspendReconnect:()=>{c.isClosed||(c.isSuspended=!0,c.retryTimeout&&(clearTimeout(c.retryTimeout),c.retryTimeout=null))},retryState:c,lastSeq:d,pendingInputs:f,inputRetryDelayMs:hm,inputRetryAttempts:0,inputFlushTimer:null,heartbeatTimer:null,pongTimer:null,lastInboundAt:Date.now(),inboundSequence:0};C.onopen=()=>{c.isClosed||m.has(C)||h||(v(),c.retryCount=0,k.lastInboundAt=Date.now(),k.inboundSequence+=1,S(k),rd(k))},C.onmessage=b=>{if(!(c.isClosed||m.has(C)||h)){k.lastInboundAt=Date.now(),k.inboundSequence+=1;try{const x=JSON.parse(b.data);if(k.wakeProbe&&Pe.get(e)===k){const L=k.wakeProbe;k.wakeProbe=void 0,clearTimeout(L.timer);for(const I of L.listeners)I()}if(x.type==="pong"){$A(C,x.qualityProbeId,x.handlerMs),k.pongTimer&&(clearTimeout(k.pongTimer),k.pongTimer=null);return}if(x.type==="tmux-result"&&x.reqId){RC(x.reqId,x.success!==!1,x.layout,x.error,x.selection,C);return}if(x.type==="tmux-layout"&&x.layout){t({type:"tmux-layout",layout:x.layout});return}if(x.type==="tmux-screen-sync"&&Array.isArray(x.chunks)){t({type:"tmux-screen-sync",chunks:x.chunks.filter(L=>typeof L=="string"),cols:typeof x.cols=="number"?x.cols:void 0,rows:typeof x.rows=="number"?x.rows:void 0,generation:typeof x.generation=="number"?x.generation:void 0});return}if(x.type==="active-program"){t({type:"active-program",activeProgram:x.activeProgram,activeProgramRaw:x.activeProgramRaw,activeProgramSource:x.activeProgramSource});return}if(x.type==="cwd"){t({type:"cwd",cwd:x.cwd});return}if(x.type==="agent-status"){t({type:"agent-status",agentStatus:x.agentStatus??null,agentIndicator:x.agentIndicator??null,agentStatusDetail:x.agentStatusDetail??null,agent:x.agent??null,agentMessage:x.agentMessage??null,agentNativeSessionId:x.agentNativeSessionId??null,agentResumeRecovered:x.agentResumeRecovered===!0,agentRich:x.agentRich===!0,agentActivity:typeof x.agentActivity=="number"?x.agentActivity:0,agentCwd:x.agentCwd??null,reviewed:typeof x.reviewed=="boolean"?x.reviewed:null});return}if(x.type==="git-status"){t({type:"git-status",gitStatus:x.gitStatus??null});return}if(x.type==="quota-status"&&Array.isArray(x.providers)){window.dispatchEvent(new CustomEvent("termdock:quota-update",{detail:x.providers}));return}if(x.type==="focus-mode"){t({type:"focus-mode",focusTrackingRequested:x.focusTrackingRequested===!0});return}if(x.type==="resize-ack"){t({type:"resize-ack",seq:typeof x.seq=="number"?x.seq:void 0,cols:typeof x.cols=="number"?x.cols:void 0,rows:typeof x.rows=="number"?x.rows:void 0,ok:x.ok!==!1,error:typeof x.error=="string"?x.error:void 0,screenSyncPending:x.screenSyncPending===!0,screenSyncGeneration:typeof x.screenSyncGeneration=="number"?x.screenSyncGeneration:void 0});return}if(x.type==="pty-size"){t({type:"pty-size",cols:typeof x.cols=="number"?x.cols:void 0,rows:typeof x.rows=="number"?x.rows:void 0,source:typeof x.source=="string"?x.source:void 0});return}if(x.type==="shell-title"){t({type:"shell-title",title:typeof x.title=="string"?x.title:""});return}if(x.type==="prompt-state"){t({type:"prompt-state",state:x.state==="running"?"running":"idle",exitCode:typeof x.exitCode=="number"?x.exitCode:void 0});return}const T=x;if(T.type==="connected"){k.appliedSeq=void 0,u=T.streamEpoch,k.streamEpoch=u,k.outputProtocol=T.outputProtocol,typeof T.replayLastSeq=="number"&&T.replayLastSeq>=0&&(d=T.replayLastSeq,k.lastSeq=d),t(T),mm(e,nd.get(e)??!0);return}if(T.type==="exit"){y(),t(T);return}if(T.type==="data"){if(k.appliedSeq=void 0,typeof T.seq=="number"&&T.seq<=d)return;typeof T.flowSeq=="number"&&(k.flowSeq=T.flowSeq)}t(T),T.type==="data"&&typeof T.seq=="number"&&Number.isFinite(T.seq)&&T.seq>d&&(d=T.seq,k.lastSeq=d)}catch(x){n?.(x,!1)}}},C.onerror=()=>{c.isClosed||m.has(C)||h||(v(),w(k),h||(h=!0,R(new Error("WebSocket connection error"),!1)))},C.onclose=b=>{if(!(c.isClosed||m.has(C)||h)){if(b.code===xg&&b.reason===Eg){k.reconnectNow({silent:!0});return}if(v(),w(k),h=!0,b.code===4001){console.warn("[Terminal] WS 4001: Session not found on server",{code:b.code,reason:b.reason,stack:new Error().stack}),R(new Error("Session not found on server"),!0);return}if(b.code===4003||b.code===4401){try{window.dispatchEvent(new CustomEvent(Ql))}catch{}R(new Error("Authentication required"),!0);return}R(new Error("WebSocket connection closed"),!1)}},l=k,Pe.set(e,l)},R=(E,C)=>{if(!c.isClosed)if(C)n?.(E,!0),y();else{c.retryCount=Math.min(c.retryCount+1,Math.max(1,o));const k=Math.min(i*Math.pow(2,c.retryCount-1),s);if(t({type:"reconnecting",attempt:c.retryCount,maxAttempts:o}),c.isSuspended)return;c.retryTimeout=setTimeout(()=>{c.isClosed||A()},k)}};return A(),y}async function DC(e,t){const n=Pe.get(e);if(n&&(n.ws.readyState===WebSocket.OPEN||n.ws.readyState===WebSocket.CONNECTING)){const i=JSON.stringify({type:"input",data:t}),s=pm.encode(i).byteLength;if(s>bC||!CC(i))throw new Br("Terminal input exceeds the encrypted socket frame limit");const a=n.pendingInputs;if(a.bytes+s>vC)throw new Br("Terminal input queue is full; retry after the connection recovers");if(a.items.push({message:i,bytes:s}),a.bytes+=s,n.ws.readyState===WebSocket.OPEN){const c=rd(n);if(c)throw c}return}const r=await re(),o=await fetch(`/api/terminal/${e}/input`,{method:"POST",headers:{"Content-Type":"text/plain","X-XSRF-TOKEN":r},body:t});if(!o.ok){const i=await o.json().catch(()=>({error:"Failed to send input"}));throw new Se(i.error||"Failed to send terminal input",o.status,i.code)}}function _C(e,t,n={}){const r=Pe.get(e);if(!r)return!1;if(r.retryState.isSuspended=!1,r.ws.readyState!==WebSocket.OPEN)return r.reconnectNow(),!0;const o=n.visible?fm:um,i=Date.now()+o,s=r.wakeProbe,a=s?.listeners??new Set;if(t&&a.add(t),s&&s.deadline<=i)return!0;s&&clearTimeout(s.timer);const c=setTimeout(()=>{Pe.get(e)!==r||r.retryState.isClosed||(r.wakeProbe=void 0,r.reconnectNow())},o);if(r.wakeProbe={timer:c,listeners:a,deadline:i},s)return!0;try{r.ws.send(JSON.stringify({type:"ping"}))}catch{clearTimeout(c),r.wakeProbe=void 0,r.reconnectNow()}return!0}function OC(e){const t=Pe.get(e);return t?(t.reconnectNow(),!0):!1}function FC(){for(const e of Pe.values())e.suspendReconnect()}function MC(e,t,n){const r=Pe.get(e);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"focus",focused:t,reason:n}))}catch{}}function mm(e,t){nd.set(e,t);const n=Pe.get(e);!n||n.ws.readyState!==WebSocket.OPEN||n.outputProtocol!==2||n.ws.send(JSON.stringify({type:"output-subscription",active:t,since:n.lastSeq,epoch:n.streamEpoch}))}function jC(e){const t=Pe.get(e);!t||t.ws.readyState!==WebSocket.OPEN||t.outputProtocol!==2||(t.appliedSeq=t.lastSeq,!(!t.flowSeq||t.flowSeq===t.acknowledgedFlowSeq)&&(t.acknowledgedFlowSeq=t.flowSeq,t.ws.send(JSON.stringify({type:"output-ack",flowSeq:t.flowSeq,since:t.appliedSeq,epoch:t.streamEpoch}))))}function UC(e,t,n){const r=Pe.get(e);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"viewing",viewing:t,reason:n}))}catch{}}function zc(e){const t=Pe.get(e);if(!(!t||t.ws.readyState!==WebSocket.OPEN))try{t.ws.send(JSON.stringify({type:"agent-review-ack"}))}catch{}}function HC(e,t,n){const r=Pe.get(e);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"flow-control",paused:t,reason:n}))}catch{}}async function $C(e,t,n,r){Number.isFinite(t)&&Number.isFinite(n)&&t>=1&&n>=1&&(sr.delete(e),sr.set(e,{cols:Math.floor(t),rows:Math.floor(n)}),sr.size>256&&sr.delete(sr.keys().next().value));const o=Pe.get(e);if(o&&o.ws.readyState===WebSocket.OPEN)try{o.ws.send(JSON.stringify({type:"resize",cols:t,rows:n,seq:r}));return}catch{}const i=await re(),s=await fetch(`/api/terminal/${e}/resize`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":i},body:JSON.stringify({cols:t,rows:n,seq:r})});if(!s.ok){const c=await s.json().catch(()=>({error:"Failed to resize terminal"}));throw new Error(c.error||"Failed to resize terminal")}const a=await s.json().catch(()=>({success:!0}));if(a?.success===!1||a?.ok===!1)throw new Error(a?.error||"Failed to resize terminal")}async function qC(e,t){const n=Pe.get(e);if(n&&n.ws.readyState===WebSocket.OPEN)return t.action==="scroll"?(n.ws.send(JSON.stringify({type:"tmux",...t})),{success:!0}):new Promise((i,s)=>{const a=Math.random().toString(36).substring(7);Eo.set(a,{resolve:i,reject:s,connection:n.ws}),n.ws.send(JSON.stringify({type:"tmux",reqId:a,...t})),setTimeout(()=>{Eo.has(a)&&(Eo.delete(a),s(new Error("Tmux action timed out")))},3e4)});const r=await re(),o=await fetch(`/api/terminal/${e}/tmux`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(t)});if(!o.ok){const i=await o.json().catch(()=>({error:"Failed to execute tmux action"}));throw new Se(i.error||"Failed to execute tmux action",o.status,i.code)}return o.json()}async function KC(e){const t=await re(),n=await fetch(`/api/terminal/${e}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok&&n.status!==404){const o=await n.json().catch(()=>({error:"Failed to close terminal"}));throw new Error(o.error||"Failed to close terminal")}Pe.get(e)?.disconnect()}async function zC(e,t){const n=Pe.get(e);if(n){n.retryState.isClosed=!0;try{n.ws.close()}catch{}Pe.delete(e)}const r=await re(),o=await fetch(`/api/terminal/${e}/restart`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify({...t.cwd?{cwd:t.cwd}:{},cols:t.cols??80,rows:t.rows??24,mode:t.mode,tmuxSessionName:t.tmuxSessionName})});if(!o.ok){const i=await o.json().catch(()=>({error:"Failed to restart terminal"}));throw new Error(i.error||"Failed to restart terminal session")}return o.json()}async function VC(e){const t=await Te(`/api/terminal/${e}/health`,{method:"GET"},cm,"Terminal health check timed out");if(!t.ok){if(t.status===404)return{healthy:!1,sessionId:e};const n=await _r(t,Dr,"Terminal health error response timed out").catch(()=>({error:"Failed to check terminal health"}));throw new Error(n.error||"Failed to check terminal health")}return _r(t,Dr,"Terminal health response timed out")}async function WC(e){const t=await re(),n=await Te("/api/terminal/force-kill",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)},uC,"Terminal force-kill request timed out");if(!n.ok){const r=await _r(n,Dr,"Terminal force-kill error response timed out").catch(()=>({error:"Failed to force kill terminal"}));throw new Error(r.error||"Failed to force kill terminal")}}async function GC(){const e=await fetch("/api/terminal/tmux/sessions",{method:"GET"});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to list tmux sessions"}));throw new Error(n.error||"Failed to list tmux sessions")}const t=await e.json();return Array.isArray(t.sessions)?t.sessions:[]}async function XC(){const e=await fetch("/api/terminal/tmux/status",{method:"GET"});if(!e.ok){const t=await e.json().catch(()=>({error:"Failed to get tmux status"}));throw new Error(t.error||"Failed to get tmux status")}return e.json()}async function YC(e){const t=e.trim();if(!t)throw new Error("tmux session name is required");const n=await re(),r=await fetch(`/api/terminal/tmux/sessions/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":n}});if(!r.ok){const i=await r.json().catch(()=>({error:"Failed to kill tmux session"}));throw new Error(i.error||"Failed to kill tmux session")}const o=await r.json();return{cleanedSessions:Array.isArray(o.cleanedSessions)?o.cleanedSessions:[],alreadyGone:!!o.alreadyGone}}async function ZC(e){const t=await re(),n=`ui-restore:${e??"current"}:${Date.now()}:${Math.random().toString(36).slice(2)}`,r=await fetch("/api/terminal/tmux/recovery/restore-all",{method:"POST",headers:{"X-XSRF-TOKEN":t,"Content-Type":"application/json"},body:JSON.stringify({idempotencyKey:n})}),o=await r.json().catch(()=>({}));if(!r.ok)throw new Se(o.error||"Failed to restore tmux Agent sessions",r.status);return o}async function JC(e,t){const n=await re(),r=await fetch(`/api/terminal/tmux/recovery/operations/${encodeURIComponent(e)}/${t?"pause":"resume"}`,{method:"POST",headers:{"X-XSRF-TOKEN":n}});if(!r.ok)throw new Se("Failed to update recovery operation",r.status)}async function QC(){const e=await re(),t=await fetch("/api/terminal/tmux/recovery",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Se("Failed to dismiss tmux recovery",t.status)}const fi=new Map;function ek(e){return JSON.stringify({preferredFrontendSessionId:e.preferredFrontendSessionId??null,mode:e.mode??null,tmuxSessionName:e.tmuxSessionName??null,cwd:e.cwd??null,termType:e.termType??null,createIfEmpty:e.createIfEmpty===!0,requireExisting:e.requireExisting===!0})}async function wm(){const e=await fetch("/api/terminal/session-inventory",{method:"GET"});if(!e.ok){const t=await e.json().catch(()=>({error:"Failed to load session inventory"}));throw new Error(t.error||"Failed to load session inventory")}return e.json()}async function ym(e){const t=ek(e),n=fi.get(t);if(n)return n;const r=await re(),o=Te("/api/terminal/session-inventory/open",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(e)},lm,"Terminal session open request timed out").then(async i=>{if(!i.ok){const s=await _r(i,Dr,"Terminal session open error response timed out").catch(()=>({error:"Failed to open session"}));throw new Se(s.error||"Failed to open session",i.status,typeof s.code=="string"?s.code:void 0)}return _r(i,Dr,"Terminal session open response timed out")}).finally(()=>{fi.get(t)===o&&fi.delete(t)});return fi.set(t,o),o}async function Ri(e,t){const n=await re(),r=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify(t)});if(!r.ok){const o=await r.json().catch(()=>({error:"Failed to update session"}));throw new Error(o.error||"Failed to update session")}return r.json()}async function bm(e){const t=await re(),n=await fetch("/api/terminal/session-inventory/reorder",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({sessionIds:e})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to reorder sessions"}));throw new Error(r.error||"Failed to reorder sessions")}return n.json()}async function vm(e){const t=await re(),n=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to remove session"}));throw new Error(r.error||"Failed to remove session")}}async function Sm(){const e=await re(),t=await fetch("/api/terminal/session-inventory/sessions",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to clear sessions"}));throw new Error(n.error||"Failed to clear sessions")}}async function tk(){const e=await fetch("/api/terminal/toolbar-presets",{method:"GET"});if(!e.ok){const t=await e.json().catch(()=>({error:"Failed to load toolbar presets"}));throw new Error(t.error||"Failed to load toolbar presets")}return e.json()}async function nk(e){const t=await re(),n=await fetch("/api/terminal/toolbar-presets",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to save toolbar presets"})),o=new Error(r.error||"Failed to save toolbar presets");throw o.current=r.current,o.code=r.code,o}return n.json()}let Yr=null,fo=null;const xm=1500;function fn(){return fo&&Date.now()-fo.readAt<xm?Promise.resolve(fo.value):Yr||(Yr=(async()=>{const e=await fetch("/api/terminal/settings",{method:"GET"});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to load settings"}));throw new Error(n.error||"Failed to load settings")}const t=await e.json();return fo={value:t,readAt:Date.now()},t})().finally(()=>{Yr=null}),Yr)}async function at(e){const t=await re(),n=await fetch("/api/terminal/settings",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to update settings"}));throw new Error(o.error||"Failed to update settings")}const r=await n.json();return fo={value:r,readAt:Date.now()},r}async function rk(e=!1){const t=await fetch(`/api/terminal/auto-title/catalog${e?"?refresh=1":""}`);if(!t.ok)throw new Error("Failed to discover title models");const n=await t.json();return Array.isArray(n?.namers)?n.namers:[]}let Zr=null,ho=null;function ok(){return ho&&Date.now()-ho.readAt<xm?Promise.resolve(ho.value):Zr||(Zr=(async()=>{const e=await fetch("/api/terminal/context-draft",{method:"GET"});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to load context draft"}));throw new Error(n.error||"Failed to load context draft")}const t=await e.json();return ho={value:t,readAt:Date.now()},t})().finally(()=>{Zr=null}),Zr)}async function ik(e,t){const n=await re(),r=await fetch("/api/terminal/context-draft",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify({text:e,origin:t})});if(!r.ok){const i=await r.json().catch(()=>({error:"Failed to update context draft"}));throw new Error(i.error||"Failed to update context draft")}const o=await r.json();return ho={value:o,readAt:Date.now()},o}async function Em(e){let t;try{t=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:e})})}catch(r){const o=_s(r);return{ok:!1,reason:Vu(o.code),error:o.message}}if(t.ok)return td(),{ok:!0};const n=await t.json().catch(()=>null);return t.status===429?{ok:!1,reason:"rateLimited",rateLimited:!0,retryAfterMs:typeof n?.retryAfterMs=="number"?n.retryAfterMs:void 0,error:n?.error||"Too many failed attempts. Please wait and try again."}:{ok:!1,reason:Vu(n?.code)||(t.status===401?"invalidPassword":"unavailable"),error:n?.error||"Login failed"}}async function sk(){Jl(),rm();const e=await re();await fetch("/api/auth/logout",{method:"POST",headers:{"X-XSRF-TOKEN":e}}),td()}async function ak(){const e=await fetch("/api/terminal/agent-launchers");if(!e.ok)throw new Error("Failed to detect agent launchers");const t=await e.json();return Array.isArray(t?.agents)?t.agents:[]}async function ck(){const e=await fetch("/api/terminal/agent-hooks");if(!e.ok)throw new Error("Failed to get agent hooks");const t=await e.json();return Array.isArray(t?.agents)?t.agents:[]}async function lk(e){const t=await re(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(e)}/install`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to install agent hooks");return{summary:r.summary??"Installed",devMode:r.devMode===!0}}async function dk(e){const t=await re(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(e)}/uninstall`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to uninstall agent hooks");return r.summary??"Removed"}class od extends Error{constructor(t,n,r){super(t),this.code=n,this.migration=r,this.name="AgentPluginManifestError"}code;migration}async function uk(){const e=await fetch("/api/terminal/agent-plugins");if(!e.ok)throw new Error("Failed to get agent plugins");return await e.json()}async function fk(e){const t=await re(),n=await fetch("/api/terminal/agent-plugins",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)}),r=await n.json().catch(()=>({}));if(!n.ok)throw new od(r.error||"Failed to create agent plugin",r.code,r.migration);return r}async function hk(e){const t=await re(),n=await fetch("/api/terminal/agent-plugins/install",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({source:e})}),r=await n.json().catch(()=>({}));if(!n.ok)throw new od(r.error||"Failed to install agent plugin",r.code,r.migration);return r}async function pk(e){const t=await re(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}/check-update`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to check plugin updates");return r}async function gk(e){const t=await re(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}/update`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to update plugin");return r}async function mk(e){const t=await re(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}/doctor`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to diagnose plugin");return r}async function wk(e){const t=await re(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||"Failed to delete agent plugin")}}async function yk(e){const t=await re(),n=await fetch(`/api/terminal/${encodeURIComponent(e)}/agent-resume`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Se(r.error||"Failed to resume agent session",n.status,typeof r.code=="string"?r.code:void 0);return{command:r.command??""}}async function bk(){const e=await fetch("/api/terminal/agent-resume-history",{method:"GET"});if(!e.ok)throw new Error("Failed to load Agent resume history");const t=await e.json().catch(()=>({entries:[]}));return Array.isArray(t.entries)?t.entries:[]}async function vk(e){const t=await re(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(e)}/prepare`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Se(r.error||"Failed to prepare Agent session resume",n.status,typeof r.code=="string"?r.code:void 0);return r}async function Sk(e){const t=await re(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok&&n.status!==404)throw new Error("Failed to remove Agent resume history")}async function xk(e){const t=await re(),n=await fetch("/api/terminal/program-rules",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to update program rules"}));throw new Error(r.error||"Failed to update program rules")}return n.json()}async function Ek(){const e=await re(),t=await fetch("/api/terminal/program-rules",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Error("Failed to reset program rules");return t.json()}async function Ak(){const e=await fetch("/api/terminal/program-detection");if(!e.ok)throw new Error("Failed to get program detection config");return e.json()}async function Ck(e){const t=await re(),n=await fetch("/api/terminal/program-detection",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok)throw new Error("Failed to save program detection config");return n.json()}async function kk(){const e=await re(),t=await fetch("/api/terminal/program-detection",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Error("Failed to reset program detection config");return t.json()}const Ik={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".bmp":"image/bmp",".ico":"image/x-icon",".svg":"image/svg+xml",".heic":"image/heic",".heif":"image/heif"};function Ms(e){const t=e.lastIndexOf(".");return t<0?null:Ik[e.slice(t).toLowerCase()]??null}function Rk(e){return Ms(e)!==null}function Am(e){const t=Ms(e);return t==="image/heic"||t==="image/heif"}const Tk={".mp4":"video/mp4",".m4v":"video/x-m4v",".webm":"video/webm",".mov":"video/quicktime",".ogv":"video/ogg",".mpeg":"video/mpeg",".mpg":"video/mpeg"};function Cm(e){const t=e.lastIndexOf(".");return t<0?null:Tk[e.slice(t).toLowerCase()]??null}function Pk(e){return Cm(e)!==null}function Nk(e){return`/api/terminal/fs/video?path=${encodeURIComponent(e)}&action=view_file`}const km=[".stl",".glb",".gltf"];function id(e){const t=e.lastIndexOf(".");if(t<0)return null;const n=e.slice(t).toLowerCase();return km.includes(n)?n:null}function Lk(e){return id(e)!==null}function sd(e){const t=e.toLowerCase();return t.endsWith(".kicad_sch")?".kicad_sch":t.endsWith(".kicad_pcb")?".kicad_pcb":null}function Bk(e){return sd(e)!==null}function Dk(e){return sd(e)===".kicad_pcb"?"pcb-front":"schematic"}const Im=[".html",".htm"];function _k(e){const t=e.lastIndexOf(".");if(t<0)return!1;const n=e.slice(t).toLowerCase();return Im.includes(n)}function Ok(e){return`/api/terminal/fs/preview/${e.split(/[\\/]+/).filter(Boolean).map(n=>encodeURIComponent(n)).join("/")}`}const Fk={".stl":"model/stl",".glb":"model/gltf-binary",".gltf":"model/gltf+json"};async function Mk(e,t,n,r="list_directory",o,i="name",s){const a=new URLSearchParams({path:e});n&&a.set("showHidden","true"),i!=="name"&&a.set("sort",i),s&&a.set("gitIgnoreRoot",s),a.set("action",r),o&&a.set("requestSlotId",o);const c=await Te(`/api/terminal/fs/list?${a}`,{signal:t},Kn,"Directory listing took too long. The folder may be on slow storage or blocked by another process.");if(!c.ok){const l=await c.json().catch(()=>({error:"Failed to list directory"}));throw new Error(l.error||"Failed to list directory")}return c.json()}async function jk(e,t,n,r,o,i="name",s,a={}){const c=new URLSearchParams({path:e,query:t,stream:"true"});o&&c.set("showHidden","true"),i==="content"&&c.set("mode","content"),s&&c.set("requestSlotId",s);for(const g of a.excludePatterns??[])c.append("exclude",g);a.caseSensitive&&c.set("caseSensitive","true"),a.wholeWord&&c.set("wholeWord","true"),a.regex&&c.set("regex","true");const l=await fetch(`/api/terminal/fs/search?${c}`,{signal:r});if(!l.ok||!l.body){const g=await l.json().catch(()=>({error:"Failed to search files"}));throw new Error(g.error||"Failed to search files")}const d=l.body.getReader(),u=new TextDecoder;let f="";const h=g=>{if(!g.trim())return;const m=JSON.parse(g);if(m.type==="meta")n({path:m.path,query:m.query,engine:m.engine,mode:m.mode,limited:m.limited});else if(m.type==="batch")n({entries:m.entries??[]});else if(m.type==="content-batch")n({contentEntries:m.contentEntries??[]});else{if(m.type==="error")throw new Error(m.message||"Search failed");m.type==="done"&&n({total:m.total,truncated:m.truncated,limited:m.limited,engine:m.engine,mode:m.mode,done:!0})}};for(;;){const{value:g,done:m}=await d.read();if(m)break;f+=u.decode(g,{stream:!0});let v=f.indexOf(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/passwordBootstrap-DADiddYD.js","assets/react-XDCjal2T.js","assets/dnd-BCFAPC0L.js","assets/terminal-C7X98Amf.js","assets/App-DhHRFEY2.js","assets/gestureArbiter-DPFs4a-w.js","assets/gestureArbiter-C2J0D0kV.css","assets/triangle-alert-BeIpvW9N.js","assets/referenceLongPress-l-iC26Y4.js","assets/DagPlayground-CiCwopwo.js","assets/ChangeWalkthroughPanel-DG4TnQvn.js","assets/sparkles-iFcvD4yM.js","assets/DiffLab-C8ItelM8.js","assets/DiffViewer-BxcK2w41.js","assets/DiffViewer-T3uj2-aP.css","assets/DiffReviewLab-CXlrQWLJ.js","assets/DiffReview-riYMjjAA.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as pl,a as Rw,g as gh}from"./react-XDCjal2T.js";import{b as N,R as lt,r as ms}from"./dnd-BCFAPC0L.js";import{L as Tw,l as Pw}from"./terminal-C7X98Amf.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();const Nw="modulepreload",Lw=function(e){return"/"+e},Id={},wn=function(t,n,r){let o=Promise.resolve();if(n&&n.length>0){let c=function(l){return Promise.all(l.map(d=>Promise.resolve(d).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),a=s?.nonce||s?.getAttribute("nonce");o=c(n.map(l=>{if(l=Lw(l),l in Id)return;Id[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":Nw,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 i(s){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=s,window.dispatchEvent(a),!a.defaultPrevented)throw s}return o.then(s=>{for(const a of s||[])a.status==="rejected"&&i(a.reason);return t().catch(i)})};var Xs={exports:{}},Hr={};var Rd;function Bw(){if(Rd)return Hr;Rd=1;var e=pl(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function s(a,c,l){var d,u={},f=null,h=null;l!==void 0&&(f=""+l),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(h=c.ref);for(d in c)r.call(c,d)&&!i.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:t,type:a,key:f,ref:h,props:u,_owner:o.current}}return Hr.Fragment=n,Hr.jsx=s,Hr.jsxs=s,Hr}var Td;function Dw(){return Td||(Td=1,Xs.exports=Bw()),Xs.exports}var p=Dw();const Dn="termdock-secure-target-v1",gl="termdock-secure-entry-v1",_w=new Set([Dn,gl,"termdock-color-theme","termdock:locale","termdock.federation.connections.v1"]),Go=typeof Storage>"u"?void 0:Storage.prototype.getItem,Ys=typeof Storage>"u"?void 0:Storage.prototype.setItem,Pd="termdock-secure-legacy-owner",ws=typeof window<"u"&&window.parent!==window&&location.pathname==="/workspace.html";function Ow(){if(typeof window>"u")return null;try{if(ws){const t=new URLSearchParams(location.search).get("termdock-workspace"),n=JSON.parse(localStorage.getItem("termdock.federation.connections.v1")||"[]"),r=Array.isArray(n)?n.find(o=>o?.targetPeerId===t):void 0;return r&&typeof r.url=="string"&&typeof r.targetPeerId=="string"?{...r,serviceName:r.label||r.serviceName}:null}const e=JSON.parse(sessionStorage.getItem(Dn)??localStorage.getItem(Dn)??"null");return e&&typeof e.url=="string"&&typeof e.targetPeerId=="string"?e:null}catch{return null}}let Oo=Ow();const ic=new Set,dr=Oo?.targetPeerId??"unpaired";function Qe(){return Oo}function $P(e){return ic.add(e),()=>ic.delete(e)}function mh(){for(const e of ic)e(Oo)}function wh(e){if(Oo=e,mh(),ws)return;const t=JSON.stringify(e);sessionStorage.setItem(Dn,t),localStorage.setItem(Dn,t)}function Fw(){Oo=null,mh(),!ws&&(localStorage.removeItem(Dn),sessionStorage.removeItem(Dn),localStorage.removeItem(gl))}function wo(e,t=dr){return _w.has(e)||e.startsWith("termdock-secure-")?e:`termdock-service:${t}:${e}`}function Mw(e){if(!(!Go||!Ys))try{if(Go.call(localStorage,Pd))return;Ys.call(localStorage,Pd,e);for(const n of[localStorage,sessionStorage]){const r=Array.from({length:n.length},(o,i)=>n.key(i)).filter(o=>!!o);for(const o of r){if(o.startsWith("termdock-service:")||wo(o,e)===o)continue;const i=wo(o,e),s=Go.call(n,o);s!==null&&Go.call(n,i)===null&&Ys.call(n,i,s)}}}catch{}}let Nd=!1;function jw(){if(Nd||typeof Storage>"u")return;Nd=!0;const e=Storage.prototype.getItem,t=Storage.prototype.setItem,n=Storage.prototype.removeItem;Storage.prototype.getItem=function(r){return e.call(this,wo(String(r)))},Storage.prototype.setItem=function(r,o){t.call(this,wo(String(r)),o)},Storage.prototype.removeItem=function(r){n.call(this,wo(String(r)))}}jw();const yh=8,bh=128,ml=2e4,ys="termdock.federation.connections.v1",sc="termdock:services-changed",wl="termdock-secure-removed-services",_i=e=>[e.id,e.targetPeerId,e.serviceOrigin||e.url].filter(t=>!!t);function yl(){try{const e=JSON.parse(localStorage.getItem(wl)||"[]");return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}catch{return[]}}function Re(e){const t=e.trim();if(!t)throw new Error("请输入服务地址。");const n=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(t)?t:`https://${t}`);n.protocol==="wss:"&&(n.protocol="https:"),n.protocol==="ws:"&&(n.protocol="http:");const r=["localhost","127.0.0.1","[::1]"].includes(n.hostname);if(!["https:","http:"].includes(n.protocol)||n.protocol==="http:"&&!r)throw new Error("请使用 HTTPS 服务地址。");if(n.username||n.password||n.search||n.hash||!["/","/api/federation/secure"].includes(n.pathname))throw new Error("请输入服务首页地址,不要包含账号或额外参数。");return n.origin}function bs(e){if(!e||typeof e!="object")return;const t=e;if(typeof t.url=="string")try{const n=Re(t.url),r=typeof t.targetPeerId=="string"&&t.targetPeerId?t.targetPeerId:void 0,o=(typeof t.label=="string"?t.label:typeof t.serviceName=="string"?t.serviceName:"").trim().slice(0,120)||new URL(n).host;return{id:typeof t.id=="string"&&t.id?t.id:r||n,url:n,label:o,...r?{targetPeerId:r}:{},...typeof t.serviceOrigin=="string"?{serviceOrigin:Re(t.serviceOrigin)}:{},...typeof t.entryServiceId=="string"&&t.entryServiceId?{entryServiceId:t.entryServiceId}:{},...Array.isArray(t.routes)?{routes:t.routes.slice(0,4).flatMap(i=>{try{return i&&typeof i.targetPeerId=="string"&&i.targetPeerId?[{url:Re(i.url),targetPeerId:i.targetPeerId}]:[]}catch{return[]}})}:{}}}catch{return}}function Kt(e,t){return e.targetPeerId&&t.targetPeerId?e.targetPeerId===t.targetPeerId:(e.serviceOrigin||e.url)===(t.serviceOrigin||t.url)}function vh(e){const t=[];for(const n of e){const r=t.findIndex(o=>Kt(o,n));r<0?t.push(n):t[r]={...t[r],...n,id:t[r].id}}return t}function Fo(){return typeof window>"u"?void 0:window.termdockDesktop}function _n(){try{const e=JSON.parse(localStorage.getItem(ys)||"[]");return Array.isArray(e)?vh(e.map(bs).filter(t=>!!t)):[]}catch{return[]}}function Sh(e){localStorage.setItem(ys,JSON.stringify(e.map(t=>({...t,serviceName:t.label})))),window.dispatchEvent(new Event(sc))}let $r;async function Ye(){const e=Fo();if(!e?.serviceConnections||!e.saveServiceConnection)return _n();if($r)return $r;$r=(async()=>{let t=await e.serviceConnections();const n=_n();for(const r of n)t.some(o=>Kt(o,r))||(t=await(e.importServiceConnection||e.saveServiceConnection)(r));return n.length&&localStorage.removeItem(ys),t})();try{return await $r}finally{$r=void 0}}async function Yt(e){const t=bs(e);if(!t)throw new Error("服务地址无效。");const n=Fo();if(n?.saveServiceConnection)return n.saveServiceConnection(t);const r=_n(),o=r.find(a=>a.id===t.id||Kt(a,t)),i=new Set([..._i(t),...o?_i(o):[]]);localStorage.setItem(wl,JSON.stringify(yl().filter(a=>!i.has(a))));const s=vh([...r.filter(a=>a!==o),{...o,...t,id:o?.id||t.id}]);return Sh(s),s}async function Uw(e){const t=bs(e);if(!t)throw new Error("服务地址无效。");const n=Fo();if(n?.importServiceConnection)return n.importServiceConnection(t);if(n?.serviceConnections){const r=await n.serviceConnections();return r.some(o=>Kt(o,t))?Yt(t):r}return _i(t).some(r=>yl().includes(r))?_n():Yt(t)}async function Hw(e){const t=Fo();if(t?.removeServiceConnection)return t.removeServiceConnection(e);const n=_n(),r=n.find(i=>i.id===e);r&&localStorage.setItem(wl,JSON.stringify([...new Set([...yl(),..._i(r)])].slice(-768)));const o=n.filter(i=>i.id!==e);return Sh(o),o}function vs(e){const t=r=>{(r.key===ys||r.key===null)&&e()};window.addEventListener(sc,e),window.addEventListener("storage",t);const n=Fo()?.onServiceConnections?.(e);return()=>{window.removeEventListener(sc,e),window.removeEventListener("storage",t),n?.()}}class $w extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}}let qw=class extends Error{static name="InvalidCryptoExchangeError";constructor(t="Invalid crypto exchange"){super(t),this.name="InvalidCryptoExchangeError"}},xt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};class xh extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}}class Eh extends Error{static name="InvalidPrivateKeyError";constructor(t="Invalid private key"){super(t),this.name="InvalidPrivateKeyError"}}class Kw extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}}class zw extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}}class Ss extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}}const Ah=Symbol.for("@libp2p/peer-id");function Vw(e){return typeof e?.handleEvent=="function"}function Ww(e){return e===!0||e===!1}function Gw(e){return Ww(e)?e:e?.capture??!1}function ac(e){const t={capture:Gw(e),once:!!e?.once};return e?.passive!=null&&(t.passive=e?.passive),e?.signal!=null&&(t.signal=e?.signal),t}function Ld(e,t){return ac(e).capture===ac(t).capture}class Xw extends EventTarget{#e=new Map;constructor(){super()}listenerCount(t){const n=this.#e.get(t);return n==null?0:n.length}addEventListener(t,n,r){const o=ac(r);if(o?.signal?.aborted===!0)return;const i=l=>{o.once&&this.removeEventListener(t,n,o),Vw(n)?n.handleEvent(l):n(l)};let s=this.#e.get(t);if(s==null&&(s=[],this.#e.set(t,s)),s.some(l=>l.callback!==n?!1:Ld(l.options,o)))return;super.addEventListener(t,i,o);const c=()=>{this.removeEventListener(t,n,o)};o.signal?.addEventListener("abort",c),s.push({callback:n,wrapper:i,options:o,onAbort:c})}removeEventListener(t,n,r){const o=this.#e.get(t);if(o==null){super.removeEventListener(t,n??null,r);return}this.#e.set(t,o.filter(i=>i.callback===n&&Ld(i.options,r)?(super.removeEventListener(t,i.wrapper,r),i.options?.signal?.removeEventListener("abort",i.onAbort),!1):!0))}safeDispatchEvent(t,n={}){return this.dispatchEvent(new CustomEvent(t,n))}}const Yw=Symbol.for("@libp2p/service-capabilities");function Zw(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0}function xs(e){if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}function Jw(e){return new TextEncoder().encode(e)}function Qw(e){return new TextDecoder().decode(e)}function ey(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var o=0;o<e.length;o++){var i=e.charAt(o),s=i.charCodeAt(0);if(n[s]!==255)throw new TypeError(i+" is ambiguous");n[s]=o}var a=e.length,c=e.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,v=0,w=0,S=g.length;w!==S&&g[w]===0;)w++,m++;for(var y=(S-w)*d+1>>>0,A=new Uint8Array(y);w!==S;){for(var R=g[w],E=0,C=y-1;(R!==0||E<v)&&C!==-1;C--,E++)R+=256*A[C]>>>0,A[C]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");v=E,w++}for(var k=y-v;k!==y&&A[k]===0;)k++;for(var b=c.repeat(m);k<y;++k)b+=e.charAt(A[k]);return b}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 v=0,w=0;g[m]===c;)v++,m++;for(var S=(g.length-m)*l+1>>>0,y=new Uint8Array(S);g[m];){var A=n[g.charCodeAt(m)];if(A===255)return;for(var R=0,E=S-1;(A!==0||R<w)&&E!==-1;E--,R++)A+=a*y[E]>>>0,y[E]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");w=R,m++}if(g[m]!==" "){for(var C=S-w;C!==S&&y[C]===0;)C++;for(var k=new Uint8Array(v+(S-C)),b=v;C!==S;)k[b++]=y[C++];return k}}}function h(g){var m=f(g);if(m)return m;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:f,decode:h}}var ty=ey,ny=ty;class ry{name;prefix;baseEncode;constructor(t,n,r){this.name=t,this.prefix=n,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}}class oy{name;prefix;baseDecode;prefixCodePoint;constructor(t,n,r){this.name=t,this.prefix=n;const o=n.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Ch(this,t)}}class iy{decoders;constructor(t){this.decoders=t}or(t){return Ch(this,t)}decode(t){const n=t[0],r=this.decoders[n];if(r!=null)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function Ch(e,t){return new iy({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}class sy{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,n,r,o){this.name=t,this.prefix=n,this.baseEncode=r,this.baseDecode=o,this.encoder=new ry(t,n,r),this.decoder=new oy(t,n,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}}function Es({name:e,prefix:t,encode:n,decode:r}){return new sy(e,t,n,r)}function Mo({name:e,prefix:t,alphabet:n}){const{encode:r,decode:o}=ny(n,e);return Es({prefix:t,name:e,encode:r,decode:i=>xs(o(i))})}function ay(e,t,n,r){let o=e.length;for(;e[o-1]==="=";)--o;const i=new Uint8Array(o*n/8|0);let s=0,a=0,c=0;for(let l=0;l<o;++l){const d=t[e[l]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<n|d,s+=n,s>=8&&(s-=8,i[c++]=255&a>>s)}if(s>=n||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function cy(e,t,n){const r=t[t.length-1]==="=",o=(1<<n)-1;let i="",s=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],s+=8;s>n;)s-=n,i+=t[o&a>>s];if(s!==0&&(i+=t[o&a<<n-s]),r)for(;(i.length*n&7)!==0;)i+="=";return i}function ly(e){const t={};for(let n=0;n<e.length;++n)t[e[n]]=n;return t}function $e({name:e,prefix:t,bitsPerChar:n,alphabet:r}){const o=ly(r);return Es({prefix:t,name:e,encode(i){return cy(i,r,n)},decode(i){return ay(i,o,n,e)}})}const Ze=Mo({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),dy=Mo({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),uy=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Ze,base58flickr:dy},Symbol.toStringTag,{value:"Module"})),yo=$e({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),fy=$e({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hy=$e({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),py=$e({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),gy=$e({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),my=$e({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),wy=$e({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),yy=$e({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),by=$e({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),vy=Object.freeze(Object.defineProperty({__proto__:null,base32:yo,base32hex:gy,base32hexpad:wy,base32hexpadupper:yy,base32hexupper:my,base32pad:hy,base32padupper:py,base32upper:fy,base32z:by},Symbol.toStringTag,{value:"Module"})),bi=Mo({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Sy=Mo({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),xy=Object.freeze(Object.defineProperty({__proto__:null,base36:bi,base36upper:Sy},Symbol.toStringTag,{value:"Module"}));var Ey=kh,Bd=128,Ay=-128,Cy=Math.pow(2,31);function kh(e,t,n){t=t||[],n=n||0;for(var r=n;e>=Cy;)t[n++]=e&255|Bd,e/=128;for(;e&Ay;)t[n++]=e&255|Bd,e>>>=7;return t[n]=e|0,kh.bytes=n-r+1,t}var ky=cc,Iy=128,Dd=127;function cc(e,r){var n=0,r=r||0,o=0,i=r,s,a=e.length;do{if(i>=a)throw cc.bytes=0,new RangeError("Could not decode varint");s=e[i++],n+=o<28?(s&Dd)<<o:(s&Dd)*Math.pow(2,o),o+=7}while(s>=Iy);return cc.bytes=i-r,n}var Ry=Math.pow(2,7),Ty=Math.pow(2,14),Py=Math.pow(2,21),Ny=Math.pow(2,28),Ly=Math.pow(2,35),By=Math.pow(2,42),Dy=Math.pow(2,49),_y=Math.pow(2,56),Oy=Math.pow(2,63),Fy=function(e){return e<Ry?1:e<Ty?2:e<Py?3:e<Ny?4:e<Ly?5:e<By?6:e<Dy?7:e<_y?8:e<Oy?9:10},My={encode:Ey,decode:ky,encodingLength:Fy},Oi=My;function lc(e,t=0){return[Oi.decode(e,t),Oi.decode.bytes]}function Fi(e,t,n=0){return Oi.encode(e,t,n),t}function Mi(e){return Oi.encodingLength(e)}function jo(e,t){const n=t.byteLength,r=Mi(e),o=r+Mi(n),i=new Uint8Array(o+n);return Fi(e,i,0),Fi(n,i,r),i.set(t,o),new bl(e,n,t,i)}function Ih(e){const t=xs(e),[n,r]=lc(t),[o,i]=lc(t.subarray(r)),s=t.subarray(r+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new bl(n,o,s,t)}function jy(e,t){if(e===t)return!0;{const n=t;return e.code===n.code&&e.size===n.size&&n.bytes instanceof Uint8Array&&Zw(e.bytes,n.bytes)}}class bl{code;size;digest;bytes;constructor(t,n,r,o){this.code=t,this.size=n,this.digest=r,this.bytes=o}}function _d(e,t){const{bytes:n,version:r}=e;return r===0?Hy(n,dc(e),t??Ze.encoder):$y(n,dc(e),t??yo.encoder)}const Od=new WeakMap;function dc(e){const t=Od.get(e);if(t==null){const n=new Map;return Od.set(e,n),n}return t}class Ae{code;version;multihash;bytes;"/";constructor(t,n,r,o){this.code=n,this.version=t,this.multihash=r,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:t,multihash:n}=this;if(t!==qr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==qy)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Ae.createV0(n)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:t,digest:n}=this.multihash,r=jo(t,n);return Ae.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return Ae.equals(this,t)}static equals(t,n){const r=n;return r!=null&&t.code===r.code&&t.version===r.version&&jy(t.multihash,r.multihash)}toString(t){return _d(this,t)}toJSON(){return{"/":_d(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;const n=t;if(n instanceof Ae)return n;if(n["/"]!=null&&n["/"]===n.bytes||n.asCID===n){const{version:r,code:o,multihash:i,bytes:s}=n;return new Ae(r,o,i,s??Fd(r,o,i.bytes))}else if(n[Ky]===!0){const{version:r,multihash:o,code:i}=n,s=Ih(o);return Ae.create(r,i,s)}else return null}static create(t,n,r){if(typeof n!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(n!==qr)throw new Error(`Version 0 CID must use dag-pb (code: ${qr}) block encoding`);return new Ae(t,n,r,r.bytes)}case 1:{const o=Fd(t,n,r.bytes);return new Ae(t,n,r,o)}default:throw new Error("Invalid version")}}static createV0(t){return Ae.create(0,qr,t)}static createV1(t,n){return Ae.create(1,t,n)}static decode(t){const[n,r]=Ae.decodeFirst(t);if(r.length!==0)throw new Error("Incorrect length");return n}static decodeFirst(t){const n=Ae.inspectBytes(t),r=n.size-n.multihashSize,o=xs(t.subarray(r,r+n.multihashSize));if(o.byteLength!==n.multihashSize)throw new Error("Incorrect length");const i=o.subarray(n.multihashSize-n.digestSize),s=new bl(n.multihashCode,n.digestSize,i,o);return[n.version===0?Ae.createV0(s):Ae.createV1(n.codec,s),t.subarray(n.size)]}static inspectBytes(t){let n=0;const r=()=>{const[u,f]=lc(t.subarray(n));return n+=f,u};let o=r(),i=qr;if(o===18?(o=0,n=0):i=r(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);const s=n,a=r(),c=r(),l=n+c,d=l-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:d,size:l}}static parse(t,n){const[r,o]=Uy(t,n),i=Ae.decode(o);if(i.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return dc(i).set(r,t),i}}function Uy(e,t){switch(e[0]){case"Q":{const n=t??Ze;return[Ze.prefix,n.decode(`${Ze.prefix}${e}`)]}case Ze.prefix:{const n=t??Ze;return[Ze.prefix,n.decode(e)]}case yo.prefix:{const n=t??yo;return[yo.prefix,n.decode(e)]}case bi.prefix:{const n=t??bi;return[bi.prefix,n.decode(e)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function Hy(e,t,n){const{prefix:r}=n;if(r!==Ze.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);const o=t.get(r);if(o==null){const i=n.encode(e).slice(1);return t.set(r,i),i}else return o}function $y(e,t,n){const{prefix:r}=n,o=t.get(r);if(o==null){const i=n.encode(e);return t.set(r,i),i}else return o}const qr=112,qy=18;function Fd(e,t,n){const r=Mi(e),o=r+Mi(t),i=new Uint8Array(o+n.byteLength);return Fi(e,i,0),Fi(t,i,r),i.set(n,o),i}const Ky=Symbol.for("@ipld/js-cid/CID"),Rh=0,zy="identity",Th=xs;function Vy(e,t){if(t?.truncate!=null&&t.truncate!==e.byteLength){if(t.truncate<0||t.truncate>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,t.truncate)}return jo(Rh,Th(e))}const Uo={code:Rh,name:zy,encode:Th,digest:Vy};function Et(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0}function nt(e=0){return new Uint8Array(e)}function Zt(e=0){return new Uint8Array(e)}function uc(e,t){t==null&&(t=e.reduce((o,i)=>o+i.length,0));const n=Zt(t);let r=0;for(const o of e)n.set(o,r),r+=o.length;return n}const Ph=Symbol.for("@achingbrain/uint8arraylist");function Md(e,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let n=0;for(const r of e){const o=n+r.byteLength;if(t<o)return{buf:r,index:t-n};n=o}throw new RangeError("index is out of bounds")}function Xo(e){return!!e?.[Ph]}class ye{bufs;length;[Ph]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let n=0;for(const r of t)if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.push(r);else if(Xo(r)){n+=r.byteLength;for(const o of r.bufs)this.bufs.push(o)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=n}prepend(...t){this.prependAll(t)}prependAll(t){let n=0;for(const r of t.reverse())if(r instanceof Uint8Array)n+=r.byteLength,this.bufs.unshift(r);else if(Xo(r))n+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=n}get(t){const n=Md(this.bufs,t);return n.buf[n.index]}set(t,n){const r=Md(this.bufs,t);r.buf[r.index]=n}write(t,n=0){if(t instanceof Uint8Array)for(let r=0;r<t.length;r++)this.set(n+r,t[r]);else if(Xo(t))for(let r=0;r<t.length;r++)this.set(n+r,t.get(r));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,n){const{bufs:r,length:o}=this._subList(t,n);return uc(r,o)}subarray(t,n){const{bufs:r,length:o}=this._subList(t,n);return r.length===1?r[0]:uc(r,o)}sublist(t,n){const{bufs:r,length:o}=this._subList(t,n),i=new ye;return i.length=o,i.bufs=r,i}_subList(t,n){if(t=t??0,n=n??this.length,t<0&&(t=this.length+t),n<0&&(n=this.length+n),t<0||n>this.length)throw new RangeError("index is out of bounds");if(t===n)return{bufs:[],length:0};if(t===0&&n===this.length)return{bufs:[...this.bufs],length:this.length};const r=[];let o=0;for(let i=0;i<this.bufs.length;i++){const s=this.bufs[i],a=o,c=a+s.byteLength;if(o=c,t>=c)continue;const l=t>=a&&t<c,d=n>a&&n<=c;if(l&&d){if(t===a&&n===c){r.push(s);break}const u=t-a;r.push(s.subarray(u,u+(n-t)));break}if(l){if(t===0){r.push(s);continue}r.push(s.subarray(t-a));continue}if(d){if(n===c){r.push(s);break}r.push(s.subarray(0,n-a));break}r.push(s)}return{bufs:r,length:n-t}}indexOf(t,n=0){if(!Xo(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=t instanceof Uint8Array?t:t.subarray();if(n=Number(n??0),isNaN(n)&&(n=0),n<0&&(n=this.length+n),n<0&&(n=0),t.length===0)return n>this.length?this.length:n;const o=r.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");const i=256,s=new Int32Array(i);for(let u=0;u<i;u++)s[u]=-1;for(let u=0;u<o;u++)s[r[u]]=u;const a=s,c=this.byteLength-r.byteLength,l=r.byteLength-1;let d;for(let u=n;u<=c;u+=d){d=0;for(let f=l;f>=0;f--){const h=this.get(u+f);if(r[f]!==h){d=Math.max(1,f-a[h]);break}}if(d===0)return u}return-1}getInt8(t){const n=this.subarray(t,t+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt8(0)}setInt8(t,n){const r=Zt(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,n),this.write(r,t)}getInt16(t,n){const r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,n)}setInt16(t,n,r){const o=nt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,n,r),this.write(o,t)}getInt32(t,n){const r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,n)}setInt32(t,n,r){const o=nt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,n,r),this.write(o,t)}getBigInt64(t,n){const r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,n)}setBigInt64(t,n,r){const o=nt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,n,r),this.write(o,t)}getUint8(t){const n=this.subarray(t,t+1);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint8(0)}setUint8(t,n){const r=Zt(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,n),this.write(r,t)}getUint16(t,n){const r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,n)}setUint16(t,n,r){const o=nt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,n,r),this.write(o,t)}getUint32(t,n){const r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,n)}setUint32(t,n,r){const o=nt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,n,r),this.write(o,t)}getBigUint64(t,n){const r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,n)}setBigUint64(t,n,r){const o=nt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,n,r),this.write(o,t)}getFloat32(t,n){const r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,n)}setFloat32(t,n,r){const o=nt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,n,r),this.write(o,t)}getFloat64(t,n){const r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,n)}setFloat64(t,n,r){const o=nt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,n,r),this.write(o,t)}equals(t){if(t==null||!(t instanceof ye)||t.bufs.length!==this.bufs.length)return!1;for(let n=0;n<this.bufs.length;n++)if(!Et(this.bufs[n],t.bufs[n]))return!1;return!0}static fromUint8Arrays(t,n){const r=new ye;return r.bufs=t,n==null&&(n=t.reduce((o,i)=>o+i.byteLength,0)),r.length=n,r}}const Wy=Mo({prefix:"9",name:"base10",alphabet:"0123456789"}),Gy=Object.freeze(Object.defineProperty({__proto__:null,base10:Wy},Symbol.toStringTag,{value:"Module"})),Xy=$e({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Yy=$e({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Zy=Object.freeze(Object.defineProperty({__proto__:null,base16:Xy,base16upper:Yy},Symbol.toStringTag,{value:"Module"})),Jy=$e({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Qy=Object.freeze(Object.defineProperty({__proto__:null,base2:Jy},Symbol.toStringTag,{value:"Module"})),Nh=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),eb=Nh.reduce((e,t,n)=>(e[n]=t,e),[]),tb=Nh.reduce((e,t,n)=>{const r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);return e[r]=n,e},[]);function nb(e){return e.reduce((t,n)=>(t+=eb[n],t),"")}function rb(e){const t=[];for(const n of e){const r=n.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${n}`);const o=tb[r];if(o==null)throw new Error(`Non-base256emoji character: ${n}`);t.push(o)}return new Uint8Array(t)}const ob=Es({prefix:"🚀",name:"base256emoji",encode:nb,decode:rb}),ib=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:ob},Symbol.toStringTag,{value:"Module"})),sb=$e({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ab=$e({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cb=$e({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),lb=$e({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),db=Object.freeze(Object.defineProperty({__proto__:null,base64:sb,base64pad:ab,base64url:cb,base64urlpad:lb},Symbol.toStringTag,{value:"Module"})),ub=$e({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),fb=Object.freeze(Object.defineProperty({__proto__:null,base8:ub},Symbol.toStringTag,{value:"Module"})),hb=Es({prefix:"\0",name:"identity",encode:e=>Qw(e),decode:e=>Jw(e)}),pb=Object.freeze(Object.defineProperty({__proto__:null,identity:hb},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const gb=20;function mb({name:e,code:t,encode:n,minDigestLength:r,maxDigestLength:o}){return new wb(e,t,n,r,o)}class wb{name;code;encode;minDigestLength;maxDigestLength;constructor(t,n,r,o,i){this.name=t,this.code=n,this.encode=r,this.minDigestLength=o??gb,this.maxDigestLength=i}digest(t,n){if(n?.truncate!=null){if(n.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&n.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){const r=this.encode(t);return r instanceof Uint8Array?jd(r,this.code,n?.truncate):r.then(o=>jd(o,this.code,n?.truncate))}else throw Error("Unknown type, must be binary type")}}function jd(e,t,n){if(n!=null&&n!==e.byteLength){if(n>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,n)}return jo(t,e)}function yb(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}const vl=mb({name:"sha2-256",code:18,encode:yb("SHA-256")}),Ud={...pb,...Qy,...fb,...Gy,...Zy,...vy,...xy,...uy,...db,...ib};function Lh(e,t,n,r){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:n},decoder:{decode:r}}}const Hd=Lh("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),Zs=Lh("ascii","a",e=>{let t="a";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t},e=>{e=e.substring(1);const t=Zt(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}),Bh={utf8:Hd,"utf-8":Hd,hex:Ud.base16,latin1:Zs,ascii:Zs,binary:Zs,...Ud};function Le(e,t="utf8"){const n=Bh[t];if(n==null)throw new Error(`Unsupported encoding "${t}"`);return n.decoder.decode(`${n.prefix}${e}`)}function ue(e,t="utf8"){const n=Bh[t];if(n==null)throw new Error(`Unsupported encoding "${t}"`);return n.encoder.encode(e).substring(1)}const bb=parseInt("11111",2),fc=parseInt("10000000",2),vb=parseInt("01111111",2),$d={0:Kr,1:Kr,2:Sb,3:Ab,4:Cb,5:Eb,6:xb,16:Kr,22:Kr,48:Kr};function Or(e,t={offset:0}){const n=e[t.offset]&bb;if(t.offset++,$d[n]!=null)return $d[n](e,t);throw new Error("No decoder for tag "+n)}function Ho(e,t){let n=0;if((e[t.offset]&fc)===fc){const r=e[t.offset]&vb;let o="0x";t.offset++;for(let i=0;i<r;i++,t.offset++)o+=e[t.offset].toString(16).padStart(2,"0");n=parseInt(o,16)}else n=e[t.offset],t.offset++;return n}function Kr(e,t){Ho(e,t);const n=[];for(;!(t.offset>=e.byteLength);){const r=Or(e,t);if(r===null)break;n.push(r)}return n}function Sb(e,t){const n=Ho(e,t),r=t.offset,o=t.offset+n,i=[];for(let s=r;s<o;s++)s===r&&e[s]===0||i.push(e[s]);return t.offset+=n,Uint8Array.from(i)}function xb(e,t){const n=Ho(e,t),r=t.offset+n,o=e[t.offset];t.offset++;let i=0,s=0;o<40?(i=0,s=o):o<80?(i=1,s=o-40):(i=2,s=o-80);let a=`${i}.${s}`,c=[];for(;t.offset<r;){const l=e[t.offset];if(t.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 Eb(e,t){return t.offset++,null}function Ab(e,t){const n=Ho(e,t),r=e[t.offset];t.offset++;const o=e.subarray(t.offset,t.offset+n-1);if(t.offset+=n,r!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Cb(e,t){const n=Ho(e,t),r=e.subarray(t.offset,t.offset+n);return t.offset+=n,r}function kb(e){let t=e.toString(16);t.length%2===1&&(t="0"+t);const n=new ye;for(let r=0;r<t.length;r+=2)n.append(Uint8Array.from([parseInt(`${t[r]}${t[r+1]}`,16)]));return n}function As(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);const t=kb(e.byteLength);return new ye(Uint8Array.from([t.byteLength|fc]),t)}function ct(e){const t=new ye,n=128;return(e.subarray()[0]&n)===n&&t.append(Uint8Array.from([0])),t.append(e),new ye(Uint8Array.from([2]),As(t),t)}function Sl(e){const t=Uint8Array.from([0]),n=new ye(t,e);return new ye(Uint8Array.from([3]),As(n),n)}function Ib(e){return new ye(Uint8Array.from([4]),As(e),e)}function Gt(e,t=48){const n=new ye;for(const r of e)n.append(r);return new ye(Uint8Array.from([t]),As(n),n)}async function Rb(e,t,n){const r=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["sign"]);n?.signal?.throwIfAborted();const o=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,t.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Tb(e,t,n,r){const o=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();const i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,n.subarray());return r?.signal?.throwIfAborted(),i}const Pb=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Nb=Uint8Array.from([6,5,43,129,4,0,34]),Lb=Uint8Array.from([6,5,43,129,4,0,35]),Dh={ext:!0,kty:"EC",crv:"P-256"},_h={ext:!0,kty:"EC",crv:"P-384"},Oh={ext:!0,kty:"EC",crv:"P-521"},ur=32,fr=48,hr=66;function Bb(e){const t=Or(e);return Db(t)}function Db(e){const t=e[1],n=ue(t,"base64url"),r=e[2][1][0],o=1;let i,s;if(t.byteLength===ur)return i=ue(r.subarray(o,o+ur),"base64url"),s=ue(r.subarray(o+ur),"base64url"),new Js({...Dh,key_ops:["sign"],d:n,x:i,y:s});if(t.byteLength===fr)return i=ue(r.subarray(o,o+fr),"base64url"),s=ue(r.subarray(o+fr),"base64url"),new Js({..._h,key_ops:["sign"],d:n,x:i,y:s});if(t.byteLength===hr)return i=ue(r.subarray(o,o+hr),"base64url"),s=ue(r.subarray(o+hr),"base64url"),new Js({...Oh,key_ops:["sign"],d:n,x:i,y:s});throw new xt(`Private key length was wrong length, got ${t.byteLength}, expected 32, 48 or 66`)}function Fh(e){const t=Or(e);return _b(t)}function _b(e){const t=e[1][1][0],n=1;let r,o;if(t.byteLength===ur*2+1)return r=ue(t.subarray(n,n+ur),"base64url"),o=ue(t.subarray(n+ur),"base64url"),new vi({...Dh,key_ops:["verify"],x:r,y:o});if(t.byteLength===fr*2+1)return r=ue(t.subarray(n,n+fr),"base64url"),o=ue(t.subarray(n+fr),"base64url"),new vi({..._h,key_ops:["verify"],x:r,y:o});if(t.byteLength===hr*2+1)return r=ue(t.subarray(n,n+hr),"base64url"),o=ue(t.subarray(n+hr),"base64url"),new vi({...Oh,key_ops:["verify"],x:r,y:o});throw new xt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Ob(e){return Gt([ct(Uint8Array.from([1])),Ib(Le(e.d??"","base64url")),Gt([Mh(e.crv)],160),Gt([Sl(new ye(Uint8Array.from([4]),Le(e.x??"","base64url"),Le(e.y??"","base64url")))],161)]).subarray()}function Fb(e){return Gt([ct(Uint8Array.from([1])),Gt([Mh(e.crv)],160),Gt([Sl(new ye(Uint8Array.from([4]),Le(e.x??"","base64url"),Le(e.y??"","base64url")))],161)]).subarray()}function Mh(e){if(e==="P-256")return Pb;if(e==="P-384")return Nb;if(e==="P-521")return Lb;throw new xt(`Invalid curve ${e}`)}class vi{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Fb(this.jwk)),this._raw}toMultihash(){return Uo.digest(Ps(this))}toCID(){return Ae.createV1(114,this.toMultihash())}toString(){return Ze.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}async verify(t,n,r){return Tb(this.jwk,n,t,r)}}class Js{type="ECDSA";jwk;publicKey;_raw;constructor(t){this.jwk=t,this.publicKey=new vi({crv:t.crv,ext:t.ext,key_ops:["verify"],kty:"EC",x:t.x,y:t.y})}get raw(){return this._raw==null&&(this._raw=Ob(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}async sign(t,n){return Rb(this.jwk,t,n)}}const Yn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function $o(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function hc(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Hn(e,...t){if(!$o(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function jh(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");hc(e.outputLen),hc(e.blockLen)}function ji(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Mb(e,t){Hn(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function kr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Qs(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Rt(e,t){return e<<32-t|e>>>t}const Uh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",jb=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Tn(e){if(Hn(e),Uh)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=jb[e[n]];return t}const Ft={_0:48,_9:57,A:65,F:70,a:97,f:102};function qd(e){if(e>=Ft._0&&e<=Ft._9)return e-Ft._0;if(e>=Ft.A&&e<=Ft.F)return e-(Ft.A-10);if(e>=Ft.a&&e<=Ft.f)return e-(Ft.a-10)}function Ui(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(Uh)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){const s=qd(e.charCodeAt(i)),a=qd(e.charCodeAt(i+1));if(s===void 0||a===void 0){const c=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a}return r}function Ub(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function xl(e){return typeof e=="string"&&(e=Ub(e)),Hn(e),e}function Lt(...e){let t=0;for(let r=0;r<e.length;r++){const o=e[r];Hn(o),t+=o.length}const n=new Uint8Array(t);for(let r=0,o=0;r<e.length;r++){const i=e[r];n.set(i,o),o+=i.length}return n}class Hh{}function $h(e){const t=r=>e().update(xl(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function El(e=32){if(Yn&&typeof Yn.getRandomValues=="function")return Yn.getRandomValues(new Uint8Array(e));if(Yn&&typeof Yn.randomBytes=="function")return Uint8Array.from(Yn.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Hb(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const o=BigInt(32),i=BigInt(4294967295),s=Number(n>>o&i),a=Number(n&i),c=r?4:0,l=r?0:4;e.setUint32(t+c,s,r),e.setUint32(t+l,a,r)}function $b(e,t,n){return e&t^~e&n}function qb(e,t,n){return e&t^e&n^t&n}let qh=class extends Hh{constructor(t,n,r,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Qs(this.buffer)}update(t){ji(this),t=xl(t),Hn(t);const{view:n,buffer:r,blockLen:o}=this,i=t.length;for(let s=0;s<i;){const a=Math.min(o-this.pos,i-s);if(a===o){const c=Qs(t);for(;o<=i-s;s+=o)this.process(c,s);continue}r.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){ji(this),Mb(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:o,isLE:i}=this;let{pos:s}=this;n[s++]=128,kr(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let u=s;u<o;u++)n[u]=0;Hb(r,o-8,BigInt(this.length*8),i),this.process(r,0);const a=Qs(t),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],i)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=o,t.pos=a,o%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}};const tn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ve=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Yo=BigInt(2**32-1),Kd=BigInt(32);function Kb(e,t=!1){return t?{h:Number(e&Yo),l:Number(e>>Kd&Yo)}:{h:Number(e>>Kd&Yo)|0,l:Number(e&Yo)|0}}function zb(e,t=!1){const n=e.length;let r=new Uint32Array(n),o=new Uint32Array(n);for(let i=0;i<n;i++){const{h:s,l:a}=Kb(e[i],t);[r[i],o[i]]=[s,a]}return[r,o]}const zd=(e,t,n)=>e>>>n,Vd=(e,t,n)=>e<<32-n|t>>>n,Zn=(e,t,n)=>e>>>n|t<<32-n,Jn=(e,t,n)=>e<<32-n|t>>>n,Zo=(e,t,n)=>e<<64-n|t>>>n-32,Jo=(e,t,n)=>e>>>n-32|t<<64-n;function Mt(e,t,n,r){const o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:o|0}}const Vb=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Wb=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Gb=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Xb=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,Yb=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Zb=(e,t,n,r,o,i)=>t+n+r+o+i+(e/2**32|0)|0,Jb=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]),nn=new Uint32Array(64);class Qb extends qh{constructor(t=32){super(64,t,8,!1),this.A=tn[0]|0,this.B=tn[1]|0,this.C=tn[2]|0,this.D=tn[3]|0,this.E=tn[4]|0,this.F=tn[5]|0,this.G=tn[6]|0,this.H=tn[7]|0}get(){const{A:t,B:n,C:r,D:o,E:i,F:s,G:a,H:c}=this;return[t,n,r,o,i,s,a,c]}set(t,n,r,o,i,s,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,n){for(let u=0;u<16;u++,n+=4)nn[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const f=nn[u-15],h=nn[u-2],g=Rt(f,7)^Rt(f,18)^f>>>3,m=Rt(h,17)^Rt(h,19)^h>>>10;nn[u]=m+nn[u-7]+g+nn[u-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=Rt(a,6)^Rt(a,11)^Rt(a,25),h=d+f+$b(a,c,l)+Jb[u]+nn[u]|0,m=(Rt(r,2)^Rt(r,13)^Rt(r,22))+qb(r,o,i)|0;d=l,l=c,c=a,a=s+h|0,s=i,i=o,o=r,r=h+m|0}r=r+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,i,s,a,c,l,d)}roundClean(){kr(nn)}destroy(){this.set(0,0,0,0,0,0,0,0),kr(this.buffer)}}const Kh=zb(["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(e=>BigInt(e))),ev=Kh[0],tv=Kh[1],rn=new Uint32Array(80),on=new Uint32Array(80);class nv extends qh{constructor(t=64){super(128,t,16,!1),this.Ah=Ve[0]|0,this.Al=Ve[1]|0,this.Bh=Ve[2]|0,this.Bl=Ve[3]|0,this.Ch=Ve[4]|0,this.Cl=Ve[5]|0,this.Dh=Ve[6]|0,this.Dl=Ve[7]|0,this.Eh=Ve[8]|0,this.El=Ve[9]|0,this.Fh=Ve[10]|0,this.Fl=Ve[11]|0,this.Gh=Ve[12]|0,this.Gl=Ve[13]|0,this.Hh=Ve[14]|0,this.Hl=Ve[15]|0}get(){const{Ah:t,Al:n,Bh:r,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:d,Fh:u,Fl:f,Gh:h,Gl:g,Hh:m,Hl:v}=this;return[t,n,r,o,i,s,a,c,l,d,u,f,h,g,m,v]}set(t,n,r,o,i,s,a,c,l,d,u,f,h,g,m,v){this.Ah=t|0,this.Al=n|0,this.Bh=r|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|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=v|0}process(t,n){for(let y=0;y<16;y++,n+=4)rn[y]=t.getUint32(n),on[y]=t.getUint32(n+=4);for(let y=16;y<80;y++){const A=rn[y-15]|0,R=on[y-15]|0,E=Zn(A,R,1)^Zn(A,R,8)^zd(A,R,7),C=Jn(A,R,1)^Jn(A,R,8)^Vd(A,R,7),k=rn[y-2]|0,b=on[y-2]|0,x=Zn(k,b,19)^Zo(k,b,61)^zd(k,b,6),T=Jn(k,b,19)^Jo(k,b,61)^Vd(k,b,6),L=Gb(C,T,on[y-7],on[y-16]),I=Xb(L,E,x,rn[y-7],rn[y-16]);rn[y]=I|0,on[y]=L|0}let{Ah:r,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:f,Fh:h,Fl:g,Gh:m,Gl:v,Hh:w,Hl:S}=this;for(let y=0;y<80;y++){const A=Zn(u,f,14)^Zn(u,f,18)^Zo(u,f,41),R=Jn(u,f,14)^Jn(u,f,18)^Jo(u,f,41),E=u&h^~u&m,C=f&g^~f&v,k=Yb(S,R,C,tv[y],on[y]),b=Zb(k,w,A,E,ev[y],rn[y]),x=k|0,T=Zn(r,o,28)^Zo(r,o,34)^Zo(r,o,39),L=Jn(r,o,28)^Jo(r,o,34)^Jo(r,o,39),I=r&i^r&a^i&a,P=o&s^o&c^s&c;w=m|0,S=v|0,m=h|0,v=g|0,h=u|0,g=f|0,{h:u,l:f}=Mt(l|0,d|0,b|0,x|0),l=a|0,d=c|0,a=i|0,c=s|0,i=r|0,s=o|0;const B=Vb(x,L,P);r=Wb(B,b,T,I),o=B|0}({h:r,l:o}=Mt(this.Ah|0,this.Al|0,r|0,o|0)),{h:i,l:s}=Mt(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Mt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=Mt(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:f}=Mt(this.Eh|0,this.El|0,u|0,f|0),{h,l:g}=Mt(this.Fh|0,this.Fl|0,h|0,g|0),{h:m,l:v}=Mt(this.Gh|0,this.Gl|0,m|0,v|0),{h:w,l:S}=Mt(this.Hh|0,this.Hl|0,w|0,S|0),this.set(r,o,i,s,a,c,l,d,u,f,h,g,m,v,w,S)}roundClean(){kr(rn,on)}destroy(){kr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const zh=$h(()=>new Qb),rv=$h(()=>new nv);const Al=BigInt(0),pc=BigInt(1);function On(e,t=""){if(typeof e!="boolean"){const n=t&&`"${t}"`;throw new Error(n+"expected boolean, got type="+typeof e)}return e}function vt(e,t,n=""){const r=$o(e),o=e?.length,i=t!==void 0;if(!r||i&&o!==t){const s=n&&`"${n}" `,a=i?` of length ${t}`:"",c=r?`length=${o}`:`type=${typeof e}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return e}function Qo(e){const t=e.toString(16);return t.length&1?"0"+t:t}function Vh(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?Al:BigInt("0x"+e)}function Cs(e){return Vh(Tn(e))}function Io(e){return Hn(e),Vh(Tn(Uint8Array.from(e).reverse()))}function Cl(e,t){return Ui(e.toString(16).padStart(t*2,"0"))}function Wh(e,t){return Cl(e,t).reverse()}function Ie(e,t,n){let r;if(typeof t=="string")try{r=Ui(t)}catch(i){throw new Error(e+" must be hex string or Uint8Array, cause: "+i)}else if($o(t))r=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");const o=r.length;if(typeof n=="number"&&o!==n)throw new Error(e+" of length "+n+" expected, got "+o);return r}function Wd(e){return Uint8Array.from(e)}const ea=e=>typeof e=="bigint"&&Al<=e;function ov(e,t,n){return ea(e)&&ea(t)&&ea(n)&&t<=e&&e<n}function gc(e,t,n,r){if(!ov(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Gh(e){let t;for(t=0;e>Al;e>>=pc,t+=1);return t}const qo=e=>(pc<<BigInt(e))-pc;function iv(e,t,n){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=h=>new Uint8Array(h),o=h=>Uint8Array.of(h);let i=r(e),s=r(e),a=0;const c=()=>{i.fill(1),s.fill(0),a=0},l=(...h)=>n(s,i,...h),d=(h=r(0))=>{s=l(o(0),h),i=l(),h.length!==0&&(s=l(o(1),h),i=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const g=[];for(;h<t;){i=l();const m=i.slice();g.push(m),h+=i.length}return Lt(...g)};return(h,g)=>{c(),d(h);let m;for(;!(m=g(u()));)d();return c(),m}}function Ko(e,t,n={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function r(o,i,s){const a=e[o];if(s&&a===void 0)return;const c=typeof a;if(c!==i||a===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${c}`)}Object.entries(t).forEach(([o,i])=>r(o,i,!1)),Object.entries(n).forEach(([o,i])=>r(o,i,!0))}function Hi(e){const t=new WeakMap;return(n,...r)=>{const o=t.get(n);if(o!==void 0)return o;const i=e(n,...r);return t.set(n,i),i}}const rt=BigInt(0),He=BigInt(1),En=BigInt(2),Xh=BigInt(3),Yh=BigInt(4),Zh=BigInt(5),sv=BigInt(7),Jh=BigInt(8),av=BigInt(9),Qh=BigInt(16);function Be(e,t){const n=e%t;return n>=rt?n:t+n}function ke(e,t,n){let r=e;for(;t-- >rt;)r*=r,r%=n;return r}function Gd(e,t){if(e===rt)throw new Error("invert: expected non-zero number");if(t<=rt)throw new Error("invert: expected positive modulus, got "+t);let n=Be(e,t),r=t,o=rt,i=He;for(;n!==rt;){const a=r/n,c=r%n,l=o-i*a;r=n,n=c,o=i,i=l}if(r!==He)throw new Error("invert: does not exist");return Be(o,t)}function kl(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function ep(e,t){const n=(e.ORDER+He)/Yh,r=e.pow(t,n);return kl(e,r,t),r}function cv(e,t){const n=(e.ORDER-Zh)/Jh,r=e.mul(t,En),o=e.pow(r,n),i=e.mul(t,o),s=e.mul(e.mul(i,En),o),a=e.mul(i,e.sub(s,e.ONE));return kl(e,a,t),a}function lv(e){const t=$n(e),n=tp(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+sv)/Qh;return(a,c)=>{let l=a.pow(c,s),d=a.mul(l,r);const u=a.mul(l,o),f=a.mul(l,i),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),v=a.cmov(l,d,m);return kl(a,v,c),v}}function tp(e){if(e<Xh)throw new Error("sqrt is not defined for small field");let t=e-He,n=0;for(;t%En===rt;)t/=En,n++;let r=En;const o=$n(e);for(;Xd(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return ep;let i=o.pow(r,t);const s=(t+He)/En;return function(c,l){if(c.is0(l))return l;if(Xd(c,l)!==1)throw new Error("Cannot find square root");let d=n,u=c.mul(c.ONE,i),f=c.pow(l,t),h=c.pow(l,s);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 v=He<<BigInt(d-g-1),w=c.pow(u,v);d=g,u=c.sqr(w),f=c.mul(f,u),h=c.mul(h,w)}return h}}function dv(e){return e%Yh===Xh?ep:e%Jh===Zh?cv:e%Qh===av?lv(e):tp(e)}const uv=(e,t)=>(Be(e,t)&He)===He,fv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hv(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=fv.reduce((r,o)=>(r[o]="function",r),t);return Ko(e,n),e}function pv(e,t,n){if(n<rt)throw new Error("invalid exponent, negatives unsupported");if(n===rt)return e.ONE;if(n===He)return t;let r=e.ONE,o=t;for(;n>rt;)n&He&&(r=e.mul(r,o)),o=e.sqr(o),n>>=He;return r}function np(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),o=t.reduce((s,a,c)=>e.is0(a)?s:(r[c]=s,e.mul(s,a)),e.ONE),i=e.inv(o);return t.reduceRight((s,a,c)=>e.is0(a)?s:(r[c]=e.mul(s,r[c]),e.mul(s,a)),i),r}function Xd(e,t){const n=(e.ORDER-He)/En,r=e.pow(t,n),o=e.eql(r,e.ONE),i=e.eql(r,e.ZERO),s=e.eql(r,e.neg(e.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function rp(e,t){t!==void 0&&hc(t);const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function $n(e,t,n=!1,r={}){if(e<=rt)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,i,s=!1,a;if(typeof t=="object"&&t!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const f=t;f.BITS&&(o=f.BITS),f.sqrt&&(i=f.sqrt),typeof f.isLE=="boolean"&&(n=f.isLE),typeof f.modFromBytes=="boolean"&&(s=f.modFromBytes),a=f.allowedLengths}else typeof t=="number"&&(o=t),r.sqrt&&(i=r.sqrt);const{nBitLength:c,nByteLength:l}=rp(e,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:qo(c),ZERO:rt,ONE:He,allowedLengths:a,create:f=>Be(f,e),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return rt<=f&&f<e},is0:f=>f===rt,isValidNot0:f=>!u.is0(f)&&u.isValid(f),isOdd:f=>(f&He)===He,neg:f=>Be(-f,e),eql:(f,h)=>f===h,sqr:f=>Be(f*f,e),add:(f,h)=>Be(f+h,e),sub:(f,h)=>Be(f-h,e),mul:(f,h)=>Be(f*h,e),pow:(f,h)=>pv(u,f,h),div:(f,h)=>Be(f*Gd(h,e),e),sqrN:f=>f*f,addN:(f,h)=>f+h,subN:(f,h)=>f-h,mulN:(f,h)=>f*h,inv:f=>Gd(f,e),sqrt:i||(f=>(d||(d=dv(e)),d(u,f))),toBytes:f=>n?Wh(f,l):Cl(f,l),fromBytes:(f,h=!0)=>{if(a){if(!a.includes(f.length)||f.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);const m=new Uint8Array(l);m.set(f,n?0:m.length-f.length),f=m}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let g=n?Io(f):Cs(f);if(s&&(g=Be(g,e)),!h&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:f=>np(u,f),cmov:(f,h,g)=>g?h:f});return Object.freeze(u)}function op(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function ip(e){const t=op(e);return t+Math.ceil(t/2)}function gv(e,t,n=!1){const r=e.length,o=op(t),i=ip(t);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const s=n?Io(e):Cs(e),a=Be(s,t-He)+He;return n?Wh(a,o):Cl(a,o)}const Ir=BigInt(0),An=BigInt(1);function $i(e,t){const n=t.negate();return e?n:t}function Cn(e,t){const n=np(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function sp(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function ta(e,t){sp(e,t);const n=Math.ceil(t/e)+1,r=2**(e-1),o=2**e,i=qo(e),s=BigInt(e);return{windows:n,windowSize:r,mask:i,maxNumber:o,shiftBy:s}}function Yd(e,t,n){const{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n;let a=Number(e&o),c=e>>s;a>r&&(a-=i,c+=An);const l=t*r,d=l+Math.abs(a)-1,u=a===0,f=a<0,h=t%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:f,isNegF:h,offsetF:l}}function mv(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function wv(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((n,r)=>{if(!t.isValid(n))throw new Error("invalid scalar at index "+r)})}const na=new WeakMap,ap=new WeakMap;function ra(e){return ap.get(e)||1}function Zd(e){if(e!==Ir)throw new Error("invalid wNAF")}class cp{constructor(t,n){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=n}_unsafeLadder(t,n,r=this.ZERO){let o=t;for(;n>Ir;)n&An&&(r=r.add(o)),o=o.double(),n>>=An;return r}precomputeWindow(t,n){const{windows:r,windowSize:o}=ta(n,this.bits),i=[];let s=t,a=s;for(let c=0;c<r;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(t,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE;const s=ta(t,this.bits);for(let a=0;a<s.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:f,offsetF:h}=Yd(r,a,s);r=c,d?i=i.add($i(f,n[h])):o=o.add($i(u,n[l]))}return Zd(r),{p:o,f:i}}wNAFUnsafe(t,n,r,o=this.ZERO){const i=ta(t,this.bits);for(let s=0;s<i.windows&&r!==Ir;s++){const{nextN:a,offset:c,isZero:l,isNeg:d}=Yd(r,s,i);if(r=a,!l){const u=n[c];o=o.add(d?u.negate():u)}}return Zd(r),o}getPrecomputes(t,n,r){let o=na.get(n);return o||(o=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(o=r(o)),na.set(n,o))),o}cached(t,n,r){const o=ra(t);return this.wNAF(o,this.getPrecomputes(o,t,r),n)}unsafe(t,n,r,o){const i=ra(t);return i===1?this._unsafeLadder(t,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,r),n,o)}createCache(t,n){sp(n,this.bits),ap.set(t,n),na.delete(t)}hasCache(t){return ra(t)!==1}}function yv(e,t,n,r){let o=t,i=e.ZERO,s=e.ZERO;for(;n>Ir||r>Ir;)n&An&&(i=i.add(o)),r&An&&(s=s.add(o)),o=o.double(),n>>=An,r>>=An;return{p1:i,p2:s}}function lp(e,t,n,r){mv(n,e),wv(r,t);const o=n.length,i=r.length;if(o!==i)throw new Error("arrays of points and scalars must have equal length");const s=e.ZERO,a=Gh(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=qo(c),d=new Array(Number(l)+1).fill(s),u=Math.floor((t.BITS-1)/c)*c;let f=s;for(let h=u;h>=0;h-=c){d.fill(s);for(let m=0;m<i;m++){const v=r[m],w=Number(v>>BigInt(h)&l);d[w]=d[w].add(n[m])}let g=s;for(let m=d.length-1,v=s;m>0;m--)v=v.add(d[m]),g=g.add(v);if(f=f.add(g),h!==0)for(let m=0;m<c;m++)f=f.double()}return f}function Jd(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return hv(t),t}else return $n(e,{isLE:n})}function dp(e,t,n={},r){if(r===void 0&&(r=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(const c of["p","n","h"]){const l=t[c];if(!(typeof l=="bigint"&&l>Ir))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Jd(t.p,n.Fp,r),i=Jd(t.n,n.Fn,r),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(const c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}const sn=BigInt(0),Fe=BigInt(1),oa=BigInt(2),bv=BigInt(8);function vv(e,t,n,r){const o=e.sqr(n),i=e.sqr(r),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function Sv(e,t={}){const n=dp("edwards",e,t,t.FpFnLE),{Fp:r,Fn:o}=n;let i=n.CURVE;const{h:s}=i;Ko(t,{},{uvRatio:"function"});const a=oa<<BigInt(o.BYTES*8)-Fe,c=v=>r.create(v),l=t.uvRatio||((v,w)=>{try{return{isValid:!0,value:r.sqrt(r.div(v,w))}}catch{return{isValid:!1,value:sn}}});if(!vv(r,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function d(v,w,S=!1){const y=S?Fe:sn;return gc("coordinate "+v,w,y,a),w}function u(v){if(!(v instanceof g))throw new Error("ExtendedPoint expected")}const f=Hi((v,w)=>{const{X:S,Y:y,Z:A}=v,R=v.is0();w==null&&(w=R?bv:r.inv(A));const E=c(S*w),C=c(y*w),k=r.mul(A,w);if(R)return{x:sn,y:Fe};if(k!==Fe)throw new Error("invZ was invalid");return{x:E,y:C}}),h=Hi(v=>{const{a:w,d:S}=i;if(v.is0())throw new Error("bad point: ZERO");const{X:y,Y:A,Z:R,T:E}=v,C=c(y*y),k=c(A*A),b=c(R*R),x=c(b*b),T=c(C*w),L=c(b*c(T+k)),I=c(x+c(S*c(C*k)));if(L!==I)throw new Error("bad point: equation left != right (1)");const P=c(y*A),B=c(R*E);if(P!==B)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(w,S,y,A){this.X=d("x",w),this.Y=d("y",S),this.Z=d("z",y,!0),this.T=d("t",A),Object.freeze(this)}static CURVE(){return i}static fromAffine(w){if(w instanceof g)throw new Error("extended point not allowed");const{x:S,y}=w||{};return d("x",S),d("y",y),new g(S,y,Fe,c(S*y))}static fromBytes(w,S=!1){const y=r.BYTES,{a:A,d:R}=i;w=Wd(vt(w,y,"point")),On(S,"zip215");const E=Wd(w),C=w[y-1];E[y-1]=C&-129;const k=Io(E),b=S?a:r.ORDER;gc("point.y",k,sn,b);const x=c(k*k),T=c(x-Fe),L=c(R*x-A);let{isValid:I,value:P}=l(T,L);if(!I)throw new Error("bad point: invalid y coordinate");const B=(P&Fe)===Fe,D=(C&128)!==0;if(!S&&P===sn&&D)throw new Error("bad point: x=0 and x_0=1");return D!==B&&(P=c(-P)),g.fromAffine({x:P,y:k})}static fromHex(w,S=!1){return g.fromBytes(Ie("point",w),S)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,S=!0){return m.createCache(this,w),S||this.multiply(oa),this}assertValidity(){h(this)}equals(w){u(w);const{X:S,Y:y,Z:A}=this,{X:R,Y:E,Z:C}=w,k=c(S*C),b=c(R*A),x=c(y*C),T=c(E*A);return k===b&&x===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}=i,{X:S,Y:y,Z:A}=this,R=c(S*S),E=c(y*y),C=c(oa*c(A*A)),k=c(w*R),b=S+y,x=c(c(b*b)-R-E),T=k+E,L=T-C,I=k-E,P=c(x*L),B=c(T*I),D=c(x*I),F=c(L*T);return new g(P,B,F,D)}add(w){u(w);const{a:S,d:y}=i,{X:A,Y:R,Z:E,T:C}=this,{X:k,Y:b,Z:x,T}=w,L=c(A*k),I=c(R*b),P=c(C*y*T),B=c(E*x),D=c((A+R)*(k+b)-L-I),F=B-P,j=B+P,M=c(I-S*L),U=c(D*F),_=c(j*M),O=c(D*M),H=c(F*j);return new g(U,_,H,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:S,f:y}=m.cached(this,w,A=>Cn(g,A));return Cn(g,[S,y])[0]}multiplyUnsafe(w,S=g.ZERO){if(!o.isValid(w))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return w===sn?g.ZERO:this.is0()||w===Fe?this:m.unsafe(this,w,y=>Cn(g,y),S)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return m.unsafe(this,i.n).is0()}toAffine(w){return f(this,w)}clearCofactor(){return s===Fe?this:this.multiplyUnsafe(s)}toBytes(){const{x:w,y:S}=this.toAffine(),y=r.toBytes(S);return y[y.length-1]|=w&Fe?128:0,y}toHex(){return Tn(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 Cn(g,w)}static msm(w,S){return lp(g,o,w,S)}_setWindowSize(w){this.precompute(w)}toRawBytes(){return this.toBytes()}}g.BASE=new g(i.Gx,i.Gy,Fe,c(i.Gx*i.Gy)),g.ZERO=new g(sn,Fe,Fe,sn),g.Fp=r,g.Fn=o;const m=new cp(g,o.BITS);return g.BASE.precompute(8),g}function xv(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is required');Ko(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:o,Fp:i,Fn:s}=e,a=n.randomBytes||El,c=n.adjustScalarBytes||(b=>b),l=n.domain||((b,x,T)=>{if(On(T,"phflag"),x.length||T)throw new Error("Contexts/pre-hash are not supported");return b});function d(b){return s.create(Io(b))}function u(b){const x=y.secretKey;b=Ie("private key",b,x);const T=Ie("hashed private key",t(b),2*x),L=c(T.slice(0,x)),I=T.slice(x,2*x),P=d(L);return{head:L,prefix:I,scalar:P}}function f(b){const{head:x,prefix:T,scalar:L}=u(b),I=o.multiply(L),P=I.toBytes();return{head:x,prefix:T,scalar:L,point:I,pointBytes:P}}function h(b){return f(b).pointBytes}function g(b=Uint8Array.of(),...x){const T=Lt(...x);return d(t(l(T,Ie("context",b),!!r)))}function m(b,x,T={}){b=Ie("message",b),r&&(b=r(b));const{prefix:L,scalar:I,pointBytes:P}=f(x),B=g(T.context,L,b),D=o.multiply(B).toBytes(),F=g(T.context,D,P,b),j=s.create(B+F*I);if(!s.isValid(j))throw new Error("sign failed: invalid s");const M=Lt(D,s.toBytes(j));return vt(M,y.signature,"result")}const v={zip215:!0};function w(b,x,T,L=v){const{context:I,zip215:P}=L,B=y.signature;b=Ie("signature",b,B),x=Ie("message",x),T=Ie("publicKey",T,y.publicKey),P!==void 0&&On(P,"zip215"),r&&(x=r(x));const D=B/2,F=b.subarray(0,D),j=Io(b.subarray(D,B));let M,U,_;try{M=e.fromBytes(T,P),U=e.fromBytes(F,P),_=o.multiplyUnsafe(j)}catch{return!1}if(!P&&M.isSmallOrder())return!1;const O=g(I,U.toBytes(),M.toBytes(),x);return U.add(M.multiplyUnsafe(O)).subtract(_).clearCofactor().is0()}const S=i.BYTES,y={secretKey:S,publicKey:S,signature:2*S,seed:S};function A(b=a(y.seed)){return vt(b,y.seed,"seed")}function R(b){const x=k.randomSecretKey(b);return{secretKey:x,publicKey:h(x)}}function E(b){return $o(b)&&b.length===s.BYTES}function C(b,x){try{return!!e.fromBytes(b,x)}catch{return!1}}const k={getExtendedPublicKey:f,randomSecretKey:A,isValidSecretKey:E,isValidPublicKey:C,toMontgomery(b){const{y:x}=e.fromBytes(b),T=y.publicKey,L=T===32;if(!L&&T!==57)throw new Error("only defined for 25519 and 448");const I=L?i.div(Fe+x,Fe-x):i.div(x-Fe,x+Fe);return i.toBytes(I)},toMontgomerySecret(b){const x=y.secretKey;vt(b,x);const T=t(b.subarray(0,x));return c(T).subarray(0,x)},randomPrivateKey:A,precompute(b=8,x=e.BASE){return x.precompute(b,!1)}};return Object.freeze({keygen:R,getPublicKey:h,sign:m,verify:w,utils:k,Point:e,lengths:y})}function Ev(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp,r=$n(t.n,e.nBitLength,!0),o={Fp:n,Fn:r,uvRatio:e.uvRatio},i={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:o,hash:e.hash,eddsaOpts:i}}function Av(e,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function Cv(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:o}=Ev(e),i=Sv(t,n),s=xv(i,r,o);return Av(e,s)}const kv=BigInt(1),Qd=BigInt(2);BigInt(3);const Iv=BigInt(5),Rv=BigInt(8),Il=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),up={p:Il,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Rv,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Tv(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=Il,a=e*e%i*e%i,c=ke(a,Qd,i)*a%i,l=ke(c,kv,i)*e%i,d=ke(l,Iv,i)*l%i,u=ke(d,t,i)*d%i,f=ke(u,n,i)*u%i,h=ke(f,r,i)*f%i,g=ke(h,o,i)*h%i,m=ke(g,o,i)*h%i,v=ke(m,t,i)*d%i;return{pow_p_5_8:ke(v,Qd,i)*e%i,b2:a}}function Pv(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const eu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Nv(e,t){const n=Il,r=Be(t*t*t,n),o=Be(r*r*t,n),i=Tv(e*o).pow_p_5_8;let s=Be(e*r*i,n);const a=Be(t*s*s,n),c=s,l=Be(s*eu,n),d=a===e,u=a===Be(-e,n),f=a===Be(-e*eu,n);return d&&(s=c),(u||f)&&(s=l),uv(s,n)&&(s=Be(-s,n)),{isValid:d||u,value:s}}const Lv=$n(up.p,{isLE:!0}),Bv={...up,Fp:Lv,hash:rv,adjustScalarBytes:Pv,uvRatio:Nv},qi=Cv(Bv);class tu extends Error{constructor(t="An error occurred while signing a message"){super(t),this.name="SigningError"}}class nu extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}}class Dv extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}}const Jt={get(e=globalThis){const t=e.crypto;if(t?.subtle==null)throw new Dv("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 t}},Ki=32,$t=64,mc=32;let pr;const fp=(async()=>{try{return await Jt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function _v(){const e=qi.utils.randomPrivateKey(),t=qi.getPublicKey(e);return{privateKey:$v(e,t),publicKey:t}}async function Ov(e,t){let n;e.length===$t?n=e.subarray(0,32):n=e;const r={crv:"Ed25519",kty:"OKP",x:ue(e.subarray(32),"base64url"),d:ue(n,"base64url"),ext:!0,key_ops:["sign"]},o=await Jt.get().subtle.importKey("jwk",r,{name:"Ed25519"},!0,["sign"]),i=await Jt.get().subtle.sign({name:"Ed25519"},o,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(i,0,i.byteLength)}function Fv(e,t){const n=e.subarray(0,mc);return qi.sign(t instanceof Uint8Array?t:t.subarray(),n)}async function Mv(e,t){return pr==null&&(pr=await fp),pr?Ov(e,t):Fv(e,t)}async function jv(e,t,n){if(e.buffer instanceof ArrayBuffer){const r=await Jt.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Jt.get().subtle.verify({name:"Ed25519"},r,t,n instanceof Uint8Array?n:n.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Uv(e,t,n){return qi.verify(t,n instanceof Uint8Array?n:n.subarray(),e)}async function Hv(e,t,n){return pr==null&&(pr=await fp),pr?jv(e,t,n):Uv(e,t,n)}function $v(e,t){const n=new Uint8Array($t);for(let r=0;r<mc;r++)n[r]=e[r],n[mc+r]=t[r];return n}function ks(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}class hp{type="Ed25519";raw;constructor(t){this.raw=Ro(t,Ki)}toMultihash(){return Uo.digest(Ps(this))}toCID(){return Ae.createV1(114,this.toMultihash())}toString(){return Ze.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,n,r){r?.signal?.throwIfAborted();const o=Hv(this.raw,n,t);return ks(o)?o.then(i=>(r?.signal?.throwIfAborted(),i)):o}}class wc{type="Ed25519";raw;publicKey;constructor(t,n){this.raw=Ro(t,$t),this.publicKey=new hp(n)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}sign(t,n){n?.signal?.throwIfAborted();const r=Mv(this.raw,t);return ks(r)?r.then(o=>(n?.signal?.throwIfAborted(),o)):(n?.signal?.throwIfAborted(),r)}}function qv(e){if(e.length>$t){e=Ro(e,$t+Ki);const r=e.subarray(0,$t),o=e.subarray($t,e.length);return new wc(r,o)}e=Ro(e,$t);const t=e.subarray(0,$t),n=e.subarray(Ki);return new wc(t,n)}function pp(e){return e=Ro(e,Ki),new hp(e)}async function Kv(){const{privateKey:e,publicKey:t}=_v();return new wc(e,t)}function Ro(e,t){if(e=Uint8Array.from(e??[]),e.length!==t)throw new xt(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}const zv=Math.pow(2,7),Vv=Math.pow(2,14),Wv=Math.pow(2,21),Rl=Math.pow(2,28),Tl=Math.pow(2,35),Pl=Math.pow(2,42),Nl=Math.pow(2,49),we=128,We=127;function qn(e){if(e<zv)return 1;if(e<Vv)return 2;if(e<Wv)return 3;if(e<Rl)return 4;if(e<Tl)return 5;if(e<Pl)return 6;if(e<Nl)return 7;if(Number.MAX_SAFE_INTEGER!=null&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function gp(e,t,n=0){switch(qn(e)){case 8:t[n++]=e&255|we,e/=128;case 7:t[n++]=e&255|we,e/=128;case 6:t[n++]=e&255|we,e/=128;case 5:t[n++]=e&255|we,e/=128;case 4:t[n++]=e&255|we,e>>>=7;case 3:t[n++]=e&255|we,e>>>=7;case 2:t[n++]=e&255|we,e>>>=7;case 1:{t[n++]=e&255,e>>>=7;break}default:throw new Error("unreachable")}return t}function Gv(e,t,n=0){switch(qn(e)){case 8:t.set(n++,e&255|we),e/=128;case 7:t.set(n++,e&255|we),e/=128;case 6:t.set(n++,e&255|we),e/=128;case 5:t.set(n++,e&255|we),e/=128;case 4:t.set(n++,e&255|we),e>>>=7;case 3:t.set(n++,e&255|we),e>>>=7;case 2:t.set(n++,e&255|we),e>>>=7;case 1:{t.set(n++,e&255),e>>>=7;break}default:throw new Error("unreachable")}return t}function mp(e,t){let n=e[t],r=0;if(r+=n&We,n<we||(n=e[t+1],r+=(n&We)<<7,n<we)||(n=e[t+2],r+=(n&We)<<14,n<we)||(n=e[t+3],r+=(n&We)<<21,n<we)||(n=e[t+4],r+=(n&We)*Rl,n<we)||(n=e[t+5],r+=(n&We)*Tl,n<we)||(n=e[t+6],r+=(n&We)*Pl,n<we)||(n=e[t+7],r+=(n&We)*Nl,n<we))return r;throw new RangeError("Could not decode varint")}function Xv(e,t){let n=e.get(t),r=0;if(r+=n&We,n<we||(n=e.get(t+1),r+=(n&We)<<7,n<we)||(n=e.get(t+2),r+=(n&We)<<14,n<we)||(n=e.get(t+3),r+=(n&We)<<21,n<we)||(n=e.get(t+4),r+=(n&We)*Rl,n<we)||(n=e.get(t+5),r+=(n&We)*Tl,n<we)||(n=e.get(t+6),r+=(n&We)*Pl,n<we)||(n=e.get(t+7),r+=(n&We)*Nl,n<we))return r;throw new RangeError("Could not decode varint")}function Yv(e,t,n=0){return t==null&&(t=Zt(qn(e))),t instanceof Uint8Array?gp(e,t,n):Gv(e,t,n)}function wp(e,t=0){return e instanceof Uint8Array?mp(e,t):Xv(e,t)}const Ll=new Float32Array([-0]),pn=new Uint8Array(Ll.buffer);function Zv(e,t,n){Ll[0]=e,t[n]=pn[0],t[n+1]=pn[1],t[n+2]=pn[2],t[n+3]=pn[3]}function Jv(e,t){return pn[0]=e[t],pn[1]=e[t+1],pn[2]=e[t+2],pn[3]=e[t+3],Ll[0]}const Bl=new Float64Array([-0]),Ge=new Uint8Array(Bl.buffer);function Qv(e,t,n){Bl[0]=e,t[n]=Ge[0],t[n+1]=Ge[1],t[n+2]=Ge[2],t[n+3]=Ge[3],t[n+4]=Ge[4],t[n+5]=Ge[5],t[n+6]=Ge[6],t[n+7]=Ge[7]}function e0(e,t){return Ge[0]=e[t],Ge[1]=e[t+1],Ge[2]=e[t+2],Ge[3]=e[t+3],Ge[4]=e[t+4],Ge[5]=e[t+5],Ge[6]=e[t+6],Ge[7]=e[t+7],Bl[0]}const t0=BigInt(Number.MAX_SAFE_INTEGER),n0=BigInt(Number.MIN_SAFE_INTEGER);class Xe{lo;hi;constructor(t,n){this.lo=t|0,this.hi=n|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){const n=~this.lo+1>>>0;let r=~this.hi>>>0;return n===0&&(r=r+1>>>0),-(n+r*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){const n=~this.lo+1>>>0;let r=~this.hi>>>0;return n===0&&(r=r+1>>>0),-(BigInt(n)+(BigInt(r)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){const t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){const t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){const t=this.lo,n=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?n===0?t<16384?t<128?1:2:t<2097152?3:4:n<16384?n<128?5:6:n<2097152?7:8:r<128?9:10}static fromBigInt(t){if(t===0n)return Pn;if(t<t0&&t>n0)return this.fromNumber(Number(t));const n=t<0n;n&&(t=-t);let r=t>>32n,o=t-(r<<32n);return n&&(r=~r|0n,o=~o|0n,++o>ru&&(o=0n,++r>ru&&(r=0n))),new Xe(Number(o),Number(r))}static fromNumber(t){if(t===0)return Pn;const n=t<0;n&&(t=-t);let r=t>>>0,o=(t-r)/4294967296>>>0;return n&&(o=~o>>>0,r=~r>>>0,++r>4294967295&&(r=0,++o>4294967295&&(o=0))),new Xe(r,o)}static from(t){return typeof t=="number"?Xe.fromNumber(t):typeof t=="bigint"?Xe.fromBigInt(t):typeof t=="string"?Xe.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new Xe(t.low>>>0,t.high>>>0):Pn}}const Pn=new Xe(0,0);Pn.toBigInt=function(){return 0n};Pn.zzEncode=Pn.zzDecode=function(){return this};Pn.length=function(){return 1};const ru=4294967296n;function r0(e){let t=0,n=0;for(let r=0;r<e.length;++r)n=e.charCodeAt(r),n<128?t+=1:n<2048?t+=2:(n&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320?(++r,t+=4):t+=3;return t}function o0(e,t,n){if(n-t<1)return"";let o;const i=[];let s=0,a;for(;t<n;)a=e[t++],a<128?i[s++]=a:a>191&&a<224?i[s++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,i[s++]=55296+(a>>10),i[s++]=56320+(a&1023)):i[s++]=(a&15)<<12|(e[t++]&63)<<6|e[t++]&63,s>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o!=null?(s>0&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))}function yp(e,t,n){const r=n;let o,i;for(let s=0;s<e.length;++s)o=e.charCodeAt(s),o<128?t[n++]=o:o<2048?(t[n++]=o>>6|192,t[n++]=o&63|128):(o&64512)===55296&&((i=e.charCodeAt(s+1))&64512)===56320?(o=65536+((o&1023)<<10)+(i&1023),++s,t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=o&63|128):(t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=o&63|128);return n-r}function mt(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function ei(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class i0{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,mt(this,10);return t}int32(){return this.uint32()|0}sint32(){const t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw mt(this,4);return ei(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw mt(this,4);return ei(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw mt(this,4);const t=Jv(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw mt(this,4);const t=e0(this.buf,this.pos);return this.pos+=8,t}bytes(){const t=this.uint32(),n=this.pos,r=this.pos+t;if(r>this.len)throw mt(this,t);return this.pos+=t,n===r?new Uint8Array(0):this.buf.subarray(n,r)}string(){const t=this.bytes();return o0(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw mt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw mt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){const t=new Xe(0,0);let n=0;if(this.len-this.pos>4){for(;n<4;++n)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<n*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;n=0}else{for(;n<3;++n){if(this.pos>=this.len)throw mt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<n*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<n*7)>>>0,t}if(this.len-this.pos>4){for(;n<5;++n)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<n*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;n<5;++n){if(this.pos>=this.len)throw mt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<n*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw mt(this,8);const t=ei(this.buf,this.pos+=4),n=ei(this.buf,this.pos+=4);return new Xe(t,n)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const t=mp(this.buf,this.pos);return this.pos+=qn(t),t}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 s0(e){return new i0(e instanceof Uint8Array?e:e.subarray())}function Is(e,t,n){const r=s0(e);return t.decode(r,void 0,n)}function a0(e){let r,o=8192;return function(s){if(s<1||s>4096)return Zt(s);o+s>8192&&(r=Zt(8192),o=0);const a=r.subarray(o,o+=s);return(o&7)!==0&&(o=(o|7)+1),a}}class co{fn;len;next;val;constructor(t,n,r){this.fn=t,this.len=n,this.next=void 0,this.val=r}}function ia(){}class c0{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}}const l0=a0();function d0(e){return globalThis.Buffer!=null?Zt(e):l0(e)}class yc{len;head;tail;states;constructor(){this.len=0,this.head=new co(ia,0,0),this.tail=this.head,this.states=null}_push(t,n,r){return this.tail=this.tail.next=new co(t,n,r),this.len+=n,this}uint32(t){return this.len+=(this.tail=this.tail.next=new f0((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(ti,10,Xe.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){const n=Xe.fromBigInt(t);return this._push(ti,n.length(),n)}uint64Number(t){return this._push(gp,qn(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){const n=Xe.fromBigInt(t).zzEncode();return this._push(ti,n.length(),n)}sint64Number(t){const n=Xe.fromNumber(t).zzEncode();return this._push(ti,n.length(),n)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(sa,1,t?1:0)}fixed32(t){return this._push(zr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){const n=Xe.fromBigInt(t);return this._push(zr,4,n.lo)._push(zr,4,n.hi)}fixed64Number(t){const n=Xe.fromNumber(t);return this._push(zr,4,n.lo)._push(zr,4,n.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Zv,4,t)}double(t){return this._push(Qv,8,t)}bytes(t){const n=t.length>>>0;return n===0?this._push(sa,1,0):this.uint32(n)._push(h0,n,t)}string(t){const n=r0(t);return n!==0?this.uint32(n)._push(yp,n,t):this._push(sa,1,0)}fork(){return this.states=new c0(this),this.head=this.tail=new co(ia,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 co(ia,0,0),this.len=0),this}ldelim(){const t=this.head,n=this.tail,r=this.len;return this.reset().uint32(r),r!==0&&(this.tail.next=t.next,this.tail=n,this.len+=r),this}finish(){let t=this.head.next;const n=d0(this.len);let r=0;for(;t!=null;)t.fn(t.val,n,r),r+=t.len,t=t.next;return n}}function sa(e,t,n){t[n]=e&255}function u0(e,t,n){for(;e>127;)t[n++]=e&127|128,e>>>=7;t[n]=e}class f0 extends co{next;constructor(t,n){super(u0,t,n),this.next=void 0}}function ti(e,t,n){for(;e.hi!==0;)t[n++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=e.lo&127|128,e.lo=e.lo>>>7;t[n++]=e.lo}function zr(e,t,n){t[n]=e&255,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function h0(e,t,n){t.set(e,n)}globalThis.Buffer!=null&&(yc.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(p0,t,e),this},yc.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(g0,t,e),this});function p0(e,t,n){t.set(e,n)}function g0(e,t,n){e.length<40?yp(e,t,n):t.utf8Write!=null?t.utf8Write(e,n):t.set(Le(e),n)}function m0(){return new yc}function Rs(e,t){const n=m0();return t.encode(e,n,{lengthDelimited:!1}),n.finish()}var zi;(function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(zi||(zi={}));function bp(e,t,n,r){return{name:e,type:t,encode:n,decode:r}}function w0(e){function t(o){if(e[o.toString()]==null)throw new Error("Invalid enum value");return e[o]}const n=function(i,s){const a=t(i);s.int32(a)},r=function(i){const s=i.int32();return t(s)};return bp("enum",zi.VARINT,n,r)}function Ts(e,t){return bp("message",zi.LENGTH_DELIMITED,e,t)}class ou extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}var Ce;(function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(Ce||(Ce={}));var bc;(function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(bc||(bc={}));(function(e){e.codec=()=>w0(bc)})(Ce||(Ce={}));var Fn;(function(e){let t;e.codec=()=>(t==null&&(t=Ts((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),Ce.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const i={},s=r==null?n.len:n.pos+r;for(;n.pos<s;){const a=n.uint32();switch(a>>>3){case 1:{i.Type=Ce.codec().decode(n);break}case 2:{i.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),t),e.encode=n=>Rs(n,e.codec()),e.decode=(n,r)=>Is(n,e.codec(),r)})(Fn||(Fn={}));var Vi;(function(e){let t;e.codec=()=>(t==null&&(t=Ts((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.Type!=null&&(r.uint32(8),Ce.codec().encode(n.Type,r)),n.Data!=null&&(r.uint32(18),r.bytes(n.Data)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const i={},s=r==null?n.len:n.pos+r;for(;n.pos<s;){const a=n.uint32();switch(a>>>3){case 1:{i.Type=Ce.codec().decode(n);break}case 2:{i.Data=n.bytes();break}default:{n.skipType(a&7);break}}}return i})),t),e.encode=n=>Rs(n,e.codec()),e.decode=(n,r)=>Is(n,e.codec(),r)})(Vi||(Vi={}));const vp=zh;class Sp{type="RSA";jwk;_raw;_multihash;constructor(t,n){this.jwk=t,this._multihash=n}get raw(){return this._raw==null&&(this._raw=Ep(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Ae.createV1(114,this._multihash)}toString(){return Ze.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,n,r){return L0(this.jwk,n,t,r)}}class y0{type="RSA";jwk;_raw;publicKey;constructor(t,n){this.jwk=t,this.publicKey=n}get raw(){return this._raw==null&&(this._raw=E0(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}sign(t,n){return N0(this.jwk,t,n)}}const b0=8192,xp=18,v0=1062,S0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function x0(e){return{n:ue(e[1],"base64url"),e:ue(e[2],"base64url"),d:ue(e[3],"base64url"),p:ue(e[4],"base64url"),q:ue(e[5],"base64url"),dp:ue(e[6],"base64url"),dq:ue(e[7],"base64url"),qi:ue(e[8],"base64url"),kty:"RSA"}}function E0(e){if(e.n==null||e.e==null||e.d==null||e.p==null||e.q==null||e.dp==null||e.dq==null||e.qi==null)throw new xt("JWK was missing components");return Gt([ct(Uint8Array.from([0])),ct(Le(e.n,"base64url")),ct(Le(e.e,"base64url")),ct(Le(e.d,"base64url")),ct(Le(e.p,"base64url")),ct(Le(e.q,"base64url")),ct(Le(e.dp,"base64url")),ct(Le(e.dq,"base64url")),ct(Le(e.qi,"base64url"))]).subarray()}function A0(e){const t=Or(e[1],{offset:0});return{kty:"RSA",n:ue(t[0],"base64url"),e:ue(t[1],"base64url")}}function Ep(e){if(e.n==null||e.e==null)throw new xt("JWK was missing components");return Gt([S0,Sl(Gt([ct(Le(e.n,"base64url")),ct(Le(e.e,"base64url"))]))]).subarray()}function C0(e){const t=Or(e);return k0(t)}function k0(e){const t=x0(e);return T0(t)}function I0(e,t){if(e.byteLength>=v0)throw new xh("Key size is too large");const n=Or(e,{offset:0});return R0(n,e,t)}function R0(e,t,n){const r=A0(e);if(n==null){const o=vp(Fn.encode({Type:Ce.RSA,Data:t}));n=jo(xp,o)}return new Sp(r,n)}function T0(e){if(B0(e)>b0)throw new xt("Key size is too large");const t=P0(e),n=vp(Fn.encode({Type:Ce.RSA,Data:Ep(t.publicKey)})),r=jo(xp,n);return new y0(t.privateKey,new Sp(t.publicKey,r))}function P0(e){if(e==null)throw new xt("Missing key parameter");return{privateKey:e,publicKey:{kty:e.kty,n:e.n,e:e.e}}}async function N0(e,t,n){const r=await Jt.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);n?.signal?.throwIfAborted();const o=await Jt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function L0(e,t,n,r){const o=await Jt.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);r?.signal?.throwIfAborted();const i=await Jt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,n instanceof Uint8Array?n:n.subarray());return r?.signal?.throwIfAborted(),i}function B0(e){if(e.kty!=="RSA")throw new xt("invalid key type");if(e.n==null)throw new xt("invalid key modulus");return Le(e.n,"base64url").length*8}class Ap extends Hh{constructor(t,n){super(),this.finished=!1,this.destroyed=!1,jh(t);const r=xl(n);if(this.iHash=t.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,i=new Uint8Array(o);i.set(r.length>o?t.create().update(r).digest():r);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=t.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),kr(i)}update(t){return ji(this),this.iHash.update(t),this}digestInto(t){ji(this),Hn(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Cp=(e,t,n)=>new Ap(e,t).update(n).digest();Cp.create=(e,t)=>new Ap(e,t);const iu=(e,t)=>(e+(e>=0?t:-t)/kp)/t;function D0(e,t,n){const[[r,o],[i,s]]=t,a=iu(s*e,n),c=iu(-o*e,n);let l=e-a*r-c*i,d=-a*o-c*s;const u=l<zt,f=d<zt;u&&(l=-l),f&&(d=-d);const h=qo(Math.ceil(Gh(n)/2))+gr;if(l<zt||l>=h||d<zt||d>=h)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:u,k1:l,k2neg:f,k2:d}}function vc(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function aa(e,t){const n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return On(n.lowS,"lowS"),On(n.prehash,"prehash"),n.format!==void 0&&vc(n.format),n}class _0 extends Error{constructor(t=""){super(t)}}const qt={Err:_0,_tlv:{encode:(e,t)=>{const{Err:n}=qt;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length&1)throw new n("tlv.encode: unpadded data");const r=t.length/2,o=Qo(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?Qo(o.length/2|128):"";return Qo(e)+i+o+t},decode(e,t){const{Err:n}=qt;let r=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[r++]!==e)throw new n("tlv.decode: wrong tlv");const o=t[r++],i=!!(o&128);let s=0;if(!i)s=o;else{const c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const l=t.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const d of l)s=s<<8|d;if(r+=c,s<128)throw new n("tlv.decode(long): not minimal encoding")}const a=t.subarray(r,r+s);if(a.length!==s)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(r+s)}}},_int:{encode(e){const{Err:t}=qt;if(e<zt)throw new t("integer: negative integers are not allowed");let n=Qo(e);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=qt;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Cs(e)}},toSig(e){const{Err:t,_int:n,_tlv:r}=qt,o=Ie("signature",e),{v:i,l:s}=r.decode(48,o);if(s.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,i),{v:l,l:d}=r.decode(2,c);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(e){const{_tlv:t,_int:n}=qt,r=t.encode(2,n.encode(e.r)),o=t.encode(2,n.encode(e.s)),i=r+o;return t.encode(48,i)}},zt=BigInt(0),gr=BigInt(1),kp=BigInt(2),ni=BigInt(3),O0=BigInt(4);function ar(e,t){const{BYTES:n}=e;let r;if(typeof t=="bigint")r=t;else{let o=Ie("private key",t);try{r=e.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function F0(e,t={}){const n=dp("weierstrass",e,t),{Fp:r,Fn:o}=n;let i=n.CURVE;const{h:s,n:a}=i;Ko(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Rp(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(L,I,P){const{x:B,y:D}=I.toAffine(),F=r.toBytes(B);if(On(P,"isCompressed"),P){d();const j=!r.isOdd(D);return Lt(Ip(j),F)}else return Lt(Uint8Array.of(4),F,r.toBytes(D))}function f(L){vt(L,void 0,"Point");const{publicKey:I,publicKeyUncompressed:P}=l,B=L.length,D=L[0],F=L.subarray(1);if(B===I&&(D===2||D===3)){const j=r.fromBytes(F);if(!r.isValid(j))throw new Error("bad point: is not on curve, wrong x");const M=m(j);let U;try{U=r.sqrt(M)}catch(H){const V=H instanceof Error?": "+H.message:"";throw new Error("bad point: is not on curve, sqrt error"+V)}d();const _=r.isOdd(U);return(D&1)===1!==_&&(U=r.neg(U)),{x:j,y:U}}else if(B===P&&D===4){const j=r.BYTES,M=r.fromBytes(F.subarray(0,j)),U=r.fromBytes(F.subarray(j,j*2));if(!v(M,U))throw new Error("bad point: is not on curve");return{x:M,y:U}}else throw new Error(`bad point: got length ${B}, expected compressed=${I} or uncompressed=${P}`)}const h=t.toBytes||u,g=t.fromBytes||f;function m(L){const I=r.sqr(L),P=r.mul(I,L);return r.add(r.add(P,r.mul(L,i.a)),i.b)}function v(L,I){const P=r.sqr(I),B=m(L);return r.eql(P,B)}if(!v(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const w=r.mul(r.pow(i.a,ni),O0),S=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(w,S)))throw new Error("bad curve params: a or b");function y(L,I,P=!1){if(!r.isValid(I)||P&&r.is0(I))throw new Error(`bad point coordinate ${L}`);return I}function A(L){if(!(L instanceof b))throw new Error("ProjectivePoint expected")}function R(L){if(!c||!c.basises)throw new Error("no endo");return D0(L,c.basises,o.ORDER)}const E=Hi((L,I)=>{const{X:P,Y:B,Z:D}=L;if(r.eql(D,r.ONE))return{x:P,y:B};const F=L.is0();I==null&&(I=F?r.ONE:r.inv(D));const j=r.mul(P,I),M=r.mul(B,I),U=r.mul(D,I);if(F)return{x:r.ZERO,y:r.ZERO};if(!r.eql(U,r.ONE))throw new Error("invZ was invalid");return{x:j,y:M}}),C=Hi(L=>{if(L.is0()){if(t.allowInfinityPoint&&!r.is0(L.Y))return;throw new Error("bad point: ZERO")}const{x:I,y:P}=L.toAffine();if(!r.isValid(I)||!r.isValid(P))throw new Error("bad point: x or y not field elements");if(!v(I,P))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function k(L,I,P,B,D){return P=new b(r.mul(P.X,L),P.Y,P.Z),I=$i(B,I),P=$i(D,P),I.add(P)}class b{constructor(I,P,B){this.X=y("x",I),this.Y=y("y",P,!0),this.Z=y("z",B),Object.freeze(this)}static CURVE(){return i}static fromAffine(I){const{x:P,y:B}=I||{};if(!I||!r.isValid(P)||!r.isValid(B))throw new Error("invalid affine point");if(I instanceof b)throw new Error("projective point not allowed");return r.is0(P)&&r.is0(B)?b.ZERO:new b(P,B,r.ONE)}static fromBytes(I){const P=b.fromAffine(g(vt(I,void 0,"point")));return P.assertValidity(),P}static fromHex(I){return b.fromBytes(Ie("pointHex",I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,P=!0){return T.createCache(this,I),P||this.multiply(ni),this}assertValidity(){C(this)}hasEvenY(){const{y:I}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(I)}equals(I){A(I);const{X:P,Y:B,Z:D}=this,{X:F,Y:j,Z:M}=I,U=r.eql(r.mul(P,M),r.mul(F,D)),_=r.eql(r.mul(B,M),r.mul(j,D));return U&&_}negate(){return new b(this.X,r.neg(this.Y),this.Z)}double(){const{a:I,b:P}=i,B=r.mul(P,ni),{X:D,Y:F,Z:j}=this;let M=r.ZERO,U=r.ZERO,_=r.ZERO,O=r.mul(D,D),H=r.mul(F,F),V=r.mul(j,j),z=r.mul(D,F);return z=r.add(z,z),_=r.mul(D,j),_=r.add(_,_),M=r.mul(I,_),U=r.mul(B,V),U=r.add(M,U),M=r.sub(H,U),U=r.add(H,U),U=r.mul(M,U),M=r.mul(z,M),_=r.mul(B,_),V=r.mul(I,V),z=r.sub(O,V),z=r.mul(I,z),z=r.add(z,_),_=r.add(O,O),O=r.add(_,O),O=r.add(O,V),O=r.mul(O,z),U=r.add(U,O),V=r.mul(F,j),V=r.add(V,V),O=r.mul(V,z),M=r.sub(M,O),_=r.mul(V,H),_=r.add(_,_),_=r.add(_,_),new b(M,U,_)}add(I){A(I);const{X:P,Y:B,Z:D}=this,{X:F,Y:j,Z:M}=I;let U=r.ZERO,_=r.ZERO,O=r.ZERO;const H=i.a,V=r.mul(i.b,ni);let z=r.mul(P,F),W=r.mul(B,j),X=r.mul(D,M),G=r.add(P,B),Y=r.add(F,j);G=r.mul(G,Y),Y=r.add(z,W),G=r.sub(G,Y),Y=r.add(P,D);let ie=r.add(F,M);return Y=r.mul(Y,ie),ie=r.add(z,X),Y=r.sub(Y,ie),ie=r.add(B,D),U=r.add(j,M),ie=r.mul(ie,U),U=r.add(W,X),ie=r.sub(ie,U),O=r.mul(H,Y),U=r.mul(V,X),O=r.add(U,O),U=r.sub(W,O),O=r.add(W,O),_=r.mul(U,O),W=r.add(z,z),W=r.add(W,z),X=r.mul(H,X),Y=r.mul(V,Y),W=r.add(W,X),X=r.sub(z,X),X=r.mul(H,X),Y=r.add(Y,X),z=r.mul(W,Y),_=r.add(_,z),z=r.mul(ie,Y),U=r.mul(G,U),U=r.sub(U,z),z=r.mul(G,W),O=r.mul(ie,O),O=r.add(O,z),new b(U,_,O)}subtract(I){return this.add(I.negate())}is0(){return this.equals(b.ZERO)}multiply(I){const{endo:P}=t;if(!o.isValidNot0(I))throw new Error("invalid scalar: out of range");let B,D;const F=j=>T.cached(this,j,M=>Cn(b,M));if(P){const{k1neg:j,k1:M,k2neg:U,k2:_}=R(I),{p:O,f:H}=F(M),{p:V,f:z}=F(_);D=H.add(z),B=k(P.beta,O,V,j,U)}else{const{p:j,f:M}=F(I);B=j,D=M}return Cn(b,[B,D])[0]}multiplyUnsafe(I){const{endo:P}=t,B=this;if(!o.isValid(I))throw new Error("invalid scalar: out of range");if(I===zt||B.is0())return b.ZERO;if(I===gr)return B;if(T.hasCache(this))return this.multiply(I);if(P){const{k1neg:D,k1:F,k2neg:j,k2:M}=R(I),{p1:U,p2:_}=yv(b,B,F,M);return k(P.beta,U,_,D,j)}else return T.unsafe(B,I)}multiplyAndAddUnsafe(I,P,B){const D=this.multiplyUnsafe(P).add(I.multiplyUnsafe(B));return D.is0()?void 0:D}toAffine(I){return E(this,I)}isTorsionFree(){const{isTorsionFree:I}=t;return s===gr?!0:I?I(b,this):T.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:I}=t;return s===gr?this:I?I(b,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(I=!0){return On(I,"isCompressed"),this.assertValidity(),h(b,this,I)}toHex(I=!0){return Tn(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(I=!0){return this.toBytes(I)}_setWindowSize(I){this.precompute(I)}static normalizeZ(I){return Cn(b,I)}static msm(I,P){return lp(b,o,I,P)}static fromPrivateKey(I){return b.BASE.multiply(ar(o,I))}}b.BASE=new b(i.Gx,i.Gy,r.ONE),b.ZERO=new b(r.ZERO,r.ONE,r.ZERO),b.Fp=r,b.Fn=o;const x=o.BITS,T=new cp(b,t.endo?Math.ceil(x/2):x);return b.BASE.precompute(8),b}function Ip(e){return Uint8Array.of(e?2:3)}function Rp(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function M0(e,t={}){const{Fn:n}=e,r=t.randomBytes||El,o=Object.assign(Rp(e.Fp,n),{seed:ip(n.ORDER)});function i(h){try{return!!ar(n,h)}catch{return!1}}function s(h,g){const{publicKey:m,publicKeyUncompressed:v}=o;try{const w=h.length;return g===!0&&w!==m||g===!1&&w!==v?!1:!!e.fromBytes(h)}catch{return!1}}function a(h=r(o.seed)){return gv(vt(h,o.seed,"seed"),n.ORDER)}function c(h,g=!0){return e.BASE.multiply(ar(n,h)).toBytes(g)}function l(h){const g=a(h);return{secretKey:g,publicKey:c(g)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof e)return!0;const{secretKey:g,publicKey:m,publicKeyUncompressed:v}=o;if(n.allowedLengths||g===m)return;const w=Ie("key",h).length;return w===m||w===v}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 v=ar(n,h);return e.fromHex(g).multiply(v).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:e,utils:{isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:h=>ar(n,h),precompute(h=8,g=e.BASE){return g.precompute(h,!1)}},lengths:o})}function j0(e,t,n={}){jh(t),Ko(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||El,o=n.hmac||((P,...B)=>Cp(t,P,Lt(...B))),{Fp:i,Fn:s}=e,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h}=M0(e,n),g={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function v(P){const B=a>>gr;return P>B}function w(P,B){if(!s.isValidNot0(B))throw new Error(`invalid signature ${P}: out of range 1..Point.Fn.ORDER`);return B}function S(P,B){vc(B);const D=h.signature,F=B==="compact"?D:B==="recovered"?D+1:void 0;return vt(P,F,`${B} signature`)}class y{constructor(B,D,F){this.r=w("r",B),this.s=w("s",D),F!=null&&(this.recovery=F),Object.freeze(this)}static fromBytes(B,D=m){S(B,D);let F;if(D==="der"){const{r:_,s:O}=qt.toSig(vt(B));return new y(_,O)}D==="recovered"&&(F=B[0],D="compact",B=B.subarray(1));const j=s.BYTES,M=B.subarray(0,j),U=B.subarray(j,j*2);return new y(s.fromBytes(M),s.fromBytes(U),F)}static fromHex(B,D){return this.fromBytes(Ui(B),D)}addRecoveryBit(B){return new y(this.r,this.s,B)}recoverPublicKey(B){const D=i.ORDER,{r:F,s:j,recovery:M}=this;if(M==null||![0,1,2,3].includes(M))throw new Error("recovery id invalid");if(a*kp<D&&M>1)throw new Error("recovery id is ambiguous for h>1 curve");const _=M===2||M===3?F+a:F;if(!i.isValid(_))throw new Error("recovery id 2 or 3 invalid");const O=i.toBytes(_),H=e.fromBytes(Lt(Ip((M&1)===0),O)),V=s.inv(_),z=R(Ie("msgHash",B)),W=s.create(-z*V),X=s.create(j*V),G=e.BASE.multiplyUnsafe(W).add(H.multiplyUnsafe(X));if(G.is0())throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return v(this.s)}toBytes(B=m){if(vc(B),B==="der")return Ui(qt.hexFromSig(this));const D=s.toBytes(this.r),F=s.toBytes(this.s);if(B==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Lt(Uint8Array.of(this.recovery),D,F)}return Lt(D,F)}toHex(B){return Tn(this.toBytes(B))}assertValidity(){}static fromCompact(B){return y.fromBytes(Ie("sig",B),"compact")}static fromDER(B){return y.fromBytes(Ie("sig",B),"der")}normalizeS(){return this.hasHighS()?new y(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Tn(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Tn(this.toBytes("compact"))}}const A=n.bits2int||function(B){if(B.length>8192)throw new Error("input is too large");const D=Cs(B),F=B.length*8-c;return F>0?D>>BigInt(F):D},R=n.bits2int_modN||function(B){return s.create(A(B))},E=qo(c);function C(P){return gc("num < 2^"+c,P,zt,E),s.toBytes(P)}function k(P,B){return vt(P,void 0,"message"),B?vt(t(P),void 0,"prehashed message"):P}function b(P,B,D){if(["recovered","canonical"].some(W=>W in D))throw new Error("sign() legacy options not supported");const{lowS:F,prehash:j,extraEntropy:M}=aa(D,g);P=k(P,j);const U=R(P),_=ar(s,B),O=[C(_),C(U)];if(M!=null&&M!==!1){const W=M===!0?r(h.secretKey):M;O.push(Ie("extraEntropy",W))}const H=Lt(...O),V=U;function z(W){const X=A(W);if(!s.isValidNot0(X))return;const G=s.inv(X),Y=e.BASE.multiply(X).toAffine(),ie=s.create(Y.x);if(ie===zt)return;const se=s.create(G*s.create(V+ie*_));if(se===zt)return;let K=(Y.x===ie?0:2)|Number(Y.y&gr),ne=se;return F&&v(se)&&(ne=s.neg(se),K^=1),new y(ie,ne,K)}return{seed:H,k2sig:z}}function x(P,B,D={}){P=Ie("message",P);const{seed:F,k2sig:j}=b(P,B,D);return iv(t.outputLen,s.BYTES,o)(F,j)}function T(P){let B;const D=typeof P=="string"||$o(P),F=!D&&P!==null&&typeof P=="object"&&typeof P.r=="bigint"&&typeof P.s=="bigint";if(!D&&!F)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(F)B=new y(P.r,P.s);else if(D){try{B=y.fromBytes(Ie("sig",P),"der")}catch(j){if(!(j instanceof qt.Err))throw j}if(!B)try{B=y.fromBytes(Ie("sig",P),"compact")}catch{return!1}}return B||!1}function L(P,B,D,F={}){const{lowS:j,prehash:M,format:U}=aa(F,g);if(D=Ie("publicKey",D),B=k(Ie("message",B),M),"strict"in F)throw new Error("options.strict was renamed to lowS");const _=U===void 0?T(P):y.fromBytes(Ie("sig",P),U);if(_===!1)return!1;try{const O=e.fromBytes(D);if(j&&_.hasHighS())return!1;const{r:H,s:V}=_,z=R(B),W=s.inv(V),X=s.create(z*W),G=s.create(H*W),Y=e.BASE.multiplyUnsafe(X).add(O.multiplyUnsafe(G));return Y.is0()?!1:s.create(Y.x)===H}catch{return!1}}function I(P,B,D={}){const{prehash:F}=aa(D,g);return B=k(B,F),y.fromBytes(P,"recovered").recoverPublicKey(B).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:f,lengths:h,Point:e,sign:x,verify:L,recoverPublicKey:I,Signature:y,hash:t})}function U0(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp;let r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0;const o=$n(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),i={Fp:n,Fn:o,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:i}}function H0(e){const{CURVE:t,curveOpts:n}=U0(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function $0(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,rp(n.Fn.ORDER,n.Fn.BITS))})}function q0(e){const{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:o}=H0(e),i=F0(t,n),s=j0(i,r,o);return $0(e,s)}function K0(e,t){const n=r=>q0({...e,hash:r});return{...n(t),create:n}}const Dl={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},z0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},su=BigInt(2);function V0(e){const t=Dl.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,d=l*l*e%t,u=ke(d,n,t)*d%t,f=ke(u,n,t)*d%t,h=ke(f,su,t)*l%t,g=ke(h,o,t)*h%t,m=ke(g,i,t)*g%t,v=ke(m,a,t)*m%t,w=ke(v,c,t)*v%t,S=ke(w,a,t)*m%t,y=ke(S,n,t)*d%t,A=ke(y,s,t)*g%t,R=ke(A,r,t)*l%t,E=ke(R,su,t);if(!Sc.eql(Sc.sqr(E),e))throw new Error("Cannot find square root");return E}const Sc=$n(Dl.p,{sqrt:V0}),mn=K0({...Dl,Fp:Sc,lowS:!0,endo:z0},zh);function W0(e,t,n){const r=vl.digest(t instanceof Uint8Array?t:t.subarray());if(ks(r))return r.then(({digest:o})=>(n?.signal?.throwIfAborted(),mn.sign(o,e).toDERRawBytes())).catch(o=>{throw o.name==="AbortError"?o:new tu(String(o))});try{return mn.sign(r.digest,e).toDERRawBytes()}catch(o){throw new tu(String(o))}}function G0(e,t,n,r){const o=vl.digest(n instanceof Uint8Array?n:n.subarray());if(ks(o))return o.then(({digest:i})=>(r?.signal?.throwIfAborted(),mn.verify(t,i,e))).catch(i=>{throw i.name==="AbortError"?i:new nu(String(i))});try{return r?.signal?.throwIfAborted(),mn.verify(t,o.digest,e)}catch(i){throw new nu(String(i))}}class Tp{type="secp256k1";raw;_key;constructor(t){this._key=Q0(t),this.raw=Z0(this._key)}toMultihash(){return Uo.digest(Ps(this))}toCID(){return Ae.createV1(114,this.toMultihash())}toString(){return Ze.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,n,r){return G0(this._key,n,t,r)}}class X0{type="secp256k1";raw;publicKey;constructor(t,n){this.raw=J0(t),this.publicKey=new Tp(n??eS(t))}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}sign(t,n){return W0(this.raw,t,n)}}function Y0(e){return new X0(e)}function Pp(e){return new Tp(e)}function Z0(e){return mn.ProjectivePoint.fromHex(e).toRawBytes(!0)}function J0(e){try{return mn.getPublicKey(e,!0),e}catch(t){throw new Eh(String(t))}}function Q0(e){try{return mn.ProjectivePoint.fromHex(e),e}catch(t){throw new xh(String(t))}}function eS(e){try{return mn.getPublicKey(e,!0)}catch(t){throw new Eh(String(t))}}async function tS(e,t){return Kv()}function xc(e,t){const{Type:n,Data:r}=Fn.decode(e),o=r??new Uint8Array;switch(n){case Ce.RSA:return I0(o,t);case Ce.Ed25519:return pp(o);case Ce.secp256k1:return Pp(o);case Ce.ECDSA:return Fh(o);default:throw new Ss}}function nS(e){const{Type:t,Data:n}=Fn.decode(e.digest),r=n??new Uint8Array;switch(t){case Ce.Ed25519:return pp(r);case Ce.secp256k1:return Pp(r);case Ce.ECDSA:return Fh(r);default:throw new Ss}}function Ps(e){return Fn.encode({Type:Ce[e.type],Data:e.raw})}function rS(e){const t=Vi.decode(e),n=t.Data??new Uint8Array;switch(t.Type){case Ce.RSA:return C0(n);case Ce.Ed25519:return qv(n);case Ce.secp256k1:return Y0(n);case Ce.ECDSA:return Bb(n);default:throw new Ss}}function oS(e){return Vi.encode({Type:Ce[e.type],Data:e.raw})}const Np=Symbol.for("nodejs.util.inspect.custom"),iS=114;class _l{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ah]=!0;toString(){return this.string==null&&(this.string=Ze.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Ae.createV1(iS,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Et(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Et(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Np](){return`PeerId(${this.toString()})`}}class Lp extends _l{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}}class Bp extends _l{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}}class Dp extends _l{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}}const sS=2336;class _p{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Uo.digest(Le(this.url))}[Np](){return`PeerId(${this.url})`}[Ah]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Ae.createV1(sS,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=ue(t)),t.toString()===this.toString())}}const aS=114,au=2336;function cS(e,t){let n;if(e.charAt(0)==="1"||e.charAt(0)==="Q")n=Ih(Ze.decode(`z${e}`));else{if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return lS(Ae.parse(e));throw new xt('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return Op(n)}function Rr(e){if(e.type==="Ed25519")return new Bp({multihash:e.toCID().multihash,publicKey:e});if(e.type==="secp256k1")return new Dp({multihash:e.toCID().multihash,publicKey:e});if(e.type==="RSA")return new Lp({multihash:e.toCID().multihash,publicKey:e});throw new Ss}function Op(e){if(uS(e))return new Lp({multihash:e});if(dS(e))try{const t=nS(e);if(t.type==="Ed25519")return new Bp({multihash:e,publicKey:t});if(t.type==="secp256k1")return new Dp({multihash:e,publicKey:t})}catch{const n=ue(e.digest);return new _p(new URL(n))}throw new zw("Supplied PeerID Multihash is invalid")}function lS(e){if(e?.multihash==null||e.version==null||e.version===1&&e.code!==aS&&e.code!==au)throw new Kw("Supplied PeerID CID is invalid");if(e.code===au){const t=ue(e.multihash.digest);return new _p(new URL(t))}return Op(e.multihash)}function dS(e){return e.code===Uo.code}function uS(e){return e.code===vl.code}class Fp extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}}class fS extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}}class Vr extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}}class cu extends Error{static name="StreamBufferError";constructor(t="The stream buffer was full"){super(t),this.name="StreamBufferError"}}class hS extends Event{data;constructor(t,n){super("message",n),this.data=t}}class Ol extends Event{error;local;constructor(t,n,r){super("close",r),this.error=n,this.local=t}}class pS extends Ol{constructor(t,n){super(!0,t,n)}}class gS extends Ol{constructor(t,n){super(!1,t,n)}}const mS=e=>e/2**32|0,wS=e=>e>>>0;function yS(e,t,n,r){const o=mS(n),i=wS(n);e.setUint32(t,r?i:o,r),e.setUint32(t+4,r?o:i,r)}function Ec(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}const Ac=e=>e?`"${e}" `:"";function Qt(e,t=""){if(typeof e!="number")throw new TypeError(Ac(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Ac(t)+"expected integer >= 0, got "+e);return e}function en(e,t,n=""){if(Ec(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Qt(t,"length");const r=Ec(e),o=t!==void 0?` of length ${t}`:"",i=r?`length=${e.length}`:`type=${typeof e}`,s=Ac(n)+"expected Uint8Array"+o+", got "+i;throw r?new RangeError(s):new TypeError(s)}function Fl(e){if(typeof e!="function"||typeof e.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Qt(e.outputLen),Qt(e.blockLen),e.outputLen<1||e.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}const bS=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},lu=(e,t)=>{bS(e,t);const n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function Wi(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Mp(e,t){en(e,void 0,"output");const n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function VP(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Nn(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ca(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Tt(e,t){return e<<32-t|e>>>t}function WP(e,t){return e<<t|e>>>32-t>>>0}const vS=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function SS(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function xS(e){for(let t=0;t<e.length;t++)e[t]=SS(e[t]);return e}const GP=vS?e=>e:xS,jp=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ES=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ml(e){if(en(e),jp)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=ES[e[n]];return t}function du(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Up(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(jp)try{return Uint8Array.fromHex(e)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}const t=e.length,n=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){const s=du(e.charCodeAt(i)),a=du(e.charCodeAt(i+1));if(s===void 0||a===void 0){const c=e[i]+e[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a}return r}function AS(e){const t=globalThis;if(typeof t.scheduler?.yield=="function"){const n=t.scheduler.yield();return e&&n.catch(e),n}return new Promise(n=>t.setTimeout(n,0))}async function XP(e,t,n,r){if(Qt(e,"iters"),Qt(t,"tick"),typeof n!="function")throw new TypeError("callback must be a function");let o=Date.now();for(let i=0;i<e;i++){n(i);const s=Date.now()-o;s>=0&&s<t||(await AS(r),o=Date.now())}}function CS(e){if(typeof e!="string")throw new TypeError("string expected");const t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{Nn(t)}}function YP(e,t=""){return typeof e=="string"?CS(e):en(e,void 0,t)}function kS(e,t,n="opts"){return lu(e,"defaults"),t!==void 0&&lu(t,n),Object.assign(Object.create(null),e,t)}function IS(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=kS({},t,"info");const n=(o,i)=>e(i).update(o).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>e(o),Object.assign(n,t),Object.freeze(n)}function RS(e=32){Qt(e,"bytesLength");const t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}const TS=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function PS(e,t,n){return e&t^~e&n}function NS(e,t,n){return e&t^e&n^t&n}class LS{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,n,r,o){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(t),this.view=ca(this.buffer)}update(t){Wi(this),en(t);const{view:n,buffer:r,blockLen:o}=this,i=t.length;let s=!1;for(let a=0;a<i;){const c=Math.min(o-this.pos,i-a);if(c===o){const l=ca(t);for(;o<=i-a;a+=o)this.process(l,a);s=!0;continue}r.set(a===0&&c===i?t:t.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(n,0),this.pos=0,s=!0)}return this.length+=t.length,s&&this.roundClean(),this}digestInto(t){Wi(this),Mp(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:o,isLE:i}=this;let{pos:s}=this;n[s++]=128,n.fill(0,s),this.padOffset>o-s&&(this.process(r,0),n.fill(0)),yS(r,o-8,this.length*8,i),this.process(r,0),this.roundClean();const a=t===n?r:ca(t),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],i)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){const{buffer:n,length:r,finished:o,destroyed:i,pos:s}=this;return t.destroyed=i,t.finished=o,t.length=r,t.pos=s,s&&t.buffer.set(n),t}clone(){return this._cloneInto()}}const BS=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),DS=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]),an=new Uint32Array(64);class _S extends LS{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(t,n){super(64,t,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){const{A:t,B:n,C:r,D:o,E:i,F:s,G:a,H:c}=this;return[t,n,r,o,i,s,a,c]}set(t,n,r,o,i,s,a,c){this.A=t|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let u=0;u<16;u++,n+=4)an[u]=t.getUint32(n,!1);for(let u=16;u<64;u++){const f=an[u-15],h=an[u-2],g=Tt(f,7)^Tt(f,18)^f>>>3,m=Tt(h,17)^Tt(h,19)^h>>>10;an[u]=m+an[u-7]+g+an[u-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const f=Tt(a,6)^Tt(a,11)^Tt(a,25),h=d+f+PS(a,c,l)+DS[u]+an[u]|0,m=(Tt(r,2)^Tt(r,13)^Tt(r,22))+NS(r,o,i)|0;d=l,l=c,c=a,a=s+h|0,s=i,i=o,o=r,r=h+m|0}r=r+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,i,s,a,c,l,d)}roundClean(){Nn(an)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Nn(this.buffer)}}class OS extends _S{constructor(){super(32,BS)}}const la=IS(()=>new OS,TS(1));function Hp(e,t,n=()=>{}){if(!Array.isArray(e))throw new TypeError(`"${t}" expected array, got type=${typeof e}`);for(let r=0;r<e.length;r++)n(e[r],`${t}[${r}]`);return e}const mr=(e,t,n)=>en(e,t,n),$p=Qt;function wr(e,t="object"){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`);return e}function bo(e,t){if(typeof e!="function")throw new TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}const FS=Ml,MS=e=>Up(e),qp=Ec,Kp=e=>RS(e),Gi=BigInt(0),uu=BigInt(1),jS=e=>e?`"${e}" `:"";function Ns(e,t=""){if(typeof e!="boolean")throw new TypeError(jS(t)+"expected boolean, got type="+typeof e);return e}function US(e){if(typeof e=="bigint"){if(!Ln(e))throw new RangeError("positive bigint expected, got "+e)}else $p(e);return e}function Cc(e,t=""){if(typeof e!="number"){const n=t&&`"${t}" `;throw new TypeError(n+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){const n=t&&`"${t}" `;throw new RangeError(n+"expected safe integer, got "+e)}}function zp(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?Gi:BigInt("0x"+e)}function Vp(e){return zp(Ml(e))}function Xi(e){return zp(Ml(To(en(e)).reverse()))}function Wp(e,t){if(Qt(t),t===0)throw new Error("zero output length is invalid");e=US(e);const n=t*2,r=e.toString(16);if(r.length>n)throw new RangeError("number is too large");return Up(r.padStart(n,"0"))}function Gp(e,t){return Wp(e,t).reverse()}function To(e){return Uint8Array.from(mr(e))}function Ln(e){return typeof e=="bigint"&&Gi<=e}function Xp(e,t,n){return Ln(e)&&Ln(t)&&Ln(n)&&t<=e&&e<n}function vo(e,t,n,r){if(!Xp(t,n,r))throw new RangeError("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function HS(e){if(e<Gi)throw new Error("expected non-negative bigint, got "+e);return e===Gi?0:e.toString(2).length}const $S=e=>(Cc(e,"n"),(uu<<BigInt(e))-uu);function Yi(e,t={},n={},r="object"){wr(e,r),wr(t,"fields"),wr(n,"optFields");function o(s,a,c){const l=r==="object"?`param "${String(s)}"`:`"${r}.${String(s)}"`,d=e[s];if(!Object.hasOwn(e,s)&&(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 i=(s,a)=>Object.entries(s).forEach(([c,l])=>o(c,l,a));i(t,!1),i(n,!0)}const je=BigInt(0),Ee=BigInt(1),kn=BigInt(2),Yp=BigInt(3),jl=BigInt(4),Zp=BigInt(5),qS=BigInt(7),Jp=BigInt(8),KS=BigInt(9),zS=BigInt(15),Qp=BigInt(16),VS=BigInt("0x10000000000000000");function xe(e,t){if(t<=je)throw new Error("mod: expected positive modulus, got "+t);const n=e%t;return n>=je?n:t+n}function WS(e,t,n){if(n<=Ee)throw new Error("pow: expected modulus > 1, got "+n);if(typeof t!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof t);if(t<je)throw new Error("invalid exponent, negatives unsupported");if(t===je)return Ee;if(t===Ee)return e;let r=e%n;if(r<je&&(r+=n),t<VS){let a=Ee;for(;t>je;)t&Ee&&(a=a*r%n),r=r*r%n,t>>=Ee;return a}const o=[];for(;t>je;)o.push(Number(t&zS)),t>>=jl;const i=new Array(16);i[0]=Ee,i[1]=r;for(let a=2;a<16;a++)i[a]=i[a-1]*r%n;let s=i[o[o.length-1]];for(let a=o.length-2;a>=0;a--){s=s*s%n,s=s*s%n,s=s*s%n,s=s*s%n;const c=o[a];c!==0&&(s=s*i[c]%n)}return s}function wt(e,t,n){if(n<=Ee)throw new Error("pow2: expected modulus > 1, got "+n);if(t<je)throw new Error("pow2: expected non-negative exponent, got "+t);let r=e;for(;t-- >je;)r*=r,r%=n;return r}function fu(e,t){if(e===je)throw new Error("invert: expected non-zero number");if(t<=Ee)throw new Error("invert: expected modulus > 1, got "+t);let n=xe(e,t),r=t,o=je,i=Ee;for(;n!==je;){const a=r/n,c=r-n*a,l=o-i*a;r=n,n=c,o=i,i=l}if(r!==Ee)throw new Error("invert: does not exist");return xe(o,t)}function Ul(e,t,n){const r=e;if(!r.eql(r.sqr(t),n))throw new Error("Cannot find square root")}function Hl(e,t){if((e&Ee)===je)throw new Error(t+": expected odd modulus, got "+e)}function eg(e,t){const n=e,r=(n.ORDER+Ee)/jl,o=n.pow(t,r);return Ul(n,o,t),o}function GS(e,t){const n=e,r=(n.ORDER-Zp)/Jp,o=n.mul(t,kn),i=n.pow(o,r),s=n.mul(t,i),a=n.mul(n.mul(s,kn),i),c=n.mul(s,n.sub(a,n.ONE));return Ul(n,c,t),c}function XS(e){const t=$l(e),n=tg(e),r=n(t,t.neg(t.ONE)),o=n(t,r),i=n(t,t.neg(r)),s=(e+qS)/Qp;return((a,c)=>{const l=a;let d=l.pow(c,s),u=l.mul(d,r);const f=l.mul(d,o),h=l.mul(d,i),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 v=l.eql(l.sqr(u),c),w=l.cmov(d,u,v);return Ul(l,w,c),w})}function tg(e){if(e<Yp)throw new Error("sqrt is not defined for small field");Hl(e,"tonelliShanks");let t=e-Ee,n=0;for(;t%kn===je;)t/=kn,n++;let r=kn;const o=$l(e);for(;Zi(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return eg;let i=o.pow(r,t);const s=(t+Ee)/kn;return function(c,l){const d=c;if(d.is0(l))return l;if(Zi(d,l)!==1)throw new Error("Cannot find square root");let u=n,f=d.mul(d.ONE,i),h=d.pow(l,t),g=d.pow(l,s);for(;!d.eql(h,d.ONE);){if(d.is0(h))throw new Error("Cannot find square root: probably non-prime P");let m=1,v=d.sqr(h);for(;!d.eql(v,d.ONE);)if(m++,v=d.sqr(v),m===u)throw new Error("Cannot find square root");const w=Ee<<BigInt(u-m-1),S=d.pow(f,w);u=m,f=d.sqr(S),h=d.mul(h,f),g=d.mul(g,S)}return g}}function YS(e){return Hl(e,"Fp.sqrt"),e%jl===Yp?eg:e%Jp===Zp?GS:e%Qp===KS?XS(e):tg(e)}const ZS=(e,t)=>(xe(e,t)&Ee)===Ee,JS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Po(e){if(wr(e,"field"),typeof e.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof e.ORDER);Cc(e.BYTES,"BYTES"),Cc(e.BITS,"BITS");for(const t of JS)bo(e[t],"field."+t);if(e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=Ee)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function ng(e,t,n=!1){Po(e),Hp(t,"nums"),Ns(n,"passZero");const r=e,o=new Array(t.length).fill(n?r.ZERO:void 0),i=t.reduce((a,c,l)=>r.is0(c)?a:(o[l]=a,r.mul(a,c)),r.ONE),s=r.inv(i);return t.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),s),o}function Zi(e,t){Po(e);const n=e;Hl(n.ORDER,"FpLegendre");const r=(n.ORDER-Ee)/kn,o=n.pow(t,r),i=n.eql(o,n.ONE),s=n.eql(o,n.ZERO),a=n.eql(o,n.neg(n.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function QS(e,t){if(t!==void 0&&$p(t),e<=je)throw new Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);const n=HS(e);if(t!==void 0&&t<n)throw new Error(`invalid n length: expected nBitLength (${t}) >= bitLen(n) (${n})`);const r=t!==void 0?t:n,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}const hu=new WeakMap;class pu{ORDER;BITS;BYTES;isLE;ZERO=je;ONE=Ee;_lengths;_mod;constructor(t,n={}){if(t<=Ee)throw new Error("invalid field: expected ORDER > 1, got "+t);let r;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:n.sqrt,enumerable:!0}),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=Object.freeze(n.allowedLengths.slice())),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));const{nBitLength:o,nByteLength:i}=QS(t,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=i,Object.freeze(this)}create(t){return xe(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return je<=t&&t<this.ORDER}is0(t){return t===je}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&Ee)===Ee}neg(t){return xe(-t,this.ORDER)}eql(t,n){return t===n}sqr(t){return xe(t*t,this.ORDER)}add(t,n){return xe(t+n,this.ORDER)}sub(t,n){return xe(t-n,this.ORDER)}mul(t,n){return xe(t*n,this.ORDER)}pow(t,n){return WS(t,n,this.ORDER)}div(t,n){return xe(t*fu(n,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,n){return t+n}subN(t,n){return t-n}mulN(t,n){return t*n}inv(t){return fu(t,this.ORDER)}sqrt(t){let n=hu.get(this);return n||hu.set(this,n=YS(this.ORDER)),n(this,t)}toBytes(t){return this.isLE?Gp(t,this.BYTES):Wp(t,this.BYTES)}fromBytes(t,n=!1){mr(t);const{_lengths:r,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(r){if(t.length<1||!r.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+t.length);const l=new Uint8Array(o);l.set(t,i?0:l.length-t.length),t=l}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=i?Xi(t):Vp(t);if(a&&(c=xe(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return ng(this,t,!0)}cmov(t,n,r){return Ns(r,"condition"),r?n:t}}function $l(e,t={}){return Object.freeze(pu.prototype),new pu(e,t)}const ql=BigInt(0),No=BigInt(1),ex=BigInt(4),da=16,gu=128,tx=5,mu=2**31;function Kl(e){const t=e;if(typeof t!="function")throw new TypeError('"Point" expected constructor, got type='+typeof e);bo(t.fromAffine,"Point.fromAffine"),bo(t.fromBytes,"Point.fromBytes"),bo(t.fromHex,"Point.fromHex"),wr(t.BASE,"Point.BASE"),wr(t.ZERO,"Point.ZERO"),Po(t.Fp),Po(t.Fn)}function nx(e,t){Kl(e),rg(t,e);const n=ng(e.Fp,t.map(r=>r.Z));return t.map((r,o)=>e.fromAffine(r.toAffine(n[o])))}function rx(e,t,n=1){if(!Number.isSafeInteger(e)||e<n||e>t)throw new Error("invalid window size, expected ["+n+".."+t+"], got W="+e)}function ox(e,t){const n=e*(4*t+128);if(n>mu)throw new Error("invalid window size: table would need ~"+Math.ceil(n/2**20)+" MiB, max "+mu/2**20+" MiB")}function ix(e,t){if(e!==void 0){bo(e,"randomBytes");try{const n=e(t);if(!qp(n)||n.length!==t)return}catch{return}return e}}function rg(e,t){Hp(e,"points"),e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function sx(e,t,n){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,o)=>{if(!(n===void 0?t.isValid(r):Ln(r)&&r<n))throw new Error("invalid scalar at index "+o)})}const og=new WeakMap;function ua(e){return og.get(e)||1}function ax(e,t){const n=e.double(),r=[e];for(let o=1;o<t;o++)r.push(r[o-1].add(n));return r}function cx(e,t){const n=2**t,r=n/2,o=BigInt(n-1),i=[];for(;e>ql;){let s=0;e&No&&(s=Number(e&o),s>=r&&(s-=n),e-=BigInt(s)),i.push(s),e>>=No}return i}function lx(e,t,n){const r=2**t,o=r/2,i=BigInt(r-1),s=BigInt(t),a=[];for(let c=0;c<n;c++){let l=Number(e&i);e>>=s,l>o&&(l-=r,e+=No),a.push(l)}if(e!==ql)throw new Error("invalid wnaf");return a}function dx(e,t,n){let r=0;for(const i of n)r=Math.max(r,i.length);let o=e;for(let i=r-1;i>=0;i--){i!==r-1&&(o=o.double());for(let s=0;s<n.length;s++){const a=n[s][i];if(a){const c=t[s][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}class ux{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(t,n){Kl(t),this.randomBytes=ix(n,da),this.Point=t,this.BASE=t.BASE,this.ZERO=t.ZERO,this.bits=t.Fn.BITS}buildWnafTable(t,n,r){const o=Math.ceil(r/n)+1,i=2**(n-1),s=[];let a=t;for(let c=0;c<o;c++){let l=a;for(let d=0;d<i;d++)s.push(l),l=l.add(a);a=s[s.length-1].double()}return{W:n,bits:r,windows:o,comp:s}}wnafCachedCT(t,n){const{W:r,windows:o,comp:i}=t,s=2**(r-1),a=lx(n,r,o);let c=this.ZERO,l=this.BASE;for(let d=0;d<o;d++){const u=a[d],f=d*s,h=Math.abs(u)-1;let g=i[f];for(let v=1;v<s;v++)g=v===h?i[f+v]:g;const m=g.negate();u===0?l=l.add(i[f]):c=c.add(u<0?m:g)}return{p:c,f:l}}getWnafPrecomputes(t,n,r,o){let i=this.wnafPrecomputes.get(n),s=i?.find(a=>a.W===t&&a.bits===r);return s||(s=this.buildWnafTable(n,t,r),typeof o=="function"&&(s={...s,comp:o(s.comp)}),i||(i=[],this.wnafPrecomputes.set(n,i)),i.push(s)),s}assertPoint(t){if(!(t instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof t)}validateMulInput(t,n){if(this.assertPoint(t),!Xp(n,No,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(t,n,r,o){const i=ua(t);return i===1?this.fixedWindowCT(t,n,r):this.wnafCachedCT(this.getWnafPrecomputes(i,t,r,o),n)}mulCT(t,n,r){return this.validateMulInput(t,n),this.runCT(t,n,this.bits,r)}mulCTBlinded(t,n,r){if(this.validateMulInput(t,n),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");const o=this.Point.Fn.BITS+gu,i=this.randomBytes(da);if(!qp(i)||i.length!==da)throw new Error("randomBytes returned invalid byte array");i[0]=i[0]&63|128;const s=n+Vp(i)*this.Point.Fn.ORDER;return this.runCT(t,s,o,r)}fixedWindowCT(t,n,r){const o=tx,i=1<<o,s=$S(o),a=new Array(i);a[0]=this.ZERO;for(let d=1;d<i;d++)a[d]=a[d-1].add(t);const c=Math.ceil(r/o);let l=this.ZERO;for(let d=c-1;d>=0;d--){if(d!==c-1)for(let h=0;h<o;h++)l=l.double();const u=Number(n>>BigInt(d*o)&s);let f=a[0];for(let h=1;h<i;h++)f=h===u?a[h]:f;l=l.add(f)}return{p:l,f:l}}shouldBlind(t,n){return this.randomBytes===void 0?!1:n===No?!0:t!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(t,n,r,o){return this.shouldBlind(t,r)?this.mulCTBlinded(t,n,o):this.mulCT(t,n,o)}mulUnsafe(t,n,r){if(this.assertPoint(t),!Ln(n))throw new Error("invalid scalar");const o=ua(t);if(o===1||n>=this.Point.Fn.ORDER)return fx(this.Point,[t],[n],!0);const i=this.getWnafPrecomputes(o,t,this.bits,r);return this.wnafCachedCT(i,n).p}setWindowSize(t,n){this.assertPoint(t),rx(n,this.bits);const r=Math.ceil((this.bits+gu)/n)+1;ox(r*2**(n-1),this.Point.Fp.BYTES),og.set(t,n),this.wnafPrecomputes.delete(t)}hasWindowSize(t){return ua(t)!==1}}function fx(e,t,n,r=!1){if(Kl(e),rg(t,e),Ns(r,"allowOversized"),sx(n,e.Fn,r?e.Fn.ORDER**ex:void 0),t.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const o=t.map(s=>ax(s,4)),i=n.map(s=>cx(s,4));return dx(e.ZERO,o,i)}function wu(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Po(t),t}else return $l(e,{isLE:n})}function hx(e,t,n={},r){if(r===void 0&&(r=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);Yi(n);for(const c of["p","n","h"]){const l=t[c];if(!(Ln(l)&&l!==ql))throw new Error(`CURVE.${c} must be positive bigint`)}const o=wu(t.p,n.Fp,r),i=wu(t.n,n.Fn,r),a=["Gx","Gy","a","d"];for(const c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}function px(e,t){return function(r){const o=e(r);return{secretKey:o,publicKey:t(o)}}}const ri=BigInt(0),oi=BigInt(1),ii=BigInt(2),gx=BigInt(4),yu=BigInt(8);function mx(e,t,n,r){const o=e.sqr(n),i=e.sqr(r),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function wx(e,t={}){Yi(t,{},{},"extraOpts");const n=t,r=hx("edwards",e,n,n.FpFnLE),{Fp:o,Fn:i}=r;let s=r.CURVE;const{h:a}=s;if(Zi(o,s.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Zi(o,s.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Yi(n,{},{uvRatio:"function",randomBytes:"function"});const c=n.randomBytes===void 0?Kp:n.randomBytes,l=ii<<BigInt(o.BYTES*8)-oi;function d(S){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(S)}const u=n.uvRatio===void 0?(S,y)=>{try{return{isValid:!0,value:o.sqrt(o.div(S,y))}}catch{return{isValid:!1,value:ri}}}:n.uvRatio;if(!mx(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");const f=o.eql(s.a,o.neg(o.ONE))?S=>o.neg(S):o.eql(s.a,o.ONE)?S=>S:S=>o.mul(s.a,S);function h(S,y,A=!1){const R=A?oi:ri;return vo("coordinate "+S,y,R,l),y}function g(S){if(!(S instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(s.Gx,s.Gy,o.ONE,o.mul(s.Gx,s.Gy));static ZERO=new m(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=i;X;Y;Z;T;constructor(y,A,R,E){this.X=h("x",y),this.Y=h("y",A),this.Z=h("z",R,!0),this.T=h("t",E),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof m)throw new Error("extended point not allowed");const{x:A,y:R}=y||{};return h("x",A),h("y",R),new m(A,R,o.ONE,o.mul(A,R))}static fromBytes(y,A=!1){const R=o.BYTES,{a:E,d:C}=s;y=To(mr(y,R,"point")),Ns(A,"zip215");const k=To(y),b=y[R-1];k[R-1]=b&-129;const x=Xi(k),T=A?l:o.ORDER;vo("point.y",x,ri,T);const L=o.sqr(x),I=o.sub(L,o.ONE),P=o.sub(o.mulN(C,L),E);let{isValid:B,value:D}=u(I,P);if(!B)throw new Error("bad point: invalid y coordinate");const F=d(D),j=(b&128)!==0;if(!A&&o.is0(D)&&j)throw new Error("bad point: x=0 and x_0=1");return j!==F&&(D=o.neg(D)),m.fromAffine({x:D,y:x})}static fromHex(y,A=!1){return m.fromBytes(MS(y),A)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=6,A=!0){return w.setWindowSize(this,y),A||this.multiply(ii),this}assertValidity(){const y=this,{a:A,d:R}=s;if(y.is0())throw new Error("bad point: ZERO");const{X:E,Y:C,Z:k,T:b}=y,x=o.sqr(E),T=o.sqr(C),L=o.sqr(k),I=o.sqr(L),P=o.mul(x,A),B=o.mul(o.add(P,T),L),D=o.add(I,o.mul(R,o.mul(x,T)));if(!o.eql(B,D))throw new Error("bad point: equation left != right (1)");const F=o.mul(E,C),j=o.mul(k,b);if(!o.eql(F,j))throw new Error("bad point: equation left != right (2)")}equals(y){g(y);const{X:A,Y:R,Z:E}=this,{X:C,Y:k,Z:b}=y,x=o.mul(A,b),T=o.mul(C,E),L=o.mul(R,b),I=o.mul(k,E);return o.eql(x,T)&&o.eql(L,I)}is0(){return this.equals(m.ZERO)}negate(){return new m(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){const{X:y,Y:A,Z:R}=this,E=o.sqr(y),C=o.sqr(A),k=o.mul(o.sqr(R),ii),b=f(E),x=o.addN(y,A),T=o.sub(o.subN(o.sqr(x),E),C),L=o.addN(b,C),I=o.subN(L,k),P=o.subN(b,C),B=o.mul(T,I),D=o.mul(L,P),F=o.mul(T,P),j=o.mul(I,L);return new m(B,D,j,F)}add(y){g(y);const{d:A}=s,{X:R,Y:E,Z:C,T:k}=this,{X:b,Y:x,Z:T,T:L}=y,I=o.mul(R,b),P=o.mul(E,x),B=o.mul(o.mulN(k,A),L),D=o.mul(C,T),F=o.sub(o.subN(o.mulN(o.addN(R,E),o.addN(b,x)),I),P),j=o.subN(D,B),M=o.addN(D,B),U=o.sub(P,f(I)),_=o.mul(F,j),O=o.mul(M,U),H=o.mul(F,U),V=o.mul(j,M);return new m(_,O,V,H)}subtract(y){return g(y),this.add(y.negate())}multiply(y){if(!i.isValidNot0(y))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");const{p:A,f:R}=w.mulSecret(this,y,a,v);return v([A,R])[0]}multiplyUnsafe(y){if(!i.isValid(y))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return y===ri?m.ZERO:this.is0()||y===oi?this:w.mulUnsafe(this,y,v)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.mulUnsafe(this,s.n).is0()}toAffine(y){const A=this;let R=y;if(R!=null&&typeof R!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof R);const{X:E,Y:C,Z:k}=A,b=A.is0();R==null&&(R=b?o.create(yu):o.inv(k));const x=o.mul(E,R),T=o.mul(C,R),L=o.mul(k,R);if(b)return{x:o.ZERO,y:o.ONE};if(!o.eql(L,o.ONE))throw new Error("invZ was invalid");return{x,y:T}}clearCofactor(){return a===oi?this:a===ii?this.double():a===gx?this.double().double():a===yu?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){const{x:y,y:A}=this.toAffine(),R=o.toBytes(A);return R[R.length-1]|=d(y)?128:0,R}toHex(){return FS(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const v=S=>nx(m,S),w=new ux(m,c);return w.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}const vn=BigInt(0),pt=BigInt(1),si=BigInt(2);function bu(e,t){return e+t-(t>>pt<<pt)}function yx(e){const t=BigInt(6)*e;return(n,r,o)=>{const i=r+o,a=((t+o-r)*n+r)%e;return{x_2:a,x_3:i-a}}}function bx(e){return Yi(e,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...e})}function vx(e){const t=bx(e),{P:n,type:r,adjustScalarBytes:o,powPminus2:i,randomBytes:s}=t,a=t.scalarMultBase,c=r==="x25519";if(!c&&r!=="x448")throw new Error("invalid type");const l=s===void 0?Kp:s,d=c?255:448,u=yx(n),f=c?32:56,h=BigInt(c?9:5),g=BigInt(c?121665:39081),m=c?si**BigInt(254):si**BigInt(447),v=c?BigInt(8)*(si**BigInt(251)-pt):BigInt(4)*(si**BigInt(445)-pt),w=m+v+pt,S=D=>xe(D,n),y=A(h);function A(D){return Gp(S(D),f)}function R(D){const F=To(mr(D,f,"uCoordinate"));return c&&(F[31]&=127),S(Xi(F))}function E(D){return Xi(o(To(mr(D,f,"scalar"))))}const C=new Set(c?[vn,pt,n-pt,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[vn,pt,n-pt]);function k(D,F){const j=R(F);if(C.has(j))throw new Error("invalid private or public key received");const M=L(j,E(D));if(M===vn)throw new Error("invalid private or public key received");return A(M)}function b(D){if(a===void 0)return k(D,y);const F=E(D);vo("scalar",F,m,w);const j=S(a(F));if(j===vn)throw new Error("invalid private or public key received");return A(j)}const x=b,T=k;function L(D,F){vo("u",D,vn,n),vo("scalar",F,m,w);const j=F,M=D;let U=pt,_=vn,O=D,H=pt;const V=j^j>>pt;for(let X=BigInt(d-1);X>=vn;X--){const G=bu(n,V>>X);({x_2:U,x_3:O}=u(G,U,O)),{x_2:_,x_3:H}=u(G,_,H);const Y=U+_,ie=S(Y*Y),se=U-_,K=S(se*se),ne=ie-K,q=O+H,Z=O-H,oe=S(Z*Y),Q=S(q*se),ee=oe+Q,te=oe-Q;O=S(ee*ee),H=S(M*S(te*te)),U=S(ie*K),_=S(ne*(ie+S(g*ne)))}const z=bu(n,j);({x_2:U,x_3:O}=u(z,U,O)),{x_2:_,x_3:H}=u(z,_,H);const W=i(_);return S(U*W)}const I={secretKey:f,publicKey:f,seed:f},P=D=>(D=D===void 0?l(f):D,mr(D,I.seed,"seed"),D),B={randomSecretKey:P};return Object.freeze(I),Object.freeze(B),Object.freeze({keygen:px(P,x),getSharedSecret:T,getPublicKey:x,scalarMult:k,scalarMultBase:b,utils:B,GuBytes:y.slice(),lengths:I})}const vu=BigInt(0),Sx=BigInt(1),Su=BigInt(2),xx=BigInt(3),Ex=BigInt(5),Ax=BigInt(8),Ls=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Cx={p:Ls,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ax,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ig(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),o=BigInt(80),i=Ls,a=e*e%i*e%i,c=wt(a,Su,i)*a%i,l=wt(c,Sx,i)*e%i,d=wt(l,Ex,i)*l%i,u=wt(d,t,i)*d%i,f=wt(u,n,i)*u%i,h=wt(f,r,i)*f%i,g=wt(h,o,i)*h%i,m=wt(g,o,i)*h%i,v=wt(m,t,i)*d%i;return{pow_p_5_8:wt(v,Su,i)*e%i,b2:a}}function kx(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const xu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ix(e,t){const n=Ls,r=xe(t*t*t,n),o=xe(r*r*t,n),i=ig(e*o).pow_p_5_8;let s=xe(e*r*i,n);const a=xe(t*s*s,n),c=s,l=xe(s*xu,n),d=a===e,u=a===xe(-e,n),f=a===xe(-e*xu,n);return d&&(s=c),(u||f)&&(s=l),ZS(s,n)&&(s=xe(-s,n)),{isValid:d||u,value:s}}const Eu=wx(Cx,{uvRatio:Ix}),ai=(()=>{const e=Ls,t=n=>{const{pow_p_5_8:r,b2:o}=ig(n);return xe(wt(r,xx,e)*o,e)};return vx({P:e,type:"x25519",powPminus2:t,adjustScalarBytes:kx,scalarMultBase:n=>{const r=xe(n,Eu.Fn.ORDER);if(r===vu)return vu;const o=Eu.BASE.multiply(r);return xe((o.Z+o.Y)*t(xe(o.Z-o.Y,e)),e)}})})();class Au{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,n){if(Fl(t),en(n,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?t.create().update(n).digest():n);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=t.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Nn(o)}update(t){return Wi(this),this.iHash.update(t),this}digestInto(t){Wi(this),Mp(t,this),this.finished=!0;const n=t.subarray(0,this.outputLen);this.iHash.digestInto(n),this.oHash.update(n),this.oHash.digestInto(n),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});const{oHash:n,iHash:r,finished:o,destroyed:i,blockLen:s,outputLen:a,canXOF:c}=this;return t=t,t.finished=o,t.destroyed=i,t.blockLen=s,t.outputLen=a,t.canXOF=c,t.oHash=n._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const sg=(()=>{const e=((t,n,r)=>new Au(t,n).update(r).digest());return e.create=(t,n)=>new Au(t,n),e})();function Cu(){const e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}class ku{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){const t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}}class fa{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new ku(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){const n=this.head;this.head=n.next=new ku(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){const n=this.tail.next;this.tail.next=null,this.tail=n,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}}class Rx extends Error{type;code;constructor(t,n){super(t??"The operation was aborted"),this.type="aborted",this.code=n??"ABORT_ERR"}}function Tx(e={}){return Px(n=>{const r=n.shift();if(r==null)return{done:!0};if(r.error!=null)throw r.error;return{done:r.done===!0,value:r.value}},e)}function Px(e,t){t=t??{};let n=t.onEnd,r=new fa,o,i,s,a=Cu();const c=async()=>{try{return r.isEmpty()?s?{done:!0}:await new Promise((v,w)=>{i=S=>{i=null,r.push(S);try{v(e(r))}catch(y){w(y)}return o}}):e(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Cu()})}},l=v=>i!=null?i(v):(r.push(v),o),d=v=>(r=new fa,i!=null?i({error:v}):(r.push({error:v}),o)),u=v=>{if(s)return o;if(t?.objectMode!==!0&&v?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:v})},f=v=>s?o:(s=!0,v!=null?d(v):l({done:!0})),h=()=>(r=new fa,f(),{done:!0}),g=v=>(f(v),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:h,throw:g,push:u,end:f,get readableLength(){return r.size},onEmpty:async v=>{const w=v?.signal;if(w?.throwIfAborted(),r.isEmpty())return;let S,y;w!=null&&(S=new Promise((A,R)=>{y=()=>{R(new Rx)},w.addEventListener("abort",y)}));try{await Promise.race([a.promise,S])}finally{y!=null&&w!=null&&w?.removeEventListener("abort",y)}}},n==null)return o;const m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(v){return m.throw(v),n!=null&&(n(v),n=void 0),{done:!0}},return(){return m.return(),n!=null&&(n(),n=void 0),{done:!0}},push:u,end(v){return m.end(v),n!=null&&(n(v),n=void 0),o},get readableLength(){return m.readableLength},onEmpty:v=>m.onEmpty(v)},o}class zl extends Error{name="TimeoutError";constructor(t,n){super(t,n),Error.captureStackTrace?.(this,zl)}}const Iu=e=>e.reason??new DOMException("This operation was aborted.","AbortError");function Nx(e,t){const{milliseconds:n,fallback:r,message:o,customTimers:i={setTimeout,clearTimeout},signal:s}=t;let a,c;const d=new Promise((u,f)=>{if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(s?.aborted){f(Iu(s));return}if(s&&(c=()=>{f(Iu(s))},s.addEventListener("abort",c,{once:!0})),e.then(u,f),n===Number.POSITIVE_INFINITY)return;const h=new zl;a=i.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){f(g)}return}typeof e.cancel=="function"&&e.cancel(),o===!1?u():o instanceof Error?f(o):(h.message=o??`Promise timed out after ${n} milliseconds`,f(h))},n)}).finally(()=>{d.clear(),c&&s&&s.removeEventListener("abort",c)});return d.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},d}const Lx=e=>{const t=e.addEventListener||e.on||e.addListener,n=e.removeEventListener||e.off||e.removeListener;if(!t||!n)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:n.bind(e)}};function Bx(e,t,n){let r;const o=new Promise((i,s)=>{if(n={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...n},!(n.count>=0&&(n.count===Number.POSITIVE_INFINITY||Number.isInteger(n.count))))throw new TypeError("The `count` option should be at least 0 or more");n.signal?.throwIfAborted();const a=[t].flat(),c=[],{addListener:l,removeListener:d}=Lx(e),u=async(...h)=>{const g=n.multiArgs?h:h[0];if(n.filter)try{if(!await n.filter(g))return}catch(m){r(),s(m);return}c.push(g),n.count===c.length&&(r(),i(c))},f=(...h)=>{r(),s(n.rejectionMultiArgs?h:h[0])};r=()=>{for(const h of a)d(h,u);for(const h of n.rejectionEvents)a.includes(h)||d(h,f)};for(const h of a)l(h,u);for(const h of n.rejectionEvents)a.includes(h)||l(h,f);n.signal&&n.signal.addEventListener("abort",()=>{f(n.signal.reason)},{once:!0}),n.resolveImmediately&&i(c)});if(o.cancel=r,typeof n.timeout=="number"){const i=Nx(o,{milliseconds:n.timeout});return i.cancel=()=>{r(),i.clear()},i}return o}function Dx(e,t,n){typeof n=="function"&&(n={filter:n}),n={...n,count:1,resolveImmediately:!1};const r=Bx(e,t,n),o=r.then(i=>i[0]);return o.cancel=r.cancel,o}class Ji extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}class _x extends Error{static name="StreamClosedError";name="StreamClosedError"}function Ox(e){return e.reason}function ag(e,t,n){if(t==null||e==null)return e;const r=Ox;if(t.aborted)return e.catch(()=>{}),Promise.reject(r(t));let o;return Promise.race([e,new Promise((i,s)=>{o=()=>{s(r(t))},t.addEventListener("abort",o)})]).finally(()=>{o!=null&&t.removeEventListener("abort",o)})}const Fx=Math.pow(2,20)*4;class cg extends Xw{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(t){super(),this.status="open",this.log=t.log,this.direction=t.direction??"outbound",this.inactivityTimeout=t.inactivityTimeout??12e4,this.maxReadBufferLength=t.maxReadBufferLength??Fx,this.maxWriteBufferLength=t.maxWriteBufferLength,this.maxMessageSize=t.maxMessageSize,this.readBuffer=new ye,this.writeBuffer=new ye,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);const n=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",n);const r=o=>{this.onDrainPromise?.reject(o.error??new _x)};this.addEventListener("close",r)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(t){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),ag(this.onDrainPromise.promise,t?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;const t=Tx(),n=i=>{t.push(i.data)};this.addEventListener("message",n);const r=i=>{t.end(i.error)};this.addEventListener("close",r);const o=()=>{t.end()};this.addEventListener("remoteCloseWrite",o);try{yield*t}finally{this.removeEventListener("message",n),this.removeEventListener("close",r),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(t){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new Vr(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",t.byteLength),this.writeBuffer.append(t),this.processSendQueue()}abort(t){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",t),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(t)}catch(n){this.log("failed to send reset to remote - %e",n)}this.dispatchEvent(new pS(t))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Vr("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 Vr("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Vr(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.append(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Vr(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.prepend(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(t){if(t.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(t),this.dispatchReadBuffer()}}addEventListener(...t){super.addEventListener.apply(this,t),t[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 t=new fS;this.dispatchEvent(new gS(t))}onTransportClosed(t){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"),t!=null?this.abort(t):(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 Ol))}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 t=!0;const n=this.writeBuffer.byteLength;let r=0;for(;this.writeBuffer.byteLength>0;){const o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){t=!1;break}const i=this.writeBuffer.sublist(0,o),s=new ye(i);this.writeBuffer.consume(i.byteLength);const a=this.sendData(i);if(t=a.canSendMore,r+=a.sentBytes,a.sentBytes!==s.byteLength&&(s.consume(a.sentBytes),this.writeBuffer.prepend(s)),!t)break}return t||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",r,n,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),t}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 t=this.readBuffer.sublist();this.readBuffer.consume(t.byteLength),this.dispatchEvent(new hS(t))}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 cu(`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 cu(`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 Mx=4194304;class Ru extends Error{static name="UnwrappedError";name="UnwrappedError"}class lg extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class jx extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class Ux extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function Hx(e){return typeof e?.closeRead=="function"}function $x(e){return typeof e?.close=="function"}function ha(e){return Hx(e)?e.remoteWriteStatus!=="writable"&&e.readBufferLength===0:$x(e)?e.status!=="open":!1}function qx(e){return e?.addEventListener!=null&&e?.removeEventListener!=null&&e?.send!=null&&e?.push!=null&&e?.log!=null}function Kx(e,t){const n=t?.maxBufferSize??Mx,r=new ye;let o,i=!1;if(!qx(e))throw new Fp("Argument should be a Stream or a Multiaddr");const s=d=>{if(r.append(d.data),r.byteLength>n){const u=r.byteLength;r.consume(r.byteLength),o?.reject(new Error(`Read buffer overflow - ${u} > ${n}`))}o?.resolve()};e.addEventListener("message",s);const a=d=>{d.error!=null?o?.reject(d.error):o?.resolve()};e.addEventListener("close",a);const c=()=>{o?.resolve()};e.addEventListener("remoteCloseWrite",c);const l={readBuffer:r,async read(d){if(i===!0)throw new Ru("Stream was unwrapped");if(ha(e)){if(d?.bytes==null)return null;if(r.byteLength<d.bytes)throw e.log.error("closed after reading %d/%d bytes",r.byteLength,d.bytes),new Ji(`Unexpected EOF - stream closed after reading ${r.byteLength}/${d.bytes} bytes`)}const u=d?.bytes??1;for(o=Promise.withResolvers();;){if(r.byteLength>=u){o.resolve();break}if(await ag(o.promise,d?.signal),ha(e)){if(r.byteLength===0&&d?.bytes==null)return null;break}o=Promise.withResolvers()}const f=d?.bytes??r.byteLength;if(r.byteLength<f){if(ha(e))throw e.log.error("closed while reading %d/%d bytes",r.byteLength,f),new Ji(`Unexpected EOF - stream closed while reading ${r.byteLength}/${f} bytes`);return l.read(d)}const h=r.sublist(0,f);return r.consume(f),h},async write(d,u){if(i===!0)throw new Ru("Stream was unwrapped");e.send(d)||await Dx(e,"drain",{signal:u?.signal,rejectionEvents:["close"]})},unwrap(){return i||(i=!0,e.removeEventListener("message",s),e.removeEventListener("close",a),e.removeEventListener("remoteCloseWrite",c),r.byteLength>0&&(e.log("stream unwrapped with %d unread bytes",r.byteLength),e.push(r))),e}};return l}function Tu(e,t={}){const n=Kx(e,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=qn(t.maxDataLength));const r=t?.lengthDecoder??wp,o=t?.lengthEncoder??Yv;return{async read(s){let a=-1;const c=new ye;for(;;){const d=await n.read({...s,bytes:1});if(d==null)break;c.append(d);try{a=r(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new lg("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ux(`Message length length too long - ${c.byteLength} > ${t.maxLengthLength}`);if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new jx(`Message length too long - ${a} > ${t.maxDataLength}`);const l=await n.read({...s,bytes:a});if(l==null)throw e.log.error("tried to read %d bytes but the stream closed",a),new Ji(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw e.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Ji(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(s,a){await n.write(new ye(o(s.byteLength),s),a)},async writeV(s,a){const c=new ye(...s.flatMap(l=>[o(l.byteLength),l]));await n.write(c,a)},unwrap(){return n.unwrap()}}}const zx=1024*1024*4,Vx=1024*1024*4;class Wx{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(t={}){this.buffer=new ye,this.maxBufferSize=t.maxBufferSize??zx,this.maxDataLength=t.maxDataLength??Vx,this.lengthDecoder=t.lengthDecoder??wp,this.encodingLength=t.encodingLength??qn}*decode(t){if(this.buffer.append(t),this.buffer.byteLength>this.maxBufferSize)throw new Fp(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let n;try{n=this.lengthDecoder(this.buffer)}catch(i){if(i instanceof RangeError)break;throw i}if(n<0||n>this.maxDataLength)throw new lg("Invalid message length");const r=this.encodingLength(n),o=r+n;if(this.buffer.byteLength>=o){const i=this.buffer.sublist(r,o);this.buffer.consume(o),i.byteLength>0&&(yield i)}else break}}}var Gx={};const Lo=65535,Pu=Lo-16,zo=!!Gx?.DUMP_SESSION_KEYS,Nu=16;function kc(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}const Qi=e=>e?`"${e}" `:"";function Ic(e,t=""){if(typeof e!="boolean")throw new TypeError(Qi(t)+"expected boolean, got type="+typeof e);return e}function yr(e,t=""){if(typeof e!="number")throw new TypeError(Qi(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Qi(t)+"expected integer >= 0, got "+e);return e}function Me(e,t,n=""){if(kc(e)&&(t===void 0||e.length===t))return e;t!==void 0&&yr(t,"length");const r=kc(e),o=t!==void 0?` of length ${t}`:"",i=r?`length=${e.length}`:`type=${typeof e}`,s=Qi(n)+"expected Uint8Array"+o+", got "+i;throw r?new RangeError(s):new TypeError(s)}const Lu=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`)};function Bu(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Xx(e,t){Me(e,void 0,"output");const n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function Vt(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function gn(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Yx(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}const br=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Zx(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Jx(e){for(let t=0;t<e.length;t++)e[t]=Zx(e[t]);return e}const In=br?e=>e:Jx;function Qx(e,t){return!e.byteLength||!t.byteLength?!1:e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function eE(e,t){if(Qx(e,t)&&e.byteOffset<t.byteOffset)throw new Error("complex overlap of input and output is not supported")}function tE(e,t){return Lu(e,"defaults"),Lu(t,"opts"),Object.assign(e,t)}function nE(e,t){if(e=Me(e),t=Me(t),e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function rE(e,t,n){const r=t,o=(()=>[]),i=(a,c)=>r(c,...o(a)).update(a).digest(),s=r(new Uint8Array(e),...o(new Uint8Array(0)));return i.outputLen=s.outputLen,i.blockLen=s.blockLen,i.create=(a,...c)=>r(a,...c),i}const oE=(e,t)=>{function n(r,...o){if(Me(r,void 0,"key"),e.nonceLength!==void 0){const u=o[0];Me(u,e.varSizeNonce?void 0:e.nonceLength,"nonce")}const i=e.tagLength,s=e.nonceLength!==void 0?1:0;if(!e.withAAD){for(let u=s;u<o.length;u++)if(kc(o[u]))throw new Error("AAD not supported")}e.withAAD&&o[s]!==void 0&&Me(o[s],void 0,"AAD");const a=t(r,...o),c=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");Me(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,Me(u,void 0,"data"),c(a.encrypt.length,f),a.encrypt(u,f)},decrypt(u,f){if(Me(u,void 0,"data"),i&&u.length<i)throw new Error('"ciphertext" expected length >= tagLength='+i);return c(a.decrypt.length,f),a.decrypt(u,f)}}}return Object.assign(n,e),n};function Rc(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(Me(t,e,"output"),n&&!es(t))throw new Error("invalid output, must be aligned");return t}function iE(e,t,n){yr(e),yr(t),Ic(n);const r=new Uint8Array(16),o=Yx(r);return o.setBigUint64(0,BigInt(t),n),o.setBigUint64(8,BigInt(e),n),r}function es(e){return e.byteOffset%4===0}function ts(e){return Uint8Array.from(Me(e))}const dg=e=>Uint8Array.from(e.split(""),t=>t.charCodeAt(0)),sE=In(Vt(dg("expand 16-byte k"))),aE=In(Vt(dg("expand 32-byte k")));function fe(e,t){return e<<t|e>>>32-t}const Wr=64,cE=16,Tc=2**32-1,Du=Uint32Array.of();function lE(e,t,n,r,o,i,s,a){const c=o.length,l=new Uint8Array(Wr),d=Vt(l),u=br&&es(o)&&es(i),f=u?Vt(o):Du,h=u?Vt(i):Du;if(!br){for(let g=0;g<c;s++){if(e(t,n,r,d,s,a),In(d),s>=Tc)throw new Error("arx: counter overflow");const m=Math.min(Wr,c-g);for(let v=0,w;v<m;v++)w=g+v,i[w]=o[w]^l[v];g+=m}return}for(let g=0;g<c;s++){if(e(t,n,r,d,s,a),s>=Tc)throw new Error("arx: counter overflow");const m=Math.min(Wr,c-g);if(u&&m===Wr){const v=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let w=0,S;w<cE;w++)S=v+w,h[S]=f[S]^d[w];g+=Wr;continue}for(let v=0,w;v<m;v++)w=g+v,i[w]=o[w]^l[v];g+=m}}function dE(e,t){const{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:i,rounds:s}=tE({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return yr(o),yr(s),Ic(i),Ic(n),(a,c,l,d,u=0)=>{Me(a,void 0,"key"),Me(c,void 0,"nonce"),Me(l,void 0,"data");const f=l.length,h=d!==void 0;if(d=Rc(f,d,!1),h&&eE(l,d),yr(u),u<0||u>=Tc)throw new Error("arx: counter overflow");const g=[];let m=a.length,v,w;if(m===32)g.push(v=ts(a)),w=aE;else if(m===16&&n)v=new Uint8Array(32),v.set(a),v.set(a,16),w=sE,g.push(v);else throw Me(a,32,"arx key"),new Error("invalid key size");(!br||!es(c))&&g.push(c=ts(c));let S=Vt(v);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");const R=c.subarray(0,16);if(br)r(w,S,Vt(R),S);else{const E=In(Uint32Array.from(w));r(E,S,Vt(R),S),gn(E),In(S)}c=c.subarray(16)}else br||In(S);const y=16-o;if(y!==c.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){const R=new Uint8Array(12);R.set(c,i?0:12-c.length),c=R,g.push(c)}const A=In(Vt(c));try{return lE(e,w,S,A,l,d,u,s),d}finally{gn(...g)}}}function Ue(e,t){return e[t++]&255|(e[t++]&255)<<8}class uE{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(t){t=ts(Me(t,32,"key"));const n=Ue(t,0),r=Ue(t,2),o=Ue(t,4),i=Ue(t,6),s=Ue(t,8),a=Ue(t,10),c=Ue(t,12),l=Ue(t,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|i<<9)&8191,this.r[4]=(i>>>4|s<<12)&255,this.r[5]=s>>>1&8190,this.r[6]=(s>>>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]=Ue(t,16+2*d)}process(t,n,r=!1){const o=r?0:2048,{h:i,r:s}=this,a=s[0],c=s[1],l=s[2],d=s[3],u=s[4],f=s[5],h=s[6],g=s[7],m=s[8],v=s[9],w=Ue(t,n+0),S=Ue(t,n+2),y=Ue(t,n+4),A=Ue(t,n+6),R=Ue(t,n+8),E=Ue(t,n+10),C=Ue(t,n+12),k=Ue(t,n+14);let b=i[0]+(w&8191),x=i[1]+((w>>>13|S<<3)&8191),T=i[2]+((S>>>10|y<<6)&8191),L=i[3]+((y>>>7|A<<9)&8191),I=i[4]+((A>>>4|R<<12)&8191),P=i[5]+(R>>>1&8191),B=i[6]+((R>>>14|E<<2)&8191),D=i[7]+((E>>>11|C<<5)&8191),F=i[8]+((C>>>8|k<<8)&8191),j=i[9]+(k>>>5|o),M=0,U=M+b*a+x*(5*v)+T*(5*m)+L*(5*g)+I*(5*h);M=U>>>13,U&=8191,U+=P*(5*f)+B*(5*u)+D*(5*d)+F*(5*l)+j*(5*c),M+=U>>>13,U&=8191;let _=M+b*c+x*a+T*(5*v)+L*(5*m)+I*(5*g);M=_>>>13,_&=8191,_+=P*(5*h)+B*(5*f)+D*(5*u)+F*(5*d)+j*(5*l),M+=_>>>13,_&=8191;let O=M+b*l+x*c+T*a+L*(5*v)+I*(5*m);M=O>>>13,O&=8191,O+=P*(5*g)+B*(5*h)+D*(5*f)+F*(5*u)+j*(5*d),M+=O>>>13,O&=8191;let H=M+b*d+x*l+T*c+L*a+I*(5*v);M=H>>>13,H&=8191,H+=P*(5*m)+B*(5*g)+D*(5*h)+F*(5*f)+j*(5*u),M+=H>>>13,H&=8191;let V=M+b*u+x*d+T*l+L*c+I*a;M=V>>>13,V&=8191,V+=P*(5*v)+B*(5*m)+D*(5*g)+F*(5*h)+j*(5*f),M+=V>>>13,V&=8191;let z=M+b*f+x*u+T*d+L*l+I*c;M=z>>>13,z&=8191,z+=P*a+B*(5*v)+D*(5*m)+F*(5*g)+j*(5*h),M+=z>>>13,z&=8191;let W=M+b*h+x*f+T*u+L*d+I*l;M=W>>>13,W&=8191,W+=P*c+B*a+D*(5*v)+F*(5*m)+j*(5*g),M+=W>>>13,W&=8191;let X=M+b*g+x*h+T*f+L*u+I*d;M=X>>>13,X&=8191,X+=P*l+B*c+D*a+F*(5*v)+j*(5*m),M+=X>>>13,X&=8191;let G=M+b*m+x*g+T*h+L*f+I*u;M=G>>>13,G&=8191,G+=P*d+B*l+D*c+F*a+j*(5*v),M+=G>>>13,G&=8191;let Y=M+b*v+x*m+T*g+L*h+I*f;M=Y>>>13,Y&=8191,Y+=P*u+B*d+D*l+F*c+j*a,M+=Y>>>13,Y&=8191,M=(M<<2)+M|0,M=M+U|0,U=M&8191,M=M>>>13,_+=M,i[0]=U,i[1]=_,i[2]=O,i[3]=H,i[4]=V,i[5]=z,i[6]=W,i[7]=X,i[8]=G,i[9]=Y}finalize(){const{h:t,pad:n}=this,r=new Uint16Array(10);let o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,r[0]=t[0]+5,o=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=t[a]+o,o=r[a]>>>13,r[a]&=8191;r[9]-=8192;let i=(o^1)-1;for(let a=0;a<10;a++)r[a]&=i;i=~i;for(let a=0;a<10;a++)t[a]=t[a]&i|r[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let s=t[0]+n[0];t[0]=s&65535;for(let a=1;a<8;a++)s=(t[a]+n[a]|0)+(s>>>16)|0,t[a]=s&65535;gn(r)}update(t){Bu(this),Me(t),t=ts(t);const{buffer:n,blockLen:r}=this,o=t.length;for(let i=0;i<o;){const s=Math.min(r-this.pos,o-i);if(s===r){for(;r<=o-i;i+=r)this.process(t,i);continue}n.set(t.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,gn(this.h,this.r,this.buffer,this.pad)}digestInto(t){Bu(this),Xx(t,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:o}=this;if(o){for(n[o++]=1;o<16;o++)n[o]=0;this.process(n,0,!0)}this.finalize();let i=0;for(let s=0;s<8;s++)t[i++]=r[s]>>>0,t[i++]=r[s]>>>8}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}}const fE=rE(32,e=>new uE(e));function hE(e,t,n,r,o,i=20){let s=e[0],a=e[1],c=e[2],l=e[3],d=t[0],u=t[1],f=t[2],h=t[3],g=t[4],m=t[5],v=t[6],w=t[7],S=o,y=n[0],A=n[1],R=n[2],E=s,C=a,k=c,b=l,x=d,T=u,L=f,I=h,P=g,B=m,D=v,F=w,j=S,M=y,U=A,_=R;for(let H=0;H<i;H+=2)E=E+x|0,j=fe(j^E,16),P=P+j|0,x=fe(x^P,12),E=E+x|0,j=fe(j^E,8),P=P+j|0,x=fe(x^P,7),C=C+T|0,M=fe(M^C,16),B=B+M|0,T=fe(T^B,12),C=C+T|0,M=fe(M^C,8),B=B+M|0,T=fe(T^B,7),k=k+L|0,U=fe(U^k,16),D=D+U|0,L=fe(L^D,12),k=k+L|0,U=fe(U^k,8),D=D+U|0,L=fe(L^D,7),b=b+I|0,_=fe(_^b,16),F=F+_|0,I=fe(I^F,12),b=b+I|0,_=fe(_^b,8),F=F+_|0,I=fe(I^F,7),E=E+T|0,_=fe(_^E,16),D=D+_|0,T=fe(T^D,12),E=E+T|0,_=fe(_^E,8),D=D+_|0,T=fe(T^D,7),C=C+L|0,j=fe(j^C,16),F=F+j|0,L=fe(L^F,12),C=C+L|0,j=fe(j^C,8),F=F+j|0,L=fe(L^F,7),k=k+I|0,M=fe(M^k,16),P=P+M|0,I=fe(I^P,12),k=k+I|0,M=fe(M^k,8),P=P+M|0,I=fe(I^P,7),b=b+x|0,U=fe(U^b,16),B=B+U|0,x=fe(x^B,12),b=b+x|0,U=fe(U^b,8),B=B+U|0,x=fe(x^B,7);let O=0;r[O++]=s+E|0,r[O++]=a+C|0,r[O++]=c+k|0,r[O++]=l+b|0,r[O++]=d+x|0,r[O++]=u+T|0,r[O++]=f+L|0,r[O++]=h+I|0,r[O++]=g+P|0,r[O++]=m+B|0,r[O++]=v+D|0,r[O++]=w+F|0,r[O++]=S+j|0,r[O++]=y+M|0,r[O++]=A+U|0,r[O++]=R+_|0}const pE=dE(hE,{counterRight:!1,counterLength:4,allowShortKeys:!1}),gE=new Uint8Array(16),_u=(e,t)=>{e.update(t);const n=t.length%16;n&&e.update(gE.subarray(n))},mE=new Uint8Array(32);function Ou(e,t,n,r,o){o!==void 0&&Me(o,void 0,"AAD");const i=e(t,n,mE),s=iE(r.length,o?o.length:0,!0),a=fE.create(i);o&&_u(a,o),_u(a,r),a.update(s);const c=a.digest();return gn(i,s),c}const wE=e=>(t,n,r)=>({encrypt(i,s){const a=i.length;s=Rc(a+16,s,!1),s.set(i);const c=s.subarray(0,-16);e(t,n,c,c,1);const l=Ou(e,t,n,c,r);return s.set(l,a),gn(l),s},decrypt(i,s){s=Rc(i.length-16,s,!1);const a=i.subarray(0,-16),c=i.subarray(-16),l=Ou(e,t,n,a,r);if(!nE(c,l))throw gn(l),new Error("invalid tag");return s.set(i.subarray(0,-16)),e(t,n,s,s,1),gn(l),s}}),Fu=oE({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},wE(pE));function yE(e,t,n){return Fl(e),n===void 0&&(n=new Uint8Array(e.outputLen)),sg(e,n,t)}const Gr=Uint8Array.of(0),bE=Uint8Array.of();function vE(e,t,n,r=32,o){Fl(e),Qt(r,"length"),en(t,void 0,"prk");const i=e.outputLen;if(t.length<i)throw new Error('"prk" must be at least HashLen octets');if(r>255*i)throw new Error("Length must be <= 255*HashLen");const s=Math.ceil(r/i);if(n===void 0?n=bE:en(n,void 0,"info"),!s)return new Uint8Array;const a=new Uint8Array(s*i),{iHash:c,oHash:l}=sg.create(e,t),d=new Uint8Array(i),u=s>1?e.create():void 0;for(let h=0;h<s-1;h++){Gr[0]=h+1;const g=c._cloneInto(u);h&&g.update(d),g.update(n).update(Gr).digestInto(d),l._cloneInto(u).update(d).digestInto(d),a.set(d,i*h)}if(Gr[0]=s,s>1&&c.update(d),c.update(n).update(Gr).digestInto(d),l.update(d).digestInto(d),a.set(d,i*(s-1)),c.destroy(),l.destroy(),u?.destroy(),d!==a&&Nn(d),Nn(Gr),r===a.length)return a;const f=a.slice(0,r);return Nn(a),f}const ug={hashSHA256(e){return la(e.subarray())},getHKDF(e,t){const n=yE(la,t,e),o=vE(la,n,void 0,96),i=o.subarray(0,32),s=o.subarray(32,64),a=o.subarray(64,96);return[i,s,a]},generateX25519KeyPair(){const e=ai.utils.randomSecretKey();return{publicKey:ai.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed(e){return{publicKey:ai.getPublicKey(e),privateKey:e}},generateX25519SharedKey(e,t){return ai.getSharedSecret(e.subarray(),t.subarray())},chaCha20Poly1305Encrypt(e,t,n,r){return Fu(r,t,n).encrypt(e.subarray())},chaCha20Poly1305Decrypt(e,t,n,r,o){return Fu(r,t,n).decrypt(e.subarray(),o)}},SE=ug;function xE(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,n)=>e.generateX25519SharedKey(t.privateKey,n).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}const ns=e=>{const t=Zt(2);return t[0]=e>>8,t[1]=e,t};ns.bytes=2;const rs=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};rs.bytes=2;function EE(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function fg(e,t){!t.enabled||!zo||(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${ue(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${ue(e.privateKey,"hex")}`)):t("Missing local static keys."))}function hg(e,t){!t.enabled||!zo||(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${ue(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${ue(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function AE(e,t){!t.enabled||!zo||t(e?`REMOTE_STATIC_PUBLIC_KEY ${ue(e.subarray(),"hex")}`:"Missing remote static public key.")}function pg(e,t){!t.enabled||!zo||t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${ue(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function gg(e,t,n){!n.enabled||!zo||(n(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&ue(e.k,"hex")}`),n(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&ue(t.k,"hex")}`))}class So extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=So.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}const CE=0,kE=4294967295,IE="Cipherstate has reached maximum n, a new handshake must be performed";class RE{n;bytes;view;constructor(t=CE){this.n=t,this.bytes=nt(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>kE)throw new Error(IE)}}const vr=nt(0);class ci{k;n;crypto;constructor(t,n=void 0,r=0){this.crypto=t,this.k=n,this.n=new RE(r)}hasKey(){return!!this.k}encryptWithAd(t,n){if(!this.hasKey())return n;this.n.assertValue();const r=this.crypto.encrypt(n,this.n.getBytes(),t,this.k);return this.n.increment(),r}decryptWithAd(t,n,r){if(!this.hasKey())return n;this.n.assertValue();const o=this.crypto.decrypt(n,this.n.getBytes(),t,this.k,r);return this.n.increment(),o}}class TE{cs;ck;h;crypto;constructor(t,n){this.crypto=t;const r=Le(n,"utf-8");this.h=NE(t,r),this.ck=this.h,this.cs=new ci(t)}mixKey(t){const[n,r]=this.crypto.hkdf(this.ck,t);this.ck=n,this.cs=new ci(this.crypto,r)}mixHash(t){this.h=this.crypto.hash(new ye(this.h,t))}encryptAndHash(t){const n=this.cs.encryptWithAd(this.h,t);return this.mixHash(n),n}decryptAndHash(t){const n=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),n}split(){const[t,n]=this.crypto.hkdf(this.ck,vr);return[new ci(this.crypto,t),new ci(this.crypto,n)]}}class PE{ss;s;e;rs;re;initiator;crypto;constructor(t){const{crypto:n,protocolName:r,prologue:o,initiator:i,s,e:a,rs:c,re:l}=t;this.crypto=n,this.ss=new TE(n,r),this.ss.mixHash(o),this.initiator=i,this.s=s,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.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(t,n=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<n+32)throw new Error("message is not long enough");this.re=t.sublist(n,n+32),this.ss.mixHash(this.re)}readS(t,n=0){if(this.rs)throw new Error("remote static public key is already set");const r=32+(this.ss.cs.hasKey()?16:0);if(t.byteLength<n+r)throw new Error("message is not long enough");const o=t.sublist(n,n+r);return this.rs=this.ss.decryptAndHash(o),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class mg extends PE{writeMessageA(t){return new ye(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){const n=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new ye(n,r,this.ss.encryptAndHash(t))}writeMessageC(t){const n=this.writeS();return this.writeSE(),new ye(n,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(n){throw new So(`handshake stage 0 validation fail: ${n.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();const n=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+n))}catch(n){throw new So(`handshake stage 1 validation fail: ${n.message}`)}}readMessageC(t){try{const n=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(n))}catch(n){throw new So(`handshake stage 2 validation fail: ${n.message}`)}}}function NE(e,t){if(t.length<=32){const n=nt(32);return n.set(t),n}else return e.hash(t)}var os;(function(e){let t;e.codec=()=>(t==null&&(t=Ts((n,r,o={})=>{if(o.lengthDelimited!==!1&&r.fork(),n.webtransportCerthashes!=null)for(const i of n.webtransportCerthashes)r.uint32(10),r.bytes(i);if(n.streamMuxers!=null)for(const i of n.streamMuxers)r.uint32(18),r.string(i);o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const i={webtransportCerthashes:[],streamMuxers:[]},s=r==null?n.len:n.pos+r;for(;n.pos<s;){const a=n.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&i.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new ou('Decode error - map field "webtransportCerthashes" had too many elements');i.webtransportCerthashes.push(n.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&i.streamMuxers.length===o.limits.streamMuxers)throw new ou('Decode error - map field "streamMuxers" had too many elements');i.streamMuxers.push(n.string());break}default:{n.skipType(a&7);break}}}return i})),t),e.encode=n=>Rs(n,e.codec()),e.decode=(n,r)=>Is(n,e.codec(),r)})(os||(os={}));var is;(function(e){let t;e.codec=()=>(t==null&&(t=Ts((n,r,o={})=>{o.lengthDelimited!==!1&&r.fork(),n.identityKey!=null&&n.identityKey.byteLength>0&&(r.uint32(10),r.bytes(n.identityKey)),n.identitySig!=null&&n.identitySig.byteLength>0&&(r.uint32(18),r.bytes(n.identitySig)),n.extensions!=null&&(r.uint32(34),os.codec().encode(n.extensions,r)),o.lengthDelimited!==!1&&r.ldelim()},(n,r,o={})=>{const i={identityKey:nt(0),identitySig:nt(0)},s=r==null?n.len:n.pos+r;for(;n.pos<s;){const a=n.uint32();switch(a>>>3){case 1:{i.identityKey=n.bytes();break}case 2:{i.identitySig=n.bytes();break}case 4:{i.extensions=os.codec().decode(n,n.uint32(),{limits:o.limits?.extensions});break}default:{n.skipType(a&7);break}}}return i})),t),e.encode=n=>Rs(n,e.codec()),e.decode=(n,r)=>Is(n,e.codec(),r)})(is||(is={}));async function wg(e,t,n){const r=await e.sign(bg(t));return is.encode({identityKey:Ps(e.publicKey),identitySig:r,extensions:n})}async function yg(e,t,n){try{const r=is.decode(e),o=xc(r.identityKey);if(n?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${n}`);if(!t)throw new Error("Remote static does not exist");const i=bg(t);if(!await o.verify(i,r.identitySig))throw new Error("Invalid payload signature");return r}catch(r){throw new $w(r.message)}}function bg(e){const t=Le("noise-libp2p-static-key:");return e instanceof Uint8Array?uc([t,e],t.length+e.length):(e.prepend(t),e)}class LE extends cg{stream;handshake;metrics;decoder;constructor(t,n,r){super({log:t.log,inactivityTimeout:t.inactivityTimeout,maxReadBufferLength:t.maxReadBufferLength,direction:t.direction}),this.stream=t,this.handshake=n,this.metrics=r,this.decoder=new Wx({lengthDecoder:rs,maxBufferSize:16*1024*1024,encodingLength:()=>2});const o=c=>{try{for(const l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);const i=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",i);const s=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",s);const a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(t){const n=new ye;for(let r=0;r<t.byteLength;r+=Pu){let o=r+Pu;o>t.byteLength&&(o=t.byteLength);let i;t instanceof Uint8Array?i=this.handshake.encrypt(t.subarray(r,o)):i=this.handshake.encrypt(t.sublist(r,o)),this.metrics?.encryptedPackets.increment(),n.append(ns(i.byteLength)),n.append(i)}return n}decrypt(t){const n=new ye;for(let r=0;r<t.byteLength;r+=Lo){let o=r+Lo;if(o>t.byteLength&&(o=t.byteLength),o-Nu<r)throw new Error("Invalid chunk");let i;t instanceof Uint8Array?i=t.subarray(r,o):i=t.sublist(r,o);const s=t.subarray(r,o-Nu);try{const a=this.handshake.decrypt(i,s);this.metrics?.decryptedPackets.increment(),n.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return n}close(t){return this.stream.close(t)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(t){this.stream.abort(t)}sendData(t){return{sentBytes:t.byteLength,canSendMore:this.stream.send(this.encrypt(t))}}}function Mu(e,t,n){return new LE(e,t,n)}async function BE(e,t){const{log:n,connection:r,crypto:o,privateKey:i,prologue:s,s:a,remoteIdentityKey:c,extensions:l}=e,d=await wg(i,a.publicKey,l),u=new mg({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:s,s:a});fg(u.s,n),n.trace("Stage 0 - Initiator starting to send first message."),await r.write(u.writeMessageA(vr),t),n.trace("Stage 0 - Initiator finished sending first message."),hg(u.e,n),n.trace("Stage 1 - Initiator waiting to receive first message from responder...");const f=u.readMessageB(await r.read(t));n.trace("Stage 1 - Initiator received the message."),pg(u.re,n),AE(u.rs,n),n.trace("Initiator going to check remote's signature...");const h=await yg(f,u.rs,c);n.trace("All good with the signature!"),n.trace("Stage 2 - Initiator sending third handshake message."),await r.write(u.writeMessageC(d),t),n.trace("Stage 2 - Initiator sent message with signed payload.");const[g,m]=u.ss.split();return gg(g,m,n),{payload:h,encrypt:v=>g.encryptWithAd(vr,v),decrypt:(v,w)=>m.decryptWithAd(vr,v,w)}}async function DE(e,t){const{log:n,connection:r,crypto:o,privateKey:i,prologue:s,s:a,remoteIdentityKey:c,extensions:l}=e,d=await wg(i,a.publicKey,l),u=new mg({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:s,s:a});fg(u.s,n),n.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await r.read(t)),n.trace("Stage 0 - Responder received first message."),pg(u.re,n),n.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await r.write(u.writeMessageB(d),t),n.trace("Stage 1 - Responder sent the second handshake message with signed payload."),hg(u.e,n),n.trace("Stage 2 - Responder waiting for third handshake message...");const f=u.readMessageC(await r.read(t));n.trace("Stage 2 - Responder received the message, finished handshake.");const h=await yg(f,u.rs,c),[g,m]=u.ss.split();return gg(g,m,n),{payload:h,encrypt:v=>m.encryptWithAd(vr,v),decrypt:(v,w)=>g.decryptWithAd(vr,v,w)}}class _E{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(t,n={}){const{staticNoiseKey:r,extensions:o,crypto:i,prologueBytes:s}=n,{metrics:a}=t;this.components=t,this.log=t.logger.forComponent("libp2p:noise");const c=i??SE;this.crypto=xE(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?EE(a):void 0,r?this.staticKey=c.generateX25519KeyPairFromSeed(r):this.staticKey=c.generateX25519KeyPair(),this.prologue=s??nt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Yw]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,n){const r=t.log?.newScope("noise")??this.log,o=Tu(t,{lengthEncoder:ns,lengthDecoder:rs,maxDataLength:Lo}),i=await this.performHandshakeInitiator(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),s=xc(i.payload.identityKey);return{connection:Mu(o.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:Rr(s),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(i.payload.extensions?.streamMuxers)}}getStreamMuxer(t){if(t==null||t.length===0)return;const n=this.components.upgrader.getStreamMuxers();if(n!=null)for(const r of t){const o=n.get(r);if(o!=null)return o}if(t.length)throw new qw("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(t,n){const r=t.log?.newScope("noise")??this.log,o=Tu(t,{lengthEncoder:ns,lengthDecoder:rs,maxDataLength:Lo}),i=await this.performHandshakeResponder(o,this.components.privateKey,r,n?.remotePeer?.publicKey,n),s=xc(i.payload.identityKey);return{connection:Mu(o.unwrap(),i,this.metrics),remoteExtensions:i.payload.extensions,remotePeer:Rr(s),streamMuxer:n?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(i.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(t,n,r,o,i){let s;const a=i?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await BE({connection:t,privateKey:n,remoteIdentityKey:o,log:r.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},i),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return s}async performHandshakeResponder(t,n,r,o,i){let s;const a=i?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await DE({connection:t,privateKey:n,remoteIdentityKey:o,log:r.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},i),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return s}}function OE(e={}){return t=>new _E(t,e)}const FE="termdock-e2ee-v1",Pc=3600*1e3,ju=512*1024*1024,Nc=4*1024*1024,Si=()=>{},Bs=Object.assign(Si,{enabled:!1,error:Si,trace:Si,newScope:()=>Bs});Object.freeze(Bs);async function vg(){const e=await tS();return{privateKey:e,peerId:Rr(e.publicKey).toString()}}function ME(e){return btoa(String.fromCharCode(...oS(e.privateKey)))}function Uu(e){if(e.length>512||!/^[A-Za-z0-9+/]+={0,2}$/.test(e))throw new Error("Invalid identity encoding");const t=rS(Uint8Array.from(atob(e),n=>n.charCodeAt(0)));if(t.type!=="Ed25519")throw new Error("Only Ed25519 device identities are supported");return{privateKey:t,peerId:Rr(t.publicKey).toString()}}class Sg{constructor(t=Si){this.consumed=t}consumed;chunks=[];size=0;ended=!1;error;wake;push(t){if(this.ended)throw this.error??new Error("Byte stream closed");if(this.size+t.byteLength>Nc)throw new Error("Secure stream buffer limit exceeded");this.chunks.push(t.slice()),this.size+=t.byteLength,this.wake?.()}end(t){this.ended=!0,this.error??=t,this.wake?.()}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const t=this.chunks.shift();if(t)this.size-=t.byteLength,yield t,this.consumed();else{if(this.ended)return;await new Promise(n=>{this.wake=n})}}}}class jE extends cg{constructor(t,n){super({log:Bs,direction:n?"outbound":"inbound",maxReadBufferLength:Nc,maxWriteBufferLength:Nc}),this.duplex=t,this.finished=t.sink(this.outgoing).catch(r=>{this.abort(Tr(r))}),this.readTransport()}duplex;outgoing=new Sg(()=>this.onMuxerDrain());finished;async readTransport(){try{for await(const t of this.duplex.source)this.onData(t.slice());this.onTransportClosed()}catch(t){this.onTransportClosed(Tr(t))}}sendData(t){return this.outgoing.push(t.subarray()),{sentBytes:t.byteLength,canSendMore:!1}}sendReset(t){this.outgoing.end(t),this.duplex.close?.(t)}sendPause(){}sendResume(){}async close(){this.outgoing.end(),this.duplex.close?.(),this.onTransportClosed(),await this.finished}}function Tr(e){return e instanceof Error?e:new Error("Secure transport failed")}class UE extends Error{code="E2EE_REHANDSHAKE_REQUIRED";constructor(){super("Encrypted connection lifetime reached; establish a new handshake without replaying pending input")}}function HE(e){const t=e?.maxAgeMs??Pc,n=e?.maxBytesPerDirection??ju;if(!Number.isSafeInteger(t)||t<=0||t>Pc||!Number.isSafeInteger(n)||n<=0||n>ju)throw new Error("Encrypted connection limits cannot exceed the production maximum");return{maxAgeMs:t,maxBytesPerDirection:n}}async function $E(e){const{identity:t,duplex:n,initiator:r,targetPinnedPeerId:o,signal:i}=e,s=HE(e.limits);if(typeof Reflect.get(Promise,"withResolvers")!="function"||typeof globalThis.crypto?.getRandomValues!="function")throw new Error("End-to-end encryption requires Node.js 22+ or a modern browser with Promise.withResolvers and secure random support");if(r&&!o)throw new Error("A pinned target identity is required");const a=o?cS(o):void 0;if(a&&a.type!=="Ed25519")throw new Error("Only Ed25519 target identities are supported");if(t.peerId!==Rr(t.privateKey.publicKey).toString())throw new Error("Local identity mismatch");if(i?.aborted)throw i.reason??new Error("Connection aborted");const c=new jE(n,r),l=new AbortController,d=setTimeout(()=>{const h=new Error("Encrypted handshake timed out");l.abort(h),c.abort(h)},15e3),u=()=>{l.abort(i?.reason),c.abort(Tr(i?.reason))};i?.addEventListener("abort",u,{once:!0}),c.addEventListener("close",()=>i?.removeEventListener("abort",u),{once:!0});const f=OE({crypto:ug,prologueBytes:new TextEncoder().encode(FE)})({privateKey:t.privateKey,peerId:Rr(t.privateKey.publicKey),logger:{forComponent:()=>Bs},upgrader:{getStreamMuxers:()=>new Map}});try{const h=await(r?f.secureOutbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}):f.secureInbound(c,{remotePeer:a,signal:l.signal,skipStreamMuxerNegotiation:!0}));if(h.remotePeer.type!=="Ed25519")throw new Error("Unsupported remote identity");return{authenticatedPeerId:h.remotePeer.toString(),duplex:qE(h.connection,s)}}catch(h){throw c.abort(Tr(h)),h}finally{clearTimeout(d),i?.removeEventListener("abort",u)}}function qE(e,t){const n=new Sg,r=performance.now(),o=Date.now();let i=0,s=0,a;const c=()=>(a??=new UE,n.end(a),e.abort(a),a),l=setTimeout(c,t.maxAgeMs);typeof l=="object"&&l.unref?.();const d=(f,h)=>{if(a)throw a;if(Math.max(performance.now()-r,Date.now()-o)>=t.maxAgeMs||f+h>=t.maxBytesPerDirection)throw c()};e.addEventListener("message",f=>{try{d(s,f.data.byteLength),s+=f.data.byteLength,n.push(f.data.subarray())}catch(h){e.abort(Tr(h))}}),e.addEventListener("close",f=>{clearTimeout(l),n.end(f.error)},{once:!0});let u=!1;return{source:n,async sink(f){if(u)throw new Error("Secure sink already consumed");u=!0;try{for await(const h of f)d(i,h.byteLength),i+=h.byteLength,e.send(h)||await e.onDrain()}catch(h){throw e.abort(Tr(h)),h}},close(f){f?e.abort(f):e.close()}}}const xg=1012,Eg="Encrypted transport renewed";class Vl{constructor(t=64){this.limit=t}limit;items=[];wake;ended=!1;error;tryPush(t){if(this.ended)throw new Error("Channel closed");return this.items.length>=this.limit?!1:(this.items.push(t),this.wake?.(),!0)}push(t){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(t),this.wake?.()}get size(){return this.items.length}end(t){this.ended=!0,this.error??=t,this.wake?.()}clear(){this.items.length=0}async*[Symbol.asyncIterator](){for(;;){if(this.error)throw this.error;const t=this.items.shift();if(t!==void 0){yield t;continue}if(this.ended)return;await new Promise(n=>{this.wake=n}),this.wake=void 0}}}class pa extends Error{code="PACKET_QUEUE_BACKPRESSURE";constructor(t="Record queue capacity exceeded"){super(t),this.name="PacketQueueBackpressureError"}}const xi=2*1024*1024,KE=xi*2+8,Hu=64*1024,zE=new TextEncoder,VE=new TextDecoder("utf-8",{fatal:!0});class WE{constructor(t){this.duplex=t;const n=this;this.done=t.sink((async function*(){for await(const r of n.outgoing)try{yield r.bytes}finally{n.releaseQueuedPacket(r)}})()),this.done.then(()=>this.discardPending(),r=>this.discardPending(r instanceof Error?r:new Error("Transport failed")))}duplex;outgoing=new Vl(256);outgoingBytes=0;queuedBytesById=new Map;closed=!1;get hasPendingWrites(){return this.outgoingBytes>0}queuedBytesFor(t){return this.queuedBytesById.get(t)??0}done;send(t){if(this.outgoing.size>=256)throw new pa("Record queue item limit exceeded");const n=zE.encode(JSON.stringify(t));if(n.length>xi)throw new Error("Record too large");const r=new Uint8Array(n.length+4);if(new DataView(r.buffer).setUint32(0,n.length),r.set(n,4),this.outgoingBytes+r.byteLength>4*1024*1024)throw new pa("Record queue byte budget exceeded");const o={id:t.id,bytes:r};if(!this.outgoing.tryPush(o))throw new pa("Record queue item limit exceeded");this.outgoingBytes+=r.byteLength,this.queuedBytesById.set(t.id,this.queuedBytesFor(t.id)+r.byteLength)}releaseQueuedPacket(t){this.outgoingBytes=Math.max(0,this.outgoingBytes-t.bytes.byteLength);const n=this.queuedBytesById.get(t.id);if(n===void 0)return;const r=n-t.bytes.byteLength;r>0?this.queuedBytesById.set(t.id,r):this.queuedBytesById.delete(t.id)}close(t){this.discardPending(t)}abort(t){this.discardPending(t)}discardPending(t){this.closed||(this.closed=!0,this.outgoing.clear(),this.outgoing.end(t),this.outgoingBytes=0,this.queuedBytesById.clear(),this.duplex.close?.(t))}async*read(){const t=[];let n=0,r=0,o;const i=d=>{const u=JSON.parse(VE.decode(d.subarray(4)));if(!u||typeof u!="object"||typeof u.id!="string"||typeof u.type!="string")throw new Error("Invalid record");return u},s=d=>{let u=0;for(;u<d.byteLength;){let f=t[t.length-1];(!f||f.end===f.bytes.byteLength)&&(f={bytes:o??new Uint8Array(Hu),start:0,end:0},o=void 0,t.push(f));const h=Math.min(d.byteLength-u,f.bytes.byteLength-f.end);f.bytes.set(d.subarray(u,u+h),f.end),f.end+=h,u+=h}r+=d.byteLength},a=d=>{let u=n,f=d;for(;u<t.length;){const h=t[u];if(!h){u++;continue}const g=h.end-h.start;if(f<g)return h.bytes[h.start+f];f-=g,u++}throw new Error("Incomplete record header")},c=d=>{for(r-=d;d>0;){const u=t[n];if(!u){n++;continue}const f=Math.min(d,u.end-u.start);u.start+=f,d-=f,u.start===u.end&&(!o&&u.bytes.byteLength===Hu&&(o=u.bytes),t[n]=void 0,n++)}r===0?(t.length=0,n=0,o=void 0):n>=64&&n*2>=t.length&&(t.splice(0,n),n=0)},l=d=>{const u=t[n];if(!u)throw new Error("Incomplete record body");if(u.end-u.start>=d){const v=u.bytes.subarray(u.start,u.start+d);return c(d),v}const h=new Uint8Array(d);let g=n,m=0;for(;m<d;){const v=t[g];if(!v){g++;continue}const w=Math.min(d-m,v.end-v.start);h.set(v.bytes.subarray(v.start,v.start+w),m),m+=w,g++}return c(d),h};for await(const d of this.duplex.source){if(r+d.byteLength>KE)throw new Error("Record buffer exceeded");if(r===0&&d.byteLength>=5){const u=d[0]*16777216+(d[1]<<16)+(d[2]<<8)+d[3]>>>0;if(u>xi||u===0)throw new Error("Invalid record size");if(d.byteLength===u+4){yield i(d);continue}}for(d.byteLength&&s(d);r>=4;){const u=a(0)*16777216+(a(1)<<16)+(a(2)<<8)+a(3)>>>0;if(u>xi||u===0)throw new Error("Invalid record size");if(r<u+4)break;const f=l(u+4);yield i(f)}}if(r)throw new Error("Truncated record")}}function Ag(e){let t="";for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return btoa(t)}function Cg(e){const t=atob(e);return Uint8Array.from(t,n=>n.charCodeAt(0))}function GE(e){const t=new Vl(64);e.binaryType="arraybuffer";const n=r=>{t.end(r),e.close(1e3)};return e.addEventListener("message",r=>{try{if(!(r.data instanceof ArrayBuffer)||r.data.byteLength>1024*1024)throw new Error("Invalid encrypted frame");t.push(new Uint8Array(r.data))}catch{n(new Error("Encrypted transport rejected frame"))}}),e.addEventListener("close",()=>t.end()),e.addEventListener("error",()=>t.end(new Error("Encrypted transport disconnected"))),{source:t,close:n,async sink(r){try{for await(const o of r)for(let i=0;i<o.length;i+=64*1024){const s=Date.now();for(;e.bufferedAmount>256*1024;){if(e.readyState!==1||Date.now()-s>15e3)throw new Error("Encrypted transport congested");await new Promise(a=>setTimeout(a,10))}if(e.readyState!==1)throw new Error("Encrypted transport closed");e.send(o.subarray(i,i+64*1024))}}catch(o){throw n(o instanceof Error?o:new Error("Encrypted transport failed")),o}}}}const XE=5*1024*1024,YE=bh+yh+8,ZE=256,li=3e4,Xr=64*1024;function dn(e){return e instanceof Error?e:new Error(String(e??"Secure connection closed"))}function $u(e){if(!e.startsWith("/")||e.startsWith("//")||e.includes("#"))throw new Error("A local API path is required");return e}class kg extends EventTarget{constructor(t,n,r){super(),this.url=t,this.transmit=n,this.disconnect=r}url;transmit;disconnect;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;binaryType="arraybuffer";bufferedAmount=0;protocol="termdock-e2ee-v1";extensions="";getConnectionDiagnostics;createdAt=performance.now();openedAfterMs;readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;send(t){if(this.readyState!==1)throw new Error("Secure socket is not open");if(typeof t!="string"||new TextEncoder().encode(t).length>1024*1024)throw new Error("Unsupported socket payload");this.transmit(t)}close(t=1e3,n=""){this.readyState!==3&&(this.disconnect(),this.finish(t,n))}accept(t){if(this.readyState!==3)if(t.type==="ws-ready"){this.openedAfterMs=performance.now()-this.createdAt,this.readyState=1;const n=new Event("open");this.dispatchEvent(n),this.onopen?.(n)}else if(t.type==="ws-data"&&typeof t.data=="string"){const n=new MessageEvent("message",{data:t.data});this.dispatchEvent(n),this.onmessage?.(n)}else t.type==="ws-close"?this.finish(typeof t.code=="number"?t.code:1e3,typeof t.reason=="string"?t.reason:""):t.type==="error"&&this.fail(dn(t.error))}fail(t){if(this.readyState===3)return;const n=new Event("error");this.dispatchEvent(n),this.onerror?.(n),this.finish(1006,t.message)}finish(t,n){if(this.readyState===3)return;this.readyState=3;const r=new CloseEvent("close",{code:t,reason:n,wasClean:t===1e3});this.dispatchEvent(r),this.onclose?.(r)}}class JE{constructor(t,n,r){this.channel=t,this.identity=n,this.targetPeerId=r,this.read().catch(o=>this.close(dn(o))),t.done.catch(o=>this.close(dn(o)))}channel;identity;targetPeerId;transportDiagnostics;establishedAt=performance.now();establishedWallTime=Date.now();lastInputAt=-1/0;pending=new Map;waiting=[];stopped=!1;closeReason;get canSwitchTransport(){return!this.channel.hasPendingWrites&&performance.now()-this.lastInputAt>=2e3&&![...this.pending.values()].some(t=>t.kind!=="socket")&&!this.waiting.some(t=>t.kind!=="socket")}get renewalDue(){return!this.stopped&&Math.max(performance.now()-this.establishedAt,Date.now()-this.establishedWallTime)>=Pc-5*6e4}get closed(){return this.stopped}hasCapacity(t){if(this.pending.size>=YE)return!1;const n=[...this.pending.values()].filter(r=>r.kind===t).length;return t==="http"?n<yh:t==="socket"?n<bh:!0}allocate(t){if(this.stopped)throw this.closeReason??new Error("Secure connection closed");const n=crypto.randomUUID(),r=new Vl(4);return this.pending.set(n,{queue:r,kind:t}),{id:n,queue:r}}reserve(t,n){return n?.aborted?Promise.reject(n.reason):this.stopped?Promise.reject(this.closeReason??new Error("Secure connection closed")):this.hasCapacity(t)?Promise.resolve(this.allocate(t)):this.waiting.length>=ZE?Promise.reject(new Error("连接繁忙,请稍后重试。")):new Promise((r,o)=>{const i=l=>{this.waiting=this.waiting.filter(d=>d!==c),c.cleanup(),o(l)},s=()=>i(n?.reason??new Error("Request aborted")),a=setTimeout(()=>i(new Error("连接等待超时,请重试。")),li),c={kind:t,resolve:r,reject:o,cleanup:()=>{clearTimeout(a),n?.removeEventListener("abort",s)}};this.waiting.push(c),n?.addEventListener("abort",s,{once:!0})})}dispatchWaiting(){if(!this.stopped)for(let t=0;t<this.waiting.length;){const n=this.waiting[t];if(!this.hasCapacity(n.kind)){t++;continue}this.waiting.splice(t,1),n.cleanup(),n.resolve(this.allocate(n.kind))}}async read(){try{for await(const t of this.channel.read()){const n=this.pending.get(t.id);n&&(n.socket?(n.socket.accept(t),(t.type==="ws-close"||t.type==="error")&&this.release(t.id)):(n.queue.push(t),(t.type==="end"||t.type==="error")&&(n.cancelUpload?.(),this.release(t.id))))}}finally{this.close(new Error("Secure connection closed"))}}release(t){this.pending.get(t)?.queue.end(),this.pending.delete(t),this.dispatchWaiting()}async request(t,n){const{id:r,queue:o}=await this.reserve("request"),i=setTimeout(()=>this.close(new Error("Secure connection timed out")),Math.max(1e3,Math.min(li,n?.timeoutMs??li)));try{if(this.stopped)throw this.closeReason;this.channel.send({...t,id:r});const s=(await o[Symbol.asyncIterator]().next()).value;if(!s)throw new Error("Secure request closed");if(s.type==="error")throw dn(s.error);return s}finally{clearTimeout(i),this.release(r)}}openSocket(t){$u(t);let n;const r=new AbortController,o=new kg(t,s=>{if(n){try{JSON.parse(s)?.type==="input"&&(this.lastInputAt=performance.now())}catch{}this.channel.send({id:n,type:"ws-data",data:s})}},()=>{if(r.abort(),n)try{this.channel.send({id:n,type:"ws-close"})}finally{this.release(n)}});let i;return o.getConnectionDiagnostics=()=>{const s=this.transportDiagnostics?.();return s?{...s,socketOpenMs:o.openedAfterMs,socketQueueMs:i,pendingWrites:this.channel.hasPendingWrites,activeRequests:[...this.pending.values()].filter(a=>a.kind!=="socket").length,waitingRequests:this.waiting.length}:void 0},this.reserve("socket",r.signal).then(s=>{if(i=performance.now()-o.createdAt,n=s.id,o.readyState===3){this.release(n);return}const a=this.pending.get(n);if(!a)throw new Error("Secure connection closed");a.socket=o,this.channel.send({id:n,type:"ws-open",path:t})}).catch(s=>{n&&this.release(n),o.fail(dn(s))}),o}async fetch(t,n){const r=typeof location>"u"?"https://termdock.invalid":location.origin,o=t instanceof Request?t:null,i=new URL(o?.url??String(t),r);if(i.origin!==r)throw new Error("Only current-service API requests are supported");const s=new Request(i,o?new Request(o,n):n),a=s.method.toUpperCase(),c=$u(i.pathname+i.search),l=i.pathname==="/api/terminal/fs/upload"?110*1024*1024:XE;if(s.signal.aborted)throw s.signal.reason;const d={};s.headers.forEach((A,R)=>{["cookie","authorization","host","connection","content-length"].includes(R)||(d[R]=A)});const{id:u,queue:f}=await this.reserve("http",s.signal),h=f[Symbol.asyncIterator]();let g;const m=()=>{g?.cancel().catch(()=>{})},v=this.pending.get(u);if(!v)throw new Error("Secure connection closed");v.cancelUpload=m;const w=()=>{m();try{this.channel.send({id:u,type:"cancel"})}catch{}f.end(dn(s.signal.reason??"Request aborted")),this.release(u)};s.signal.addEventListener("abort",w,{once:!0});const S=()=>{s.signal.removeEventListener("abort",w),this.release(u)},y=async()=>{let A;try{const R=(await Promise.race([h.next(),new Promise((E,C)=>{A=setTimeout(()=>C(new Error("服务响应超时,请重试。")),li)})])).value;if(!R)throw new Error("Secure response ended unexpectedly");if(R.type==="error")throw dn(R.error);return R}finally{clearTimeout(A)}};try{if(s.signal.aborted)throw s.signal.reason;if(this.channel.send({id:u,type:"http",method:a,path:c,headers:d}),s.body){const k=s.body.getReader();g=k;let b=0,x=0;try{for(;;){const{done:T,value:L}=await k.read();if(T)break;if(b+=L.byteLength,b>l)throw new Error("Request body exceeds upload limit");for(let I=0;I<L.byteLength;I+=Xr){if(this.channel.send({id:u,type:"upload",data:Ag(L.subarray(I,I+Xr))}),(await y()).type!=="upload-ack")throw new Error("Invalid upload acknowledgement");x+=Math.min(Xr,L.byteLength-I),n?.onUploadProgress?.(x)}}}catch(T){throw await k.cancel(T).catch(()=>{}),T}finally{g=void 0,k.releaseLock()}}if(s.signal.aborted||this.stopped)throw new Error("Request aborted");this.channel.send({id:u,type:"upload-end"});const A=await y();if(A.type!=="head"||typeof A.status!="number")throw new Error("Invalid response header");const R=new Headers(A.headers);if(a==="HEAD"||[204,205,304].includes(A.status)){if((await y()).type!=="end")throw new Error("Unexpected response body");return S(),new Response(null,{status:A.status,headers:R})}let E=!1;const C=new ReadableStream({pull:async k=>{try{E&&(this.channel.send({id:u,type:"ack"}),E=!1);const b=await y();if(b.type==="end"){k.close(),S();return}if(b.type!=="chunk"||typeof b.data!="string")throw new Error("Invalid response chunk");const x=Cg(b.data);if(x.length>Xr)throw new Error("Response chunk exceeds budget");k.enqueue(x),E=!0}catch(b){k.error(b),w(),S()}},cancel:()=>{w(),S()}},{highWaterMark:Xr,size:k=>k.byteLength});return new Response(C,{status:A.status,headers:R})}catch(A){throw w(),S(),A}}retire(){for(const t of this.pending.values())t.socket?.accept({id:"",type:"ws-close",code:xg,reason:Eg});this.close()}close(t=new Error("Secure connection closed")){if(!this.stopped){this.stopped=!0,this.closeReason=t;for(const n of this.waiting.splice(0))n.cleanup(),n.reject(t);for(const n of this.pending.values())n.queue.end(t),n.cancelUpload?.(),n.socket?.fail(t);this.pending.clear(),this.channel.close(t)}}}async function Mn(e){const t=new URL(e.url);if(!["wss:","ws:"].includes(t.protocol))throw new Error("A WebSocket endpoint is required");if(t.protocol==="ws:"&&!["127.0.0.1","localhost","[::1]"].includes(t.hostname))throw new Error("Remote secure channels require WSS");const n=e.identity??await vg(),r=performance.now(),o=(e.socketFactory??(l=>new WebSocket(l)))(t.href),i=GE(o),s=new AbortController,a=setTimeout(()=>s.abort(new Error("Secure handshake timed out")),2e4),c=e.signal?AbortSignal.any([e.signal,s.signal]):s.signal;try{await new Promise((m,v)=>{if(c.aborted){v(c.reason);return}const w=()=>{c.removeEventListener("abort",A),o.removeEventListener("open",S),o.removeEventListener("error",y),o.removeEventListener("close",y)},S=()=>{w(),m()},y=()=>{w(),v(new Error("Secure transport unavailable"))},A=()=>{w(),v(c.reason)};c.addEventListener("abort",A,{once:!0}),o.addEventListener("open",S),o.addEventListener("error",y),o.addEventListener("close",y),o.readyState===1&&S()});const l=performance.now(),d=await $E({identity:n,duplex:i,initiator:!0,targetPinnedPeerId:e.targetPeerId,signal:c}),u=new JE(new WE(d.duplex),n,d.authenticatedPeerId),f=performance.now(),h=Date.now(),g=o.connectionTimings;if(u.transportDiagnostics=()=>({endpoint:t.host,path:g?"relay":"direct",targetPeerId:d.authenticatedPeerId,transportOpenMs:l-r,handshakeMs:f-l,establishedAt:h,relay:g?{...g}:void 0,bufferedBytes:o.bufferedAmount,pendingWrites:!1,activeRequests:0,waitingRequests:0}),e.pairingCode)try{await u.request({type:"pair",code:e.pairingCode})}catch(m){throw u.close(dn(m)),m}return u}catch(l){throw o.close(),l}finally{clearTimeout(a)}}const qu=256*1024,QE=1024*1024;class e1 extends EventTarget{constructor(t,n,r=o=>new WebSocket(o)){if(super(),this.url=t,!/^[a-zA-Z0-9_.:-]{1,160}$/.test(n))throw new Error("Invalid target identity");const o=performance.now();let i;this.upstream=r(t),this.upstream.addEventListener("open",()=>{this.connectionTimings.entryOpenMs=performance.now()-o}),this.deadline=setTimeout(()=>this.fail("Relay connection timed out"),ml),this.upstream.addEventListener("message",s=>{if(this.readyState!==3)try{if(typeof s.data!="string"||new TextEncoder().encode(s.data).length>qu)throw new Error("Invalid relay envelope");const a=JSON.parse(s.data);if(a.type==="ready"&&!this.requested){i=performance.now(),this.requested=!0,this.transmit({type:"open",streamId:this.streamId,serviceId:n});return}if(a.streamId!==this.streamId)return;if(a.type==="opened"&&this.readyState===0){this.connectionTimings.routeOpenMs=i===void 0?null:performance.now()-i,clearTimeout(this.deadline),this.readyState=1;const u=new Event("open");this.dispatchEvent(u),this.onopen?.(u);return}if(a.type==="close"){this.finish(1001,"Relay route closed"),this.upstream.close();return}if(a.type!=="data"||this.readyState!==1||a.encoding!=="base64"||typeof a.payload!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(a.payload))throw new Error("Invalid ciphertext relay frame");const c=Cg(a.payload),l=this.binaryType==="blob"?new Blob([c]):c.buffer,d=new MessageEvent("message",{data:l});this.dispatchEvent(d),this.onmessage?.(d)}catch{this.fail("Relay protocol rejected frame")}}),this.upstream.addEventListener("close",s=>this.finish(s.code||1006,"Relay disconnected")),this.upstream.addEventListener("error",()=>this.fail("Relay transport unavailable"))}url;CONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3;protocol="";extensions="";binaryType="arraybuffer";readyState=0;onopen=null;onmessage=null;onerror=null;onclose=null;connectionTimings={entryOpenMs:null,routeOpenMs:null};upstream;streamId=crypto.randomUUID();requested=!1;deadline;get bufferedAmount(){return this.upstream.bufferedAmount}transmit(t){const n=JSON.stringify(t);if(this.upstream.readyState!==1||this.upstream.bufferedAmount+n.length>QE||n.length>qu)throw new Error("Relay unavailable or congested");this.upstream.send(n)}send(t){if(this.readyState!==1)throw new Error("Relay socket is not open");let n;if(ArrayBuffer.isView(t))n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);else if(t instanceof ArrayBuffer)n=new Uint8Array(t);else throw new Error("Relay secure transport requires binary bytes");try{this.transmit({type:"data",streamId:this.streamId,encoding:"base64",payload:Ag(n)})}catch(r){throw this.fail("Relay transport congested"),r}}close(t=1e3,n=""){if(this.readyState!==3){try{this.requested&&this.transmit({type:"close",streamId:this.streamId})}catch{}this.finish(t,n),this.upstream.close()}}fail(t){if(this.readyState===3)return;const n=new Event("error");this.dispatchEvent(n),this.onerror?.(n),this.finish(1006,t),this.upstream.close()}finish(t,n){if(this.readyState===3)return;clearTimeout(this.deadline),this.readyState=3;const r=new CloseEvent("close",{code:t,reason:n,wasClean:t===1e3});this.dispatchEvent(r),this.onclose?.(r)}}function Ig(e){return t=>new e1(t,e)}function t1(e){if(typeof e!="string"||!e.startsWith("/api/")||/[\\\x00-\x20\x7f#]/.test(e))return null;const t=e.split("?")[0];if(t.includes("//"))return null;try{const r=t.split("/").map((o,i)=>{if(i===0||o===""&&i===t.split("/").length-1)return o;const s=decodeURIComponent(o);if(!s||s==="."||s===".."||/[\\/\x00-\x1f\x7f]/.test(s)||/%[a-f0-9]{2}/i.test(s))throw new Error("Ambiguous API path");return s}).join("/");return r.endsWith("/")&&!r.startsWith("/api/terminal/fs/preview/")?null:r}catch{return null}}function n1(e){if(!("serviceWorker"in navigator))return()=>{};const t=new Set,n=r=>{if(r.source!==navigator.serviceWorker.controller||r.data?.type!=="termdock-secure-fetch"||r.ports.length!==1)return;const o=r.ports[0],{path:i,method:s,headers:a,body:c,expectedTargetPeerId:l,previewPrefix:d}=r.data;let u;try{u=new URL(i,location.origin)}catch{o.close();return}if(u.origin!==location.origin||!u.pathname.startsWith("/api/")||t.size>=32||typeof s!="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(s)||!t1(u.pathname)?.startsWith(d))){o.postMessage({type:"error"}),o.close();return}const f=new AbortController;let h,g,m=!1,v=!1;const w=()=>{v||(v=!0,t.delete(w),f.abort(),h?.cancel().catch(()=>{}),o.close())};t.add(w),o.onmessage=S=>{if(S.data?.type==="cancel"){w();return}S.data?.type!=="pull"||m||v||(m=!0,(async()=>{if(!h){o.postMessage({type:"end"}),w();return}if(!g?.length){const A=await h.read();if(A.done){o.postMessage({type:"end"}),w();return}g=A.value}const y=g.slice(0,64*1024);g=g.subarray(y.length),o.postMessage({type:"chunk",data:y.buffer},[y.buffer])})().catch(()=>{o.postMessage({type:"error"}),w()}).finally(()=>{m=!1}))},o.onmessageerror=w,o.start(),(async()=>{const S=await e();if(v)return;if(l&&l!==S.targetPeerId)throw new Error("Preview target changed");const y=await S.fetch(u.pathname+u.search,{method:s,headers:a,body:["GET","HEAD"].includes(s)?void 0:c,signal:f.signal});if(v){await y.body?.cancel();return}h=y.body?.getReader();const A={};y.headers.forEach((R,E)=>{A[E]=R}),o.postMessage({type:"head",status:y.status,headers:A,bodyless:!h,targetPeerId:S.targetPeerId})})().catch(()=>{v||(o.postMessage({type:"error"}),w())})};return navigator.serviceWorker.addEventListener("message",n),()=>{navigator.serviceWorker.removeEventListener("message",n);for(const r of[...t])r()}}class ut extends Error{constructor(){super("Device authorization expired or revoked")}}const di=new WeakMap;function Fr(e,t={}){const n=di.get(e);if(!e.closed&&n&&(!n.settled||Date.now()-n.at<(t.maxAgeMs??1e3)))return n.pending;const r={at:Date.now(),settled:!1,pending:void 0},o=r1(e,t.timeoutMs??5e3).then(i=>(r.at=Date.now(),r.settled=!0,i),i=>{throw di.get(e)===r&&di.delete(e),i});return r.pending=o,di.set(e,r),o}async function r1(e,t){const n=await e.request({type:"permissions"},{timeoutMs:t});if(n.type!=="result"||typeof n.fullService!="boolean"||!Array.isArray(n.grants))throw new Error("Invalid permission response");const r=n.grants,o=n.fullService===!0;if(!o&&r.length===0)throw new ut;return{fullService:o,grants:r,canManage:o&&r.length>0||r.some(i=>i.actions.includes("authorization.manage"))}}const Rg="termdock-secure-last-path:",o1=10*6e4;function Tg(e){try{const t=JSON.parse(sessionStorage.getItem(Rg+e)||"null");return t&&typeof t.key=="string"&&Date.now()-t.at<o1?t.key:void 0}catch{return}}function Lc(e,t){try{sessionStorage.setItem(Rg+e,JSON.stringify({key:t,at:Date.now()}))}catch{}}function Pg(e,t,n=!1){return new Promise((r,o)=>{let i=0,s=0,a=!1,c,l,d;const u=new Set,f=()=>{clearTimeout(d);for(const g of u)g.abort();u.clear()},h=()=>{if(a)return;if(i>=e.length){s||(a=!0,f(),o(l||c||new Error("没有可用的连接路线。")));return}if(s>=(n?1:2))return;const g=e[i++],m=performance.now(),v=S=>{performance.getEntriesByName("termdock:connection-path").length>64&&performance.clearMeasures("termdock:connection-path"),performance.measure("termdock:connection-path",{start:m,end:performance.now(),detail:{path:g.key.startsWith("relay:")?"relay":"direct",ok:S}})},w=new AbortController;u.add(w),s++,g.run(w.signal).then(S=>{if(v(!0),u.delete(w),a){t(S);return}a=!0,f(),r({value:S,key:g.key})},S=>{if(v(!1),u.delete(w),s--,!a){if(c=S,S instanceof Error&&S.name==="UnexpectedPeerError"&&(l=S),S instanceof ut){a=!0,f(),o(S);return}h()}}),clearTimeout(d),!n&&i<e.length&&(d=setTimeout(h,400))};h()})}const i1=3,s1=1/0,a1=10,Ng="termdock-secure-workspace-limit";function Lg(e){return e===1/0||Number.isInteger(e)&&e>=3&&e<=a1}function c1(){try{const e=localStorage.getItem(Ng),t=e==="unlimited"?1/0:Number(e);if(Lg(t))return t}catch{}return navigator.maxTouchPoints>0?i1:s1}function l1(e,t,n,r){if(e.length<=r)return e;const o=new Set(["root",t,...n?[n]:[]]),i=[...e].reverse().sort((s,a)=>a.touchedAt-s.touchedAt);for(const s of i){if(o.size>=r)break;o.add(s.key)}return e.filter(s=>o.has(s.key))}const Bg="termdock-workspace",Bo="termdock:workspace-visibility",Bc="termdock:workspace-activate";function Ds(){return window.parent!==window&&location.pathname==="/workspace.html"&&new URLSearchParams(location.search).get(Bg)||"root"}let Ku,zu;function Bt(){try{if(window.parent===window)return window.__termdockWorkspaceHost;const e=window.parent.__termdockWorkspaceHost;return e&&e!==Ku&&(Ku=e,zu={...e,subscribe(t){const n=e.subscribe(t,Ds()),r=o=>{o.persisted||n()};return window.addEventListener("pagehide",r),()=>{n(),window.removeEventListener("pagehide",r)}}}),e?zu:void 0}catch{return}}function Ei(){const e=Bt();return!e||e.snapshot().activeKey===Ds()}function ss(e,t=!0){return Bt()?.activate(e,t)??!1}function or(e){Bt()?.report(Ds(),e)}const Dc="termdock-secure-workspace-session:",Dg="termdock-secure-last-workspace";function d1(){for(const e of["sessionStorage","localStorage"])try{const t=window[e].getItem(Dg);if(t)return t}catch{}return null}function u1(e){for(const t of["sessionStorage","localStorage"])try{window[t].setItem(Dg,e)}catch{}}function ZP(e){if(e)try{const t=JSON.parse(localStorage.getItem(Dc+e)||"null");return localStorage.removeItem(Dc+e),t&&typeof t.sessionId=="string"&&Date.now()-t.at<6e4?t.sessionId:void 0}catch{return}}function f1(e){if(window.parent!==window||window.termdockDesktop)return;if(window.__termdockWorkspaceHost)return window.__termdockWorkspaceHost;let t={activeKey:"root",items:[{key:"root",service:e,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]};try{const u=d1(),f=e&&u!==e.targetPeerId?_n().find(h=>h.targetPeerId===u):void 0;f?.targetPeerId&&(t={activeKey:f.targetPeerId,items:[...t.items,{key:f.targetPeerId,service:f,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()}]})}catch{}let n=c1(),r=t.activeKey==="root"?"root":null;const o=new Map,i=new Map([["root",window]]),s=new Set,a=()=>{for(const u of[...o.keys()])u()},c=()=>{const u=l1(t.items,t.activeKey,r,n),f=new Set(u.map(h=>h.key));t={...t,items:u};for(const[h,g]of o)g&&!f.has(g)&&o.delete(h);for(const h of i.keys())f.has(h)||i.delete(h);for(const h of s)f.has(h)||s.delete(h)},l=(u,f)=>{try{const h=f.document.createEvent("CustomEvent");if(h.initCustomEvent(Bo,!1,!1,{active:t.activeKey===u}),f.dispatchEvent(h),t.activeKey===u){const g=f.document.createEvent("Event");if(g.initEvent("resize",!1,!1),f.dispatchEvent(g),s.delete(u)){const m=f.document.createEvent("Event");m.initEvent(Bc,!1,!1),f.dispatchEvent(m)}}else f.document.activeElement?.blur?.()}catch{}},d={snapshot:()=>t,subscribe:(u,f)=>(o.set(u,f),()=>{o.delete(u)}),present(u){r=u},retentionLimit:()=>n,setRetentionLimit(u){if(Lg(u)){n=u;try{localStorage.setItem(Ng,u===1/0?"unlimited":String(u))}catch{}c(),a()}},activate(u,f=!0){const h=bs(u);if(!h?.targetPeerId)return!1;const g=t.items.find(w=>w.service?.targetPeerId===h.targetPeerId),m=g?.key||h.targetPeerId,v=g?{...g,service:h,touchedAt:Date.now()}:{key:m,service:h,phase:"connecting",runningCount:0,reviewCount:0,touchedAt:Date.now()};t={activeKey:m,items:g?t.items.map(w=>w===g?v:w):[...t.items,v]},c(),u1(h.targetPeerId),f&&s.add(m),a();for(const[w,S]of i)l(w,S);return!0},report(u,f){const h=t.items.find(m=>m.key===u);if(!h||f.service&&h.service?.targetPeerId&&f.service.targetPeerId!==h.service.targetPeerId)return;const g={...h,...f};JSON.stringify(g)!==JSON.stringify(h)&&(t={...t,items:t.items.map(m=>m===h?g:m)},a())},attach(u,f){f&&t.items.some(h=>h.key===u)?(i.set(u,f),l(u,f)):i.delete(u)},focusSession(u,f){const h=_n().find(m=>m.targetPeerId===u);if(!h)return!1;try{localStorage.setItem(Dc+u,JSON.stringify({sessionId:f,at:Date.now()}))}catch{return!1}d.activate(h,!1);const g=i.get(t.activeKey);if(g){const m=g.document.createEvent("CustomEvent");m.initCustomEvent("termdock:workspace-session",!1,!1,null),g.dispatchEvent(m)}return!0}};return window.__termdockWorkspaceHost=d,d}let ga;async function ft(){return ga||(ga=(async()=>{const e=await new Promise((t,n)=>{const r=indexedDB.open("termdock-device-identity",1);r.onupgradeneeded=()=>r.result.createObjectStore("keys"),r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)});try{const t=await new Promise((o,i)=>{const s=e.transaction("keys").objectStore("keys").get("identity");s.onsuccess=()=>o(s.result),s.onerror=()=>i(s.error)});if(t)return Uu(t);const n=await vg();let r=n;return await new Promise((o,i)=>{const s=e.transaction("keys","readwrite"),a=s.objectStore("keys"),c=a.get("identity");c.onsuccess=()=>{typeof c.result=="string"?r=Uu(c.result):a.put(ME(n),"identity")},s.oncomplete=()=>o(),s.onerror=()=>i(s.error)}),r}finally{e.close()}})()),ga}const h1="termdock:secure-ready";let _c="ready";const Oc=new Set;function cr(e){if(e!==_c){_c=e;for(const t of Oc)t();e==="ready"&&window.dispatchEvent(new Event(h1))}}function JP(){return N.useSyncExternalStore(e=>(Oc.add(e),()=>{Oc.delete(e)}),()=>_c)}function _g(e){const t=e instanceof Error?e.message:String(e);return/^(Secure connection closed|Secure connection timed out|Secure request closed|Secure response ended unexpectedly|Encrypted connection unavailable|Encrypted transport disconnected|Secure transport unavailable|Secure handshake timed out|WebSocket closed|WebSocket connection failed)$/.test(t)}const as={CONNECTION_FAILED:{reason:"connectionFailed",status:503,message:"暂时连不上这台服务,请检查地址和网络后重试。"},INVALID_PASSWORD:{reason:"invalidPassword",status:401,message:"密码不正确,或服务身份无法验证。请检查后重试。"},IDENTITY_MISMATCH:{reason:"identityMismatch",status:409,message:"服务身份与已保存的记录不一致,请确认目标服务。"},RATE_LIMITED:{reason:"rateLimited",status:429,message:"尝试次数较多,请稍后再试。"},LOGIN_UNAVAILABLE:{reason:"unavailable",status:503,message:"暂时无法登录这台服务,请稍后重试。"},DEVICE_AUTHORIZATION_REQUIRED:{reason:"authorizationRequired",status:403,message:"请检查目标服务与入口的设备授权后重试。"}};function Vu(e){return typeof e=="string"&&Object.hasOwn(as,e)?as[e].reason:void 0}class yt extends Error{constructor(t,n){super(as[t].message),this.code=t,this.retryAfterMs=n,this.status=as[t].status}code;retryAfterMs;status}function _s(e){if(e instanceof yt)return e;if(e instanceof ut)return new yt("DEVICE_AUTHORIZATION_REQUIRED");if(e instanceof Error){if(e.name==="UnexpectedPeerError"||e.message==="PEER_IDENTITY_MISMATCH")return new yt("IDENTITY_MISMATCH");if(e.message==="LOGIN_RATE_LIMIT"||e.message==="Too many password login attempts")return new yt("RATE_LIMITED");if(e.message==="AUTHORIZATION_DENIED")return new yt("DEVICE_AUTHORIZATION_REQUIRED");if(e instanceof TypeError||["TimeoutError","AbortError"].includes(e.name)||_g(e)||e.message==="Encrypted handshake timed out"||e.message==="Encrypted transport failed")return new yt("CONNECTION_FAILED");if(e.message==="Password authentication failed"||e.message==="Password login expired"||e.message==="INVALID_LOGIN")return new yt("INVALID_PASSWORD")}return new yt("LOGIN_UNAVAILABLE")}const dt="termdock:secure-state";let ae,ir,Je,Pr="direct",Ai=!1,Wu=0,Ci=!1,Gu=-1/0;const Nr=globalThis.fetch.bind(globalThis);function ce(){return Qe()}function bt(){return ae}function p1(){return Je}function Wl(){ae?.close(),Je?.close(),ae=void 0,Je=void 0}class ma extends Error{constructor(){super("Secure read target changed"),this.name="SecureReadTargetChanged"}}function g1(e){if(_g(e))return!0;if(!e||typeof e!="object")return!1;const t=e;return t.name==="UnexpectedEOFError"&&typeof t.message=="string"&&/^Unexpected EOF - stream closed while reading \d+\/\d+ bytes$/.test(t.message)}async function m1(e,t){const n=ce(),r=n?.targetPeerId,o=JSON.stringify(n),i=()=>JSON.stringify(ce())===o,s=bt(),a=c=>{if(!i())throw new ma;if(t?.aborted)throw new DOMException("The operation was aborted","AbortError");return c};try{return a(await e())}catch(c){if(c instanceof ma||t?.aborted||c instanceof Error&&c.name==="AbortError"||c&&typeof c=="object"&&"status"in c||!r||!i()||!s?.closed&&!g1(c))throw c;if(cr(navigator.onLine===!1?"offline":"reconnecting"),s&&bt()===s&&Wl(),window.dispatchEvent(new Event(dt)),await jg(t),!i())throw new ma;const l=a(await e());return cr("ready"),l}}async function Og(){const e=await Nr("/api/auth/status",{signal:AbortSignal.timeout(5e3)});if(!e.ok)throw new Error("Failed to query auth status");return e.json()}async function w1(){if(ce()){await gt();return}if((await Og()).enabled)return;const e=await Nr("/api/auth/open/parameters",{cache:"no-store"});if(!e.ok)throw new Error("Open service unavailable");const{serviceIdentity:t}=await e.json();if(typeof t!="string"||!t)throw new Error("Invalid service identity");await St({url:location.origin,targetPeerId:t,serviceName:location.hostname})}async function y1(e,t){const{startPasswordBootstrap:n,finishPasswordBootstrap:r}=await wn(async()=>{const{startPasswordBootstrap:u,finishPasswordBootstrap:f}=await import("./passwordBootstrap-DADiddYD.js");return{startPasswordBootstrap:u,finishPasswordBootstrap:f}},__vite__mapDeps([0,1,2,3])),o=typeof window<"u"?window.termdockDesktop:void 0;let i=location.origin;if(o?.previewCapabilities&&o.passwordBootstrapOrigin){const u=o.passwordBootstrapOrigin(e),f=new URL(u);if(f.origin!==u||e!==location.origin&&f.origin!==e||!["http:","https:"].includes(f.protocol)||f.username||f.password)throw new yt("LOGIN_UNAVAILABLE");i=u}const s=u=>e===location.origin?u:new URL(u,e).href,a=async(u,f)=>{const h=await Nr(s(u),{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(15e3),...f?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)}:{}});if(!h.ok){const g=await h.json().catch(()=>null),m=typeof g?.retryAfterMs=="number"&&Number.isFinite(g.retryAfterMs)&&g.retryAfterMs>=0?g.retryAfterMs:void 0;throw new yt(h.status===429?"RATE_LIMITED":h.status===401?"INVALID_PASSWORD":"LOGIN_UNAVAILABLE",m)}return h.json()},{saltHex:c}=await a("/api/auth/password/parameters"),l=await ft(),d=await n(t,c);try{const u=await a("/api/auth/password/start",{startLoginRequest:d.startLoginRequest,clientIdentity:l.peerId}),f=await r(d,u,{clientIdentity:l.peerId,origin:i});await a("/api/auth/password/finish",{attemptId:f.attemptId,finishLoginRequest:f.finishLoginRequest});const h=i===location.origin?e:i;return{url:h,targetPeerId:f.serverIdentity,serviceName:new URL(h).host,serviceOrigin:h}}finally{d.passwordKey=""}}async function Gl(e,t){const n=ce();if(n&&(n.serviceOrigin||n.url)===e)return await Fc(n,t),n;try{return await y1(e,t)}catch(r){if(!(r instanceof TypeError)&&!(r instanceof DOMException))throw r;const o=(await Ye()).find(s=>s.targetPeerId&&(s.serviceOrigin||s.url)===e);if(!o?.targetPeerId)throw _s(r);const i={...o,targetPeerId:o.targetPeerId,serviceName:o.label};return await Fc(i,t),i}}async function Fc(e,t){const n=await Xl(e),{startPasswordBootstrap:r,finishPasswordBootstrap:o}=await wn(async()=>{const{startPasswordBootstrap:s,finishPasswordBootstrap:a}=await import("./passwordBootstrap-DADiddYD.js");return{startPasswordBootstrap:s,finishPasswordBootstrap:a}},__vite__mapDeps([0,1,2,3]));let i;try{const s=await n.request({type:"password-parameters"},{timeoutMs:5e3});i=await r(t,String(s.saltHex));const a=await n.request({type:"password-start",startLoginRequest:i.startLoginRequest,origin:location.origin}),c=await o(i,a,{clientIdentity:(await ft()).peerId,origin:location.origin});if(c.serverIdentity!==e.targetPeerId)throw new yt("IDENTITY_MISMATCH");await n.request({type:"password-finish",attemptId:c.attemptId,finishLoginRequest:c.finishLoginRequest})}catch(s){throw _s(s)}finally{i&&(i.passwordKey=""),n.close()}}async function b1(e){try{const t=ce(),n=t?.serviceOrigin||location.origin,r=await Gl(n,e);return await St({...r,routes:t?.routes,serviceName:t?.serviceName||r.serviceName}),Response.json({ok:!0})}catch(t){const n=_s(t);return Response.json({error:n.message,code:n.code,retryAfterMs:n.retryAfterMs},{status:n.status})}}async function Xu(e,t){const n=Re(e),r=(await Ye()).find(s=>(s.serviceOrigin||s.url)===n&&s.targetPeerId);if(t===void 0&&r?.targetPeerId)try{return await St({...r,targetPeerId:r.targetPeerId,serviceName:r.label}),{}}catch(s){if(!(s instanceof ut))throw s}if(t!==void 0){const s=await Gl(n,t);if(r?.targetPeerId&&r.targetPeerId!==s.targetPeerId)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await St({...s,routes:r?.routes,serviceName:r?.label||s.serviceName}),{}}const o=await Nr(new URL("/api/auth/open/parameters",n).href,{credentials:"omit",cache:"no-store",signal:AbortSignal.timeout(1e4)}).catch(()=>{throw new Error("暂时连不上这台服务,请检查地址和网络后重试。")});if(o.status===403)return{passwordRequired:!0};if(!o.ok)throw new Error("这台服务暂时不可用,请稍后重试。");const{serviceIdentity:i}=await o.json();if(typeof i!="string"||!i)throw new Error("这不是可连接的 Termdock 服务。");if(r?.targetPeerId&&r.targetPeerId!==i)throw new Error("这台服务的身份已改变。请先移除旧记录,再重新添加。");return await St({url:n,targetPeerId:i,serviceName:r?.label||new URL(n).host,serviceOrigin:n}),{}}function At(e){const t=[...e.routes||[]];if(e.entryServiceId&&e.entryServiceId!==e.targetPeerId&&t.unshift({url:e.url,targetPeerId:e.entryServiceId}),!t.length&&e.routes===void 0)try{const r=JSON.parse(localStorage.getItem(gl)||"null");r&&r.targetPeerId!==e.targetPeerId&&new URL(r.url).host===new URL(e.url).host&&t.push(r)}catch{}const n=new Set;return t.flatMap(r=>{try{if(!r.targetPeerId||r.targetPeerId===e.targetPeerId)return[];const o=Re(r.url),i=JSON.stringify([r.targetPeerId,o]);return n.has(i)?[]:(n.add(i),[{url:o,targetPeerId:r.targetPeerId}])}catch{return[]}}).slice(0,4)}const xo=e=>`relay:${e.targetPeerId}:${e.url}`;async function Fg(e){const t=At(e),n=new Set(t.map(xo)),r=[],o=await Ye(),i=o.some(s=>s.targetPeerId===e.targetPeerId);for(const s of o)if(!(!s.targetPeerId||s.targetPeerId===e.targetPeerId||!i&&!At({...s,targetPeerId:s.targetPeerId}).some(a=>a.targetPeerId===e.targetPeerId)))for(const a of yn({...s,targetPeerId:s.targetPeerId})){const c={url:a,targetPeerId:s.targetPeerId};n.has(xo(c))||(n.add(xo(c)),r.push(c))}return r.slice(0,Math.max(0,4-Math.max(e.routes?.length??0,t.length)))}async function Mg(e,t,n){n.throwIfAborted();const r=await e.request({type:"route-targets"},{timeoutMs:5e3}),o=(Array.isArray(r.items)?r.items:[]).find(c=>c.serviceId===t);if(!o?.available)throw new Error("反向中转通道尚未建立。");if(n.throwIfAborted(),o.authorized===!0)return;if(r.canManage!==!0)throw new Error("反向中转尚未授权。");const i=await e.request({type:"route-access"},{timeoutMs:5e3}),s=(await ft()).peerId;if(n.throwIfAborted(),!Array.isArray(i.grants))throw new Error("入口未返回有效的路由授权记录。");if(i.grants.some(c=>c.subjectId===s&&c.targetServiceId===t&&c.revokedAt!==void 0))throw new Error("反向中转授权已撤销。");await e.request({type:"route-grant",serviceId:t,subjectId:s})}function yn(e){const t=At(e),n=[e.serviceOrigin||e.url,...(e.routes||[]).slice(0,4).filter(o=>o.targetPeerId===e.targetPeerId).map(o=>o.url)],r=new Set;for(const o of n)try{const i=Re(o);t.some(s=>s.url===i)||r.add(i)}catch{}return[...r]}function jn(e){const t=new URL("/api/federation/secure",Re(e));return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.href}async function bn(e,t){return Mn({url:jn(e.url),targetPeerId:e.targetPeerId,identity:await ft(),signal:t?AbortSignal.any([t,AbortSignal.timeout(5e3)]):AbortSignal.timeout(5e3)})}async function Xl(e,t){const n=await ft(),r=yn(e).map(a=>({key:`direct:${a}`,run:c=>Mn({url:jn(a),targetPeerId:e.targetPeerId,identity:n,signal:AbortSignal.any([c,AbortSignal.timeout(8e3),...t?[t]:[]])})})),o=await Fg(e);for(const a of[...At(e),...o])r.push({key:xo(a),run:async c=>{t&&(c=AbortSignal.any([c,t]));const l=[ae,Je].find(u=>u&&!u.closed&&u.targetPeerId===a.targetPeerId),d=l||await bn(a,c);try{if(c.aborted)throw c.reason;o.includes(a)&&await Mg(d,e.targetPeerId,c);const u=await d.request({type:"route-ticket",serviceId:e.targetPeerId},{timeoutMs:5e3});if(c.aborted)throw c.reason;if(typeof u.routeToken!="string")throw new Error("入口未允许此设备连接该服务。");const f=new URL(jn(a.url));return f.pathname="/api/federation/relay",f.searchParams.set("routeToken",u.routeToken),await Mn({url:f.href,targetPeerId:e.targetPeerId,identity:n,socketFactory:Ig(e.targetPeerId),signal:AbortSignal.any([c,AbortSignal.timeout(ml)])})}finally{l||d.close()}}});const i=Tg(e.targetPeerId);r.sort((a,c)=>+(c.key===i)-+(a.key===i));const s=await Pg(r,a=>a.close());return Lc(e.targetPeerId,s.key),s.value}async function v1(e,t){const n=await Xl(e,t);try{const o=(await n.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node;if(o?.serviceId!==e.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");return{...o,serviceId:e.targetPeerId}}finally{n.close()}}async function S1(e,t){const n=await Xl(e,t),r=()=>n.close();t.addEventListener("abort",r,{once:!0});try{if(t.aborted||(await Fr(n,{timeoutMs:3e3}),t.aborted))throw t.reason;return n}catch(o){throw n.close(),o}finally{t.removeEventListener("abort",r)}}async function St(e,t={}){const n=ae,r=Je,o=await ft(),i=Re(e.serviceOrigin||e.url),s=(await Ye()).find(S=>S.targetPeerId===e.targetPeerId),a={...e,routes:e.routes??s?.routes},c=await Fg(a),l=[...At(a),...c],d=yn(a);let u,f,h=e.pairingCode,g="direct";const m=new Set,v=new Map,w=async(S,y)=>{if(n&&!n.closed&&n.targetPeerId===S.targetPeerId)return n;if(r&&!r.closed&&r.targetPeerId===S.targetPeerId)return r;const A=JSON.stringify([S.targetPeerId,S.url]),R=v.get(A);if(R&&!R.closed)return R;const E=await bn(S,y);return m.add(E),v.set(A,E),E};try{if(e.routeCode&&e.entryServiceId){const T=l.find(P=>P.targetPeerId===e.entryServiceId);if(!T)throw new Error("邀请缺少入口信息。");if((await(await w(T)).request({type:"route-pair",code:e.routeCode})).serviceId!==e.targetPeerId)throw new Error("邀请的目标服务不一致。");e.routeOnly&&await Yt({id:e.targetPeerId,url:i,label:e.serviceName||new URL(i).host,targetPeerId:e.targetPeerId,serviceOrigin:i,routes:l})}const S=[],y=async(T,L)=>{const I=()=>T.close();L.addEventListener("abort",I,{once:!0});try{if(L.aborted||(await Fr(T),L.aborted))throw L.reason}catch(P){throw T.close(),P}finally{L.removeEventListener("abort",I)}};for(const T of d)S.push({key:`direct:${T}`,run:async L=>{const I=await Mn({url:jn(T),targetPeerId:e.targetPeerId,pairingCode:h,identity:o,signal:AbortSignal.any([L,AbortSignal.timeout(8e3)])});return h=void 0,await y(I,L),{client:I,path:"direct"}}});for(const T of l)S.push({key:`relay:${T.targetPeerId}:${T.url}`,run:async L=>{let I,P;try{if(I=await w(T,L),L.aborted)throw L.reason;c.includes(T)&&await Mg(I,e.targetPeerId,L);const B=await I.request({type:"route-ticket",serviceId:e.targetPeerId},{timeoutMs:5e3});if(L.aborted)throw L.reason;if(typeof B.routeToken!="string"||!B.routeToken)throw new Error("入口未允许此设备连接该服务。");const D=new URL(jn(T.url));return D.pathname="/api/federation/relay",D.searchParams.set("routeToken",B.routeToken),P=await Mn({url:D.href,targetPeerId:e.targetPeerId,pairingCode:h,identity:o,socketFactory:Ig(e.targetPeerId),signal:AbortSignal.any([L,AbortSignal.timeout(ml)])}),h=void 0,await y(P,L),{client:P,entry:I,path:"relay"}}catch(B){throw P?.close(),I&&I!==r&&I!==n&&I.close(),B}}});const A=Tg(e.targetPeerId);S.sort((T,L)=>+(L.key===A)-+(T.key===A));const R=await Pg(S,T=>{T.client.close(),T.entry&&T.entry!==n&&T.entry!==r&&T.entry.close()},!!h);if(u=R.value.client,f=R.value.entry,g=R.value.path,t.renewIfCurrent){if(ae!==t.renewIfCurrent||n!==t.renewIfCurrent||n.closed||!n.canSwitchTransport||ce()?.targetPeerId!==e.targetPeerId){u.close();for(const T of m)T!==Je&&T!==ae&&T.close();return ae??n}ae=u,Pr=g,Je=f,Lc(e.targetPeerId,R.key),n.retire();for(const T of new Set([r,...m]))T&&T!==n&&T!==u&&T!==f&&T.close();return window.dispatchEvent(new Event(dt)),u}if(Lc(e.targetPeerId,R.key),ae!==n&&ae&&!ae.closed&&ae.targetPeerId===e.targetPeerId){u.close();for(const T of m)T!==Je&&T.close();return ae}g==="direct"&&new URL(i).host===location.host&&Mw(e.targetPeerId);const E=(await Ye()).find(T=>T.targetPeerId===e.targetPeerId||!T.targetPeerId&&(T.serviceOrigin||T.url)===i),C=E?.label||e.serviceName||new URL(i).host,k=c.find(T=>xo(T)===R.key),b=a.routes??At(a),x={url:i,targetPeerId:e.targetPeerId,serviceName:C,serviceOrigin:i,routes:k?[...b,k]:b};if(await(t.rememberOnly?Uw:Yt)({id:E?.id||e.targetPeerId,...x,label:C}),dr!=="unpaired"&&dr!==e.targetPeerId&&Bt()&&ss({id:E?.id||e.targetPeerId,...x,label:C})){u.close();for(const T of m)T!==n&&T!==r&&T.close();return n||u}wh(x),ae=u,Pr=g,Je=f;for(const T of new Set([n,r,...m]))T&&T!==u&&T!==f&&T.close();return dr!==e.targetPeerId?(location.reload(),new Promise(()=>{})):(window.dispatchEvent(new Event(dt)),u)}catch(S){u?.close();for(const y of m)y!==r&&y.close();throw S}}async function x1(){const e=ae,t=ce();if(!(Ci||Ai||ir||!e?.renewalDue||!e.canSwitchTransport||!t||performance.now()-Gu<3e4)){Gu=performance.now(),Ci=!0;try{await St(t,{renewIfCurrent:e})}catch(n){console.debug("[connection] renewal deferred",{reason:n instanceof Error?n.message:"unknown"})}finally{Ci=!1}}}async function E1(){const e=ae,t=ce();if(Date.now()-Wu<6e4||Ci||Ai||Pr!=="relay"||!e||e.closed||!e.canSwitchTransport||!t?.serviceOrigin)return;Ai=!0,Wu=Date.now();let n;try{for(const o of yn(t))try{n=await Mn({url:jn(o),targetPeerId:t.targetPeerId,identity:await ft(),signal:AbortSignal.timeout(3e3)}),await Fr(n);break}catch(i){if(n?.close(),n=void 0,i instanceof ut)throw i}if(!n||ae!==e||!e.canSwitchTransport)return;const r=Je;ae=n,n=void 0,Je=void 0,Pr="direct",e.close(),r?.close(),window.dispatchEvent(new Event(dt))}catch(r){r instanceof ut&&ae===e&&(Wl(),window.dispatchEvent(new Event("auth:unauthorized")))}finally{n?.close(),Ai=!1}}function A1(){return Pr}async function jg(e){return e?(e.throwIfAborted(),new Promise((t,n)=>{const r=()=>n(e.reason);e.addEventListener("abort",r,{once:!0}),gt().then(o=>{e.removeEventListener("abort",r),e.aborted?n(e.reason):t(o)},o=>{e.removeEventListener("abort",r),n(o)})})):gt()}async function gt(){if(ae&&!ae.closed){const t=ae;return x1(),t}if(ae=void 0,ir)return ir;const e=ce();if(!e)throw new Error("DEVICE_PAIRING_REQUIRED");return ir=St(e,{rememberOnly:!0}).catch(t=>{if(ae&&!ae.closed&&ae.targetPeerId===e.targetPeerId)return ae;throw t}).finally(()=>{ir=void 0}),ir}function Ug(e){const t=new URL(e,location.href);if(ae&&!ae.closed)return ae.openSocket(t.pathname+t.search);let n;const r=new kg(e,o=>n?.send(o),()=>n?.close());return gt().then(o=>{r.readyState!==3&&(n=o.openSocket(t.pathname+t.search),r.getConnectionDiagnostics=()=>{const i=n?.getConnectionDiagnostics?.();return i?{...i,socketOpenMs:r.openedAfterMs}:void 0},n.onopen=()=>r.accept({type:"ws-ready",id:""}),n.onmessage=i=>r.accept({type:"ws-data",id:"",data:i.data}),n.onclose=i=>r.accept({type:"ws-close",id:"",code:i.code,reason:i.reason}),n.onerror=()=>r.fail(new Error("Encrypted connection unavailable")))}).catch(o=>r.fail(o)),r}function C1(){n1(gt),window.fetch=async(e,t)=>{const n=new URL(e instanceof Request?e.url:String(e),location.href);if(!n.pathname.startsWith("/api/"))return Nr(e,t);if(n.origin!==location.origin)throw new Error("Remote business API requires a paired encrypted service");if(n.pathname==="/api/meta")return Nr(e,t);if(n.pathname==="/api/auth/status"){if(!ce()){const i=await Og();return Response.json({enabled:i.enabled,authenticated:!1})}try{const i=await Fr(await gt());return Response.json({enabled:i.grants.length>0,authenticated:!0})}catch(i){if(i instanceof ut)return Response.json({enabled:!0,authenticated:!1});throw i}}if(n.pathname==="/api/auth/login"){const s=await new Request(e instanceof Request?e:n.href,t).json();return b1(typeof s.password=="string"?s.password:"")}if(n.pathname==="/api/csrf-token")return Response.json({csrfToken:"encrypted-device-channel"});if(n.pathname==="/api/auth/logout")return ae&&!ae.closed&&await ae.request({type:"logout"}),ae?.close(),Je?.close(),ae=void 0,Je=void 0,Fw(),location.reload(),Response.json({ok:!0});const r=t?.signal!==void 0?t.signal:e instanceof Request?e.signal:void 0,o=await jg(r);return e instanceof Request?o.fetch(e,t):o.fetch(n.pathname+n.search,t)}}async function k1(e){if(!e.targetPeerId)throw new Error("请先连接这台服务,再查看可中转的服务。");for(const t of yn({...e,targetPeerId:e.targetPeerId})){let n;const r={url:t,targetPeerId:e.targetPeerId};try{n=await bn(r)}catch{continue}try{const o=await n.request({type:"route-targets"},{timeoutMs:5e3});if(!Array.isArray(o.items))throw new Error("入口服务需要更新后才能查看中转列表。");return{route:r,canManage:o.canManage===!0,items:o.items}}catch(o){throw o instanceof Error&&/UNKNOWN|UNSUPPORTED/i.test(o.message)?new Error("入口服务需要更新后才能查看中转列表。"):o}finally{n.close()}}throw new Error("暂时连不上中转入口,请检查地址和网络后重试。")}async function I1(e,t){const n=await bn(e);try{const r=await n.request({type:"route-targets"},{timeoutMs:5e3}),o=(Array.isArray(r.items)?r.items:[]).find(c=>c.serviceId===t);if(!o)throw new Error("该服务已不可见,请刷新列表或请入口管理员授权。");if(!o.available)throw new Error("入口暂时无法中转到这台服务,请稍后重试。");const i=(await Ye()).find(c=>c.targetPeerId===o.serviceId),s=[e,...(i?.routes||[]).filter(c=>c.targetPeerId!==e.targetPeerId||Re(c.url)!==Re(e.url))];if(s.length>4)throw new Error("这台服务已保存 4 个备用连接,请先移除一个后重试。");if(!o.authorized){if(!r.canManage)throw new Error("请先让入口管理员授权此设备。");await n.request({type:"route-grant",serviceId:o.serviceId,subjectId:(await ft()).peerId})}const a=i?.serviceOrigin||i?.url||o.url||e.url;return{url:a,serviceOrigin:a,targetPeerId:o.serviceId,serviceName:i?.label||o.label||(o.url?new URL(o.url).host:`中转服务 ${o.serviceId.slice(0,8)}`),routes:s}}finally{n.close()}}async function R1(e,t){const n=await bn(e);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),o=(await ft()).peerId;return{canManage:r.canManage===!0,grants:(Array.isArray(r.grants)?r.grants:[]).filter(i=>i.subjectId===o&&i.targetServiceId===t)}}finally{n.close()}}async function T1(e,t,n){if(n!==void 0&&(await Gl(Re(t.url),n)).targetPeerId!==t.targetPeerId)throw new Error("入口服务的身份已改变,请重新连接并确认。");const r=await bn(t);try{await r.request({type:"route-grant",serviceId:e.targetPeerId,subjectId:(await ft()).peerId,url:Re(e.serviceOrigin||e.url)})}finally{r.close()}}async function P1(e,t){const n=await bn(t);try{const r=await n.request({type:"route-access"},{timeoutMs:5e3}),o=(await ft()).peerId,i=(Array.isArray(r.grants)?r.grants:[]).filter(s=>s.subjectId===o&&s.targetServiceId===e&&s.active);for(const s of i)await n.request({type:"route-revoke",grantId:s.id})}finally{n.close()}}async function Hg(e,t){const n=await bn(t);try{const r=await n.request({type:"route-invite-create",serviceId:e.targetPeerId});if(typeof r.routeCode!="string"||typeof r.expiresAt!="number")throw new Error("暂时无法生成备用连接邀请。");return{routeCode:r.routeCode,expiresAt:r.expiresAt}}finally{n.close()}}async function ki(e,t){const n=(await Ye()).find(o=>o.id===e.id||e.targetPeerId&&o.targetPeerId===e.targetPeerId)||e;await Yt({...n,url:n.serviceOrigin||n.url,entryServiceId:void 0,routes:t});const r=ce();r&&r.targetPeerId===e.targetPeerId&&wh({...r,url:r.serviceOrigin||r.url,entryServiceId:void 0,routes:t})}async function N1(e,t){const n=e.targetPeerId;if(!n)throw new Error("请先连接这台服务,再添加备用地址。");let r;try{r=Re(t)}catch{throw new Error("请输入有效的 HTTPS 地址,例如 https://电脑地址:9834。")}const o=async()=>(await Ye()).find(a=>a.targetPeerId===n)||e,i=a=>{const c=a.routes??At({...a,targetPeerId:n});if(Re(a.serviceOrigin||a.url)===r||c.some(l=>Re(l.url)===r))throw new Error("这个地址已经在连接列表中。");if(c.length>=4)throw new Error("最多保存 4 个备用地址或入口,请先移除不再使用的连接。");return[...c,{url:r,targetPeerId:n}]};i(await o());let s;try{try{s=await Mn({url:jn(r),targetPeerId:n,identity:await ft(),signal:AbortSignal.timeout(5e3)}),await Fr(s)}catch(l){throw l instanceof ut?new Error("这台服务尚未授权当前设备,请先恢复设备授权。"):new Error("无法验证这个地址。请确认能访问该地址、HTTPS 证书受信任,且运行的是同一台 Termdock 服务。")}const a=await o(),c=i(a);if(await ki(a,c),ce()?.targetPeerId===n&&dr===n&&(!ae||ae.closed)){const l=ae,d=Je;ae=s,s=void 0,Je=void 0,Pr="direct",l?.close(),d?.close(),window.dispatchEvent(new Event(dt))}return c}finally{s?.close()}}async function Yu(e,t){await Fc(e,t),await St({...e,pairingCode:void 0,routeCode:void 0})}function L1(){let e=!1,t=!1,n=!1,r;const o=new Map,i=new Set,s=new Map,a=async(f,h,g)=>{const m=JSON.stringify(g);if(o.get(h.serviceId)===m)return;const v=AbortSignal.timeout(1e4),w=await f.fetch("/api/csrf-token",{signal:v});if(!w.ok)throw new Error("CONNECTION_AUTHORIZATION_REQUIRED");const S=await w.json();if(typeof S.csrfToken!="string")throw new Error("INVALID_CSRF_TOKEN");const y=await f.fetch("/api/terminal/operations/collaboration-connections",{method:"POST",signal:v,headers:{"Content-Type":"application/json","X-XSRF-TOKEN":S.csrfToken},body:JSON.stringify({origin:h.origin,nodes:g})});if(!y.ok){const A=await y.json().catch(()=>({}));throw new Error(A.error||`HTTP_${y.status}`)}o.set(h.serviceId,m)},c=async()=>{if(e){n=!0;return}const f=ce(),h=bt();if(!(t||!f||!h||h.closed)){e=!0,n=!1;try{let g;const m=await Promise.race([Ye(),new Promise((R,E)=>{g=setTimeout(()=>E(new Error("SERVICE_DIRECTORY_TIMEOUT")),8e3)})]).finally(()=>clearTimeout(g));m.some(R=>R.targetPeerId===f.targetPeerId)||m.push({...f,id:f.targetPeerId,label:f.serviceName||f.url});const v=[...new Map(m.filter(R=>!!R.targetPeerId).map(R=>[R.targetPeerId,R])).values()].slice(0,64);if(v.length<2)return;const w=[];for(const R of v)try{const E=`${R.targetPeerId}:${R.serviceOrigin||R.url}`;let C=s.get(E);if(!C){const k=R.targetPeerId===f.targetPeerId?(await h.request({type:"collaboration-descriptor"},{timeoutMs:5e3})).node:await v1({...R,targetPeerId:R.targetPeerId},AbortSignal.timeout(8e3));if(k?.serviceId!==R.targetPeerId)throw new Error("PEER_IDENTITY_MISMATCH");const b=k.origin||R.serviceOrigin||R.url,x=new URL(b);if(x.protocol!=="https:"||x.origin!==b)throw new Error("INVALID_SERVICE_ORIGIN");C={serviceId:k.serviceId,origin:b,...k.caFingerprint256?{caFingerprint256:k.caFingerprint256}:{}},s.set(E,C)}w.push({service:R,node:C})}catch{}if(t||bt()!==h||ce()?.targetPeerId!==f.targetPeerId)return;const S=w.find(R=>R.node.serviceId===f.targetPeerId);if(!S||w.length<2){l(3e4);return}const y=w.map(R=>R.node).sort((R,E)=>R.serviceId.localeCompare(E.serviceId));await a(h,S.node,y);let A=w.length<v.length;for(const R of w){if(R===S||o.get(R.node.serviceId)===JSON.stringify(y))continue;let E;try{E=await S1({...R.service,targetPeerId:R.node.serviceId},AbortSignal.timeout(8e3)),await a(E,R.node,y)}catch{let C=i.has(R.node.serviceId);if(!C&&E)try{(await E.request({type:"collaboration-scoped-peer",origin:R.node.origin,node:S.node},{timeoutMs:8e3})).type==="result"&&(i.add(R.node.serviceId),C=!0)}catch{}C||(A=!0)}finally{E?.close()}}window.dispatchEvent(new CustomEvent("termdock:collaboration-enrollment",{detail:{ok:!0}})),A&&l(3e4)}catch(g){window.dispatchEvent(new CustomEvent("termdock:collaboration-enrollment",{detail:{ok:!1,error:g instanceof Error?g.message:"CONNECTION_ENROLLMENT_FAILED"}})),l(3e4)}finally{e=!1,n&&l(100)}}};function l(f=100){t||(clearTimeout(r),r=setTimeout(()=>{c()},f))}const d=()=>{l()},u=vs(d);window.addEventListener(dt,d),window.addEventListener("termdock:collaboration-enroll",d),window.addEventListener("online",d),window.addEventListener("pageshow",d),window.addEventListener("pagehide",f=>{f.persisted||(t=!0,clearTimeout(r),u(),window.removeEventListener("termdock:collaboration-enroll",d),window.removeEventListener(dt,d),window.removeEventListener("online",d),window.removeEventListener("pageshow",d))}),l()}var ui={},Zu;function B1(){if(Zu)return ui;Zu=1;var e=Rw();return ui.createRoot=e.createRoot,ui.hydrateRoot=e.hydrateRoot,ui}var D1=B1();const _1=gh(D1);function et({size:e=16,className:t="",...n}){const r=!!(n["aria-label"]||n["aria-labelledby"]);return p.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none","aria-hidden":r?void 0:!0,role:r?"img":void 0,focusable:"false",...n,className:`td-loading-spinner animate-spin ${t.replace(/\b(?:animate-spin|service-spinning)\b/g,"")}`,children:p.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2.5",strokeDasharray:"18 44.8",strokeLinecap:"round"})})}function O1(){return p.jsx("span",{className:"td-loading-dots","aria-hidden":"true",children:[0,1,2].map(e=>p.jsx("span",{style:{animationDelay:`${(e-3)*400}ms`}},e))})}function QP({label:e,className:t="",dots:n=!1}){return p.jsxs("div",{role:"status","aria-live":"polite","aria-atomic":"true",className:`flex items-center justify-center gap-2 text-sm text-muted-foreground ${t}`,children:[n?p.jsx(O1,{}):p.jsx(et,{size:18}),p.jsx("span",{children:e})]})}const $g=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();const F1=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const M1=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());const Ju=e=>{const t=M1(e);return t.charAt(0).toUpperCase()+t.slice(1)};var wa={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 j1=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1},U1=N.createContext({}),H1=()=>N.useContext(U1),$1=N.forwardRef(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:o="",children:i,iconNode:s,...a},c)=>{const{size:l=24,strokeWidth:d=2,absoluteStrokeWidth:u=!1,color:f="currentColor",className:h=""}=H1()??{},g=r??u?Number(n??d)*24/Number(t??l):n??d;return N.createElement("svg",{ref:c,...wa,width:t??l??wa.width,height:t??l??wa.height,stroke:e??f,strokeWidth:g,className:$g("lucide",h,o),...!i&&!j1(a)&&{"aria-hidden":"true"},...a},[...s.map(([m,v])=>N.createElement(m,v)),...Array.isArray(i)?i:[i]])});const qe=(e,t)=>{const n=N.forwardRef(({className:r,...o},i)=>N.createElement($1,{ref:i,iconNode:t,className:$g(`lucide-${F1(Ju(e))}`,`lucide-${e}`,r),...o}));return n.displayName=Ju(e),n};const q1=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],qg=qe("arrow-left",q1);const K1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],z1=qe("arrow-right",K1);const V1=[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]],W1=qe("arrow-up-right",V1);const G1=[["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"}]],Kg=qe("bell-dot",G1);const X1=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],cs=qe("check",X1);const Y1=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],zg=qe("chevron-down",Y1);const Z1=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Un=qe("chevron-right",Z1);const J1=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Q1=qe("chevron-up",J1);const eA=[["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"}]],Vg=qe("copy",eA);const tA=[["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"}]],Wg=qe("ellipsis",tA);const nA=[["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"}]],rA=qe("monitor",nA);const oA=[["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"}]],iA=qe("pencil",oA);const sA=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Gg=qe("plus",sA);const aA=[["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"}]],Os=qe("server",aA);const cA=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],Xg=qe("smartphone",cA);const lA=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],dA=qe("terminal",lA);const uA=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Yg=qe("x",uA),fA={},Qu=e=>{let t;const n=new Set,r=(d,u)=>{const f=typeof d=="function"?d(t):d;if(!Object.is(f,t)){const h=t;t=u??(typeof f!="object"||f===null)?f:Object.assign({},t,f),n.forEach(g=>g(t,h))}},o=()=>t,c={setState:r,getState:o,getInitialState:()=>l,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(fA?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},l=t=e(r,o,c);return c},hA=e=>e?Qu(e):Qu;var ya={exports:{}},ba={},va={exports:{}},Sa={};var ef;function pA(){if(ef)return Sa;ef=1;var e=pl();function t(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,i=e.useLayoutEffect,s=e.useDebugValue;function a(u,f){var h=f(),g=r({inst:{value:h,getSnapshot:f}}),m=g[0].inst,v=g[1];return i(function(){m.value=h,m.getSnapshot=f,c(m)&&v({inst:m})},[u,h,f]),o(function(){return c(m)&&v({inst:m}),u(function(){c(m)&&v({inst:m})})},[u]),s(h),h}function c(u){var f=u.getSnapshot;u=u.value;try{var h=f();return!n(u,h)}catch{return!0}}function l(u,f){return f()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?l:a;return Sa.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:d,Sa}var tf;function gA(){return tf||(tf=1,va.exports=pA()),va.exports}var nf;function mA(){if(nf)return ba;nf=1;var e=pl(),t=gA();function n(l,d){return l===d&&(l!==0||1/l===1/d)||l!==l&&d!==d}var r=typeof Object.is=="function"?Object.is:n,o=t.useSyncExternalStore,i=e.useRef,s=e.useEffect,a=e.useMemo,c=e.useDebugValue;return ba.useSyncExternalStoreWithSelector=function(l,d,u,f,h){var g=i(null);if(g.current===null){var m={hasValue:!1,value:null};g.current=m}else m=g.current;g=a(function(){function w(E){if(!S){if(S=!0,y=E,E=f(E),h!==void 0&&m.hasValue){var C=m.value;if(h(C,E))return A=C}return A=E}if(C=A,r(y,E))return C;var k=f(E);return h!==void 0&&h(C,k)?(y=E,C):(y=E,A=k)}var S=!1,y,A,R=u===void 0?null:u;return[function(){return w(d())},R===null?void 0:function(){return w(R())}]},[d,u,f,h]);var v=o(l,g[0],g[1]);return s(function(){m.hasValue=!0,m.value=v},[v]),c(v),v},ba}var rf;function wA(){return rf||(rf=1,ya.exports=mA()),ya.exports}var yA=wA();const bA=gh(yA),Zg={},{useDebugValue:vA}=lt,{useSyncExternalStoreWithSelector:SA}=bA;let of=!1;const xA=e=>e;function EA(e,t=xA,n){(Zg?"production":void 0)!=="production"&&n&&!of&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),of=!0);const r=SA(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return vA(r),r}const sf=e=>{(Zg?"production":void 0)!=="production"&&typeof e!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const t=typeof e=="function"?hA(e):e,n=(r,o)=>EA(t,r,o);return Object.assign(n,t),n},Fs=e=>e?sf(e):sf,ls=e=>`@collaboration:${e}`,Jg=Fs(e=>({activePaneId:null,setActivePane:t=>e({activePaneId:t}),docks:{},hosts:{},setDock:(t,n)=>e(r=>{const o={...r.docks};return n?o[t]=n:delete o[t],{docks:o,...!n&&r.activePaneId===ls(t)?{activePaneId:r.docks[t]?.sessionId??null}:{}}}),setHost:(t,n)=>e(r=>{const o={...r.hosts};return n?o[t]=n:delete o[t],{hosts:o}})})),Rn=new Map;let ds;function Qg(){const e=Jg.getState().activePaneId,t=Rn.get(ds??"");if(t?.requiresFocus&&e===ls(t.paneKey))return t.receive;for(const n of Rn.values())if(n.requiresFocus&&e===ls(n.paneKey))return n.receive;return t&&!t.requiresFocus?t.receive:void 0}function AA(e){const t=Rn.get(e);t&&(ds=e,Jg.getState().setActivePane(t.requiresFocus?ls(t.paneKey):null))}function CA(e){const t=Qg();return!t||!e?!1:(t(e),!0)}function e2(e,t="default",n=!1,r=t){Rn.set(t,{receive:e,requiresFocus:n,paneKey:r}),n||AA(t);const o=i=>{const{text:s,nonce:a}=i.detail??{};!s||Qg()!==e||(e(s),i.stopImmediatePropagation(),a&&window.dispatchEvent(new CustomEvent("termdock-insert-reference-ack",{detail:{nonce:a,ok:!0}})))};return window.addEventListener("termdock-insert-reference",o,!0),()=>{Rn.get(t)?.receive===e&&(Rn.delete(t),ds===t&&(ds=[...Rn.keys()].at(-1))),window.removeEventListener("termdock-insert-reference",o,!0)}}const kA=/^[A-Za-z0-9_@%+=:,./-]$/;function IA(e){return Array.from(e,t=>(t.codePointAt(0)??0)>127||kA.test(t)?t:`\\${t}`).join("")}let RA=0;function TA(e,t){if(!t)return!1;try{const n=new URL(t.serviceOrigin||t.url);return n.origin===e&&/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})$/.test(n.hostname)&&!(t.routes??[]).some(r=>r.targetPeerId!==t.targetPeerId)}catch{return!1}}function PA(e,t=!0){const n=new Set,r=new Set,o=new WeakMap,i=l=>l.target instanceof Element?l.target.closest("[data-termdock-terminal-dropzone]"):null,s=()=>!t||!TA(location.origin,Qe()),a=l=>{const d=i(l);!d||!s()||!l.dataTransfer?.types.includes("Files")||(l.preventDefault(),l.stopImmediatePropagation(),l.dataTransfer.dropEffect="copy",d.dataset.nativeFileDrag="true",d.dataset.nativeFileDropState="remote")},c=l=>{const d=i(l),u=Array.from(l.dataTransfer?.files??[]);if(!d||!u.length||!s())return;l.preventDefault(),l.stopImmediatePropagation(),o.get(d)?.abort();const f=new AbortController;o.set(d,f);const h=d.dataset.termdockTerminalDropzone??"",g=Qe(),m=d.dataset.termdockTerminalOwner,v=g?.targetPeerId??null,w=String(++RA),S=()=>!f.signal.aborted&&d.isConnected&&d.dataset.termdockTerminalDropzone===h&&d.dataset.nativeFileDropOperation===w&&Qe()===g&&Qe()?.targetPeerId===v&&d.dataset.termdockTerminalOwner===m,y=()=>S()?!1:(d.dataset.nativeFileDropOperation===w&&(delete d.dataset.nativeFileDrag,delete d.dataset.nativeFileDropState,delete d.dataset.nativeFileDropOperation,delete d.dataset.nativeFileDropProgress,delete d.dataset.nativeFileDropCancellable),!0);d.dataset.nativeFileDropOperation=w,d.dataset.nativeFileDrag="true",d.dataset.nativeFileDropState="uploading",d.dataset.nativeFileDropCancellable="true",delete d.dataset.nativeFileDropProgress;const A=b=>{(b?.type==="auth:unauthorized"||b?.type==="pagehide"||!S())&&(f.abort(),y())},R=new MutationObserver(()=>A());R.observe(d,{attributes:!0,attributeFilter:["data-termdock-terminal-dropzone","data-termdock-terminal-owner","data-native-file-drop-operation"]});const E=()=>{f.abort(),y(),k()},C=b=>{if(!(b.target instanceof Element)||b.target.closest("[data-termdock-terminal-dropzone]")!==d||!S())return;E(),d.dataset.nativeFileDrag="true",d.dataset.nativeFileDropOperation=w,d.dataset.nativeFileDropState="cancelled";const x=window.setTimeout(()=>{r.delete(x),d.dataset.nativeFileDropOperation===w&&d.dataset.nativeFileDropState==="cancelled"&&(delete d.dataset.nativeFileDrag,delete d.dataset.nativeFileDropState,delete d.dataset.nativeFileDropOperation)},3e3);r.add(x)};window.addEventListener("termdock:file-drop-cancel",C);const k=()=>{window.removeEventListener("termdock:file-drop-cancel",C),R.disconnect();for(const b of["termdock:secure-state","auth:unauthorized","pagehide"])window.removeEventListener(b,A);n.delete(E)};n.add(E);for(const b of["termdock:secure-state","auth:unauthorized","pagehide"])window.addEventListener(b,A);wn(async()=>{const{uploadFiles:b}=await Promise.resolve().then(()=>qI);return{uploadFiles:b}},void 0).then(({uploadFiles:b})=>{if(!S())throw new DOMException("Drop target changed","AbortError");return b("/tmp",u,f.signal,x=>{S()&&(d.dataset.nativeFileDropProgress=String(Math.round(x)))},S)}).then(b=>{if(b.files.length!==u.length||b.files.some(T=>!T.path))throw new Error("Upload did not return every file path");if(y())return;delete d.dataset.nativeFileDropCancellable,delete d.dataset.nativeFileDropProgress,e({sessionKey:h,paths:b.files.map(T=>T.path)}),d.dataset.nativeFileDropState="uploaded";const x=window.setTimeout(()=>{r.delete(x),S()&&d.dataset.nativeFileDropState==="uploaded"&&(delete d.dataset.nativeFileDrag,delete d.dataset.nativeFileDropState,delete d.dataset.nativeFileDropOperation)},3e3);r.add(x)}).catch(b=>{if(y())return;delete d.dataset.nativeFileDropCancellable,delete d.dataset.nativeFileDropProgress,d.dataset.nativeFileDropState="error",d.dispatchEvent(new CustomEvent("termdock:file-drop-error",{bubbles:!0,detail:b instanceof Error?b.message:"File upload failed"}));const x=window.setTimeout(()=>{r.delete(x),S()&&d.dataset.nativeFileDropState==="error"&&(delete d.dataset.nativeFileDrag,delete d.dataset.nativeFileDropState,delete d.dataset.nativeFileDropOperation)},3e3);r.add(x)}).finally(k)};return window.addEventListener("dragover",a,!0),window.addEventListener("drop",c,!0),()=>{window.removeEventListener("dragover",a,!0),window.removeEventListener("drop",c,!0);for(const l of n)l();for(const l of r)clearTimeout(l);r.clear()}}function it(){return typeof window>"u"?null:window.termdockDesktop??null}const xa=new Set;let af=!1;function t2(e){const t=it();if(xa.add(e),!af){const n=r=>{if(!CA(r.paths.map(IA).join(" ")+" "))for(const o of xa)o(r)};PA(n,!!t),t?.onNativeFileDrop(n),af=!0}return()=>{xa.delete(e)}}function em(e=navigator.userAgent,t=navigator.maxTouchPoints){const n=/iPad/.test(e)||/Macintosh/.test(e)&&t>1?"iPad":/iPhone/.test(e)?"iPhone":/Android/.test(e)?"Android":/Windows/.test(e)?"Windows":/Macintosh|Mac OS X/.test(e)?"Mac":/Linux/.test(e)?"Linux":"设备",r=/Electron/.test(e)?"Termdock":/Edg\//.test(e)?"Edge":/Firefox|FxiOS/.test(e)?"Firefox":/Chrome|CriOS/.test(e)?"Chrome":/Safari/.test(e)?"Safari":"浏览器";return`${n} · ${r}`}let NA;function LA(){return NA??=(async()=>{const e=navigator.userAgent,[t,n]=em().split(" · "),r=/(?:Edg|Firefox|FxiOS|Chrome|CriOS|Version)\/([\d.]+)/g,o=[...e.matchAll(r)],i=/(?:CPU (?:iPhone )?OS |Mac OS X |Android )([\d._]+)/.exec(e)?.[1]?.replaceAll("_","."),s={system:`${t}${i?` ${i}`:""}`,client:`${n}${o.length?` ${o.at(-1)[1]}`:""}`,mode:matchMedia("(display-mode: standalone)").matches||navigator.standalone?"已安装的网页应用":"网页"},a=it();if(a){s.mode="桌面客户端";const l=/Electron\/([\d.]+)/.exec(e)?.[1];s.client=l?`Termdock(Electron ${l})`:"Termdock";try{Object.assign(s,await a.deviceInfo?.())}catch{}return s}const c=navigator.userAgentData;try{const l=await c?.getHighEntropyValues(["model","architecture","bitness","platformVersion"]);typeof l?.model=="string"&&l.model&&(s.model=l.model),typeof l?.architecture=="string"&&l.architecture&&(s.arch=`${l.architecture}${l.bitness?` ${l.bitness} 位`:""}`)}catch{}return s})()}const tt=[],Mc=new Set,cf=()=>Mc.forEach(e=>e()),BA=()=>tt.length>0,DA=()=>tt[tt.length-1]??null;function n2(e){const t=DA(),n=t?Yl(t.element):[document.body];return e.isConnected&&!e.closest('[hidden], [inert], [aria-hidden="true"]')&&(!t||n.some(r=>r.contains(e)))&&tm(e,n)}function r2(){return N.useSyncExternalStore(e=>(Mc.add(e),()=>{Mc.delete(e)}),BA,()=>!1)}function Yl(e){const t=Array.from(document.querySelectorAll("[data-sidebar-composer-popover]")).filter(n=>e.id&&n.dataset.sidebarComposerPopover===e.id);return[e,...t]}function tm(e,t){for(let n=e;n;n=n.parentElement){const r=getComputedStyle(n);if(r.display==="none"||r.visibility==="hidden")return!1;if(t.includes(n))break}return!0}function lf(e){const t=Yl(e);return t.flatMap(n=>Array.from(n.querySelectorAll("button:not(:disabled), input:not(:disabled), textarea:not(:disabled), select:not(:disabled), a[href], summary, [tabindex]"))).filter(n=>{const r=n.closest("details:not([open])"),o=r?.querySelector("summary");return n.tabIndex>=0&&!n.matches(":disabled")&&!n.closest('[hidden], [inert], [aria-hidden="true"]')&&(!r||!!o?.contains(n))&&tm(n,t)})}function _A(e,t,n,r){const o=N.useRef(n);o.current=n;const i=N.useRef(r);i.current=r,N.useLayoutEffect(()=>{const s=e.current;if(!t||!s)return;const a=document.activeElement instanceof HTMLElement?document.activeElement:null,c={element:s},l=tt.findIndex(v=>s.contains(v.element));l<0?tt.push(c):tt.splice(l,0,c),cf();const d=()=>tt[tt.length-1]===c,u=v=>v instanceof Node&&Yl(s).some(w=>w.contains(v)),f=()=>(lf(s)[0]??s).focus({preventScroll:!0});d()&&f();const h=v=>{d()&&!u(v.target)&&f()},g=v=>{if(!d()||v.key!=="Tab"||v.defaultPrevented)return;const w=lf(s),S=w[0],y=w[w.length-1];(!S||!u(document.activeElement)||(v.shiftKey?document.activeElement===S:document.activeElement===y))&&(v.preventDefault(),(v.shiftKey?y:S)?.focus({preventScroll:!0}))},m=v=>{!d()||v.key!=="Escape"||v.defaultPrevented||v.isComposing||(v.preventDefault(),v.stopImmediatePropagation(),o.current())};return document.addEventListener("focusin",h,!0),document.addEventListener("keydown",g,!0),document.addEventListener("keydown",m),()=>{const v=d();if(tt.splice(tt.indexOf(c),1),cf(),document.removeEventListener("focusin",h,!0),document.removeEventListener("keydown",g,!0),document.removeEventListener("keydown",m),v){const w=tt[tt.length-1];queueMicrotask(()=>{if(tt[tt.length-1]!==w)return;(a?.isConnected&&a!==document.body?a:i.current?.())?.focus({preventScroll:!0})})}}},[t,e])}function OA({service:e,onBusyChange:t,onConnect:n,onConnectWithPassword:r}){const[o,i]=N.useState(),[s,a]=N.useState(!0),[c,l]=N.useState(!1),[d,u]=N.useState(""),[f,h]=N.useState(0),[g,m]=N.useState(),[v,w]=N.useState("");N.useEffect(()=>{let A=!1,R=!1,E;a(!0),u(""),i(void 0);const C=async k=>{try{const b=await k1(e);if(A)return;R=!0,i(b),u("")}catch(b){!A&&(!R||k)&&u(b instanceof Error?b.message:"暂时无法读取中转列表,请重试。")}finally{A||(a(!1),E=setTimeout(()=>{C(!1)},2e3))}};return C(!0),()=>{A=!0,clearTimeout(E)}},[e.id,e.url,f]);const S=async A=>{if(!c){l(!0),t(!0),u("");try{await A()}catch(R){u(R instanceof Error?R.message:"暂时无法连接,请重试。")}finally{l(!1),t(!1)}}},y=async A=>{const R=await I1(o.route,A.serviceId);try{await n(R)}catch(E){if(!(E instanceof ut))throw E;m(R)}};return p.jsxs("div",{className:"service-form",children:[g?p.jsxs("form",{className:"service-form",onSubmit:A=>{A.preventDefault(),S(async()=>{try{await r?.(g,v)}finally{w("")}})},children:[p.jsxs("p",{className:"service-help",children:["已通过“",e.label,"”连接到“",g.serviceName,"”。请登录目标服务,完成此设备的访问授权。"]}),r?p.jsxs(p.Fragment,{children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"目标服务密码"}),p.jsx("input",{type:"password",autoFocus:!0,required:!0,autoComplete:"current-password",value:v,disabled:c,onChange:A=>w(A.target.value)})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:c||!v,children:c?"正在登录…":"登录并连接"})]}):p.jsx("p",{className:"service-help",children:"请让目标服务管理员邀请此设备后再连接。"}),p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>{m(void 0),w(""),u(""),h(A=>A+1)},children:"返回中转列表"})]}):p.jsxs(p.Fragment,{children:[p.jsxs("p",{className:"service-help",children:["通过“",e.label,"”连接下方服务。",o?.canManage?"选择未授权的服务会授权此设备使用该中转。":"这里只显示已授权给此设备的中转。","目标服务会单独验证访问权限。"]}),s?p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(et,{size:16,className:"service-spinning"}),"正在读取可中转的服务…"]}):o&&p.jsxs("div",{className:"service-list",children:[o.items.map(A=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:c||!A.available,onClick:()=>{S(()=>y(A))},children:[p.jsx("span",{className:"service-icon",children:p.jsx(Os,{size:19})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:A.label||(A.url?new URL(A.url).host:`中转服务 ${A.serviceId.slice(0,8)}`)}),p.jsx("span",{className:"service-description",children:A.available?A.authorized?"已获中转授权 · 连接":"授权此设备并连接":"中转暂不可用"})]}),p.jsx(Un,{size:16})]},A.serviceId)),o.items.length===0&&p.jsx("p",{className:"service-empty",children:o.canManage?"暂无可中转的服务。可在本机 Mac 客户端连接目标服务,或在目标服务的“备用连接”中启用本入口。":"暂无已授权的中转服务,请让入口管理员分享备用连接邀请。"})]}),c&&p.jsxs("p",{className:"service-feedback",role:"status",children:[p.jsx(et,{size:16,className:"service-spinning"}),"正在授权并连接目标服务…"]}),!s&&p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:c,onClick:()=>h(A=>A+1),children:"刷新列表"})]}),d&&p.jsx("p",{className:"service-error",role:"alert",children:d})]})}const jc="#termdock-invite=";function nm(e){const t=new URL(e.entryUrl);t.hash="",t.search="",t.pathname="/";const n=new TextEncoder().encode(JSON.stringify(e));return t.hash=jc.slice(1)+btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),t.href}function Bn(e){const t=new URL(e);if(!["https:","http:"].includes(t.protocol)||!t.hash.startsWith(jc))throw new Error("这不是有效的 Termdock 邀请链接");const n=t.hash.slice(jc.length);if(n.length>8192)throw new Error("邀请链接过长");let r;try{const s=n.replace(/-/g,"+").replace(/_/g,"/");r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(atob(s),a=>a.charCodeAt(0))))}catch{throw new Error("邀请链接不完整,请重新复制")}if(r.v!==1||typeof r.serviceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(r.serviceId)||r.routeOnly!==!0&&(typeof r.code!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(r.code)))throw new Error("邀请信息无效或版本不兼容");const o=new URL(r.entryUrl);if(o.origin!==t.origin||o.username||o.password||!["https:","http:"].includes(o.protocol))throw new Error("邀请地址与服务不一致");if(o.protocol==="http:"&&!["localhost","127.0.0.1","[::1]"].includes(o.hostname))throw new Error("远程邀请需要 HTTPS");if(r.entryServiceId!==void 0&&(typeof r.entryServiceId!="string"||!/^12D3KooW[1-9A-HJ-NP-Za-km-z]{44}$/.test(r.entryServiceId)))throw new Error("邀请入口身份无效");if(r.routeCode!==void 0&&(typeof r.routeCode!="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(r.routeCode)||!r.entryServiceId))throw new Error("邀请入口权限无效");if(r.routeOnly===!0&&(!r.entryServiceId||!r.routeCode||r.code!==void 0))throw new Error("备用连接邀请不完整");let i=o.origin;if(r.serviceUrl!==void 0){const s=new URL(r.serviceUrl);if(!["https:","http:"].includes(s.protocol)||s.username||s.password)throw new Error("目标服务地址无效");i=r.entryServiceId&&r.entryServiceId!==r.serviceId?s.origin:o.origin}return{url:o.origin,targetPeerId:r.serviceId,pairingCode:r.code,...r.routeOnly===!0?{routeOnly:!0}:{},serviceOrigin:i,serviceName:typeof r.name=="string"?r.name.slice(0,120):void 0,entryServiceId:r.entryServiceId,routeCode:r.routeCode}}function FA({service:e,onBusyChange:t}){const n={...e,targetPeerId:e.targetPeerId,serviceName:e.label},[r,o]=N.useState(()=>e.routes??At(n)),[i,s]=N.useState([]),[a,c]=N.useState(!0),[l,d]=N.useState(!1),[u,f]=N.useState(""),h=_=>{d(_),t(_)},[g,m]=N.useState(),[v,w]=N.useState(""),[S,y]=N.useState(""),[A,R]=N.useState(""),[E,C]=N.useState(!1),[k,b]=N.useState(),[x,T]=N.useState(),[L,I]=N.useState(!1);N.useEffect(()=>{let _=!1;return Ye().then(O=>{_||s(O.filter(H=>H.targetPeerId&&H.targetPeerId!==e.targetPeerId))}).catch(()=>{_||f("暂时无法读取可用服务。")}).finally(()=>{_||c(!1)}),()=>{_=!0}},[e.targetPeerId]);const P=_=>i.find(O=>O.targetPeerId===_.targetPeerId)?.label||new URL(_.url).host,B=async _=>{h(!0),f(""),R("");try{await _()}catch(O){const H=O instanceof Error?O.message:"";f(/AUTHORIZATION|DENIED/.test(H)?"当前设备没有入口管理权限。请让管理员分享备用连接邀请,或使用入口密码授权。":"暂时无法完成。请确认入口能连接目标服务,且目标地址、证书和授权有效。")}finally{h(!1)}},D=async(_,O)=>{const H={url:_.serviceOrigin||_.url,targetPeerId:_.targetPeerId};await B(async()=>{const V=await R1(H,n.targetPeerId);if(!V.grants.some(W=>W.active)){if(!V.canManage&&O===void 0){m(_);return}await T1(n,H,O)}const z=[...r.filter(W=>W.targetPeerId!==H.targetPeerId||W.url!==H.url),H];await ki(e,z),o(z),m(void 0),w("")})};if(x)return p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["把链接发给需要使用此备用连接的人。它只允许通过入口连接“",e.label,"”,对方仍需获得目标服务的访问权限。"]}),p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用连接邀请"}),p.jsx("input",{readOnly:!0,value:x,onFocus:_=>_.target.select()})]}),p.jsxs("button",{type:"button",className:"service-button service-primary",onClick:()=>{navigator.clipboard.writeText(x).then(()=>I(!0)).catch(()=>f("无法自动复制,请长按链接复制。"))},children:[p.jsx(Vg,{size:16}),L?"已复制":"复制邀请链接"]}),p.jsx("button",{type:"button",className:"service-button service-secondary",onClick:()=>{T(void 0),I(!1)},children:"返回备用连接"}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u})]});if(g)return p.jsxs("form",{className:"service-form",onSubmit:_=>{_.preventDefault(),D(g,v).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:v,onChange:_=>w(_.target.value),autoComplete:"current-password",disabled:l,autoFocus:!0})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||!v,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 F=r.filter(_=>_.targetPeerId===n.targetPeerId),j=r.filter(_=>_.targetPeerId!==n.targetPeerId),M=i.flatMap(_=>yn({..._,targetPeerId:_.targetPeerId}).map(O=>({..._,id:JSON.stringify([_.id,O]),url:O,serviceOrigin:O}))),U=async()=>{if(!l){h(!0),C(!0),f(""),R("");try{o(await N1({...e,routes:r},S)),y(""),R("备用地址已验证并保存。")}catch(_){f(_ instanceof Error?_.message:"暂时无法添加地址,请重试。")}finally{h(!1),C(!1)}}};return p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"电脑换了网络?添加它在新网络下的地址,原地址连不上时会自动尝试。只接受同一台服务。"}),p.jsxs("form",{className:"service-form",onSubmit:_=>{_.preventDefault(),U()},children:[p.jsxs("label",{className:"service-field",children:[p.jsx("span",{children:"备用地址"}),p.jsx("input",{value:S,onChange:_=>{y(_.target.value),f(""),R("")},required:!0,disabled:l||r.length>=4,inputMode:"url",autoComplete:"off",autoCapitalize:"none",spellCheck:!1,placeholder:"例如:192.168.10.20:9834"})]}),p.jsx("button",{type:"submit",className:"service-button service-primary",disabled:l||r.length>=4||!S.trim(),children:E?p.jsxs(p.Fragment,{children:[p.jsx(et,{size:16,className:"service-spinning"}),"正在验证…"]}):"验证并添加"})]}),u&&p.jsx("p",{role:"alert",className:"service-error",children:u}),A&&p.jsx("p",{role:"status",className:"service-help",children:A}),r.length>=4&&p.jsx("p",{className:"service-help",children:"已保存 4 个备用连接。移除不再使用的地址或入口后,可以继续添加。"}),p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"首选地址"}),p.jsx("p",{className:"service-address",children:e.serviceOrigin||e.url})]}),F.length>0&&p.jsx("div",{className:"service-list",children:F.map(_=>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:_.url}),p.jsx("button",{type:"button",className:"service-icon-button","aria-label":`移除地址 ${_.url}`,disabled:l,onClick:()=>b(_),children:"移除"})]}),k?.targetPeerId===_.targetPeerId&&k.url===_.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:()=>b(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{B(async()=>{const O=r.filter(H=>H.targetPeerId!==_.targetPeerId||H.url!==_.url);await ki(e,O),o(O),b(void 0)})},children:"确认移除"})]})]})]},_.url))}),p.jsxs("details",{className:"service-relay-options",children:[p.jsxs("summary",{children:["通过其他服务中转",j.length?`(${j.length})`:""]}),p.jsxs("div",{className:"service-form",children:[p.jsx("p",{className:"service-help",children:"所有直连地址都不可用时,尝试下方已授权入口;直连恢复后自动切回。"}),j.length>0&&p.jsx("div",{className:"service-list",children:j.map(_=>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(Os,{size:18})}),p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:P(_)}),p.jsx("span",{className:"service-description",children:_.url})]}),p.jsx(cs,{size:16,className:"service-selected"})]}),k?.targetPeerId===_.targetPeerId&&k.url===_.url?p.jsxs("div",{className:"service-form",children:[p.jsxs("p",{className:"service-help",children:["撤销此设备经“",P(_),"”所有地址连接目标的权限?如当前无法直连,目标服务将断开。"]}),p.jsxs("div",{className:"service-actions service-actions-pair",children:[p.jsx("button",{type:"button",className:"service-button service-secondary",disabled:l,onClick:()=>b(void 0),children:"取消"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>{B(async()=>{await P1(n.targetPeerId,_);const O=r.filter(H=>H.targetPeerId!==_.targetPeerId);await ki(e,O),o(O),b(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:()=>{B(async()=>{const O=await Hg(n,_);T(nm({v:1,routeOnly:!0,serviceId:n.targetPeerId,name:e.label,serviceUrl:e.serviceOrigin||e.url,entryUrl:_.url,entryServiceId:_.targetPeerId,routeCode:O.routeCode}))})},children:"分享备用连接"}),p.jsx("button",{type:"button",className:"service-button service-danger",disabled:l,onClick:()=>b(_),children:"撤销授权"})]})]},JSON.stringify([_.targetPeerId,_.url])))}),a?p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(et,{size:16,className:"service-spinning"}),"正在读取服务…"]}):p.jsxs("div",{children:[p.jsx("p",{className:"service-help",children:"添加中转入口"}),M.filter(_=>!r.some(O=>O.targetPeerId===_.targetPeerId&&O.url===_.url)).map(_=>p.jsxs("button",{type:"button",className:"service-row-open service-full-width",disabled:l||r.length>=4,onClick:()=>{D(_)},children:[p.jsxs("span",{className:"service-row-copy",children:[p.jsx("span",{className:"service-name",children:_.label}),p.jsx("span",{className:"service-description",children:_.url})]}),p.jsx(Un,{size:16})]},_.id)),i.length===0&&p.jsx("p",{className:"service-empty",children:"添加并登录另一台服务后,可以将它设为中转入口。"})]})]})]}),l&&!E&&p.jsxs("p",{role:"status",className:"service-feedback",children:[p.jsx(et,{size:16,className:"service-spinning"}),"正在验证连接与授权…"]})]})}const MA={architecture:{choosePaths:"Choose folders or files",browsePaths:"Browse",addScopeReference:"Add to analysis scope",searchScopePaths:"Search files or folders",useCurrentFile:"Use current file",useCurrentDirectory:"Use current folder",browsePathsHint:"Expand folders to browse. Use the reference button on a row to add it to the analysis scope.",correctPathsFirst:"Correct the entered paths before adding more scope.",pathsHint:"Choose scope or paste file/line references. Paths are relative to this project.",featureScopeHint:"Locate this feature within the selected scope first",removePath:"Remove path",chooseThisDirectory:"Select this folder",filterDirectory:"Filter this folder",loadingPaths:"Loading folder…",pathsLoadFailed:"Could not read this folder. Check connection or access, then retry.",noPaths:"No matching files or folders here.",pathsTruncated:"This folder has too many entries to show at once. Open a subfolder or paste its path directly.",selectedPaths:"Selected paths",usePaths:"Use selected scope",expandDetail:"Read module details",collapseDetail:"Collapse module details",backToMap:"Back to map",backToModule:"Back to module",previousModule:"Previous module",parentModule:"Back to parent",viewPrepared:"View this analysis",closeDetail:"Close module details",connections:"Connections",outgoing:"To",incoming:"From",browseMode:"Browse mode",outlineMode:"Module details",graphMode:"Relationship diagram",analysisNotes:"Analysis notes",limitations:"Scope and limitations",analyzedPaths:"Analyzed sources",fitGraph:"Fit entire diagram",fullscreen:"Open fullscreen diagram",closeFullscreen:"Close fullscreen diagram",panHint:"Drag to pan, pinch to zoom; select a module for details",newAnalysis:"New analysis",updateAnalysis:"Update current analysis",closePreparation:"Close analysis settings",analysisRange:"Analysis scope",projectRange:"Entire project",moduleRange:"Directory / module",featureRange:"Feature flow",modulePaths:"Module paths (one per line)",modulePlaceholder:"Choose folders/files or paste existing references, one per line",featureTarget:"Feature to understand",featurePlaceholder:"For example: file upload from selecting a file to storage",invalidPaths:"Choose up to 20 project folders/files or paste their references; outside paths and .. are not allowed.",requiredFeature:"Describe a specific feature and check that optional starting paths are project-relative.",independentHint:"Scoped analyses are saved separately. Repeating the same scope updates its map; the entire project uses the project overview.",updateOnly:"Only this analysis will be updated. Other maps are preserved.",analysisOptions:"Dependencies and other options",dependencyDepth:"Dependency tracing",boundaryDepth:"Scope boundary (faster)",followDepth:"Follow relevant calls and dependencies",startPaths:"Feature scope (optional)",focus:"Analysis request and constraints (optional)",focusPlaceholder:"For example: explain permission checks and retries; skip styling.",savedAnalyses:"Saved analyses",libraryFailed:"Could not list analyses. The current map is still available. Refresh to retry.",awaitingFile:"This analysis has not been saved yet. Send the prepared prompt to your Agent; the result will appear after the file is saved.",analyzeModule:"Analyze this module in detail",scopeUnavailable:"This scoped map is missing analysis metadata. Create a new analysis to specify its boundaries.",tab:"Map",title:"Code architecture",generate:"Generate",update:"Update",refresh:"Refresh architecture",prepare:"Prepare architecture analysis",promptHint:"Use the Agent in this project's terminal to analyze the code. The prompt goes into the current input or context draft for you to review and send. This view refreshes when the architecture is saved. Open an Agent first; analysis uses its time and allowance.",insertPrompt:"Insert prompt",copyPrompt:"Copy prompt",previewPrompt:"Review analysis prompt",inserting:"Adding to the current input…",insertFailed:"Could not add the prompt. Check the current session, or copy it below.",inserted:"Review the current input or context draft, then send it to your Agent.",copied:"Prompt copied.",failed:"Copy failed. Copy manually from the prompt below.",loading:"Reading project architecture…",invalid:"The architecture file is invalid. Analyze the project again to repair it.",loadFailed:"Could not read project architecture. Check connection and access, then retry.",previous:"The last successfully loaded architecture remains below.",retry:"Retry",empty:"Understand this project's architecture",emptyHint:"Start with the project, selected paths or one feature. A full project map is not required.",savedAt:"Saved",perspective:"Perspective",breadcrumb:"Architecture hierarchy",modules:"Modules",explore:"Explore submodules",sourceFiles:"Related source",diagram:"Architecture diagram",diagramHint:"Select a module for details",zoomOut:"Zoom out diagram",zoomIn:"Zoom in diagram",resetZoom:"Reset diagram zoom",download:"Download architecture SVG",downloadFailed:"Download failed. Please retry.",diagramFailed:"The diagram could not render. You can still explore the modules below.",rendering:"Drawing architecture…"},computer:{returnToDesktop:"Return to desktop",tools:"Control settings",closeTools:"Close control settings",keyboard:"Keyboard",keyboardInput:"Type directly on the computer",keyboardPlaceholder:"Tap to type directly on the computer",hideKeyboard:"Hide keyboard",keyboardNavigation:"Keyboard navigation",desktopZoom:"Desktop zoom",zoomIn:"Zoom in desktop",zoomOut:"Zoom out desktop",resetZoom:"Fit desktop to screen",pinchHint:"Pinch to zoom",keyEscape:"Send Esc",keyLeft:"Move left",keyDown:"Move down",keyUp:"Move up",keyRight:"Move right",keySelectAll:"Select all",clipboardTool:"Clipboard",zoom:"Zoom in",expand:"Full screen",switchTouchMode:"Switch touch mode",touchMode:"Touch mode",trackpadMode:"Trackpad",directTouchMode:"Direct touch",trackpadHint:"Slide to move, tap to click, hold to drag. Use two fingers to scroll or tap for right-click.",directTouchHint:"Tap a position on the screen to click. Drag your finger to interact with the desktop.",trustCertificateHere:"Trust this computer’s certificate",rememberLogin:"Remember login",autoConnect:"Connect automatically next time",forgetLogin:"Forget login",savedPassword:"Saved — leave empty to connect",loginExpired:"Saved login expired. Enter your password again.",loginSaveFailed:"Could not save or retrieve login details. Please retry.",title:"Computer control",host:"Computer address",hostPlaceholder:"192.168.1.20 or computer.local",username:"Username (optional)",password:"Password",passwordHint:"Enter the target computer’s VNC password. Include a username if the server requires account sign-in. Remember login encrypts credentials on the service after a successful connection.",connect:"Connect",disconnect:"Disconnect",cancel:"Cancel",connecting:"Connecting…",connected:"Connected",disconnected:"Disconnected. You can reconnect.",viewOnly:"View only",control:"Allow control",fit:"Fit to panel",actualSize:"Actual size",fullscreen:"Expand desktop",exitFullscreen:"Collapse desktop",setup:"How to connect a computer",step1:"On your Mac, open System Settings → General → Sharing → Screen Sharing.",step2:"Allow your user in Screen Sharing settings. For a VNC password, enable “VNC viewers may control screen with password”.",step3:"Enter a private computer address reachable from this service. To control the computer running this service, choose “This computer”.",networkHint:"Uses VNC port 5900. Browser-to-Termdock traffic is encrypted; use a trusted LAN or VPN for the VNC connection from the service to the target computer.",service:"Current service: {name}",remoteTitle:"Remote computer desktop",startHint:"Connect to view the desktop and control the computer with mouse, touch, and keyboard.",credentials:"Enter login credentials",authenticate:"Sign in",authFailed:"Sign-in failed. Check the username, password, and remote desktop permissions.",sharingOff:"VNC connection refused. Start desktop sharing and check port 5900.",unreachable:"Cannot reach the computer. Check the address, network, and firewall.",timeout:"Connection timed out. Make sure the target computer is awake and reachable from this service.",invalidHost:"Enter a private IP or hostname without a protocol or port.",privateOnly:"Only private or local addresses are supported. For remote access, switch to the Termdock service on the target computer.",permission:"Computer control requires full access to the current service.",failed:"Connection failed. Please reconnect.",clipboard:"Send clipboard",clipboardPlaceholder:"Send text to the computer clipboard",clipboardHint:"Enter text and press {shortcut} to paste, or send it to the clipboard only. Character support depends on the target computer.",remoteClipboard:"Text copied on the computer",copyToDevice:"Copy to this device",clipboardCopied:"Copied to this device",clipboardAccessFailed:"System clipboard is unavailable. Enter text here to send, or select the received text and copy it manually.",clipboardSent:"Sent to computer clipboard",shortcuts:"Shortcuts",switchApps:"Switch apps",spotlight:"Spotlight search",desktop:"Show desktop",loading:"Loading computer control…",platform:"Target system",thisComputer:"This computer",otherComputer:"Another computer",target:"Computer to connect",localService:"Computer running the current Termdock service · {name}",advanced:"Advanced settings",rdpLoginHint:"Use the credentials from Remote Desktop settings.",vncLoginHint:"Use your screen sharing VNC password.",checkSettings:"Check connection settings",localHint:"Local means the computer running the current Termdock service. Enable the selected remote desktop protocol on the target first.",linuxStep1:"Ubuntu / Linux needs a VNC server. To share the current desktop with x11vnc, use an X11 session; select “Ubuntu on Xorg” at the Ubuntu login screen.",linuxStep2:"Set a VNC password and listen on port 5900. RDP-only desktop sharing cannot connect here.",linuxCommandHint:"Run these commands in a desktop terminal on the target, then enter the VNC password you set. This example only accepts connections from the service computer. Commands are not run automatically:",linuxProtocolHint:"Ubuntu 24.04’s built-in Remote Desktop uses RDP; this panel uses VNC. Wayland needs a VNC server compatible with the desktop. TigerVNC virtual desktops are separate sessions, not the current screen.",windowsStep1:"Install and start a compatible VNC server on Windows. Windows RDP Remote Desktop cannot connect here.",windowsStep2:"Set a VNC password, enable keyboard and mouse control, and allow this service to reach port 5900 through the firewall.",systemSearch:"System search",protocol:"Connection protocol",port:"RDP port",rdpUsername:"RDP username",domain:"Domain (optional)",rdpPasswordHint:"Use the RDP username and password configured in Remote Desktop settings. Ubuntu remote login credentials may differ from your system account. Remember login encrypts credentials on the service after a successful connection.",rdpBackendUnavailable:"RDP support is unavailable on this service. Complete the server-side RDP setup first.",rdpBackendRecovery:"Start the RDP backend (guacd) on the computer running this Termdock service, then refresh this page to check again. Connection settings are kept; you can also switch to VNC in advanced settings.",rdpFailed:"RDP connection failed. Check Remote Desktop, the port, and credentials. For a self-signed certificate, verify the computer’s identity before enabling certificate trust.",rdpLinuxStep1:"On Ubuntu, open Settings → System → Remote Desktop. Enable Desktop Sharing or Remote Login and configure RDP credentials.",rdpStep1:"Enable RDP on the target computer. On Windows, use Settings → System → Remote Desktop. Use VNC for built-in Mac Screen Sharing.",rdpStep2:"Enter the username, password, and port from Remote Desktop settings. The default RDP port is 3389; Ubuntu Desktop Sharing may use 3390. Verify the target before trusting a self-signed certificate.",rdpNetworkHint:"Display and input use the encrypted browser-to-Termdock channel. The current service connects to the target over RDP. Desktop Sharing and Remote Login may use different sessions; showing the current screen depends on the target service’s settings.",trustCertificate:"Trust this computer’s RDP certificate (skip verification)",settingsLoading:"Loading connection settings…",settingsSaving:"Saving settings…",settingsSaved:"Connection settings saved on this service.",settingsSaveFailed:"Settings could not be saved. Your edits are still on this page.",settingsLoadFailed:"Connection settings could not be loaded. Please retry.",retry:"Retry",retryConnect:"Retry connection",rdpCertificate:"The target computer’s RDP certificate could not be verified. After confirming the computer’s identity, trust its certificate below and retry.",clipboardFailed:"Failed to send clipboard. Try again."},app:{name:"Termdock"},android:{device:"Device",selectDevice:"Select device",noDevices:"No device found",closeTab:"Close device tab",refresh:"Refresh devices",connect:"Connect",disconnect:"Stop mirroring",addDevice:"Connect over network",addressPlaceholder:"ip:port, e.g. 192.168.1.20:5555",adbUnavailable:"adb (Android platform-tools) not found; mirroring is unavailable. macOS: brew install android-platform-tools; Ubuntu: sudo apt install adb; or set TERMDOCK_ADB_BIN in ~/.termdock/.env.",scrcpyUnavailable:"scrcpy / scrcpy-server not found; mirroring is unavailable. macOS: brew install scrcpy; Ubuntu: sudo apt install scrcpy; or set TERMDOCK_SCRCPY_BIN in ~/.termdock/.env.",connecting:"Connecting to device…",reconnecting:"Connection lost, reconnecting…",retrySchedule:"Retry {attempt} starts in {seconds} seconds",lastError:"Last error (retained while reconnecting)",retry:"Retry",idleHint:"Pick a device to start mirroring",noDevicesHint:"Connect a phone over USB with debugging enabled, or add a network device",back:"Back",home:"Home",recents:"Recents",notifications:"Notifications",rotate:"Rotate",volumeUp:"Volume up",volumeDown:"Volume down",power:"Power",zoomIn:"Zoom in",zoomOut:"Zoom out",zoomPanHint:"Two-finger drag to move the view",inputText:"Type text",inputPlaceholder:"Text to send to the phone",send:"Send",splitOpen:"Open in split view",splitClose:"Exit split view",splitDockedHint:"Mirroring is shown in the split area.",splitDrag:"Drag to reposition",insertFixPrompt:"Insert fix prompt",screenshot:"Screenshot and insert",recordingStart:"Start recording",recordingStop:"Stop recording",recording:"Recording…",recordingLimit:"Reached the 5-minute limit, recording stopped",recordingStopped:"Mirroring stopped, recording ended",captureInserted:"Screenshot inserted",recordingInserted:"Recording inserted",recordingConfirm:"Recording finished. What next?",recordingInsert:"Insert directly",recordingSave:"Save to a folder",recordingSaveHint:"Recorded on the server. Insert a file reference, or save to a server folder.",recordingDiscard:"Discard recording",captureInserting:"Inserting…",recordingSaving:"Saving recording…",captureFailed:"Insert failed",captureUnavailable:"Cannot insert into the terminal right now",more:"More",fullscreen:"Fullscreen",fillSidebar:"Fill sidebar",exitFullscreen:"Exit fullscreen",fullscreenHint:"Mirroring is shown in fullscreen.",quality:"Quality",qualityAutoHint:"Adapts bitrate to connection and decoding performance without reconnecting. Resolution stays stable; controls and server recording are unaffected.",qualityAutoUnavailable:"Automatic bitrate adjustment paused; video stays connected.",qualityAutoVersionError:"Server scrcpy version is not supported (details).",qualityAutoBuildError:"Server scrcpy build has not been verified (details).",qualityAutoExtensionError:"Bitrate extension could not be read, verified or transferred (details).",qualityAutoTimeoutError:"Bitrate confirmation timed out; encoder support is unknown (details).",qualityAutoEncoderError:"Device encoder rejected this adjustment (details).",qualityAutoChannelError:"Bitrate control channel failed (details).",qualityAutoUnknownError:"Server did not provide a reason; update that server and retry (details).",qualityLow:"Smooth",qualityMedium:"Standard",qualityHigh:"HD",qualityCustom:"Custom",qualityResolution:"Resolution",qualityBitRate:"Bitrate",qualityFrameRate:"Frame rate",qualityAuto:"Auto",qualityApply:"Apply",presetNamePlaceholder:"Preset name",presetSave:"Save preset",presetDelete:"Delete preset",stateUnauthorized:"unauthorized",stateOffline:"offline",stateUnknown:"unknown state",unauthorizedHint:"Confirm the USB debugging prompt on the phone.",offlineHint:"Device is offline; reconnect the cable or network device."},common:{cancel:"Cancel",close:"Close",save:"Save",reset:"Reset",loading:"Loading…",error:"Error",retry:"Retry",refresh:"Refresh",search:"Search",clear:"Clear",delete:"Delete",on:"On",off:"Off",back:"Back",copy:"Copy",decrease:"Decrease",increase:"Increase",use:"Use",previous:"Previous",next:"Next"},login:{prompt:"termdock login",placeholder:"Enter password",placeholderBlocked:({s:e})=>`Please wait ${e}s`,submit:"Sign in",invalidPassword:"The password is incorrect, or the service identity could not be verified. Check and try again.",identityMismatch:"The service identity has changed. Check the address with its owner before trying again.",unavailable:"Password sign-in is temporarily unavailable. Check the connection and try again.",authorizationRequired:"This device needs authorization. Ask the service owner for a new invitation.",currentTarget:({address:e})=>`Signing in to ${e}`,manageServices:"Manage services / use another address",failed:"Could not sign in. Check the connection and try again.",rateLimited:"Too many attempts. Please wait and try again.",continueAfterReconnect:"You can continue signing in when the network returns.",savedConnectionRetained:"Saved service retained. Access will be checked after reconnecting.",invalidAddress:"Enter a valid HTTPS service address, for example computer.example:9834 or https://computer.example:9834.",invalidInvitation:"This invitation is incomplete or invalid. Copy the full invitation link and try again."},sidebar:{sessionCreating:"Starting…",sessionCreateDirectoryUnavailable:"The working directory is unavailable. Choose another folder and try again.",sessionCreatePermissionDenied:"You do not have permission to start here. Choose another folder.",sessionCreateConnectionFailed:"Could not connect. Check the connection and try again.",sessionCreateFailed:"Could not start the session. Please try again.",sessions:"Sessions",noSessions:"No open sessions yet.",noMatchingSessions:"No matching sessions.",toggleSearch:"Toggle search",settings:"Settings",moreActions:"More actions",subscriptionQuota:"Subscription quota",pinSidebar:"Keep sidebar open",unpinSidebar:"Stop keeping sidebar open",runningSessionButton:"Running sessions button",runningSessionButtonHint:"Tap to cycle, swipe sideways to select, hold to drag",attentionButton:"Attention button",attentionButtonHint:"Show the yellow floating bell for unread or pending sessions",updateAvailable:({version:e})=>`Termdock ${e} is available`,updateInstalling:"Installing in the background without interrupting this service.",updateReady:"The update is installed and ready for a confirmed restart.",updateRestart:"Restart and finish update",updateRestartConfirm:({version:e})=>`Restart Termdock and switch to ${e}? This page will reconnect briefly and sessions will stay open.`,updateRestarting:"Restarting; this page will reconnect automatically…",updateFailed:"Automatic installation failed. This reminder will remain.",updateRetry:"Try again",serverAttention:"The service had a problem",filterSessions:"Filter sessions",clearSearch:"Clear search",groupByFolder:"Group by folder",groupByFolderTitle:"Collapse sessions into groups by working directory. Mutually exclusive with drag sorting.",ungrouped:"Other",needsAttention:"Needs attention",waitingForYou:"Waiting for you",completedUnread:"Completed · unread",closeSession:({name:e})=>`Close ${e}`,newShell:"Shell",newTmux:"Tmux",newTmuxDisabled:"tmux not available on server",confirmNewShell:"Create Shell?",confirmNewTmux:"Create Tmux?",newSession:"New terminal",newSessionWithAgent:({agent:e})=>`New ${e}`,moreLaunchOptions:"More launch options",recoverableSessions:"Recoverable sessions",confirmCloseRecoverableSession:({name:e})=>`End ${e}? This stops all processes in the session.`,endRecoverableSession:"End session",closeRecoverableSessionFailed:"Could not end the session. Please retry.",refreshRecoverableSessions:"Refresh recoverable sessions",restoreRecoverableSession:({name:e})=>`Restore ${e}`,restoringRecoverableSession:"Restoring…",restore:"Restore",newSessionAdvanced:"Quick-launch agent",newSessionComposerTitle:"Start a session",newSessionHint:"Choose how and where it starts",launchSessionWith:({name:e})=>`Start ${e}`,setNewSessionDefault:({name:e})=>`Set ${e} as default`,currentNewSessionDefault:({name:e})=>`${e} is the current default`,currentDefaultAgent:({name:e})=>`Current default: ${e}`,defaultAgent:"Default",makeDefault:"Make default",sessionMode:"Run mode",tmuxKeepsRunning:"Keeps running after disconnect",resumeHistory:"Recent conversations",resumeHistoryCount:({n:e})=>`${e} saved`,resumeHistoryLoading:"Loading recent Agent conversations…",resumeHistoryAction:({title:e})=>`Resume ${e}`,resumeHistoryRemove:({title:e})=>`Remove ${e} from recent conversations`,resumeHistoryLoadFailed:"Could not load recent Agent conversations.",resumeHistoryFailed:"Could not prepare this Agent conversation for resume.",resumeHistoryRemoveFailed:"Could not remove the conversation from history.",customStartupCommand:"Custom command",changeStartupCommand:"Change startup command",saveStartupCommand:"Save command",startupCommandSaved:"Saved",saveStartupCommandFailed:"Could not save. Check browser storage permissions.",addStartupCommand:"Add custom command…",deleteStartupCommand:"Delete command",startupCommand:"Startup command",resetStartupCommand:"Reset",startupCommandPlaceholder:"e.g. vim, htop or npm run dev",agentStartupCommandHint:"Edit the full command; leave blank for the Agent default. Saved in this browser.",terminalStartupCommandHint:"Run a program in the selected directory, e.g. vim README.md. Saved in this browser.",workingDirectory:"Working directory",directoryPlaceholder:"Enter a directory path",browseDirectories:"Browse",hideDirectoryBrowser:"Hide browser",chooseDirectory:"Choose working directory",directoryPickerHint:"Open a folder, then confirm the current location.",useThisFolder:"Use folder",recentDirectories:"Recent directories",startCommand:"Start command",customCommand:"Other command",commandPlaceholder:"Optional, e.g. codex",detectAgents:"Detect agents again",savePreset:"Save as preset",createAndRun:"Create and run",createSession:"Create terminal",openLeftSidebar:"Open left sidebar",openRightSidebar:"Open right sidebar",closeSidebar:"Close sidebar"},rightSidebar:{workspace:"Workspace",currentProject:"Project",browsingLocation:"Browsing",parentFolder:"Parent folder",backToProjectRoot:"Back to project",refreshFiles:"Refresh current folder",resizeFileTree:"Drag to resize file browser",pinCurrentFolder:"Pin current folder to this project",unpinCurrentFolder:"Unpin current folder",showHiddenFiles:"Show hidden files",hideHiddenFiles:"Hide hidden files",hideGitIgnoredFiles:"Hide Git-ignored files",showGitIgnoredFiles:"Show Git-ignored files",gitIgnoreSaveFailed:"Could not save Git ignore visibility. Please retry.",gitIgnoreConfigureHint:"Long-press or right-click to configure exceptions",gitIgnoreExceptionsTitle:"Git ignore filter exceptions",gitIgnoreExceptionsHint:"Select files or folders to keep visible while filtering is enabled. Use the arrow beside a folder to browse inside it. Selected folders include all descendants; parent folders of selected files stay visible. Save to apply.",gitIgnoreExceptionsPaths:"Select files or folders",gitIgnoreExceptionsInvalid:"Select up to 200 files or folders.",gitIgnoreExceptionsLoadFailed:"Could not load this folder. Please retry.",gitIgnoreExceptionsEmptyDirectory:"This folder is empty",gitIgnoreExceptionsOpenDirectory:({name:e})=>`Open folder ${e}`,gitIgnoreExceptionsSelected:({count:e})=>`${e} selected`,gitIgnoreExceptionsClear:"Clear selection",gitIgnoreExceptionsRemove:({path:e})=>`Remove ${e}`,gitIgnoreExceptionsTruncated:"This folder has too many entries; only some are shown.",gitIgnoreExceptionsSaveFailed:"Could not save. Check that all paths are inside the current folder (up to 200), then retry.",insertCurrentFolder:"Insert current folder reference",insertCurrentFolderShort:"Insert",pinnedFolders:"Pinned",unpinFolder:({name:e})=>`Unpin ${e}`,fileWatchUnavailable:({message:e})=>`File watcher unavailable: ${e}. Click to refresh manually.`,browsingOutsideProject:"Browsing outside current project",browsingOutsideProjectHint:"Git and Changes still use the current project. File references from here are inserted as external paths.",toggleSearch:"Toggle search",refreshGit:"Refresh Git status",gitLastUpdated:({time:e})=>`Last updated: ${e}`,close:"Close",filterChanges:"Filter changes or files",searchPlaceholderContent:"Search text in files…",searchModeName:"File",searchModeContent:"Content",clearSearch:"Clear search",searchScope:"Scope",searchScopePlaceholder:"Relative folder or absolute path",resetSearchScope:"Reset to current folder",searchOptions:"Search options",searchExclude:"Exclude",searchExcludePlaceholder:"dist/**, *.lock",clearSearchExclude:"Clear exclusions",contentSearchOptions:"Content search options",matchCase:"Match case",matchWholeWord:"Whole word",useRegex:"Regex",insertGitContext:"Insert current Git context into terminal",copyGitContext:"Copy Git context",insertChangeAuditPrompt:"Explain changes",insertChangeAuditPromptTitle:"Insert the change audit prompt into the current session",changeAuditShort:"Explain changes",changeAuditLoading:"Loading hunk explanations…",changeAuditLoaded:({count:e})=>`${e} hunk explanation${e===1?"":"s"} loaded`,changeAuditLoadedAt:({time:e})=>`Generated ${e}`,changeAuditRegenerate:"Regenerate",changeAuditRefreshStale:"Fill stale",changeAuditRefreshStaleTitle:"Insert a prompt to refresh stale hunk explanations",clearChangeAudit:"Clear change explanations",clearChangeAuditTitle:"Clear hunk explanations for the current repository",changeAuditClearFailed:({message:e})=>`Failed to clear hunk explanations: ${e}`,changeAuditScopeAll:"All repositories",changeAuditScopeLabel:"Explain scope",branchAuditTitle:"Branch explanation",branchAuditShort:"Explain branch changes",branchAuditBaseLabel:"Base branch",branchAuditBasePlaceholder:"Base branch, e.g. master",branchAuditBaseSearchPlaceholder:"Search base branch",branchAuditBaseEmpty:"No branch options. Type a branch name directly.",branchAuditGenerate:"Generate",branchAuditRegenerate:"Regenerate",branchAuditGenerateTitle:"Insert a prompt to explain this branch against the base branch",branchAuditViewDiff:"View diff",branchAuditViewDiffTitle:"View target branch changes against the base branch",branchAuditDiffLoading:"Loading branch diff...",branchAuditDiffEmpty:"No changes between this branch and the base branch.",branchAuditMissingBase:({repo:e})=>`${e} has no base branch set`,branchAuditRefreshDiff:"Refresh diff",branchAuditRefreshStale:"Fill stale",branchAuditRefreshStaleTitle:"Insert a prompt to refresh stale branch explanations",branchAuditClearTitle:"Clear current branch explanation",branchAuditClearFailed:({message:e})=>`Failed to clear branch explanation: ${e}`,branchAuditCommitCount:({count:e})=>`${e} commit${e===1?"":"s"}`,branchAuditFileCount:({count:e})=>`${e} file${e===1?"":"s"}`,branchAuditTruncated:"diff truncated",branchAuditCurrent:"Saved explanation",branchAuditStale:"Explanation is stale",branchAuditEmpty:"No branch explanation yet. Generate one to persist it here for later review.",branchAuditView:"View explanations",branchAuditSaved:({count:e})=>`${e} hunk explanation${e===1?"":"s"} saved`,branchAuditGeneratedAt:({time:e})=>`Generated ${e}`,insertPreset:({label:e})=>`Insert: ${e}`,tabChanges:"Changes",tabGit:"Git",tabFiles:"Files",tabAndroid:"Device",tabComputer:"Mac",showAndroidTab:"Show device tab",showArchitectureTab:"Show architecture tab",showComputerTab:"Show computer tab",inserted:"Inserted",copied:"Copied",toggleContextDraft:"Toggle context draft",contextDraftTitle:"Context draft",contextDraftHint:"References are added here while enabled. Keep browsing, add instructions, then insert once.",contextDraftPlaceholder:"Compose a longer prompt here. Keep using sidebar references to add context…",contextDraftCollapse:"Collapse context draft",contextDraftExpand:"Expand context draft",contextDraftDisable:"Disable context draft",contextDraftClear:"Clear draft",contextDraftInsert:"Insert",contextDraftInsertAndSend:"Insert & send",contextDraftInserted:"Inserted",contextDraftSent:"Sent",contextDraftSend:"Send draft",contextDraftAppended:"Reference added",contextDraftResize:"Drag to resize, double-click for default height",contextDraftAutoCollapseAfterSend:"Collapse after insert/send",contextDraftInsertFailed:"Input not accepted — draft kept. Close the active form or return to the terminal and retry.",contextDraftPending:"Waiting…",contextDraftCharacterCount:({count:e})=>`${e} chars`,selectFilePrompt:"Select a file to preview its contents",backToFileList:"Back to file list",backToPreviousPreview:"Back to source document",insertLineRef:({lineLabel:e})=>`Insert ${e}`,insertFileRef:"Insert",copyFileRef:"Copy file reference",findInFile:"Find in file",findInFilePlaceholder:"Find in this file…",previousSearchMatch:"Previous match",nextSearchMatch:"Next match",closeFileSearch:"Close file search",downloadFile:"Download file",downloadFailed:"Download failed",downloadCanceled:"Download canceled",downloadSaved:"File saved",downloadStarted:"Browser download started",uploadPending:"Uploading…",uploadInserting:"File uploaded · waiting for input acceptance…",uploadDone:({count:e})=>`${e} files uploaded`,uploadReferenceDone:"File uploaded · reference added",uploadReferenceRejected:"File uploaded; reference not added. Close the active form or return to the original terminal and retry.",uploadLimit:"Choose up to 50 files. None were uploaded; select a smaller batch.",uploadCanceled:"Upload stopped. Check the target directory before uploading again.",uploadFileCount:({count:e})=>`${e} selected files`,uploadFile:"Upload file",uploadFiles:"Upload files",insertLocalFile:"Insert local file",insertLocalImage:"Insert local image",layoutMode:"Display mode",layoutModeAuto:"Auto",layoutModeNarrow:"Narrow",layoutModeWide:"Wide",dropToUpload:"Drop files to upload",uploading:"Uploading…",uploadSuccess:({count:e})=>`${e} file${e===1?"":"s"} uploaded`,uploadFailed:"Upload failed",binaryPreviewHint:"Binary files cannot be previewed. Use the download button above to save it.",selectedLineHint:({lineLabel:e})=>`Selected ${e} · tap "Insert" below to add to terminal`,multiLineHint:"Multi-line select: tap start line, then end line",loadingImage:"Loading image…",imagePreviewHint:"Pinch or ⌘/Ctrl + scroll to zoom · double-tap to reset",imageLoadFailed:"Failed to load image preview",loadingVideo:"Loading video…",videoPreviewHint:"Click to play · hold 2× and drag forward to speed up · arrows seek/volume · space pauses",videoLoadFailed:"Failed to load video preview",videoUnsupported:"Your browser does not support this video format",videoPlay:"Play",videoPause:"Pause",videoLongPressSpeed:({rate:e})=>`Playing at ${e}×`,videoVolume:({percent:e})=>`Volume ${e}%`,videoRotate:"Rotate 90° clockwise",videoFullscreenEnter:"Enter fullscreen",videoFullscreenExit:"Exit fullscreen",model3dLoading:"Loading 3D model…",model3dExplode:"Exploded view",model3dExplodeAxis:"Explosion axis (viewer coordinates)",model3dExplodeAmount:"Explosion amount",model3dHome:"Reset view",model3dFit:"Fit visible parts",model3dFront:"Front view",model3dTop:"Top view",model3dRight:"Right view",model3dAssemble:"Restore assembly",model3dExplodedNotice:"Exploded · dimensions and references remain assembled",model3dLoadFailed:"Failed to load 3D model preview",model3dTimeout:"3D model transfer timed out. Check your connection and retry.",model3dDimensions:({dims:e})=>`Dimensions: ${e}`,model3dHintMouse:"Drag to orbit · two-finger pan · pinch or scroll to zoom",model3dHintTouch:"One finger to orbit · two fingers to zoom & pan",model3dFullscreenEnter:"Fullscreen",model3dFullscreenExit:"Exit fullscreen",model3dBgToLight:"Light background",model3dBgToDark:"Dark background",model3dRefresh:"Reload model",model3dClipToggle:"Section view",model3dClipPosition:"Section position",model3dClipFlip:"Flip section direction",model3dFeatureToggle:"Features",model3dFeatureStatus:({total:e,positioned:t})=>`Features: ${e} · positioned ${t}`,model3dFeatureInsert:"Insert reference",model3dGlossaryToggle:"Modeling terms",model3dPickToggle:"Select part / reference",model3dPickHint:"Select a part to hide it or insert a point reference",model3dHidePart:"Hide part",model3dShowAllParts:({count:e})=>`Show all (${e})`,model3dParts:"Parts",model3dCloseParts:"Close parts",model3dSearchParts:"Find a part",model3dClearPartSearch:"Clear part search",model3dHiddenParts:({count:e})=>`${e} hidden`,model3dShowNamedPart:({name:e})=>`Show ${e}`,model3dHideNamedPart:({name:e})=>`Hide ${e}`,model3dIsolateNamedPart:({name:e})=>`Only show ${e}`,model3dIsolatePart:"Only this part",model3dShowPart:"Show part",model3dNoParts:"No matching parts",model3dUndoVisibility:"Undo",model3dClearSelection:"Clear selection",model3dAllPartsVisible:"All parts visible",model3dInspectHint:"Drag to orbit · double-tap to zoom · double-tap empty space to fit",model3dUnnamedPart:({index:e})=>`Part ${e}`,model3dCanvas:"3D model",model3dMore:"More model options",edaLoading:"Rendering KiCad file…",reviewTargetChanged:"The active session changed. Return to the original session before inserting this reference.",reviewReference:"Review reference",reviewReferenceHint:"Add context, then insert. Nothing is sent automatically.",reviewSnapshot:"Snapshot of the selected viewer",reviewCapturing:"Capturing this view…",reviewIncludeImage:"Include snapshot (stored temporarily on this server)",reviewCaptureFailed:"Snapshot unavailable; location can still be inserted.",reviewNote:"Your comment (optional)",reviewNotePlaceholder:"What should change here?",reviewDetails:"View location and quoted content",reviewUploading:"Preparing reference…",reviewAddToDraft:"Add to context draft",reviewInsert:"Insert reference",reviewUploadFailed:"Could not prepare the reference. Your comment is kept. Retry, or uncheck the snapshot to insert text only.",edaLoadFailed:"Failed to render KiCad preview",edaTimeout:"KiCad preview rendering or transfer timed out. Please retry.",edaRefresh:"Render again",edaPickHint:"Click a schematic or PCB location to create an electronics annotation",edaPickedPosition:({x:e,y:t})=>`Selected ${e}%, ${t}%`,edaPickedBoardPosition:({x:e,y:t,object:n})=>`Board ${e}, ${t} mm · ${n}`,edaInspecting:"Reading board coordinates and nearby object…",edaNoNearbyObject:"No nearby object",edaInsertAnnotation:"Insert electronics annotation",csvUnnamedColumn:({index:e})=>`Column ${e}`,csvSelectedCell:({row:e,column:t})=>`Row ${e} · ${t}`,csvPickHint:({rows:e,columns:t})=>`${e} records · ${t} columns; click a cell to reference`,csvInsertAnnotation:"Insert table annotation",csvTablePreview:"Table preview: select a cell to reference its record",kicadLocalStateNotice:"This is local UI state and is not part of schematic, PCB, or manufacturing review.",kicadShowRawJson:"Show raw JSON",kicadProjectPickHint:"Select a setting to insert a reference",kicadInsertSetting:"Insert setting",markdownPreview:"Preview",markdownSource:"Source",markdownParseFailed:"Markdown preview parsing failed or exceeded its limits. Showing the source text.",markdownPreviewHint:"Tap a line/section to reference, tap another to extend; drag the left rail to select a range",htmlPreview:"Preview",htmlSource:"Source",htmlPreviewHint:"Sandboxed iframe preview; scripts run sandboxed",htmlFullscreenEnter:"Enter fullscreen preview",htmlFullscreenExit:"Exit fullscreen preview",markdownOutline:"Markdown outline",markdownOutlineShort:"Outline",closeMarkdownOutline:"Close outline",changedFromPath:({path:e})=>`from ${e}`,selectedLineFooter:({lineLabel:e})=>`Selected ${e}`,clearSelection:"Clear",allChanges:"All changes",backToChangeList:"Back to list",allRepositories:"All repositories",allRepositoriesShort:"All",repositories:"Repositories",gitRepositorySectionTitle:"Repository",gitRepositoryLabel:"Repository",gitRepositoryPlaceholder:"Select repository",gitRepositorySearchPlaceholder:"Search repositories",gitRepositoryEmpty:"No available repositories",selectRepositoryForGitActions:"Select a repository before running Git actions",selectRepositoryForDiff:"Select a repository or file to view diff",repoNotLoaded:"Tap to load",repoChangedCount:({count:e})=>`${e} change${e===1?"":"s"}`,repoStagedCount:({count:e})=>`${e} staged`,noChanges:"No changes",noMatchingChanges:"No matching changes",loadingGitChanges:"Loading Git changes…",loadingGitChangesSlow:"Large repositories can take a few seconds.",refreshingGitChanges:"Refreshing Git changes…",gitChangesLoadFailed:"Unable to load Git changes",retryGitChanges:"Retry",insertThisFile:"Insert this file reference into terminal",viewDiff:"View diff",diffViewMode:"Change file display mode",diffViewModeList:"Flat list",diffViewModeTree:"Folder tree",diffViewModeAi:"AI walkthrough",changeWalkthroughEmpty:"No AI walkthrough yet. Generate explanations to show the overview, flow, and checks here.",gitInfo:"Git context",wrapLongLines:"Wrap long lines",wrapOn:"Wrapped",wrapOff:"Raw",multiRepoScan:"Scan sub-repos",multiRepoScanTitle:"Scan this workspace for nested Git repositories. Off keeps a single-repo view, which opens much faster on large repos.",horizontalScrollHint:"Swipe left/right to see the full diff",stageFile:"Stage",stageAll:"Stage all",unstageFile:"Unstage",stashFile:"Stash",stashAll:"Stash all",restoreFile:"Restore",gitQuickActions:"Git Actions",gitUnavailable:"Current directory is not a Git repository",branchSectionTitle:"Current branch",currentBranchLabel:"Branch",switchBranchPlaceholder:"Select branch",switchBranchSearchPlaceholder:"Search local branch",switchNoBranches:"No local branches",switchBranch:"Switch",noStagedChangesShort:"no staged",stagedCount:({count:e})=>`${e} staged`,stagedCountShort:({count:e})=>`${e} staged`,commitSectionTitle:"Commit",commitReadyHint:({count:e})=>`${e} file${e===1?"":"s"} ready`,commitMessagePlaceholder:"Commit message",commitChanges:"Commit",commitNeedsStaged:"Stage changes before committing",commitAhead:"↑ Unpushed",commitBehind:"↓ Incoming",commitSynced:"Synced",recentCommitsTitle:"Recent commits",recentCommitsSearchPlaceholder:"Search commit hash or message",recentCommitsLoadMore:"Load more commits",recentCommitsEmpty:"No commit history",pushSectionTitle:"Remote sync",pushRemoteLabel:"Remote",pushRemotePlaceholder:"origin",pushRemoteSearchPlaceholder:"Search remote",pushNoRemotes:"No remotes",pushBranchLabel:"Target",pushBranchPlaceholder:({branch:e})=>`${e}`,pushBranchSearchPlaceholder:"Search branch",pushNoBranches:"No branches",pushUpstreamBadge:"upstream",pushCurrentBranchBadge:"current",pushNoUpstream:"No upstream configured",pushUpToDate:"Up to date with remote",pushAheadCount:({count:e})=>`${e} commit${e===1?"":"s"} to push`,pushBehindCount:({count:e})=>`${e} commit${e===1?"":"s"} to pull`,pushDivergedCount:({ahead:e,behind:t})=>`${e} ahead / ${t} behind`,pullChanges:"Pull",pushChanges:"Push",gitActionRunning:"Running…",gitActionFailed:({message:e})=>`Git action failed: ${e}`,confirmRestoreTitle:"Discard changes?",confirmRestoreDescription:({path:e})=>`This will discard unstaged changes in ${e}. Termdock cannot recover them.`,confirmRestorePhrase:"discard changes",confirmRestorePlaceholder:"Type “discard changes” to confirm",confirmStashAllTitle:"Stash all changes?",confirmStashAllDescription:"This moves current working tree changes, including untracked files, into a stash.",confirmAction:"Confirm",renderingHtml:"Rendering HTML…",footnotes:"Footnotes",backToFootnote:({index:e})=>`Back to footnote ${e}`,openMermaidDiagram:"Open Mermaid diagram",mermaidDiagram:"Mermaid diagram",renderingDiagram:"Rendering diagram…",markdownImage:"Markdown image",image:"Image",previousImage:"Previous image",nextImage:"Next image",closeImagePreview:"Close image preview",emptyFile:"Empty file.",insertReference:({reference:e})=>`Insert reference: ${e}`,copyReference:({reference:e})=>`Copy reference: ${e}`,byteCount:({count:e})=>`${e} bytes`,previewTruncated:"Preview truncated to 1 MB",branchCandidatesLoading:"Loading branch candidates…",includeUncommitted:"Include local uncommitted changes",includeUncommittedCurrentBranchOnly:"Available only when the compared branch is checked out",includeUncommittedHint:"Include working tree and untracked diffs when viewing or explaining changes",missingBaseReposSkipped:({repositories:e})=>`Repositories without a base branch will be skipped: ${e}`,localBranch:"local",remoteBranch:"remote"},fileTree:{insertRef:"Insert",insertRefTitle:"Insert file reference into active terminal",openDirRoot:"Open",openDirRootTitle:"Use this folder as the current browsing root",openInFileBrowser:"Reveal in Finder",openInFileBrowserTitle:"Open this item in the system file browser",openInFileBrowserFailed:"Failed to open file browser",moreDirActions:"More folder actions",searchFromDir:"Search from here",searchFromDirTitle:"Search only this folder and its descendants",pinDir:"Pin",pinDirTitle:"Pin this folder to the current project",unpinDir:"Pinned",unpinDirTitle:"Unpin this folder",pinFileTitle:"Pin this file to the current project",unpinFileTitle:"Unpin this file",pinFile:"Pin",unpinFile:"Unpin",moreFileActions:"More file actions",deleteFile:"Delete file",deleteFileConfirm:({name:e})=>`Delete “${e}”? This action cannot be undone.`,deleteFileFailed:({message:e})=>`Failed to delete file: ${e}`,noWorkingDir:"No working directory detected.",emptyDir:"Empty directory.",noMatchingFiles:"No matching files.",searching:"Searching files…",searchingWithCount:({count:e})=>`Searching… ${e} found`,searchResults:({count:e})=>`${e} results`,searchScope:"Search scope",searchTruncatedHint:({count:e})=>`Fallback search scanned a large directory and stopped after ${e} matches. Install ripgrep or refine the query for complete results.`,searchStillRunning:"Search is still running. More results will appear automatically.",showingSearchResults:({shown:e,total:t})=>`Showing ${e} of ${t}`,loadMoreSearchResults:({shown:e,total:t})=>`Show more (${e}/${t})`,contentMatchesCount:({count:e})=>`${e} file${e===1?"":"s"} with matches`,moreMatches:({count:e})=>`+${e} more match${e===1?"":"es"}`,noContentMatches:"No matches found in file contents.",contentSearchNeedsRipgrep:"Content search requires ripgrep (rg). Install it on the server to search inside files.",truncatedHint:"Showing first 1000 entries. Use search or open a smaller folder for better performance.",dropToUploadHere:"Upload here",symbolicLink:"Symbolic link",sortByModified:"Sort by recent changes",sortByName:"Sort by name",sortedByModified:"Sorted by recent changes"},diffViewer:{noFileChanges:"No changes in this file.",noUnstagedChanges:"No unstaged changes.",emptyHint:"Make some changes, or pull from a remote.",loading:"Loading diff…",insertAllDiff:"Insert current diff as context",insertFileDiff:"Insert this file's diff",insertHunkDiff:"Insert this hunk",insertLineDiff:"Insert the selected diff lines",insertHunkShort:"Insert",insertFileShort:"Insert",insertAllShort:"Insert all",stageHunk:"Stage",stageHunkTitle:"Stage only this hunk (git apply --cached)",revertHunk:"Revert",revertHunkTitle:"Revert this hunk in the worktree (cannot be undone)",revertHunkConfirm:"Confirm revert?",hunkActionReverted:"Reverted",hunkActionStaged:"Staged",hunkActionApplying:"Applying…",hunkActionUnavailable:"Cannot build a patch for this hunk",hunkActionFailed:({message:e})=>`Failed: ${e}. If the changes moved on, refresh and retry.`,auditExplanation:"Change meaning",auditStale:"Explanation stale",auditClear:"Clear explanation",auditGeneratedAt:({time:e})=>`Generated ${e}`,allDiffLabel:"all changes",allChangesLabel:"all changes",workingTree:"Working tree changes",allUnstaged:"All unstaged changes",binaryOrEmpty:"No textual changes to display.",noFinalNewline:"No newline at end of file",noHunks:"No hunks",hunkOutline:"Hunks",expandHunkRail:"Show hunk list",collapseHunkRail:"Hide hunk list",prevHunk:"Previous hunk",nextHunk:"Next hunk",prevFile:"Previous",nextFile:"Next",expandFile:"Expand file",collapseFile:"Collapse file",expandAll:"Expand all",collapseAll:"Collapse all",collapseHunk:"Collapse hunk",useBracketKeysHint:"Press [ / ] to jump between hunks",unified:"Unified",unifiedMode:"Unified view",split:"Split",splitMode:"Side-by-side view",moreActions:"More actions",view:"View",loadingPreviousFile:"Loading previous file…",loadingNextFile:"Loading next file…",resizeNavigation:"Resize diff navigation",focusPathHint:"Select a label to focus its path",whitespace:"Whitespace",whitespaceDefault:"Default",whitespaceTrim:"Ignore trailing",whitespaceIgnore:"Ignore all",whitespaceIgnoreBlankLines:"Ignore blank lines",context:"Context",expandAbove:({count:e})=>`Expand ${e} lines above`,expandBelow:({count:e})=>`Expand ${e} lines below`,contextLines:({count:e})=>`${e} lines`,contextAll:"All"},settings:{title:"Settings",font:"Font",render:"Render",workspaceLimit:"Keep service pages",workspaceUnlimited:"Unlimited",workspaceLimitHint:"Applies on this device, including the entry page. Lower limits save memory. Older background pages reconnect when revisited; terminal tasks keep running.",theme:"Theme",darkTheme:"Dark",lightTheme:"Light",newTab:"New tab",debug:"Debug",noSleep:"No sleep",noSleepUnavailable:"No network — disabled",updateTitle:"Termdock update",updateRuntimeTitle:"CLI and service runtime",updateHint:"A manual check downloads and installs a new version immediately. The service restarts only after you confirm.",updateCheck:"Check for updates",updateCheckAgain:"Check again",updateChecking:"Checking npm for the latest version…",updateCheckingShort:"Checking…",updateInstallingShort:"Installing…",updateCurrent:"Termdock is up to date.",desktopUpdateTitle:"macOS desktop app",desktopUpdateHint:"Manually check signed desktop releases published on GitHub.",desktopUpdateUnsupported:"In-app updates require an installed, signed macOS app.",desktopUpdateChecking:"Checking for a desktop update…",desktopUpdateCurrent:"The desktop app is up to date.",desktopUpdateDownloadingShort:"Downloading…",desktopUpdateDownloading:"A new version is downloading in the background…",desktopUpdateReady:"The desktop update is downloaded and ready to install.",desktopUpdateInstalling:"Restarting to install the desktop update…",desktopUpdateCheck:"Check desktop app",desktopUpdateCheckAgain:"Check again",desktopUpdateRestart:"Restart and install",desktopUpdateRestartConfirm:"Restart Termdock and install the downloaded desktop update? The terminal service and tmux sessions will remain running.",serverHealthTitle:"Service health",serverHealthHint:"What happened to the Termdock service recently.",serverHealthSupervised:"Automatic recovery is on: the service will attempt to restart if it crashes or stops responding.",serverHealthUnsupervised:"Built-in automatic recovery is off. A crash may require a manual restart.",serverHealthEnable:"Enable and restart",serverHealthEnableHint:"Enabling restarts the service and briefly disconnects clients. Plain terminals may close; tmux sessions can reconnect. Repeated startup failures stop automatic retries.",serverHealthEnabling:"Enabling…",serverHealthEnablePending:"Waiting for reconnection to confirm automatic recovery…",serverHealthEnableError:"Could not confirm automatic recovery. Reconnect to check its status. If the service is unreachable, check the startup logs on its host.",serverHealthEnableUnavailable:"This launch method cannot enable recovery here. Configure supervision on the service host; desktop and externally managed services remain managed by their launcher.",serverHealthClean:"No problems recorded.",serverHealthHistory:"Previous problem",serverHealthRunningNow:"The service is running now with automatic recovery enabled.",serverHealthLastIncident:"Last problem",serverHealthRestarted:({count:e})=>`Restarted automatically ${e}${e===1?" time":" times"}`,serverHealthGaveUp:({count:e})=>`This supervisor stopped retrying after ${e} consecutive failures.`,serverHealthSupervisorLost:"Automatic recovery is unavailable. The service is still running.",serverHealthOomNote:"Memory was near the limit before it died; the OOM killer may have taken it.",serverHealthUptime:({duration:e})=>`ran for ${e}`,serverHealthDismiss:"Got it",serverHealthDismissed:"Acknowledged",serverHealthUnknownEvent:"Something went wrong",serverHealthEventStartupFailure:"Failed to start",serverHealthEventCrash:"Crashed",serverHealthEventCrashNative:"Crashed in native code",serverHealthEventKilled:"Killed outright",serverHealthEventWedge:"Stopped responding and had to be killed",serverHealthEventPortConflict:"Could not start: the port is already in use",serverHealthEventGaveUp:"Repeated failures; retries stopped at that time",serverHealthEventExitZero:"Exited with code 0 without being asked to",serverHealthEventTerminated:"Terminated by another process",serverHealthEventSupervisorLost:"Lost contact with the supervisor",serverHealthEventUncaughtException:"Hit an uncaught exception",serverHealthEventUnhandledRejection:"Had an unhandled promise rejection",serverHealthEventExitNonzero:"Exited with an error code",notifications:"Notify",notificationsTitle:"Notification settings",notificationsHint:"Notify when an AI task finishes while Termdock is hidden.",notificationsPageHint:"Choose which Termdock events can send system notifications. The master switch controls browser permission and delivery; event switches decide what should notify you.",notificationsMaster:"System notifications",notificationsMasterHint:"Allow Termdock to send notifications when it is hidden or running as an installed PWA.",notificationsIOSInstallHint:"On iPhone and iPad, install Termdock to the Home Screen before enabling notifications.",notificationsPermission:"Permission",notificationsPermissionSystem:"Managed by macOS",notificationsTest:"Send test",notificationsTestChecking:"Waiting for macOS to confirm delivery…",notificationsTestDelivered:"Delivered to Notification Center. If no banner appeared, check the alert style and Focus.",notificationsTestFailed:"macOS did not deliver the notification. Allow Termdock in System Settings.",notificationsOpenSystemSettings:"Open system notification settings",notificationsAlertStyle:"Alert style",notificationsAlertStyleHint:"Browsers and Android still decide the final heads-up behavior. Termdock can only request quiet/default/sticky notification options.",notificationsStyleNormal:"Default",notificationsStyleNormalHint:"Sound/vibration if allowed",notificationsStyleQuiet:"Quiet",notificationsStyleQuietHint:"Status tray, no sound",notificationsStylePersistent:"Sticky",notificationsStylePersistentHint:"Stay until dismissed",notificationsEvents:"Events",notificationsAiFinished:"AI task finished",notificationsAiFinishedHint:"Notify when an AI agent stops while Termdock is in the background.",notificationsSessionExited:"Terminal exited",notificationsSessionExitedHint:"Notify when a terminal process exits on its own (closing it yourself does not trigger; delivered via Web Push).",notificationsFutureHint:"More notification types can be added here later without changing the top-level settings layout.",notificationsOffSummary:"System notifications disabled",notificationsAiOnSummary:"AI task finished enabled",notificationsExitOnSummary:"Terminal exit enabled",notificationsBothOnSummary:"AI task finished and terminal exit enabled",notificationsNoEventsSummary:"No notification events enabled",notificationsDenied:"Browser notification permission is blocked. Enable it in site settings.",notificationsUnsupported:"Notifications require a secure context and service worker support.",notificationsTestBody:"Notifications are enabled. You will be notified when an AI task finishes in the background.",shell:"Shell",tmux:"Tmux",auto:"Auto",webgl:"WebGL",canvas:"Built-in",tmuxServer:"Tmux server",tmuxUnavailable:"unavailable",noTmuxSessions:"No tmux sessions on the server.",installTmuxHint:"Install tmux on the server to enable.",refresh:"Refresh",attached:"Attached",restorable:"Restorable",attach:"Attach",attaching:"Attaching…",destroy:"Destroy",sessions:({n:e})=>`${e} session${e===1?"":"s"}`,windows:({n:e})=>`${e} window${e===1?"":"s"}`,keyboardToolbar:"Keyboard toolbar",aiAgentDetection:"AI agent detection",signOut:"Sign out",language:"Language",programNamePlaceholder:"Program name (e.g. claude)",patternPlaceholder:"Regex pattern (e.g. Thinking|Generating)",statusPlaceholder:"Status",addProgram:"Add program",addPattern:"Add pattern",resetDefaults:"Reset defaults",invalidRegex:"Invalid regex",removeProgram:"Remove program",removeRule:"Remove rule",keepLabel:"keep",customColor:"Custom color",tabIndicator:"Tab indicator style",toolbarPresets:"Toolbar presets",detectionRules:"Detection rules",agentHooksHint:"With hooks installed, agents report their own status: working (green), waiting for you (amber), turn done (check) — and you get a notification the moment one needs your input. Hooks install globally but only fire inside termdock terminals.",agentHooksInstall:"Install",agentHooksInstalled:"Installed",agentHooksOutdated:"Outdated",agentHooksNeedsApproval:"Needs approval",agentHooksApprovalHint:"Run /hooks in Codex and approve the Termdock hooks",agentHooksNotInstalled:"Not installed",agentHooksUninstall:"Uninstall",agentHooksReinstall:"Reinstall",agentHooksDevMode:"Dev mode: hooks point at TS sources and need a built install to fire",agentHooksTarget:"writes to",agentAutoRename:"Automatic session titles",agentAutoRenameHint:"Update the title from recent work when an agent finishes a turn. Off by default; manual titles are never overwritten. External plugin CLIs run only after their title feature is enabled.",agentAutoRenameToggle:"Toggle automatic titles for this agent",agentAutoRenameShort:"Auto title",agentAutoRenameNamer:"Title agent",agentAutoRenameFollow:"Follow current session",agentAutoRenameModelsFromCli:"Models discovered from local CLIs",agentAutoRenameRefreshModels:"Refresh CLI models",agentAutoRenameCliDefault:"CLI default model",agentAutoRenameAutomatic:"Automatic selection",agentAutoRenameNoCli:"No supported title CLI detected",agentAutoRenameAdvanced:"Advanced title preferences",agentAutoRenamePreference:"Additional preferences",agentAutoRenamePreferenceHint:"Optional. Add preferences for title style or emphasis; Termdock keeps its default naming rules. Saved when you leave the field.",agentAutoRenamePreferencePlaceholder:"For example: emphasize user value; use action phrases; avoid technical jargon",agentAutoRenamePayloadLimit:"User-message context limit (characters)",agentAutoRenamePayloadLimitHint:"Total raw prompt-submit payload characters retained. Default 12000; range 1000–64000.",agentPlugins:"Agent Plugins",agentPluginAdd:"Add Plugin",agentPluginHint:"Install from an HTTPS Git repository or local directory after reviewing the source. Hooks and executable title CLIs require separate user opt-in.",agentPluginCreate:"Create Plugin",agentPluginDelete:"Delete Plugin",agentPluginInvalid:"Invalid plugin manifest",agentPluginCopyAiPrompt:"Copy AI fix prompt",agentPluginCopied:"Copied",agentPluginSourcePlaceholder:"https://github.com/user/agent-plugin or local directory",agentPluginInstallPackage:"Install plugin",agentPluginAdvancedManifest:"Advanced: paste manifest.json",agentPluginUpdateAvailable:"Update available",agentPluginManualSource:"Manual manifest",agentPluginUpdate:"Update",agentPluginCheck:"Check",agentPluginDoctor:"Diagnose",agentPluginDoctorHint:"Explicitly probe plugin models without generating a title",agentPluginDoctorStatusOk:"Title and model capabilities are healthy",agentPluginDoctorStatusMissing:"titleNamer is not declared",agentPluginDoctorStatusCliDefault:"Titles are available using the CLI default model",agentPluginDoctorStatusNoModels:"No usable model data was returned",agentPluginDoctorStatusFailed:"Model probe failed",agentPluginDoctorModels:"usable models",agentPluginDoctorAutomatic:"automatic",agentPluginDoctorCliDefault:"When no model is specified, the Agent CLI default model is used",agentAutoRenameInterval:"Recheck interval",agentAutoRenameMinutes:"minutes",mobileKeyboard:"Mobile keyboard",saving:"Saving…",rulesHint:"Configure regex patterns to detect what an AI tool is doing in a terminal tab. Each rule can choose its label, color, icon style and how long the indicator is kept after output quiets down. When it stops and you haven't viewed the tab yet, the tab keeps a yellow review hint.",programsHelp:"Supports multiple programs in one config. Separate with commas.",programLabelResolution:"Program label resolution",rawCommandMapping:"Raw command mapping",rawCommandMappingHint:"Rules below map the raw command line to the tab display label. User rules run before built-ins.",genericProgramNames:"Generic program names",genericProgramNamesHint:"Trigger ps-based deep detection (e.g. node, python)",wrapperScriptNames:"Wrapper script names",wrapperScriptNamesHint:"CLI wrappers that launch another tool (e.g. aiden, npx)",shellNamesConfig:"Shell names",shellNamesHint:"Filtered out from tab display (e.g. bash, zsh)",addTag:"+ add",customRules:"Custom rules",addRule:"Add rule",localAccess:"Local access",localAccessHint:"Connection addresses and phone setup instructions",resetAutoName:"Reset auto",mobileSetupIntro:"Connect your phone to the same network as this service. If HTTPS is enabled, install and trust its CA certificate first, then open an address below.",mobileSetupDownload:"1. Scan to download the CA certificate",mobileSetupIos:"iPhone / iPad: scan with the Camera and open in Safari. Install the downloaded profile in Settings → General → VPN & Device Management, then enable full trust in Settings → General → About → Certificate Trust Settings.",mobileSetupAndroid:"Android: download the certificate and install it as a CA certificate in system security settings. Menu names vary by device.",mobileSetupConnect:"2. Open Termdock",mobileSetupConnectHint:"After trusting the certificate, scan an IP address QR code below or copy the local address to your phone browser. If the hostname does not resolve, use an IP address.",onboardingUrl:"Mobile setup",httpsActive:"HTTPS active",httpsInactive:"HTTPS inactive",caMissing:"CA download unavailable",closeSettings:"Close settings",desktopTitle:"Termdock Desktop",desktopStatusLoading:"Reading native macOS status…",desktopSwitchService:"Switch service",desktopOpenDataDirectory:"Open data directory"},toolbarPresets:{preview:"Preview",presets:"Presets",label:"Label",new:"New",reset:"Reset",presetLabelPlaceholder:"Preset label",deletePreset:({name:e})=>`Delete preset ${e}`,matchPrograms:"Match programs",typeEnterHint:"Type & Enter",programsPlaceholder:"vim, nvim, /^claude(-code)?$/i …",programsHelp:"Plain names match as case-insensitive substrings. Wrap in /…/flags for regex (tested against the lowercase program name).",altSlot:"Alt modifier slot",altSlotHint:"Reserve one preview slot for the Alt key.",desktopVisibility:"Show on desktop",desktopVisibilityHint:"Desktop shows only this preset’s custom actions, not the basic keyboard shortcuts.",rowLayout:"Row layout",rowLayoutHint:"Buttons per expanded row.",addRow:"Row",rowN:({n:e})=>`Row ${e}`,del:"Del",buttons:"Buttons",buttonsHint:"Tap to edit. Use ↑↓ to reorder.",addButton:"Add button",noCustomButtons:"No custom buttons yet. Add one to override the default toolbar.",moveUp:"Move up",moveDown:"Move down",removeRow:({n:e})=>`Remove row ${e}`,removeAction:({name:e})=>`Remove ${e}`,labelField:"Label",labelPlaceholder:"Label shown on the button",sequence:"Sequence",sequencePlaceholder:"e.g. /undo or \\t or /||undo",sequenceHint:"Double-tap sequence",doubleTap:"Double-tap sequence",doubleTapAdd:"+ Add",doubleTapPlaceholder:"e.g. /undo\\r or /||undo ||\\r",remove:"Remove",noSequence:"No sequence",preset:"Preset",overCapacityHint:"More buttons than slots. Extra rows will use the last row size."},agentRules:{ruleColors:{green:"Green",yellow:"Yellow",red:"Red",blue:"Blue",purple:"Purple",orange:"Orange",gray:"Gray"}},tab:{session:"Session",new:"New session",rename:"Rename",renameHint:"Change the tab display name",renamePlaceholder:"Leave empty to reset to default",copyCwd:"Copy cwd",copyCwdHint:"Copy the current working directory",fontSize:"Font size",fontSizeHint:"Only for this session",fontSizeReset:"Follow global",resumeAgent:"Resume agent session",resumeAgentHint:"Resume the last conversation by its native session id",resumeAgentAvailable:"Agent conversation available to resume",resumeAgentRecoveredTitle:({agent:e})=>`${e} conversation available`,resumeAgentRecoveredHint:"This terminal was rebuilt after an interruption. Continue where you left off.",resumeAgentNow:"Resume",resumeAgentLater:"Dismiss for now",resumeAgentSubmitting:"Submitting the native resume command…",resumeAgentWaiting:"Waiting for the Agent to confirm the restored conversation…",resumeAgentSuccess:({agent:e})=>`${e} conversation restored`,resumeAgentFailed:"Could not resume the Agent conversation. You can retry.",resumeAgentConflict:"This Agent conversation is already open in another terminal.",resumeAgentBusy:"Wait for the current Agent turn to finish before resuming.",resumeAgentTimeout:"The Agent did not confirm the restored conversation. Check the terminal or retry.",tmuxRecoveryTitle:({count:e})=>`tmux exited unexpectedly; ${e} Agent session(s) can be restored`,tmuxRecoveryHint:"Termdock kept the native session IDs. Restore continues each conversation in its original tab.",tmuxRecoveryRestoreAll:"Restore all",tmuxRecoveryRestoring:"Restoring…",tmuxRecoveryDismiss:"Not now",tmuxRecoveryPartial:({restored:e,failed:t})=>`Restored ${e}; ${t} still need attention.`,tmuxRecoveryFailed:"Recovery failed. Check the terminals and try again.",tmuxRecoveryDismissFailed:"Could not dismiss the recovery notice.",tmuxRecoveryProgress:({total:e,queued:t,paused:n,resourceWait:r,running:o,succeeded:i,failed:s})=>`Recovery: ${i}/${e} complete · ${t} queued · ${n} paused (${r} waiting for resources) · ${o} running · ${s} failed`,tmuxRecoveryPausedForResources:"Resources are below budget. New launches are paused and will resume automatically when capacity returns.",tmuxRecoveryPause:"Pause",tmuxRecoveryResume:"Resume",tmuxRecoveryInProgress:"Recovery in progress",copied:"Copied",close:"Close session",closeHint:"Remove this tab from the list",longPressTip:"Tip: hold a tab still for a moment to open actions; hold and drag to reorder.",sessionsTitle:"Sessions",explorerTitle:"Explorer",split:"Split",splitTitle:"Add to split workspace",closeFailed:({name:e})=>`Could not close ${e}. The session is still open. Try again.`,splitNew:"New session in workspace",splitNewHint:"Uses the current directory and default type; add as many panes as needed",splitExisting:"Choose a session or workspace",splitExistingHint:"Create multiple independent workspaces; choosing another workspace merges them",splitCurrent:"Current",splitClose:"Exit split",splitLayout:"Split layout",splitHorizontal:"Side by side",splitVertical:"Stacked",splitGrid:"Grid",splitWorkspace:"Split group",splitWorkspaces:"Split workspaces",splitRename:"Rename split group",splitRemovePane:"Remove from split",splitExistingGroups:"Existing split groups",splitAvailableSessions:"Available sessions",splitOccupied:"Grouped",splitUnavailableGrouped:"Grouped mode only supports sessions in the same directory",splitEndedGrouped:"Split ended: grouped mode does not support mixed directories",splitNoOtherSessions:"No other sessions are available",sessionCount:({count:e})=>`${e} session${e===1?"":"s"}`,closeChooserTitle:"Destroy tmux session?",closeChooserDescription:"This will stop the session and every process inside it. This cannot be undone.",destroySession:"Destroy session",confirmDestroySession:"Confirm destroy",destroySessionHint:"Stop the tmux session and every process inside it.",dragToClose:"Drag here to close",releaseToClose:"Release to confirm"},agent:{aiRunning:"AI running",needsReview:"Needs review",finishedReview:"AI finished — needs review",aiWaiting:"AI waiting",copyMode:"Copy mode",jumpToNext:"Jump to next session needing attention",jumpToNextRunning:"Jump to next running session",selectRunningSession:"Select a running session",runningSessionGestureHint:"Tap to cycle · swipe sideways to select · hold to drag",currentSession:"Current"},serviceAttention:{title:"Attention across services",summary:"{services} services · {count} sessions",currentService:"Current service",waiting:"Waiting for you",offline:"Offline · Last known status",login:"Sign-in required · Last known status",empty:"No sessions need attention",viewService:"Open service",scope:"Includes opened services. Select a session to go directly to it.",changed:"The pending sessions have changed. Please choose again.",unavailable:"Unable to open this service. Retry from the service list."},connection:{reconnecting:"Reconnecting…"},desktopServices:{switchService:"Switch Termdock service",openServices:"Open services",idle:"Idle",manageServices:"Manage services and names"},terminal:{input:"Terminal input",error:"Error",dropFilesToPastePaths:"Drop files to paste paths",loading:"Loading terminal…",initializing:"Initializing terminal engine…",failedToLoad:"Failed to load terminal",unknownError:"An unknown error occurred",componentFailed:"Terminal component failed to load",paste:"Paste",copied:"Copied",copyFailed:"Copy failed",longPressSelectsText:"Long press selects text",longPressSendsArrows:"Long press sends arrow keys",switchLongPressToArrows:"Switch long press to arrow keys",switchLongPressToCopy:"Switch long press to copy selection"},quota:{title:"Subscription Quota",noProviders:"No subscription providers detected.",noProvidersHint:"Quota tracking becomes available when you use AI coding agents with API keys or OAuth login.",exhausted:"Exhausted",left:({n:e})=>`${e} left`,updated:({time:e})=>`Updated ${e}`,refresh:"Refresh",close:"Close"},errorBoundary:{title:"Something went wrong",unexpected:"An unexpected error occurred",retry:"Try Again",copyDetails:"Copy error details",copied:"Copied",copyFailed:"Copy failed"},error:{type:{network:"Network error",session:"Session error",terminal:"Terminal error",auth:"Authentication error",validation:"Validation error",unknown:"Unknown error"},severity:{low:"Notice: ",medium:"Warning: ",high:"Error: ",critical:"Critical: "},suggestion:{networkCheck:"Check your network connection",networkRetry:"Try reconnecting",networkProxy:"Check proxy settings",networkWait:"Wait for the network to recover",sessionRecreate:"Recreate the session",sessionServer:"Check the server status",sessionCache:"Clear your browser cache",terminalRestart:"Restart the terminal",terminalConfig:"Check the terminal configuration",terminalClear:"Clear the terminal output",authRelogin:"Sign in again",authCredentials:"Check your credentials",authAdmin:"Contact the administrator",validationFormat:"Check the input format",validationParams:"Verify your parameters",validationDocs:"See the documentation",unknownReload:"Reload the page",unknownApp:"Restart the app",unknownSupport:"Contact support"}}},jA={architecture:{choosePaths:"选择目录或文件",browsePaths:"浏览目录",addScopeReference:"引用到分析范围",searchScopePaths:"搜索文件或目录",useCurrentFile:"引用当前文件",useCurrentDirectory:"引用当前目录",browsePathsHint:"展开目录浏览,点击右侧引用按钮加入分析范围。",correctPathsFirst:"请先修正已填写的路径,再添加范围。",pathsHint:"可选择范围或粘贴文件/行引用,路径相对当前项目。",featureScopeHint:"优先在所选范围内定位功能",removePath:"移除路径",chooseThisDirectory:"选择此目录",filterDirectory:"筛选当前目录",loadingPaths:"正在读取目录…",pathsLoadFailed:"无法读取目录,请检查连接或访问权限后重试。",noPaths:"当前目录没有匹配的文件或子目录。",pathsTruncated:"当前目录条目较多,仅显示部分结果;可进入子目录,或直接粘贴目标路径。",selectedPaths:"已选路径",usePaths:"使用所选范围",expandDetail:"查看详情",collapseDetail:"收起说明",backToMap:"返回架构",backToModule:"返回模块",previousModule:"上一模块",parentModule:"返回上一级",viewPrepared:"查看这份分析",closeDetail:"关闭模块详情",connections:"连接关系",outgoing:"连向",incoming:"来自",browseMode:"浏览方式",outlineMode:"模块说明",graphMode:"关系图",analysisNotes:"分析说明",limitations:"范围与限制",analyzedPaths:"已分析源码",fitGraph:"查看全图",fullscreen:"全屏看图",closeFullscreen:"关闭全屏图",panHint:"拖动浏览,双指缩放;点击模块查看说明",newAnalysis:"新建分析",updateAnalysis:"更新当前分析",closePreparation:"关闭分析设置",analysisRange:"分析范围",projectRange:"整个项目",moduleRange:"目录 / 模块",featureRange:"功能链路",modulePaths:"模块路径(每行一个)",modulePlaceholder:"选择目录或文件,或粘贴已有引用,每行一个",featureTarget:"想了解的功能",featurePlaceholder:"例如:文件上传从选择文件到写入存储的完整流程",invalidPaths:"请选择项目内的目录或文件,或粘贴其引用,最多 20 个;项目外路径和 .. 无法使用。",requiredFeature:"请描述一个具体功能,并检查可选起始路径是否为项目内相对路径。",independentHint:"局部分析单独保存,可随时切换。同一范围再次生成会更新对应的图;整个项目使用项目总览。",updateOnly:"只更新当前这份分析,其他架构图会保留。",analysisOptions:"依赖深度与其他选项",dependencyDepth:"依赖追踪",boundaryDepth:"范围边界(更快)",followDepth:"追踪相关调用与依赖",startPaths:"功能范围(可选)",focus:"分析诉求与限制(可选)",focusPlaceholder:"例如:重点解释权限检查和失败重试,忽略界面样式。",savedAnalyses:"已保存分析",libraryFailed:"无法读取分析列表,当前图仍可浏览。请点击刷新重试。",awaitingFile:"这份分析尚未保存。将准备好的指令发送给 Agent;文件保存后这里会自动显示结果。",analyzeModule:"细化分析这个模块",scopeUnavailable:"这份局部架构缺少范围信息,请新建分析以明确分析边界。",tab:"架构",title:"代码架构",generate:"生成",update:"更新",refresh:"刷新架构",prepare:"准备架构分析",promptHint:"使用当前项目的 Agent 分析代码。提示词会放入当前输入区或上下文草稿,检查后发送;架构保存后,这里会自动刷新。请先在终端打开 Agent,分析会消耗其时间和额度。",insertPrompt:"放入输入区",copyPrompt:"复制提示词",previewPrompt:"查看分析提示词",inserting:"正在添加到当前输入区…",insertFailed:"未能添加提示词,请检查当前会话,或从下方复制。",inserted:"请检查当前输入区或上下文草稿,并发送给 Agent。",copied:"提示词已复制。",failed:"复制失败,请从下方提示词中手动复制。",loading:"正在读取项目架构…",invalid:"架构文件格式有误。可以重新分析项目来修复。",loadFailed:"无法读取项目架构,请检查连接与访问权限后重试。",previous:"下面保留上次成功读取的架构。",retry:"重试",empty:"了解这个项目的代码架构",emptyHint:"可以从整个项目、指定目录或某个功能开始分析,无需先生成全项目架构。",savedAt:"保存于",perspective:"视角",breadcrumb:"架构层级",modules:"模块",explore:"展开子模块",sourceFiles:"相关源码",diagram:"架构关系图",diagramHint:"点击模块查看详情",zoomOut:"缩小架构图",zoomIn:"放大架构图",resetZoom:"重置架构图缩放",download:"下载架构图 SVG",downloadFailed:"下载失败,请重试。",diagramFailed:"图表暂时无法渲染,仍可通过下方模块查看架构。",rendering:"正在绘制架构图…"},computer:{returnToDesktop:"返回桌面",tools:"控制设置",closeTools:"关闭控制设置",keyboard:"键盘",keyboardInput:"直接输入到电脑",keyboardPlaceholder:"点这里打字,文字直接发送到电脑",hideKeyboard:"收起键盘",keyboardNavigation:"键盘导航",desktopZoom:"桌面缩放",zoomIn:"放大桌面",zoomOut:"缩小桌面",resetZoom:"恢复适应屏幕",pinchHint:"双指捏合缩放",keyEscape:"发送 Esc",keyLeft:"向左",keyDown:"向下",keyUp:"向上",keyRight:"向右",keySelectAll:"全选",clipboardTool:"剪贴板",zoom:"放大",expand:"全屏",switchTouchMode:"切换触摸方式",touchMode:"触控模式",trackpadMode:"触控板",directTouchMode:"直接触摸",trackpadHint:"单指滑动移动鼠标,轻点点击,长按拖动;双指滚动,双指轻点右键。",directTouchHint:"轻点屏幕上的位置即可点击,拖动手指操作桌面。",trustCertificateHere:"信任此电脑的证书",rememberLogin:"记住登录",autoConnect:"下次打开自动连接",forgetLogin:"清除登录",savedPassword:"已保存,留空直接连接",loginExpired:"登录信息已失效,请重新输入密码。",loginSaveFailed:"登录信息保存或读取失败,请重试。",title:"电脑控制",host:"电脑地址",hostPlaceholder:"192.168.1.20 或 computer.local",username:"用户名(可选)",password:"密码",passwordHint:"填写目标电脑的 VNC 密码;服务器要求账户登录时,同时填写用户名。勾选记住登录后,成功连接时在服务端加密保存。",connect:"连接",disconnect:"断开",cancel:"取消",connecting:"正在连接…",connected:"已连接",disconnected:"连接已断开,可以重新连接。",viewOnly:"仅查看",control:"允许控制",fit:"适应面板",actualSize:"原始尺寸",fullscreen:"展开桌面",exitFullscreen:"收起桌面",setup:"如何连接电脑",step1:"在 Mac 上打开「系统设置 → 通用 → 共享 → 屏幕共享」。",step2:"在屏幕共享设置中允许你的用户访问;使用 VNC 密码时,开启「VNC 查看器可以使用密码控制屏幕」。",step3:"填写当前服务能访问的电脑内网地址;控制服务所在电脑时,选择「当前电脑」。",networkHint:"使用 VNC 端口 5900。浏览器到 Termdock 全程加密;服务到目标电脑的 VNC 段请使用可信内网或 VPN。",service:"当前服务:{name}",remoteTitle:"远程电脑桌面",startHint:"连接后可在这里查看桌面,用鼠标、触摸和键盘操作电脑。",credentials:"请填写登录信息",authenticate:"登录",authFailed:"登录失败,请检查用户名、密码和目标电脑的远程桌面权限。",sharingOff:"电脑未接受 VNC 连接,请先启动桌面共享服务,并检查端口 5900。",unreachable:"无法连接电脑,请检查地址、网络以及防火墙。",timeout:"连接超时,请确认目标电脑已唤醒且能从当前服务访问。",invalidHost:"请填写电脑的内网 IP 或主机名,无需协议或端口。",privateOnly:"仅支持内网或本机地址;远程访问可切换到目标电脑上的 Termdock 服务。",permission:"电脑控制需要当前服务的全权授权。",failed:"电脑连接失败,请重新连接。",clipboard:"发送剪贴板",clipboardPlaceholder:"发送文字到电脑剪贴板",clipboardHint:"输入文字后点 {shortcut} 即可粘贴;也可以只发送到剪贴板。字符支持取决于目标电脑。",remoteClipboard:"电脑复制的文字",copyToDevice:"复制到本机",clipboardCopied:"已复制到本机",clipboardAccessFailed:"无法访问系统剪贴板。可在此输入文字发送,或选中电脑复制的文字手动复制。",clipboardSent:"已发送到电脑剪贴板",shortcuts:"快捷键",switchApps:"切换应用",spotlight:"Spotlight 搜索",desktop:"显示桌面",loading:"正在加载电脑控制…",platform:"目标系统",thisComputer:"当前电脑",otherComputer:"其他电脑",target:"连接哪台电脑",localService:"运行当前 Termdock 服务的电脑 · {name}",advanced:"高级设置",rdpLoginHint:"使用远程桌面设置中的账号和密码。",vncLoginHint:"使用屏幕共享的 VNC 密码。",checkSettings:"检查连接设置",localHint:"本机指运行当前 Termdock 服务的电脑;目标电脑需先启用所选协议的远程桌面服务。",linuxStep1:"Ubuntu / Linux 需要运行 VNC 服务。共享当前桌面时,x11vnc 需要 X11 会话;Ubuntu 登录界面可选择「Ubuntu on Xorg」。",linuxStep2:"设置 VNC 密码,并让服务监听 5900 端口;只有 RDP 的桌面共享无法在此连接。",linuxCommandHint:"在目标电脑的桌面终端执行以下命令,然后填写设置的 VNC 密码。此示例仅允许连接服务所在电脑,不会自动执行:",linuxProtocolHint:"Ubuntu 24.04 的内置远程桌面使用 RDP,此处使用 VNC。Wayland 需要兼容该桌面的 VNC 服务;TigerVNC 虚拟桌面是独立会话,不等同于当前屏幕。",windowsStep1:"在 Windows 上安装并启动兼容 VNC 的桌面共享服务器;Windows 的 RDP 远程桌面无法在此连接。",windowsStep2:"设置 VNC 密码,启用键盘和鼠标控制,并允许当前服务通过防火墙访问 5900 端口。",systemSearch:"系统搜索",protocol:"连接协议",port:"RDP 端口",rdpUsername:"RDP 用户名",domain:"域(可选)",rdpPasswordHint:"填写远程桌面设置中的 RDP 用户名和密码;Ubuntu 的远程登录凭据可能与系统账户不同。勾选记住登录后,成功连接时在服务端加密保存。",rdpBackendUnavailable:"当前服务的 RDP 支持不可用,请先完成服务端 RDP 配置。",rdpBackendRecovery:"请在运行 Termdock 服务的电脑上启动 RDP 后台(guacd),然后刷新此页面重新检查。连接设置会保留;也可在高级设置中切换为 VNC。",rdpFailed:"远程桌面连接失败。请检查目标地址、端口和电脑上的远程桌面设置。",rdpLinuxStep1:"在 Ubuntu 打开「设置 → 系统 → 远程桌面」,启用「桌面共享」或「远程登录」,并设置 RDP 登录凭据。",rdpStep1:"在目标电脑启用 RDP 远程桌面。Windows 可在「设置 → 系统 → 远程桌面」中开启;Mac 内置屏幕共享请使用 VNC。",rdpStep2:"填写远程桌面设置中的用户名、密码和实际端口。RDP 默认端口为 3389;Ubuntu 的桌面共享也可能使用 3390。目标使用自签名证书时,确认电脑身份后可勾选信任证书。",rdpNetworkHint:"浏览器到 Termdock 的画面和输入复用加密通道;RDP 由当前服务连接目标电脑。桌面共享与远程登录可能连接不同会话,是否显示当前屏幕取决于目标服务的设置。",trustCertificate:"信任此电脑的 RDP 证书(跳过校验)",settingsLoading:"正在读取连接设置…",settingsSaving:"正在保存设置…",settingsSaved:"连接设置已保存到当前服务。",settingsSaveFailed:"设置未能保存,当前修改仍在此页面。",settingsLoadFailed:"连接设置读取失败,请重试。",retry:"重试",retryConnect:"重试连接",rdpCertificate:"目标电脑的 RDP 证书未通过校验。确认是你的电脑后,可勾选信任证书并重试。",clipboardFailed:"剪贴板发送失败,请重试。"},app:{name:"Termdock"},android:{device:"设备",selectDevice:"选择设备",noDevices:"未发现设备",closeTab:"关闭设备 Tab",refresh:"刷新设备",connect:"连接",disconnect:"停止投屏",addDevice:"网络连接",addressPlaceholder:"ip:port,例如 192.168.1.20:5555",adbUnavailable:"本机未找到 adb(Android platform-tools),无法投屏。macOS: brew install android-platform-tools;Ubuntu: sudo apt install adb;或在 ~/.termdock/.env 设置 TERMDOCK_ADB_BIN。",scrcpyUnavailable:"本机未找到 scrcpy / scrcpy-server,无法投屏。macOS: brew install scrcpy;Ubuntu: sudo apt install scrcpy;或在 ~/.termdock/.env 设置 TERMDOCK_SCRCPY_BIN。",connecting:"正在连接设备…",reconnecting:"连接断开,正在自动重连…",retrySchedule:"第 {attempt} 次重试将在 {seconds} 秒后开始",lastError:"最近一次错误(重连期间保留)",retry:"重试",idleHint:"选择设备开始投屏",noDevicesHint:"用 USB 连接手机并开启 USB 调试,或在此添加网络设备",back:"返回",home:"主页",recents:"多任务",notifications:"通知栏",rotate:"旋转屏幕",volumeUp:"音量 +",volumeDown:"音量 -",power:"电源",zoomIn:"放大",zoomOut:"缩小",zoomPanHint:"双指拖动可移动画面",inputText:"输入文字",inputPlaceholder:"输入要发送到手机的文字",send:"发送",splitOpen:"在分屏中打开",splitClose:"退出分屏",splitDockedHint:"投屏已在分屏区域显示。",splitDrag:"按住拖动调整位置",insertFixPrompt:"插入修复提示词",screenshot:"截图并插入",recordingStart:"开始录屏",recordingStop:"停止录屏",recording:"正在录屏…",recordingLimit:"已达 5 分钟上限,录屏已停止",recordingStopped:"投屏已中断,录屏已停止",captureInserted:"截图已插入",recordingInserted:"录屏已插入",recordingConfirm:"录屏已结束,如何处理?",recordingInsert:"直接插入",recordingSave:"保存到指定目录",recordingSaveHint:"录像已保存在服务端。可插入终端引用,或另存到服务端目录。",recordingDiscard:"丢弃录屏",captureInserting:"正在插入…",recordingSaving:"正在保存录屏…",captureFailed:"插入失败",captureUnavailable:"当前无法插入到终端",more:"更多",fullscreen:"全屏",fillSidebar:"铺满侧栏",exitFullscreen:"退出全屏",fullscreenHint:"投屏正在全屏显示。",quality:"画质",qualityAutoHint:"根据连接与解码表现动态调码率,不断流、不重连。分辨率保持稳定,操作和服务端录屏不受影响。",qualityAutoUnavailable:"自动调码率已暂停,画面保持连接。",qualityAutoVersionError:"服务端 scrcpy 版本尚未适配(点击查看详情)。",qualityAutoBuildError:"服务端 scrcpy 文件尚未验证兼容(点击查看详情)。",qualityAutoExtensionError:"调码率扩展文件读取、校验或推送失败(点击查看详情)。",qualityAutoTimeoutError:"调码率确认超时,不能据此判断编码器不支持(点击查看详情)。",qualityAutoEncoderError:"设备编码器拒绝了这次调节(点击查看详情)。",qualityAutoChannelError:"调码率控制通道异常(点击查看详情)。",qualityAutoUnknownError:"服务端未提供具体原因,请更新该服务端后重试(点击查看详情)。",qualityLow:"流畅",qualityMedium:"标准",qualityHigh:"高清",qualityCustom:"自定义",qualityResolution:"分辨率",qualityBitRate:"码率",qualityFrameRate:"帧率",qualityAuto:"自动",qualityApply:"应用",presetNamePlaceholder:"预设名称",presetSave:"保存预设",presetDelete:"删除预设",stateUnauthorized:"未授权",stateOffline:"离线",stateUnknown:"状态未知",unauthorizedHint:"请在手机上确认 USB 调试授权。",offlineHint:"设备离线,请重新插拔或重连。"},common:{cancel:"取消",close:"关闭",save:"保存",reset:"重置",loading:"加载中…",error:"错误",retry:"重试",refresh:"刷新",search:"搜索",clear:"清除",delete:"删除",on:"开",off:"关",back:"返回",copy:"复制",decrease:"减少",increase:"增加",use:"使用",previous:"上一个",next:"下一个"},login:{prompt:"termdock login",placeholder:"请输入密码",placeholderBlocked:({s:e})=>`请稍候 ${e}s`,submit:"登录",invalidPassword:"密码不正确,或服务身份无法验证。请检查后重试。",identityMismatch:"服务身份已改变。请与服务所有者核对地址后再试。",unavailable:"暂时无法登录此服务,请检查连接后重试。",authorizationRequired:"此设备需要授权。请向服务所有者索取新的邀请。",currentTarget:({address:e})=>`正在登录 ${e}`,manageServices:"管理服务 / 使用其他地址",failed:"暂时无法登录,请检查连接后重试。",rateLimited:"尝试次数较多,请稍后再试。",continueAfterReconnect:"网络恢复后可继续登录。",savedConnectionRetained:"已保留服务记录,恢复连接后会重新检查访问权限。",invalidAddress:"请输入有效的 HTTPS 服务地址,例如 computer.example:9834 或 https://computer.example:9834。",invalidInvitation:"邀请链接不完整或无效,请重新复制完整链接后重试。"},sidebar:{sessionCreating:"正在启动…",sessionCreateDirectoryUnavailable:"工作目录已失效,请重新选择目录后重试。",sessionCreatePermissionDenied:"没有权限在此目录启动,请选择其他目录。",sessionCreateConnectionFailed:"连接失败,请检查连接后重试。",sessionCreateFailed:"无法启动会话,请重试。",sessions:"会话",noSessions:"暂无打开的会话。",noMatchingSessions:"没有匹配的会话。",toggleSearch:"切换搜索",settings:"设置",moreActions:"更多操作",subscriptionQuota:"订阅额度",pinSidebar:"常驻边栏",unpinSidebar:"取消常驻",runningSessionButton:"运行中会话按钮",runningSessionButtonHint:"轻点循环,横向滑动选择,长按拖动",attentionButton:"待处理提醒按钮",attentionButtonHint:"显示未读、等待处理的黄色悬浮铃铛",updateAvailable:({version:e})=>`Termdock ${e} 可用`,updateInstalling:"正在后台安装,不会中断当前服务。",updateReady:"更新已安装,确认后将重启服务。",updateRestart:"重启并完成更新",updateRestartConfirm:({version:e})=>`确认重启 Termdock 并切换到 ${e}?当前网页会短暂重连,会话不会被关闭。`,updateRestarting:"正在重启,网页将自动重连…",updateFailed:"自动安装失败,提醒会保留。",updateRetry:"重新尝试",serverAttention:"服务出过问题",filterSessions:"过滤会话",clearSearch:"清除搜索",groupByFolder:"按文件夹分组",groupByFolderTitle:"按工作目录把会话归组折叠;与拖拽排序互斥。",ungrouped:"其他",needsAttention:"待处理",waitingForYou:"等你操作",completedUnread:"完成待查看",closeSession:({name:e})=>`关闭 ${e}`,newShell:"Shell",newTmux:"Tmux",newTmuxDisabled:"服务端未安装 tmux",confirmNewShell:"创建 Shell?",confirmNewTmux:"创建 Tmux?",newSession:"新建 Terminal",newSessionWithAgent:({agent:e})=>`新建 ${e}`,moreLaunchOptions:"更多启动选项",recoverableSessions:"可恢复会话",confirmCloseRecoverableSession:({name:e})=>`结束 ${e}?这会停止该会话中的所有进程。`,endRecoverableSession:"结束会话",closeRecoverableSessionFailed:"结束会话失败,请重试。",refreshRecoverableSessions:"刷新可恢复会话",restoreRecoverableSession:({name:e})=>`恢复 ${e}`,restoringRecoverableSession:"恢复中…",restore:"恢复",newSessionAdvanced:"快速启动 Agent",newSessionComposerTitle:"开始新会话",newSessionHint:"选好运行方式和目录后再启动",launchSessionWith:({name:e})=>`启动 ${e}`,setNewSessionDefault:({name:e})=>`将 ${e} 设为默认`,currentNewSessionDefault:({name:e})=>`${e} 是当前默认`,currentDefaultAgent:({name:e})=>`当前默认:${e}`,defaultAgent:"默认",makeDefault:"设为默认",sessionMode:"运行方式",tmuxKeepsRunning:"断开后继续运行",resumeHistory:"最近会话",resumeHistoryCount:({n:e})=>`已保存 ${e} 条`,resumeHistoryLoading:"正在载入最近的 Agent 会话…",resumeHistoryAction:({title:e})=>`恢复 ${e}`,resumeHistoryRemove:({title:e})=>`从最近会话中移除 ${e}`,resumeHistoryLoadFailed:"无法载入最近的 Agent 会话。",resumeHistoryFailed:"无法准备恢复该 Agent 会话。",resumeHistoryRemoveFailed:"无法从历史中移除该会话。",customStartupCommand:"自定义命令",changeStartupCommand:"更改启动命令",saveStartupCommand:"保存命令",startupCommandSaved:"已保存",saveStartupCommandFailed:"保存失败,请检查浏览器存储权限",addStartupCommand:"新增自定义命令…",deleteStartupCommand:"删除命令",startupCommand:"启动命令",resetStartupCommand:"恢复默认",startupCommandPlaceholder:"例如 vim、htop 或 npm run dev",agentStartupCommandHint:"可修改完整命令;留空使用 Agent 默认命令。保存到当前浏览器。",terminalStartupCommandHint:"在所选目录启动程序,例如 vim README.md。保存到当前浏览器。",workingDirectory:"工作目录",directoryPlaceholder:"输入目录路径",browseDirectories:"浏览目录",hideDirectoryBrowser:"收起目录",chooseDirectory:"选择工作目录",directoryPickerHint:"进入文件夹,确认后才会更改工作目录。",useThisFolder:"使用此目录",recentDirectories:"最近使用的目录",startCommand:"启动命令",customCommand:"其他命令",commandPlaceholder:"可选,例如 codex",detectAgents:"重新检测 Agent",savePreset:"保存为预设",createAndRun:"创建并运行",createSession:"创建 Terminal",openLeftSidebar:"打开左侧边栏",openRightSidebar:"打开右侧边栏",closeSidebar:"关闭边栏"},rightSidebar:{workspace:"工作区",currentProject:"项目",browsingLocation:"浏览中",parentFolder:"上一级目录",backToProjectRoot:"回到当前项目",refreshFiles:"刷新当前目录",resizeFileTree:"拖动调整文件目录宽度",pinCurrentFolder:"固定当前目录到这个项目",unpinCurrentFolder:"取消固定当前目录",showHiddenFiles:"显示隐藏文件",hideHiddenFiles:"不显示隐藏文件",hideGitIgnoredFiles:"隐藏 Git 忽略文件",showGitIgnoredFiles:"显示 Git 忽略文件",gitIgnoreSaveFailed:"保存 Git 忽略文件显示设置失败,请重试",gitIgnoreConfigureHint:"长按或右键配置例外",gitIgnoreExceptionsTitle:"Git 忽略过滤例外",gitIgnoreExceptionsHint:"勾选过滤开启时仍需显示的文件或目录。点击目录右侧箭头可进入选择;选中目录会包含所有子项,文件的父目录会自动保留。保存后生效。",gitIgnoreExceptionsPaths:"选择文件或目录",gitIgnoreExceptionsInvalid:"最多选择 200 个文件或目录。",gitIgnoreExceptionsLoadFailed:"无法加载目录,请重试。",gitIgnoreExceptionsEmptyDirectory:"此目录为空",gitIgnoreExceptionsOpenDirectory:({name:e})=>`进入目录 ${e}`,gitIgnoreExceptionsSelected:({count:e})=>`已选 ${e} 项`,gitIgnoreExceptionsClear:"清空选择",gitIgnoreExceptionsRemove:({path:e})=>`移除 ${e}`,gitIgnoreExceptionsTruncated:"此目录项目过多,仅显示部分内容。",gitIgnoreExceptionsSaveFailed:"保存失败,请检查路径是否位于当前目录内(最多 200 个),然后重试。",insertCurrentFolder:"引用当前目录",insertCurrentFolderShort:"引用",pinnedFolders:"固定",unpinFolder:({name:e})=>`取消固定 ${e}`,fileWatchUnavailable:({message:e})=>`文件监听不可用:${e}。可点击手动刷新。`,browsingOutsideProject:"正在浏览当前项目外目录",browsingOutsideProjectHint:"Git 和改动仍使用当前项目;这里引用的文件会按外部路径插入。",toggleSearch:"切换搜索",refreshGit:"刷新 Git 状态",gitLastUpdated:({time:e})=>`上次更新:${e}`,close:"关闭",filterChanges:"过滤改动或文件",searchPlaceholderContent:"在文件内容中搜索…",searchModeName:"文件",searchModeContent:"内容",clearSearch:"清除搜索",searchScope:"范围",searchScopePlaceholder:"相对目录或绝对路径",resetSearchScope:"恢复搜索当前目录",searchOptions:"搜索选项",searchExclude:"排除",searchExcludePlaceholder:"dist/**, *.lock",clearSearchExclude:"清空排除规则",contentSearchOptions:"内容搜索选项",matchCase:"区分大小写",matchWholeWord:"全词",useRegex:"正则",insertGitContext:"把当前 Git 信息插入 Terminal",copyGitContext:"复制 Git 信息",insertChangeAuditPrompt:"解释当前改动",insertChangeAuditPromptTitle:"把更改审计提示词插入当前会话",changeAuditShort:"解释当前改动",changeAuditLoading:"正在加载 hunk 解释…",changeAuditLoaded:({count:e})=>`已加载 ${e} 条 hunk 解释`,changeAuditLoadedAt:({time:e})=>`最近生成 ${e}`,changeAuditRegenerate:"重新生成",changeAuditRefreshStale:"补充失效",changeAuditRefreshStaleTitle:"为已失效的 hunk 解释插入补充生成提示词",clearChangeAudit:"清理改动解释",clearChangeAuditTitle:"清理当前仓库的 hunk 解释",changeAuditClearFailed:({message:e})=>`清理 hunk 解释失败:${e}`,changeAuditScopeAll:"全部仓库",changeAuditScopeLabel:"解释范围",branchAuditTitle:"分支解释",branchAuditShort:"解释分支改动",branchAuditBaseLabel:"基线分支",branchAuditBasePlaceholder:"基线分支,例如 master",branchAuditBaseSearchPlaceholder:"搜索基线分支",branchAuditBaseEmpty:"没有可选分支,可直接输入分支名",branchAuditGenerate:"生成解释",branchAuditRegenerate:"重新生成",branchAuditGenerateTitle:"生成当前分支相对于基线分支的解释提示词",branchAuditViewDiff:"查看对比",branchAuditViewDiffTitle:"查看目标分支相对于基线分支的改动",branchAuditDiffLoading:"正在加载分支对比…",branchAuditDiffEmpty:"当前分支相对于基线分支暂无改动。",branchAuditMissingBase:({repo:e})=>`${e} 未设置基线分支`,branchAuditRefreshDiff:"刷新对比",branchAuditRefreshStale:"补充失效",branchAuditRefreshStaleTitle:"为已失效的分支解释插入补充生成提示词",branchAuditClearTitle:"清理当前分支解释",branchAuditClearFailed:({message:e})=>`清理分支解释失败:${e}`,branchAuditCommitCount:({count:e})=>`${e} 个提交`,branchAuditFileCount:({count:e})=>`${e} 个文件`,branchAuditTruncated:"diff 已截断",branchAuditCurrent:"已保存解释",branchAuditStale:"解释已失效",branchAuditEmpty:"暂无分支解释。生成后会持久化保存,可随时回来查看。",branchAuditView:"查看解释",branchAuditSaved:({count:e})=>`已保存 ${e} 条 hunk 解释`,branchAuditGeneratedAt:({time:e})=>`生成于 ${e}`,insertPreset:({label:e})=>`插入:${e}`,tabChanges:"改动",tabGit:"Git",tabFiles:"文件",tabAndroid:"设备",tabComputer:"电脑",showAndroidTab:"显示设备 Tab",showArchitectureTab:"显示架构 Tab",showComputerTab:"显示电脑 Tab",inserted:"已插入",copied:"已复制",toggleContextDraft:"切换上下文草稿",contextDraftTitle:"上下文草稿",contextDraftHint:"启用后,引用会追加到这里;可以继续浏览、补写描述,最后一次插入。",contextDraftPlaceholder:"在这里组织长提示词,继续点击侧栏中的引用来追加上下文…",contextDraftCollapse:"收起上下文草稿",contextDraftExpand:"展开上下文草稿",contextDraftDisable:"停用上下文草稿",contextDraftClear:"清空草稿",contextDraftInsert:"插入",contextDraftInsertAndSend:"插入并发送",contextDraftInserted:"已插入",contextDraftSent:"已发送",contextDraftSend:"发送草稿",contextDraftAppended:"已追加引用",contextDraftResize:"拖动调整高度,双击恢复默认",contextDraftAutoCollapseAfterSend:"插入/发送后收起",contextDraftInsertFailed:"输入未被接受,草稿已保留。关闭当前表单或返回终端后重试。",contextDraftPending:"等待接收…",contextDraftCharacterCount:({count:e})=>`${e} 字`,selectFilePrompt:"选择文件以预览内容",backToFileList:"返回文件列表",backToPreviousPreview:"返回来源文档",insertLineRef:({lineLabel:e})=>`引用${e}`,insertFileRef:"引用",copyFileRef:"复制文件引用",findInFile:"在文件内查找",findInFilePlaceholder:"在当前文件中查找…",previousSearchMatch:"上一个匹配项",nextSearchMatch:"下一个匹配项",closeFileSearch:"关闭文件搜索",downloadFile:"下载文件",downloadFailed:"下载失败",downloadCanceled:"下载已取消",downloadSaved:"文件已保存",downloadStarted:"浏览器已开始下载",uploadPending:"正在上传…",uploadInserting:"文件已上传,等待输入接收…",uploadDone:({count:e})=>`已上传 ${e} 个文件`,uploadReferenceDone:"文件已上传,引用已添加",uploadReferenceRejected:"文件已上传,引用尚未添加。关闭当前表单或返回原终端后重试。",uploadLimit:"每次最多上传 50 个文件。本次未上传,请重新选择较小批次。",uploadCanceled:"已停止上传。再次上传前请检查目标目录。",uploadFileCount:({count:e})=>`已选择 ${e} 个文件`,uploadFile:"上传文件",uploadFiles:"上传文件",insertLocalFile:"插入本地文件",insertLocalImage:"插入本地图片",layoutMode:"显示模式",layoutModeAuto:"自动",layoutModeNarrow:"窄版",layoutModeWide:"宽版",dropToUpload:"拖放文件以上传",uploading:"上传中…",uploadSuccess:({count:e})=>`已上传 ${e} 个文件`,uploadFailed:"上传失败",binaryPreviewHint:"二进制文件无法预览,请使用上方下载按钮保存到本地",selectedLineHint:({lineLabel:e})=>`已选 ${e} · 点下方「引用」按钮插入`,multiLineHint:"多行引用:先点起始行,再点结束行",loadingImage:"正在加载图片…",imagePreviewHint:"双指捏合或 ⌘/Ctrl + 滚动缩放 · 双击还原",imageLoadFailed:"图片预览加载失败",loadingVideo:"正在加载视频…",videoPreviewHint:"点击播放 · 长按 2× 并前拖提速 · 方向键调进度/音量 · 空格暂停",videoLoadFailed:"视频预览加载失败",videoUnsupported:"当前浏览器不支持该视频格式",videoPlay:"播放",videoPause:"暂停",videoLongPressSpeed:({rate:e})=>`正在 ${e}× 播放`,videoVolume:({percent:e})=>`音量 ${e}%`,videoRotate:"顺时针旋转 90°",videoFullscreenEnter:"全屏播放",videoFullscreenExit:"退出全屏",model3dLoading:"正在加载 3D 模型…",model3dExplode:"爆炸展开",model3dExplodeAxis:"展开方向(查看器坐标)",model3dExplodeAmount:"展开程度",model3dHome:"回正并看全",model3dFit:"看全可见零件",model3dFront:"正视图",model3dTop:"俯视图",model3dRight:"右视图",model3dAssemble:"恢复装配",model3dExplodedNotice:"爆炸展示 · 尺寸与引用仍为原始装配坐标",model3dLoadFailed:"3D 模型预览加载失败",model3dTimeout:"3D 模型传输超时,请检查连接后重试。",model3dDimensions:({dims:e})=>`尺寸: ${e}`,model3dHintMouse:"拖拽旋转 / 双指平移 / 捏合或滚轮缩放",model3dHintTouch:"单指旋转 / 双指缩放平移",model3dFullscreenEnter:"全屏查看",model3dFullscreenExit:"退出全屏",model3dBgToLight:"切换为白底",model3dBgToDark:"切换为黑底",model3dRefresh:"重新加载模型",model3dClipToggle:"切面查看",model3dClipPosition:"切面位置",model3dClipFlip:"反转切面方向",model3dFeatureToggle:"特征标注",model3dFeatureStatus:({total:e,positioned:t})=>`特征: ${e} 个 · 已定位 ${t}`,model3dFeatureInsert:"引用",model3dGlossaryToggle:"建模名词说明",model3dPickToggle:"选择零件 / 引用",model3dPickHint:"点选零件后可临时隐藏,或引用所选位置",model3dHidePart:"隐藏零件",model3dShowAllParts:({count:e})=>`显示全部(${e})`,model3dParts:"零件",model3dCloseParts:"关闭零件列表",model3dSearchParts:"查找零件",model3dClearPartSearch:"清空零件搜索",model3dHiddenParts:({count:e})=>`已隐藏 ${e}`,model3dShowNamedPart:({name:e})=>`显示 ${e}`,model3dHideNamedPart:({name:e})=>`隐藏 ${e}`,model3dIsolateNamedPart:({name:e})=>`只看 ${e}`,model3dIsolatePart:"只看此件",model3dShowPart:"显示零件",model3dNoParts:"没有匹配的零件",model3dUndoVisibility:"撤销",model3dClearSelection:"取消选择",model3dAllPartsVisible:"全部可见",model3dInspectHint:"单指旋转 · 双指缩放平移 · 双击局部放大,双击空白看全",model3dUnnamedPart:({index:e})=>`零件 ${e}`,model3dCanvas:"三维模型",model3dMore:"更多模型选项",edaLoading:"正在渲染 KiCad 文件…",reviewTargetChanged:"当前会话已切换,请回到创建这条引用的会话后再插入。",reviewReference:"审阅引用",reviewReferenceHint:"补充意见后插入,不会自动发送。",reviewSnapshot:"选中位置的视图快照",reviewCapturing:"正在截取当前视图…",reviewIncludeImage:"附带截图(临时保存在当前服务器)",reviewCaptureFailed:"截图未成功,仍可插入定位信息。",reviewNote:"你的意见(可选)",reviewNotePlaceholder:"例如:这里太厚了,能否减薄?",reviewDetails:"查看定位信息和引用原文",reviewUploading:"正在准备引用…",reviewAddToDraft:"加入引用草稿",reviewInsert:"插入引用",reviewUploadFailed:"引用准备失败,意见已保留。请重试,或取消附带截图后只插入文字。",edaLoadFailed:"KiCad 预览渲染失败",edaTimeout:"KiCad 预览生成或传输超时,请重试。",edaRefresh:"重新渲染",edaPickHint:"点击原理图或 PCB 上的问题位置,生成电子标注",edaPickedPosition:({x:e,y:t})=>`已选位置 ${e}%, ${t}%`,edaPickedBoardPosition:({x:e,y:t,object:n})=>`板坐标 ${e}, ${t} mm · ${n}`,edaInspecting:"正在读取板坐标和附近对象…",edaNoNearbyObject:"附近无对象",edaInsertAnnotation:"引用电子标注",csvUnnamedColumn:({index:e})=>`第 ${e} 列`,csvSelectedCell:({row:e,column:t})=>`已选第 ${e} 行 · ${t}`,csvPickHint:({rows:e,columns:t})=>`${e} 条记录 · ${t} 列,点击单元格引用`,csvInsertAnnotation:"引用表格标注",csvTablePreview:"表格预览:点击单元格后可引用完整记录",kicadLocalStateNotice:"这是本机界面状态文件,不参与原理图、PCB 或生产审查。",kicadShowRawJson:"查看原始 JSON",kicadProjectPickHint:"点击一项配置后可插入引用",kicadInsertSetting:"引用配置",markdownPreview:"预览",markdownSource:"源码",markdownParseFailed:"Markdown 预览解析失败或超过限制,已显示原文。",markdownPreviewHint:"点按行/段落引用,再点一行扩选;拖左侧竖条可连续框选",htmlPreview:"预览",htmlSource:"源码",htmlPreviewHint:"HTML 沙箱 iframe 预览,脚本受限",htmlFullscreenEnter:"全屏预览",htmlFullscreenExit:"退出全屏预览",markdownOutline:"Markdown 目录",markdownOutlineShort:"目录",closeMarkdownOutline:"关闭目录",changedFromPath:({path:e})=>`来自 ${e}`,selectedLineFooter:({lineLabel:e})=>`已选 ${e}`,clearSelection:"清除",allChanges:"全部改动",backToChangeList:"返回目录",allRepositories:"全部仓库",allRepositoriesShort:"全部",repositories:"仓库",gitRepositorySectionTitle:"操作仓库",gitRepositoryLabel:"仓库",gitRepositoryPlaceholder:"选择仓库",gitRepositorySearchPlaceholder:"搜索仓库",gitRepositoryEmpty:"没有可操作的仓库",selectRepositoryForGitActions:"请选择一个仓库后再执行 Git 操作",selectRepositoryForDiff:"选择一个仓库或文件查看 diff",repoNotLoaded:"点击加载",repoChangedCount:({count:e})=>`${e} 个改动`,repoStagedCount:({count:e})=>`${e} 已暂存`,noChanges:"没有改动",noMatchingChanges:"没有匹配的改动",loadingGitChanges:"正在加载 Git 改动…",loadingGitChangesSlow:"仓库较大时可能需要几秒。",refreshingGitChanges:"正在刷新 Git 改动…",gitChangesLoadFailed:"无法加载 Git 改动",retryGitChanges:"重试",insertThisFile:"把这个文件引用插入 Terminal",viewDiff:"查看 diff",diffViewMode:"改动文件展示方式",diffViewModeList:"平铺列表",diffViewModeTree:"目录结构",diffViewModeAi:"AI 导览",changeWalkthroughEmpty:"暂无 AI 导览。生成解释后会在这里展示总览、链路和验证点。",gitInfo:"Git 信息",wrapLongLines:"长行换行",wrapOn:"已换行",wrapOff:"原始",multiRepoScan:"扫描子仓库",multiRepoScanTitle:"扫描当前工作区下的嵌套 Git 仓库。关闭时只看单个仓库,大仓库打开更快。",horizontalScrollHint:"左右滑动查看完整 diff",stageFile:"暂存",stageAll:"全部暂存",unstageFile:"取消暂存",stashFile:"贮藏",stashAll:"全部贮藏",restoreFile:"丢弃",gitQuickActions:"Git 操作",gitUnavailable:"当前目录不是 Git 仓库",branchSectionTitle:"当前分支",currentBranchLabel:"分支",switchBranchPlaceholder:"选择分支",switchBranchSearchPlaceholder:"搜索本地分支",switchNoBranches:"没有本地分支",switchBranch:"切换",noStagedChangesShort:"无暂存",stagedCount:({count:e})=>`已暂存 ${e}`,stagedCountShort:({count:e})=>`已暂存 ${e}`,commitSectionTitle:"提交",commitReadyHint:({count:e})=>`${e} 个文件已准备提交`,commitMessagePlaceholder:"提交信息",commitChanges:"提交",commitNeedsStaged:"请先暂存要提交的改动",commitAhead:"↑ 待推送",commitBehind:"↓ 待拉取",commitSynced:"已同步",recentCommitsTitle:"近期提交",recentCommitsSearchPlaceholder:"搜索提交 hash 或信息",recentCommitsLoadMore:"加载更多提交",recentCommitsEmpty:"暂无提交历史",pushSectionTitle:"同步远端",pushRemoteLabel:"Remote",pushRemotePlaceholder:"origin",pushRemoteSearchPlaceholder:"搜索 Remote",pushNoRemotes:"没有 Remote",pushBranchLabel:"目标分支",pushBranchPlaceholder:({branch:e})=>`${e}`,pushBranchSearchPlaceholder:"搜索分支",pushNoBranches:"没有分支",pushUpstreamBadge:"upstream",pushCurrentBranchBadge:"当前",pushNoUpstream:"当前分支未设置 upstream",pushUpToDate:"与远端同步",pushAheadCount:({count:e})=>`领先远端 ${e} 个提交`,pushBehindCount:({count:e})=>`落后远端 ${e} 个提交`,pushDivergedCount:({ahead:e,behind:t})=>`领先 ${e} / 落后 ${t} 个提交`,pullChanges:"拉取",pushChanges:"推送",gitActionRunning:"执行中…",gitActionFailed:({message:e})=>`Git 操作失败:${e}`,confirmRestoreTitle:"确认丢弃改动",confirmRestoreDescription:({path:e})=>`将丢弃 ${e} 的未暂存改动,此操作不可从 Termdock 恢复。`,confirmRestorePhrase:"丢弃改动",confirmRestorePlaceholder:"输入“丢弃改动”确认",confirmStashAllTitle:"确认贮藏全部改动",confirmStashAllDescription:"会把当前工作区改动(包含未跟踪文件)移入贮藏。",confirmAction:"确认",renderingHtml:"正在渲染 HTML…",footnotes:"脚注",backToFootnote:({index:e})=>`返回脚注 ${e}`,openMermaidDiagram:"打开 Mermaid 图表",mermaidDiagram:"Mermaid 图表",renderingDiagram:"正在渲染图表…",markdownImage:"Markdown 图片",image:"图片",previousImage:"上一张图片",nextImage:"下一张图片",closeImagePreview:"关闭图片预览",emptyFile:"空文件。",insertReference:({reference:e})=>`插入引用:${e}`,copyReference:({reference:e})=>`复制引用:${e}`,byteCount:({count:e})=>`${e} 字节`,previewTruncated:"预览已截断至 1 MB",branchCandidatesLoading:"正在加载分支候选…",includeUncommitted:"包含本地未提交改动",includeUncommittedCurrentBranchOnly:"仅当对比分支是当前检出分支时可开启",includeUncommittedHint:"查看对比或生成解释时纳入工作区和未跟踪文件的 diff",missingBaseReposSkipped:({repositories:e})=>`未设置基线的仓库会跳过:${e}`,localBranch:"本地",remoteBranch:"远端"},fileTree:{insertRef:"引用",insertRefTitle:"Insert file reference into active terminal",openDirRoot:"进入",openDirRootTitle:"把这个目录作为当前浏览根目录",openInFileBrowser:"在 Finder 中显示",openInFileBrowserTitle:"在系统文件浏览器中打开这个项目",openInFileBrowserFailed:"打开文件浏览器失败",moreDirActions:"更多目录操作",searchFromDir:"从这里搜索",searchFromDirTitle:"只搜索这个目录及其子目录",pinDir:"固定",pinDirTitle:"固定这个目录到当前项目",unpinDir:"已固定",unpinDirTitle:"取消固定这个目录",pinFileTitle:"固定这个文件到当前项目",unpinFileTitle:"取消固定这个文件",pinFile:"固定",unpinFile:"已固定",moreFileActions:"更多文件操作",deleteFile:"删除文件",deleteFileConfirm:({name:e})=>`确认删除“${e}”?此操作无法撤销。`,deleteFileFailed:({message:e})=>`删除文件失败:${e}`,noWorkingDir:"未检测到工作目录。",emptyDir:"空目录。",noMatchingFiles:"没有匹配的文件。",searching:"正在搜索文件…",searchingWithCount:({count:e})=>`搜索中…已找到 ${e} 项`,searchResults:({count:e})=>`${e} 个结果`,searchScope:"搜索范围",searchTruncatedHint:({count:e})=>`降级搜索已扫描大量目录并在找到 ${e} 项后停止。安装 ripgrep 或输入更精确关键词可获得完整结果。`,searchStillRunning:"搜索仍在进行,更多结果会自动出现。",showingSearchResults:({shown:e,total:t})=>`正在展示 ${e}/${t}`,loadMoreSearchResults:({shown:e,total:t})=>`查看更多(${e}/${t})`,contentMatchesCount:({count:e})=>`${e} 个文件命中`,moreMatches:({count:e})=>`还有 ${e} 处匹配`,noContentMatches:"文件内容中没有匹配。",contentSearchNeedsRipgrep:"内容搜索需要 ripgrep(rg),请在服务端安装后再在文件内搜索。",truncatedHint:"仅展示前 1000 项。使用搜索或打开更小的文件夹以获得更好性能。",dropToUploadHere:"上传到这里",symbolicLink:"符号链接",sortByModified:"按最近修改排序",sortByName:"按名称排序",sortedByModified:"已按最近修改排序"},diffViewer:{noFileChanges:"此文件无改动。",noUnstagedChanges:"没有未暂存的改动。",emptyHint:"做一些改动,或从远程拉取。",loading:"正在加载 diff…",insertAllDiff:"把当前 diff 内容作为上下文插入 Terminal",insertFileDiff:"引用这个文件的 diff",insertHunkDiff:"引用这段 diff hunk",insertLineDiff:"引用选中的这几行 diff",insertHunkShort:"引用",insertFileShort:"引用",insertAllShort:"全部",stageHunk:"暂存",stageHunkTitle:"只把这个 hunk 加入暂存区 (git apply --cached)",revertHunk:"撤销",revertHunkTitle:"撤销这个 hunk 的工作区改动(不可恢复)",revertHunkConfirm:"确认撤销?",hunkActionReverted:"已撤销",hunkActionStaged:"已暂存",hunkActionApplying:"应用中…",hunkActionUnavailable:"无法为这个 hunk 构造补丁",hunkActionFailed:({message:e})=>`操作失败:${e}。如改动已变化,请刷新后重试。`,auditExplanation:"更改意义",auditStale:"解释已失效",auditClear:"清除解释",auditGeneratedAt:({time:e})=>`生成于 ${e}`,allDiffLabel:"全部 diff",allChangesLabel:"全部改动",workingTree:"工作区改动",allUnstaged:"所有未暂存改动",binaryOrEmpty:"没有可显示的文本改动。",noFinalNewline:"文件末尾没有换行符",noHunks:"没有 hunk",hunkOutline:"Hunk 列表",expandHunkRail:"显示 hunk 列表",collapseHunkRail:"隐藏 hunk 列表",prevHunk:"上一个 hunk",nextHunk:"下一个 hunk",prevFile:"上一个",nextFile:"下一个",expandFile:"展开文件",collapseFile:"折叠文件",expandAll:"全部展开",collapseAll:"全部折叠",collapseHunk:"折叠 hunk",useBracketKeysHint:"按 [ / ] 在 hunk 之间跳转",unified:"统一",unifiedMode:"统一视图",split:"分屏",splitMode:"左右分屏视图",moreActions:"更多操作",view:"视图",loadingPreviousFile:"正在加载上一个文件…",loadingNextFile:"正在加载下一个文件…",resizeNavigation:"调整 diff 导航宽度",focusPathHint:"点击标注聚焦路径",whitespace:"空白",whitespaceDefault:"默认",whitespaceTrim:"忽略行尾空白",whitespaceIgnore:"忽略所有空白",whitespaceIgnoreBlankLines:"忽略空行",context:"上下文",expandAbove:({count:e})=>`向上展开 ${e} 行`,expandBelow:({count:e})=>`向下展开 ${e} 行`,contextLines:({count:e})=>`${e} 行`,contextAll:"全部"},settings:{title:"设置",font:"字体",render:"渲染",workspaceLimit:"保留服务页面",workspaceUnlimited:"不限制",workspaceLimitHint:"在本机生效,包含入口页面。数量越少越省内存;超限释放最久未用的后台页面,切回时重新连接,终端任务继续运行。",theme:"主题",darkTheme:"深色",lightTheme:"浅色",newTab:"新标签",debug:"调试",noSleep:"常亮",noSleepUnavailable:"无网络 — 已禁用",updateTitle:"Termdock 更新",updateRuntimeTitle:"CLI 与服务 Runtime",updateHint:"手动检查会立即下载并安装新版本;服务只会在你确认后重启。",updateCheck:"检查更新",updateCheckAgain:"再次检查",updateChecking:"正在检查 npm 上的最新版本…",updateCheckingShort:"检查中…",updateInstallingShort:"安装中…",updateCurrent:"Termdock 已是最新版本。",desktopUpdateTitle:"macOS 桌面版",desktopUpdateHint:"手动检查 GitHub 发布的签名桌面版本。",desktopUpdateUnsupported:"仅签名安装的 macOS 桌面版支持应用内更新。",desktopUpdateChecking:"正在检查桌面版更新…",desktopUpdateCurrent:"桌面版已是最新版本。",desktopUpdateDownloadingShort:"下载中…",desktopUpdateDownloading:"发现新版本,正在后台下载…",desktopUpdateReady:"桌面版更新已下载,可以重启安装。",desktopUpdateInstalling:"正在重启并安装桌面版更新…",desktopUpdateCheck:"检查桌面版",desktopUpdateCheckAgain:"再次检查",desktopUpdateRestart:"重启并安装",desktopUpdateRestartConfirm:"重启 Termdock 并安装已下载的桌面版更新?终端服务和 tmux 会话不会被停止。",serverHealthTitle:"服务健康",serverHealthHint:"Termdock 服务最近出过什么事。",serverHealthSupervised:"自动恢复已开启:服务崩溃或无响应时会尝试自动重启。",serverHealthUnsupervised:"内置自动恢复未开启,服务异常退出后可能需要手动重启。",serverHealthEnable:"开启并重启",serverHealthEnableHint:"开启后会重启服务并短暂断连。普通终端可能中断,tmux 会话可在重连后恢复。连续多次启动失败时会停止重试。",serverHealthEnabling:"正在开启…",serverHealthEnablePending:"等待服务重连并确认自动恢复状态…",serverHealthEnableError:"未能确认自动恢复已开启。请重连后查看状态;若服务无法连接,请在服务所在设备检查启动日志。",serverHealthEnableUnavailable:"当前启动方式不支持在此开启。请在服务所在设备配置守护启动;桌面版或外部托管服务由原启动程序管理。",serverHealthClean:"没有异常记录。",serverHealthHistory:"历史异常",serverHealthRunningNow:"当前服务正在运行,自动恢复已开启。",serverHealthLastIncident:"最近一次异常",serverHealthRestarted:({count:e})=>`已自动重启 ${e} 次`,serverHealthGaveUp:({count:e})=>`连续失败 ${e} 次后,该守护进程已停止重试。`,serverHealthSupervisorLost:"自动恢复已失效,服务仍在运行。",serverHealthOomNote:"退出前内存接近上限,可能是被 OOM killer 杀掉的。",serverHealthUptime:({duration:e})=>`运行了 ${e}`,serverHealthDismiss:"知道了",serverHealthDismissed:"已确认",serverHealthUnknownEvent:"服务出过问题",serverHealthEventStartupFailure:"启动失败",serverHealthEventCrash:"崩溃退出",serverHealthEventCrashNative:"原生代码崩溃",serverHealthEventKilled:"被强制杀掉",serverHealthEventWedge:"卡死无响应,只能杀掉",serverHealthEventPortConflict:"起不来:端口已被占用",serverHealthEventGaveUp:"当时连续失败,停止重试",serverHealthEventExitZero:"未经要求地以 0 退出",serverHealthEventTerminated:"被其他进程终止",serverHealthEventSupervisorLost:"与监督者失联",serverHealthEventUncaughtException:"触发了未捕获异常",serverHealthEventUnhandledRejection:"有未处理的 Promise 拒绝",serverHealthEventExitNonzero:"以错误码退出",notifications:"通知",notificationsTitle:"通知设置",notificationsHint:"Termdock 在后台时,AI 任务结束后发送系统通知。",notificationsPageHint:"选择哪些 Termdock 事件可以发送系统通知。总开关负责浏览器权限和投递,事件开关决定具体哪些内容提醒你。",notificationsMaster:"系统通知",notificationsMasterHint:"允许 Termdock 在隐藏或作为 PWA 安装运行时发送通知。",notificationsIOSInstallHint:"在 iPhone 或 iPad 上,请先将 Termdock 添加到主屏幕,再开启通知。",notificationsPermission:"权限",notificationsPermissionSystem:"由 macOS 管理",notificationsTest:"发送测试",notificationsTestChecking:"正在等待 macOS 确认投递…",notificationsTestDelivered:"已投递到通知中心;若没有横幅,请检查提醒样式和专注模式。",notificationsTestFailed:"macOS 未投递通知,请在系统设置中允许 Termdock 通知。",notificationsOpenSystemSettings:"打开系统通知设置",notificationsAlertStyle:"提醒方式",notificationsAlertStyleHint:"最终是否横幅弹出仍由浏览器和 Android 系统决定。Termdock 只能请求静默、默认或持续显示等通知选项。",notificationsStyleNormal:"默认",notificationsStyleNormalHint:"允许时声音/震动",notificationsStyleQuiet:"静默",notificationsStyleQuietHint:"仅状态栏,无声音",notificationsStylePersistent:"持续",notificationsStylePersistentHint:"保留到手动关闭",notificationsEvents:"事件",notificationsAiFinished:"AI 任务结束",notificationsAiFinishedHint:"当 Termdock 在后台时,AI agent 停止后发送通知。",notificationsSessionExited:"终端退出",notificationsSessionExitedHint:"终端进程自行结束时发送通知(主动关闭不触发,经 Web Push 投递)。",notificationsFutureHint:"后续可以在这里继续增加更多通知类型,不需要改变顶层设置布局。",notificationsOffSummary:"系统通知已关闭",notificationsAiOnSummary:"AI 任务结束通知已开启",notificationsExitOnSummary:"终端退出通知已开启",notificationsBothOnSummary:"AI 任务结束、终端退出通知已开启",notificationsNoEventsSummary:"暂无开启的通知事件",notificationsDenied:"浏览器通知权限已被阻止,请在站点设置中开启。",notificationsUnsupported:"通知需要安全上下文和 Service Worker 支持。",notificationsTestBody:"通知已开启。后台 AI 任务结束后会提醒你。",shell:"Shell",tmux:"Tmux",auto:"自动",webgl:"WebGL",canvas:"内置",tmuxServer:"Tmux 服务",tmuxUnavailable:"不可用",noTmuxSessions:"服务端没有 tmux 会话。",installTmuxHint:"请在服务端安装 tmux 后启用。",refresh:"刷新",attached:"已连接",restorable:"可恢复",attach:"连接",attaching:"连接中…",destroy:"销毁",sessions:({n:e})=>`${e} 个会话`,windows:({n:e})=>`${e} 个窗口`,keyboardToolbar:"键盘工具栏",aiAgentDetection:"AI 代理检测",signOut:"退出登录",language:"语言",programNamePlaceholder:"程序名(如 claude)",patternPlaceholder:"正则表达式(如 Thinking|Generating)",statusPlaceholder:"状态",addProgram:"添加程序",addPattern:"添加规则",resetDefaults:"恢复默认",invalidRegex:"无效的正则",removeProgram:"移除程序",removeRule:"移除规则",keepLabel:"保持",customColor:"自定义颜色",tabIndicator:"标签指示器样式",toolbarPresets:"工具栏预设",detectionRules:"检测规则",agentHooksHint:"安装 hooks 后,agent 会主动上报状态:回合进行中(绿)、等你授权/回答(黄)、回合完成(对勾),并在等待你输入时推送通知。hooks 全局安装但只在 termdock 的终端里生效。",agentHooksInstall:"安装",agentHooksInstalled:"已安装",agentHooksOutdated:"需更新",agentHooksNeedsApproval:"待授权",agentHooksApprovalHint:"在 Codex 中输入 /hooks,批准 Termdock Hook 后生效",agentHooksNotInstalled:"未安装",agentHooksUninstall:"卸载",agentHooksReinstall:"重新安装",agentHooksDevMode:"开发模式:hooks 指向 TS 源码,需要构建后的版本才能生效",agentHooksTarget:"写入",agentAutoRename:"自动更新会话标题",agentAutoRenameHint:"Agent 完成一轮后,根据近期内容更新标题。默认全部关闭,手工命名的会话不会被覆盖;启用外部插件标题后才会执行其 CLI。",agentAutoRenameToggle:"切换此 Agent 的自动标题",agentAutoRenameShort:"自动标题",agentAutoRenameNamer:"起名 Agent",agentAutoRenameFollow:"跟随当前会话",agentAutoRenameModelsFromCli:"模型由本机 CLI 动态提供",agentAutoRenameRefreshModels:"重新查询 CLI 模型",agentAutoRenameCliDefault:"CLI 默认模型",agentAutoRenameAutomatic:"自动选择",agentAutoRenameNoCli:"未检测到可用于起名的 CLI",agentAutoRenameAdvanced:"高级标题偏好",agentAutoRenamePreference:"补充偏好",agentAutoRenamePreferenceHint:"可选。仅补充你对标题风格或重点的偏好;Termdock 的默认起名规则仍会保留。离开输入框时自动保存。",agentAutoRenamePreferencePlaceholder:"例如:突出用户收益;优先使用动宾结构;避免技术术语",agentAutoRenamePayloadLimit:"用户消息上下文上限(字符)",agentAutoRenamePayloadLimitHint:"保留 prompt-submit 原始 payload 的总字符数,默认 12000,可设置 1000–64000。",agentPlugins:"Agent 插件",agentPluginAdd:"添加插件",agentPluginHint:"从 HTTPS Git 仓库或本地目录安装;请先审查来源。Hooks 和可执行的标题 CLI 均需用户分别启用。",agentPluginCreate:"创建插件",agentPluginDelete:"删除插件",agentPluginInvalid:"插件配置无效",agentPluginCopyAiPrompt:"复制 AI 修复提示",agentPluginCopied:"已复制",agentPluginSourcePlaceholder:"https://github.com/user/agent-plugin 或本地目录",agentPluginInstallPackage:"安装插件",agentPluginAdvancedManifest:"高级:直接粘贴 manifest.json",agentPluginUpdateAvailable:"有更新",agentPluginManualSource:"手动 manifest",agentPluginUpdate:"更新",agentPluginCheck:"检查更新",agentPluginDoctor:"诊断",agentPluginDoctorHint:"显式运行插件模型探测,不会调用标题生成",agentPluginDoctorStatusOk:"标题与模型能力正常",agentPluginDoctorStatusMissing:"未声明 titleNamer",agentPluginDoctorStatusCliDefault:"标题可用,使用 CLI 默认模型",agentPluginDoctorStatusNoModels:"没有可用的模型数据",agentPluginDoctorStatusFailed:"模型探测失败",agentPluginDoctorModels:"个可用模型",agentPluginDoctorAutomatic:"自动选择",agentPluginDoctorCliDefault:"未指定模型时使用 Agent CLI 默认模型",agentAutoRenameInterval:"重新判断间隔",agentAutoRenameMinutes:"分钟",mobileKeyboard:"移动键盘",saving:"保存中…",rulesHint:"配置正则表达式来识别 AI 工具在终端标签中的状态。每条规则可独立设置标签、颜色、图标样式以及输出静默后指示器保留的时长。停止后若你未查看该标签,标签会保留一个黄色待查看提示。",programsHelp:"支持在一个配置中匹配多个程序,用英文逗号分隔。",programLabelResolution:"程序名识别",rawCommandMapping:"原始命令映射",rawCommandMappingHint:"以下规则将原始命令行映射为标签显示名。用户规则优先于内置规则。",genericProgramNames:"通用程序名",genericProgramNamesHint:"触发 ps 深度识别(如 node, python)",wrapperScriptNames:"包装脚本名",wrapperScriptNamesHint:"CLI 包装器,启动其他工具(如 aiden, npx)",shellNamesConfig:"Shell 名称",shellNamesHint:"从标签显示中过滤(如 bash, zsh)",addTag:"+ 添加",customRules:"自定义规则",addRule:"添加规则",localAccess:"本地访问",localAccessHint:"连接地址与手机访问引导",resetAutoName:"恢复自动",mobileSetupIntro:"手机与此服务需处于同一网络。启用 HTTPS 时,先安装并信任本地 CA 证书,再打开下方访问地址。",mobileSetupDownload:"1. 扫码下载 CA 证书",mobileSetupIos:"iPhone / iPad:用相机扫码后在 Safari 打开。在「设置 → 通用 → VPN 与设备管理」安装已下载的描述文件,再到「设置 → 通用 → 关于本机 → 证书信任设置」开启完全信任。",mobileSetupAndroid:"Android:下载证书后,在系统安全设置中将其安装为 CA 证书。不同品牌的菜单名称可能有所不同。",mobileSetupConnect:"2. 打开 Termdock",mobileSetupConnectHint:"信任证书后,扫描下方 IP 地址二维码,或将本地地址复制到手机浏览器。若域名无法解析,请使用 IP 地址。",onboardingUrl:"手机引导",httpsActive:"HTTPS 已启用",httpsInactive:"HTTPS 未启用",caMissing:"未配置 CA 下载",closeSettings:"关闭设置",desktopTitle:"Termdock 桌面端",desktopStatusLoading:"正在读取 macOS 原生状态…",desktopSwitchService:"切换服务",desktopOpenDataDirectory:"打开数据目录"},toolbarPresets:{preview:"预览",presets:"预设",label:"标签",new:"新建",reset:"重置",presetLabelPlaceholder:"预设名称",deletePreset:({name:e})=>`删除预设 ${e}`,matchPrograms:"匹配程序",typeEnterHint:"输入后回车",programsPlaceholder:"vim, nvim, /^claude(-code)?$/i …",programsHelp:"纯字符串按大小写不敏感子串匹配。用 /…/flags 包裹则为正则(针对小写程序名测试)。",altSlot:"Alt 修饰键槽",altSlotHint:"在预览中保留一个 Alt 键槽位。",desktopVisibility:"桌面端显示",desktopVisibilityHint:"桌面端只显示该预设的自定义按钮,不显示基础快捷键。",rowLayout:"行布局",rowLayoutHint:"每行按钮数。",addRow:"行",rowN:({n:e})=>`第 ${e} 行`,del:"删",buttons:"按钮",buttonsHint:"点击编辑,使用 ↑↓ 排序。",addButton:"添加按钮",noCustomButtons:"暂无自定义按钮。添加一个来覆盖默认工具栏。",moveUp:"上移",moveDown:"下移",removeRow:({n:e})=>`移除第 ${e} 行`,removeAction:({name:e})=>`移除 ${e}`,labelField:"标签",labelPlaceholder:"按钮上显示的文本",sequence:"序列",sequencePlaceholder:"例如 /undo 或 \\t 或 /||undo",sequenceHint:"双击序列",doubleTap:"双击序列",doubleTapAdd:"+ 添加",doubleTapPlaceholder:"例如 /undo\\r 或 /||undo ||\\r",remove:"移除",noSequence:"无序列",preset:"预设",overCapacityHint:"按钮数超过槽位,多余按钮将使用最后一行的尺寸。"},agentRules:{ruleColors:{green:"绿",yellow:"黄",red:"红",blue:"蓝",purple:"紫",orange:"橙",gray:"灰"}},tab:{session:"会话",new:"新建会话",rename:"重命名",renameHint:"修改标签的显示名称",renamePlaceholder:"留空则恢复默认名称",copyCwd:"复制当前目录",copyCwdHint:"复制当前工作目录",fontSize:"字体大小",fontSizeHint:"仅对这个会话生效",fontSizeReset:"跟随全局",resumeAgent:"恢复 Agent 会话",resumeAgentHint:"用原生 session id 恢复上次对话",resumeAgentAvailable:"有可恢复的 Agent 对话",resumeAgentRecoveredTitle:({agent:e})=>`可继续上次的 ${e} 对话`,resumeAgentRecoveredHint:"Terminal 曾异常中断,已重新创建;可以从上次对话继续。",resumeAgentNow:"恢复",resumeAgentLater:"暂不恢复",resumeAgentSubmitting:"正在提交原生恢复命令…",resumeAgentWaiting:"正在等待 Agent 确认已载入原会话…",resumeAgentSuccess:({agent:e})=>`${e} 会话已恢复`,resumeAgentFailed:"Agent 会话恢复失败,可以重试。",resumeAgentConflict:"该 Agent 会话已在另一个 Terminal 中打开。",resumeAgentBusy:"当前 Agent 回合尚未结束,暂时不能恢复。",resumeAgentTimeout:"Agent 未确认已载入原会话,请查看 Terminal 输出或重试。",tmuxRecoveryTitle:({count:e})=>`检测到 tmux 异常退出,${e} 个 Agent 可恢复`,tmuxRecoveryHint:"Termdock 保留了原生会话 ID。恢复操作会在原标签页中继续之前的对话。",tmuxRecoveryRestoreAll:"恢复全部",tmuxRecoveryRestoring:"正在恢复…",tmuxRecoveryDismiss:"暂不处理",tmuxRecoveryPartial:({restored:e,failed:t})=>`已恢复 ${e} 个,${t} 个需要重试。`,tmuxRecoveryFailed:"恢复失败,请检查终端状态后重试。",tmuxRecoveryDismissFailed:"暂时无法关闭该恢复提示。",tmuxRecoveryProgress:({total:e,queued:t,paused:n,resourceWait:r,running:o,succeeded:i,failed:s})=>`恢复进度:总计 ${e} · 排队 ${t} · 暂停 ${n}(资源等待 ${r}) · 执行中 ${o} · 完成 ${i} · 失败 ${s}`,tmuxRecoveryPausedForResources:"资源不足,已暂停启动;资源恢复后会自动继续。",tmuxRecoveryPause:"暂停",tmuxRecoveryResume:"继续",tmuxRecoveryInProgress:"恢复进行中",copied:"已复制",close:"关闭会话",closeHint:"从列表移除该标签",longPressTip:"提示:按住标签不动约半秒打开操作菜单,按住并拖动可排序。",sessionsTitle:"会话",explorerTitle:"资源管理器",split:"分屏",splitTitle:"添加到分屏工作区",closeFailed:({name:e})=>`未能关闭「${e}」。会话仍保留,请重试。`,splitNew:"新建会话并加入",splitNewHint:"沿用当前目录和默认会话类型;可连续加入多个会话",splitExisting:"选择已有会话或工作区",splitExistingHint:"会话可组成多个独立工作区;选择另一工作区会将两组合并",splitCurrent:"当前",splitClose:"退出分屏",splitLayout:"分屏布局",splitHorizontal:"左右",splitVertical:"上下",splitGrid:"网格",splitWorkspace:"分屏组",splitWorkspaces:"分屏工作区",splitRename:"重命名分屏组",splitRemovePane:"移出分屏",splitExistingGroups:"已有分屏组",splitAvailableSessions:"可加入的会话",splitOccupied:"已成组",splitUnavailableGrouped:"分组模式下只能分屏同一目录的会话",splitEndedGrouped:"已退出分屏:分组模式不支持跨目录组合",splitNoOtherSessions:"没有可组合的其他会话",sessionCount:({count:e})=>`${e} 个会话`,closeChooserTitle:"销毁 Tmux 会话?",closeChooserDescription:"确认后会终止该会话及其中的所有进程,此操作无法撤销。",destroySession:"销毁会话",confirmDestroySession:"确认销毁",destroySessionHint:"终止 tmux 会话及其中的所有进程。",dragToClose:"拖到此处关闭",releaseToClose:"松手后确认"},agent:{aiRunning:"AI 运行中",needsReview:"需要查看",finishedReview:"AI 已完成 — 需要查看",aiWaiting:"AI 等待中",copyMode:"Copy 模式",jumpToNext:"跳到下一个待处理",jumpToNextRunning:"跳到下一个运行中会话",selectRunningSession:"选择运行中的 Session",runningSessionGestureHint:"轻点循环 · 横向滑动选择 · 长按拖动",currentSession:"当前"},serviceAttention:{title:"所有服务的待处理",summary:"{services} 个服务 · {count} 个会话",currentService:"当前服务",waiting:"等待你处理",offline:"连接已断开 · 显示上次状态",login:"需要重新登录 · 显示上次状态",empty:"暂时没有待处理会话",viewService:"进入服务查看",scope:"汇总已打开的服务,点会话直接进入",changed:"待处理状态已更新,请重新选择。",unavailable:"暂时无法打开该服务,请从服务列表重试。"},connection:{reconnecting:"正在重连…"},desktopServices:{switchService:"切换 Termdock 服务",openServices:"已打开的服务",idle:"空闲",manageServices:"管理服务与名称"},terminal:{input:"终端输入",error:"错误",dropFilesToPastePaths:"拖放文件以输入路径",loading:"正在加载终端…",initializing:"正在初始化终端引擎…",failedToLoad:"终端加载失败",unknownError:"发生未知错误",componentFailed:"终端组件加载失败",paste:"粘贴",copied:"已复制",copyFailed:"复制失败",longPressSelectsText:"长按选择文本",longPressSendsArrows:"长按发送方向键",switchLongPressToArrows:"将长按切换为方向键",switchLongPressToCopy:"将长按切换为复制所选文本"},quota:{title:"订阅配额",noProviders:"未检测到订阅服务。",noProvidersHint:"使用 AI 编程工具并登录后,自动显示配额信息。",exhausted:"已用完",left:({n:e})=>`剩余 ${e}`,updated:({time:e})=>`${e} 更新`,refresh:"刷新",close:"关闭"},errorBoundary:{title:"出现了一些问题",unexpected:"发生意外错误",retry:"重试",copyDetails:"复制错误信息",copied:"已复制",copyFailed:"复制失败"},error:{type:{network:"网络连接错误",session:"会话错误",terminal:"终端错误",auth:"认证错误",validation:"验证错误",unknown:"未知错误"},severity:{low:"提示:",medium:"警告:",high:"错误:",critical:"严重错误:"},suggestion:{networkCheck:"检查网络连接",networkRetry:"尝试重新连接",networkProxy:"检查代理设置",networkWait:"等待网络恢复",sessionRecreate:"重新创建会话",sessionServer:"检查服务器状态",sessionCache:"清理浏览器缓存",terminalRestart:"重启终端",terminalConfig:"检查终端配置",terminalClear:"清除终端输出",authRelogin:"重新登录",authCredentials:"检查凭证",authAdmin:"联系管理员",validationFormat:"检查输入格式",validationParams:"验证参数",validationDocs:"参考文档",unknownReload:"刷新页面",unknownApp:"重启应用",unknownSupport:"联系技术支持"}}},UA=["en","zh"],Lr="en",Uc=new WeakMap;let HA=0;function $A(e,t,n){const r=Uc.get(e);if(!r?.pending||r.pending.id!==t)return;const o=performance.now();if(!document.hidden&&o-r.lastPoll<2500){const i=o-r.pending.sentAt;r.samples.push(i<8e3?i:null),r.samples=r.samples.slice(-20),i<8e3&&(r.lastReply=o,r.handlerMs=typeof n=="number"&&Number.isFinite(n)&&n>=0&&n<=i?n:void 0)}r.pending=void 0}function qA(e){const t={connected:!1,rtt:null,average:null,jitter:null,timeouts:0,samples:0,waiting:!1};if(!e||e.readyState!==WebSocket.OPEN)return t;const n=performance.now();let r=Uc.get(e);if(r||(r={lastPoll:n,lastSent:-1/0,lastReply:-1/0,samples:[]},Uc.set(e,r)),(document.hidden||n-r.lastPoll>=2500)&&(r.pending=void 0,r.lastSent=-1/0,r.lastReply=-1/0),r.lastPoll=n,!document.hidden&&(r.pending&&n-r.pending.sentAt>=8e3&&(r.samples.push(null),r.samples=r.samples.slice(-20),r.pending=void 0),!r.pending&&n-r.lastSent>=5e3)){const l=`quality-${++HA}`;r.pending={id:l,sentAt:n},r.lastSent=n;try{e.send(JSON.stringify({type:"ping",qualityProbeId:l}))}catch{return r.pending=void 0,t}}const o=r.samples.filter(l=>l!==null),i=r.samples[r.samples.length-1],s=n-r.lastReply<15e3,a=o.slice(1).map((l,d)=>Math.abs(l-o[d])),c=[...o].sort((l,d)=>l-d);return{diagnostics:e.getConnectionDiagnostics?.(),minimum:c[0],maximum:c[c.length-1],p95:c[Math.ceil(c.length*.95)-1],history:[...r.samples],handlerMs:s&&i!=null?r.handlerMs:void 0,lastReplyAgeMs:Number.isFinite(r.lastReply)?n-r.lastReply:void 0,connected:!0,rtt:s&&i!=null?Math.round(i):null,average:o.length?Math.round(o.reduce((l,d)=>l+d,0)/o.length):null,jitter:a.length?Math.round(a.reduce((l,d)=>l+d,0)/a.length):null,timeouts:r.samples.length-o.length,samples:r.samples.length,waiting:!!r.pending&&n-r.pending.sentAt>=1500}}function KA(e){const t=e.serviceLabel?.trim();if(!t||/^https?:\/\//i.test(t)||t===e.serviceOrigin)return"远端服务";try{const n=new URL(e.serviceOrigin??"");if(t===n.host||t===n.hostname)return"远端服务"}catch{}return t}function o2(e,t){const n=i=>{const s=i.name.trim();return!s||/^(?:tmux:|remote:|wt-)/i.test(s)||s===i.sessionId?i.agent?.displayName?.trim()||"成员":s},r=n(e),o=t.filter(i=>n(i)===r);return o.length>1?`${r} ${o.findIndex(i=>i.sessionId===e.sessionId)+1}`:r}function i2(e){return e.serviceConnected===!1||["offline","disconnected","service-unreachable","closed","exited"].includes(e.status??"")?"disconnected":e.serviceConnected===!0?"connected":"unknown"}function lo(e){if(!e.startsWith("remote:"))return null;const t=e.slice(7).split(":");if(t.length!==2)return null;try{const n=decodeURIComponent(t[0]),r=decodeURIComponent(t[1]);return!r||new URL(n).origin!==n||!/^https?:/.test(n)?null:{origin:n,id:r}}catch{return null}}class zA{constructor(t){this.source=t,this.peers={state:t.peerProtocol==="unsupported"?"unsupported":t.readPeers?"loading":"unavailable",checkedAt:null}}source;local=null;remote=[];peers;localInFlight=null;peerInFlight=null;listeners=new Set;disposed=!1;peerTimer;lastPeerAttempt=-1/0;generation=0;localHealthy=!1;subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}snapshot(){if(!this.local)return null;const t=new Map;for(const n of this.local.groups)for(const r of n.remoteSessions??[]){const o=lo(r.sessionId);o&&o.origin!==this.source.origin&&o.origin!==this.source.peerOrigin&&t.set(r.sessionId,{...r,status:"offline",serviceConnected:!1})}for(const n of this.remote)t.set(n.sessionId,n);for(const n of this.local.sessions){const r=lo(n.sessionId);t.set(n.sessionId,r&&r.origin!==this.source.origin&&r.origin!==this.source.peerOrigin?{...n,status:"offline",serviceConnected:!1}:n)}for(const n of this.remote){const r=this.peers.services?.find(o=>o.origin===n.serviceOrigin||o.origin===lo(n.sessionId)?.origin);t.set(n.sessionId,r?.connected===!1?{...n,status:"offline",serviceConnected:!1}:n)}return{groups:this.local.groups.map(n=>({...n,remoteSessions:n.remoteSessions?.map(r=>t.get(r.sessionId)??r)})),sessions:[...t.values()],peers:this.peers,capabilities:this.local.capabilities}}emit(){if(this.disposed||!this.localHealthy)return;const t=this.snapshot();if(t)for(const n of this.listeners)n(t)}load(){if(this.disposed)return Promise.reject(new Error("协作连接已切换,请重新加载"));if(this.localInFlight)return this.localInFlight;this.refreshPeers();const t=this.generation,n=Promise.resolve().then(()=>this.source.readLocal()).then(r=>{if(this.disposed)throw new Error("协作连接已切换,请重新加载");if(t!==this.generation)return this.load();if(!Array.isArray(r.groups)||!Array.isArray(r.sessions))throw new Error("协作会话响应无效,请更新服务后重试");return this.local=r,this.localHealthy=!0,this.emit(),this.snapshot()}).catch(r=>{throw t===this.generation&&(this.localHealthy=!1,this.remote=this.remote.map(o=>({...o,status:"offline",serviceConnected:!1}))),r}).finally(()=>{this.localInFlight===n&&(this.localInFlight=null)});return this.localInFlight=n,n}invalidate(){this.generation++,this.localInFlight=null,this.localHealthy=!1}refreshPeers(t=!1){if(this.disposed||!this.source.readPeers||this.peerInFlight||!t&&Date.now()-this.lastPeerAttempt<2e3)return;this.lastPeerAttempt=Date.now(),this.peers.checkedAt||(this.peers={state:"loading",checkedAt:null}),this.emit();const n=this.source.readPeers;this.peerInFlight=Promise.race([Promise.resolve().then(()=>n()),new Promise((r,o)=>{this.peerTimer=setTimeout(()=>o(new Error("服务端协作目录加载超时,请检查服务连接")),2e4)})]).then(r=>{if(this.disposed)return;const o=r.origin===this.source.origin||!!this.source.peerOrigin&&r.origin===this.source.peerOrigin;if(!Array.isArray(r.sessions)||this.source.peerProtocol==="v2"&&(r.protocolVersion!==2||!o)||r.origin&&!o||r.protocolVersion!==void 0&&r.protocolVersion!==2)throw new Error("协作目录响应与当前服务不匹配,请升级服务后重试");this.remote=r.sessions.filter(s=>{const a=lo(s.sessionId);return a&&a.origin!==this.source.origin&&a.origin!==this.source.peerOrigin});const i=r.services?.filter(s=>s.origin!==this.source.origin&&s.origin!==this.source.peerOrigin);this.peers={state:i?.some(s=>!s.connected)?"partial":"ready",checkedAt:Date.now(),services:i,removedServices:r.removedServices}}).catch(r=>{this.disposed||(this.remote=this.remote.map(o=>({...o,status:"offline",serviceConnected:!1})),this.peers={state:"error",checkedAt:Date.now(),error:r instanceof Error?r.message:"跨服务会话加载失败"})}).finally(()=>{clearTimeout(this.peerTimer),this.peerInFlight=null,this.emit()})}dispose(){this.disposed=!0,clearTimeout(this.peerTimer),this.listeners.clear(),this.local=null,this.remote=[]}}async function VA(e,t){const n=navigator.serviceWorker?.controller;if(!n)return null;const r=new MessageChannel;return new Promise(o=>{const i=a=>{clearTimeout(s),r.port1.close(),o(a)},s=setTimeout(()=>i(null),5e3);r.port1.onmessage=a=>{try{const c=new URL(a.data.url,location.origin);i(c.origin===location.origin&&/^\/__termdock-download\/[a-f0-9-]{36}$/.test(c.pathname)?c.href:null)}catch{i(null)}},r.port1.onmessageerror=()=>i(null);try{n.postMessage({type:"termdock:prepare-download",blob:e,filename:t},[r.port2])}catch{i(null)}})}const WA=4*1024*1024,GA=256*1024,XA=1440*6e4;let Sr=0,df;function Zl(){return typeof indexedDB>"u"?Promise.resolve(null):df??=new Promise(e=>{const t=indexedDB.open(`termdock-terminal-snapshots:${dr}`,1);t.onupgradeneeded=()=>t.result.createObjectStore("snapshots",{keyPath:"id"}),t.onerror=()=>e(null),t.onblocked=()=>e(null),t.onsuccess=()=>{t.result.onversionchange=()=>{t.result.close(),df=void 0},e(t.result)}})}function Hc(e){return!!e&&e.version===1&&typeof e.epoch=="string"&&e.epoch.length>0&&Number.isSafeInteger(e.cols)&&e.cols>0&&Number.isSafeInteger(e.rows)&&e.rows>0&&Number.isSafeInteger(e.seq)&&e.seq>0&&typeof e.data=="string"&&e.data.length*2<=GA&&e.savedAt<=Date.now()&&Date.now()-e.savedAt<XA}async function s2(e){const t=Sr;try{const n=await Zl();return!n||t!==Sr?null:await new Promise(r=>{const o=n.transaction("snapshots").objectStore("snapshots").get(e);o.onerror=()=>r(null),o.onsuccess=()=>r(t===Sr&&Hc(o.result)?o.result:null)})}catch{return null}}async function a2(e){const t=Sr;if(Hc(e))try{const n=await Zl();if(!n||t!==Sr)return;await new Promise(r=>{const o=n.transaction("snapshots","readwrite"),i=o.objectStore("snapshots");i.put(e);const s=i.getAll();s.onsuccess=()=>{let a=0,c=0;for(const l of s.result.sort((d,u)=>u.savedAt-d.savedAt))a+=l.data.length*2,(++c>32||a>WA||!Hc(l))&&i.delete(l.id)},o.oncomplete=()=>r(),o.onerror=o.onabort=()=>r()})}catch{}}async function rm(){Sr+=1;try{(await Zl())?.transaction("snapshots","readwrite").objectStore("snapshots").clear()}catch{}}typeof window<"u"&&window.addEventListener("auth:unauthorized",()=>{rm()});const Ut=new Map,un=new Map,YA=32*1024*1024,ZA=8*1024*1024,JA=48;let uo=0,$c=0;function Jl(){$c+=1,Ut.clear(),uo=0;for(const e of un.values())e.controller.abort();un.clear()}typeof window<"u"&&window.addEventListener("auth:unauthorized",Jl);function QA(e,t){const n=Ut.get(e);if(n&&(uo-=n.blob.size,Ut.delete(e)),!(t.blob.size>ZA))for(Ut.set(e,t),uo+=t.blob.size;Ut.size>JA||uo>YA;){const r=Ut.keys().next().value;uo-=Ut.get(r).blob.size,Ut.delete(r)}}async function om(e,t={}){const n=new URL(e,typeof location<"u"?location.origin:"http://localhost");if(!/^\/api\/terminal\/fs\/(read|blob)$/.test(n.pathname))return fetch(e,{signal:t.signal});if(t.signal?.aborted)throw t.signal.reason??new DOMException("Aborted","AbortError");n.searchParams.delete("requestSlotId"),n.searchParams.delete("action"),n.searchParams.sort();const r=n.href;let o=un.get(r);if(!o){const s=new AbortController,a=$c,c=Ut.get(r),l=new Headers,d=c?.headers.get("ETag");d&&l.set("If-None-Match",d);const u=setTimeout(()=>s.abort(new DOMException("File preview timed out. Please retry.","TimeoutError")),t.timeoutMs??15e3),f={controller:s,readers:0,promise:Promise.resolve(null)};f.promise=(async()=>{const h=await fetch(r,{headers:l,signal:s.signal,cache:"no-cache"});let g;return h.status===304&&c?g=c:g={blob:await h.blob(),headers:new Headers(h.headers),status:h.status},$c===a&&!s.signal.aborted&&g.status===200&&g.headers.has("ETag")&&QA(r,g),h.status===401&&Jl(),g})().finally(()=>{clearTimeout(u),un.get(r)===f&&un.delete(r)}),o=f,un.set(r,o)}const i=o;return i.readers+=1,new Promise((s,a)=>{let c=!1;const l=()=>c?!1:(c=!0,t.signal?.removeEventListener("abort",d),i.readers-=1,i.readers===0&&un.get(r)===i&&(un.delete(r),i.controller.abort()),!0),d=()=>{l()&&a(t.signal?.reason??new DOMException("Aborted","AbortError"))};if(t.signal?.addEventListener("abort",d,{once:!0}),t.signal?.aborted){d();return}i.promise.then(u=>{l()&&s(new Response(u.blob,{status:u.status,headers:u.headers}))},u=>{l()&&a(u)})})}const Ql="auth:unauthorized";let lr=null;class Se extends Error{constructor(t,n,r){super(t),this.status=n,this.code=r,this.name="TerminalApiError"}status;code}class Br extends Error{code="TERMINAL_INPUT_REJECTED";constructor(t){super(t),this.name="TerminalInputError"}}async function eC(){const e=await fetch("/api/terminal/update");if(!e.ok)throw new Se("Failed to load update state",e.status);return e.json()}async function tC(){const e=await re(),t=await fetch("/api/terminal/update/check",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Se("Failed to check for updates",t.status);return t.json()}async function nC(e){if(e&&!e())throw new Se("Update confirmation expired");const t=await re();if(e&&!e())throw new Se("Update confirmation expired");const n=await fetch("/api/terminal/update/restart",{method:"POST",headers:{"X-XSRF-TOKEN":t}});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to restart Termdock"}));throw new Se(r.error||"Failed to restart Termdock",n.status)}return n.json()}async function rC(){const e=await re(),t=await fetch("/api/terminal/server-health/enable-supervision",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Se("Failed to enable automatic recovery",t.status)}async function oC(){const e=await fetch("/api/terminal/server-health");if(!e.ok)throw new Se("Failed to load server health",e.status);return e.json()}async function iC(){const e=await re(),t=await fetch("/api/terminal/server-health/dismiss",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Se("Failed to dismiss server health",t.status);return t.json()}async function sC(){const e=await fetch("/api/terminal/quota");if(!e.ok)throw new Se("Failed to fetch quota",e.status);return e.json()}async function aC(){const e=await re(),t=await fetch("/api/terminal/quota/refresh",{method:"POST",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Se("Failed to refresh quota",t.status);return t.json()}const Kn=8e3,im=6e4,cC=32e3,sm=125e3,Xt=1e4,lC=65e3,xr=45e3,dC=18e4,am=8e3,cm=8e3,lm=15e3,uC=1e4,Dr=5e3;let fC=0;const Ii=[];let Ea=!1;function jt(e,t={}){if(typeof window>"u")return;const n=JSON.stringify({level:e==="error"||e==="timeout_or_abort"||e==="response_body_timeout"||e==="response_body_parse_error"?"warn":"info",message:`DIFF_API ${e}`,data:{seq:++fC,ts:Date.now(),...t}});Ii.push(n),hC()}async function hC(){if(!Ea){Ea=!0;try{for(;Ii.length>0;){const e=Ii[0];try{await fetch("/api/client-log",{method:"POST",headers:{"Content-Type":"application/json"},body:e,keepalive:!0}),Ii.shift()}catch{break}}}finally{Ea=!1}}}function ed(e,t,n){const r=new AbortController;let o=setTimeout(()=>{r.abort(new DOMException(n,"TimeoutError"))},t);const i=()=>r.abort(e?.reason);return e&&(e.aborted?i():e.addEventListener("abort",i,{once:!0})),{signal:r.signal,cleanup:()=>{o&&(clearTimeout(o),o=null),e?.removeEventListener("abort",i)}}}async function Te(e,t,n,r){const{signal:o,cleanup:i}=ed(t?.signal??void 0,n,r);try{return await fetch(e,{...t,signal:o})}catch(s){throw s instanceof DOMException&&s.name==="TimeoutError"?new Error(r):s}finally{i()}}async function dm(e,t,n){let r=null;const o=new Promise((i,s)=>{r=setTimeout(()=>s(new Error(n)),t)});try{return await Promise.race([e.text(),o])}finally{r&&clearTimeout(r)}}async function _r(e,t,n){const r=await dm(e,t,n);return JSON.parse(r)}if(typeof window<"u"&&!window.__termdockFetchPatched){window.__termdockFetchPatched=!0;const e=window.fetch.bind(window);window.fetch=async(...t)=>{const n=await e(...t);if(n.status===401){lr=null,Vo();try{window.dispatchEvent(new CustomEvent(Ql))}catch{}}return n}}async function re(){if(lr)return lr;const e=await Te("/api/csrf-token",void 0,am,"CSRF token request timed out");if(!e.ok)throw new Error("Failed to get CSRF token");const t=await _r(e,Dr,"CSRF token response timed out");if(!t.csrfToken)throw new Error("Invalid CSRF token response");return lr=t.csrfToken,lr}function td(){Vo(),lr=null}const pC=2e4,uf=8e3,um=1500,fm=um,Pe=new Map,nd=new Map;function gC(e){return qA(Pe.get(e)?.ws)}const mC=24,wC=40,yC=40,bC=1024*1024,vC=1024*1024,SC=2*1024*1024,xC=36,hm=50,EC=1e3,AC=20,pm=new TextEncoder;function gm(e){return e.items.length-e.head}function ff(e){e.head===e.items.length?(e.items.length=0,e.head=0):e.head>=64&&e.head*2>=e.items.length&&(e.items.splice(0,e.head),e.head=0)}function CC(e){const t=JSON.stringify({id:"0".repeat(xC),type:"ws-data",data:e});return pm.encode(t).byteLength<=SC}function kC(e){return typeof e=="object"&&e!==null&&e.code==="PACKET_QUEUE_BACKPRESSURE"}function hf(e,t){const n=t instanceof Br?t:new Br(t.message),r=e.pendingInputs;r.items.length=0,r.head=0,r.bytes=0,e.inputFlushTimer&&(clearTimeout(e.inputFlushTimer),e.inputFlushTimer=null);try{e.onError?.(n,!0)}finally{e.disconnect()}return n}function IC(e){const t=gm(e.pendingInputs);return e.retryState.retryCount>=2||t>=yC?"congested":e.retryState.retryCount>=1||t>=8?"degraded":"good"}function pf(e){const t=e.pendingInputs;if(!(gm(t)===0||e.ws.readyState!==WebSocket.OPEN))for(;t.head<t.items.length;){const n=t.items[t.head];if(!n){t.head++,ff(t);continue}try{e.ws.send(n.message)}catch(r){if(!kC(r))return hf(e,r instanceof Error?r:new Error(String(r)));if(e.inputRetryAttempts++,e.inputRetryAttempts>=AC)return hf(e,new Br("Terminal input was not accepted after repeated encrypted-channel backpressure"));const o=e.inputRetryDelayMs;e.inputRetryDelayMs=Math.min(EC,o*2),!e.inputFlushTimer&&!e.retryState.isClosed&&(e.inputFlushTimer=setTimeout(()=>{e.inputFlushTimer=null,rd(e)},o));return}t.bytes-=n.bytes,t.items[t.head]=void 0,t.head++,ff(t),e.inputRetryDelayMs=hm,e.inputRetryAttempts=0}}function rd(e){if(e.ws.readyState!==WebSocket.OPEN||e.inputFlushTimer)return;const t=IC(e);if(t==="good")return pf(e);const n=t==="congested"?wC:mC;e.inputFlushTimer=setTimeout(()=>{e.inputFlushTimer=null,pf(e)},n)}const Eo=new Map;function RC(e,t,n,r,o,i){const s=Eo.get(e);!s||s.connection!==i||(Eo.delete(e),t?s.resolve({success:!0,layout:n,selection:o}):s.reject(new Error(r||"Tmux action failed")))}const sr=new Map;function TC(e,t,n,r){const i=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/terminal/${e}/ws`,s=new URLSearchParams({flow:"2",transport:"tmux-client",active:nd.get(e)===!1?"0":"1"});t>0&&s.set("since",String(t)),n&&s.set("epoch",n);const a=r??sr.get(e);return a&&(s.set("cols",String(a.cols)),s.set("rows",String(a.rows))),`${i}?${s}`}const qc=new Map,Kc=new Map;function PC(e,t,n){qc.set(e,t),Kc.set(e,n)}function NC(e){const t=Pe.get(e);return t?.streamEpoch&&t.appliedSeq===t.lastSeq&&t.lastSeq>0?{seq:t.lastSeq,epoch:t.streamEpoch}:null}async function LC(e){const t=await re(),n=await fetch("/api/terminal/create",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({cols:e.cols||80,rows:e.rows||24,mode:e.mode||"shell",tmuxSessionName:e.tmuxSessionName,cwd:e.cwd,termType:e.termType})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to create terminal"}));throw new Error(r.error||"Failed to create terminal session")}return n.json()}function BC(e,t,n,r={}){const{maxRetries:o=10,initialRetryDelay:i=1e3,maxRetryDelay:s=2e4,connectionTimeout:a=15e3}=r,c={maxRetries:o,initialDelayMs:i,maxDelayMs:s,connectionTimeoutMs:a,retryCount:0,retryTimeout:null,connectionTimeoutId:null,isClosed:!1,isSuspended:!1};let l=null,d=qc.get(e)??0,u=Kc.get(e);Kc.delete(e),qc.delete(e);const f={items:[],head:0,bytes:0};let h=!1,g=null;const m=new WeakSet,v=()=>{c.retryTimeout&&(clearTimeout(c.retryTimeout),c.retryTimeout=null),c.connectionTimeoutId&&(clearTimeout(c.connectionTimeoutId),c.connectionTimeoutId=null),g&&(clearTimeout(g),g=null)},w=E=>{E.wakeProbe&&(clearTimeout(E.wakeProbe.timer),E.wakeProbe=void 0),E.heartbeatTimer&&(clearInterval(E.heartbeatTimer),E.heartbeatTimer=null),E.pongTimer&&(clearTimeout(E.pongTimer),E.pongTimer=null),E.inputFlushTimer&&(clearTimeout(E.inputFlushTimer),E.inputFlushTimer=null)},S=E=>{w(E),E.heartbeatTimer=setInterval(()=>{if(E.ws.readyState===WebSocket.OPEN){try{E.ws.send(JSON.stringify({type:"ping"}))}catch{}E.pongTimer&&clearTimeout(E.pongTimer),E.pongTimer=setTimeout(()=>{if(Date.now()-E.lastInboundAt>=uf){h=!0,w(E);try{E.ws.close()}catch{}R(new Error("WebSocket heartbeat timeout"),!1)}},uf)}},pC)},y=()=>{if(c.isClosed=!0,v(),f.items.length=0,f.head=0,f.bytes=0,l){w(l),Pe.delete(e);try{l.ws.close()}catch{}l=null}},A=()=>{if(c.isClosed)return;if(l){m.add(l.ws),w(l);try{l.ws.close()}catch{}}const E=TC(e,d,u,r.getDimensions?.()),C=Ug(E);h=!1,c.connectionTimeoutId=setTimeout(()=>{C.readyState!==WebSocket.OPEN&&(h=!0,C.close(),R(new Error("WebSocket connection timeout"),!1))},a);const k={ws:C,onEvent:t,onError:n,disconnect:y,reconnectNow:b=>{if(!c.isClosed&&(c.isSuspended=!1,!g)){if(v(),l){m.add(l.ws),w(l);try{l.ws.close()}catch{}}b?.silent||t({type:"reconnecting",attempt:Math.min(c.retryCount+1,o),maxAttempts:o}),c.retryCount=Math.min(c.retryCount+1,o),h=!0,g=setTimeout(()=>{g=null,h=!1,A()},0)}},suspendReconnect:()=>{c.isClosed||(c.isSuspended=!0,c.retryTimeout&&(clearTimeout(c.retryTimeout),c.retryTimeout=null))},retryState:c,lastSeq:d,pendingInputs:f,inputRetryDelayMs:hm,inputRetryAttempts:0,inputFlushTimer:null,heartbeatTimer:null,pongTimer:null,lastInboundAt:Date.now(),inboundSequence:0};C.onopen=()=>{c.isClosed||m.has(C)||h||(v(),c.retryCount=0,k.lastInboundAt=Date.now(),k.inboundSequence+=1,S(k),rd(k))},C.onmessage=b=>{if(!(c.isClosed||m.has(C)||h)){k.lastInboundAt=Date.now(),k.inboundSequence+=1;try{const x=JSON.parse(b.data);if(k.wakeProbe&&Pe.get(e)===k){const L=k.wakeProbe;k.wakeProbe=void 0,clearTimeout(L.timer);for(const I of L.listeners)I()}if(x.type==="pong"){$A(C,x.qualityProbeId,x.handlerMs),k.pongTimer&&(clearTimeout(k.pongTimer),k.pongTimer=null);return}if(x.type==="tmux-result"&&x.reqId){RC(x.reqId,x.success!==!1,x.layout,x.error,x.selection,C);return}if(x.type==="tmux-layout"&&x.layout){t({type:"tmux-layout",layout:x.layout});return}if(x.type==="tmux-screen-sync"&&Array.isArray(x.chunks)){t({type:"tmux-screen-sync",chunks:x.chunks.filter(L=>typeof L=="string"),cols:typeof x.cols=="number"?x.cols:void 0,rows:typeof x.rows=="number"?x.rows:void 0,generation:typeof x.generation=="number"?x.generation:void 0});return}if(x.type==="active-program"){t({type:"active-program",activeProgram:x.activeProgram,activeProgramRaw:x.activeProgramRaw,activeProgramSource:x.activeProgramSource});return}if(x.type==="cwd"){t({type:"cwd",cwd:x.cwd});return}if(x.type==="agent-status"){t({type:"agent-status",agentStatus:x.agentStatus??null,agentIndicator:x.agentIndicator??null,agentStatusDetail:x.agentStatusDetail??null,agent:x.agent??null,agentMessage:x.agentMessage??null,agentNativeSessionId:x.agentNativeSessionId??null,agentResumeRecovered:x.agentResumeRecovered===!0,agentRich:x.agentRich===!0,agentActivity:typeof x.agentActivity=="number"?x.agentActivity:0,agentCwd:x.agentCwd??null,reviewed:typeof x.reviewed=="boolean"?x.reviewed:null});return}if(x.type==="git-status"){t({type:"git-status",gitStatus:x.gitStatus??null});return}if(x.type==="quota-status"&&Array.isArray(x.providers)){window.dispatchEvent(new CustomEvent("termdock:quota-update",{detail:x.providers}));return}if(x.type==="focus-mode"){t({type:"focus-mode",focusTrackingRequested:x.focusTrackingRequested===!0});return}if(x.type==="resize-ack"){t({type:"resize-ack",seq:typeof x.seq=="number"?x.seq:void 0,cols:typeof x.cols=="number"?x.cols:void 0,rows:typeof x.rows=="number"?x.rows:void 0,ok:x.ok!==!1,error:typeof x.error=="string"?x.error:void 0,screenSyncPending:x.screenSyncPending===!0,screenSyncGeneration:typeof x.screenSyncGeneration=="number"?x.screenSyncGeneration:void 0});return}if(x.type==="pty-size"){t({type:"pty-size",cols:typeof x.cols=="number"?x.cols:void 0,rows:typeof x.rows=="number"?x.rows:void 0,source:typeof x.source=="string"?x.source:void 0});return}if(x.type==="shell-title"){t({type:"shell-title",title:typeof x.title=="string"?x.title:""});return}if(x.type==="prompt-state"){t({type:"prompt-state",state:x.state==="running"?"running":"idle",exitCode:typeof x.exitCode=="number"?x.exitCode:void 0});return}const T=x;if(T.type==="connected"){k.appliedSeq=void 0,u=T.streamEpoch,k.streamEpoch=u,k.outputProtocol=T.outputProtocol,typeof T.replayLastSeq=="number"&&T.replayLastSeq>=0&&(d=T.replayLastSeq,k.lastSeq=d),t(T),mm(e,nd.get(e)??!0);return}if(T.type==="exit"){y(),t(T);return}if(T.type==="data"){if(k.appliedSeq=void 0,typeof T.seq=="number"&&T.seq<=d)return;typeof T.flowSeq=="number"&&(k.flowSeq=T.flowSeq)}t(T),T.type==="data"&&typeof T.seq=="number"&&Number.isFinite(T.seq)&&T.seq>d&&(d=T.seq,k.lastSeq=d)}catch(x){n?.(x,!1)}}},C.onerror=()=>{c.isClosed||m.has(C)||h||(v(),w(k),h||(h=!0,R(new Error("WebSocket connection error"),!1)))},C.onclose=b=>{if(!(c.isClosed||m.has(C)||h)){if(b.code===xg&&b.reason===Eg){k.reconnectNow({silent:!0});return}if(v(),w(k),h=!0,b.code===4001){console.warn("[Terminal] WS 4001: Session not found on server",{code:b.code,reason:b.reason,stack:new Error().stack}),R(new Error("Session not found on server"),!0);return}if(b.code===4003||b.code===4401){try{window.dispatchEvent(new CustomEvent(Ql))}catch{}R(new Error("Authentication required"),!0);return}R(new Error("WebSocket connection closed"),!1)}},l=k,Pe.set(e,l)},R=(E,C)=>{if(!c.isClosed)if(C)n?.(E,!0),y();else{c.retryCount=Math.min(c.retryCount+1,Math.max(1,o));const k=Math.min(i*Math.pow(2,c.retryCount-1),s);if(t({type:"reconnecting",attempt:c.retryCount,maxAttempts:o}),c.isSuspended)return;c.retryTimeout=setTimeout(()=>{c.isClosed||A()},k)}};return A(),y}async function DC(e,t){const n=Pe.get(e);if(n&&(n.ws.readyState===WebSocket.OPEN||n.ws.readyState===WebSocket.CONNECTING)){const i=JSON.stringify({type:"input",data:t}),s=pm.encode(i).byteLength;if(s>bC||!CC(i))throw new Br("Terminal input exceeds the encrypted socket frame limit");const a=n.pendingInputs;if(a.bytes+s>vC)throw new Br("Terminal input queue is full; retry after the connection recovers");if(a.items.push({message:i,bytes:s}),a.bytes+=s,n.ws.readyState===WebSocket.OPEN){const c=rd(n);if(c)throw c}return}const r=await re(),o=await fetch(`/api/terminal/${e}/input`,{method:"POST",headers:{"Content-Type":"text/plain","X-XSRF-TOKEN":r},body:t});if(!o.ok){const i=await o.json().catch(()=>({error:"Failed to send input"}));throw new Se(i.error||"Failed to send terminal input",o.status,i.code)}}function _C(e,t,n={}){const r=Pe.get(e);if(!r)return!1;if(r.retryState.isSuspended=!1,r.ws.readyState!==WebSocket.OPEN)return r.reconnectNow(),!0;const o=n.visible?fm:um,i=Date.now()+o,s=r.wakeProbe,a=s?.listeners??new Set;if(t&&a.add(t),s&&s.deadline<=i)return!0;s&&clearTimeout(s.timer);const c=setTimeout(()=>{Pe.get(e)!==r||r.retryState.isClosed||(r.wakeProbe=void 0,r.reconnectNow())},o);if(r.wakeProbe={timer:c,listeners:a,deadline:i},s)return!0;try{r.ws.send(JSON.stringify({type:"ping"}))}catch{clearTimeout(c),r.wakeProbe=void 0,r.reconnectNow()}return!0}function OC(e){const t=Pe.get(e);return t?(t.reconnectNow(),!0):!1}function FC(){for(const e of Pe.values())e.suspendReconnect()}function MC(e,t,n){const r=Pe.get(e);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"focus",focused:t,reason:n}))}catch{}}function mm(e,t){nd.set(e,t);const n=Pe.get(e);!n||n.ws.readyState!==WebSocket.OPEN||n.outputProtocol!==2||n.ws.send(JSON.stringify({type:"output-subscription",active:t,since:n.lastSeq,epoch:n.streamEpoch}))}function jC(e){const t=Pe.get(e);!t||t.ws.readyState!==WebSocket.OPEN||t.outputProtocol!==2||(t.appliedSeq=t.lastSeq,!(!t.flowSeq||t.flowSeq===t.acknowledgedFlowSeq)&&(t.acknowledgedFlowSeq=t.flowSeq,t.ws.send(JSON.stringify({type:"output-ack",flowSeq:t.flowSeq,since:t.appliedSeq,epoch:t.streamEpoch}))))}function UC(e,t,n){const r=Pe.get(e);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"viewing",viewing:t,reason:n}))}catch{}}function zc(e){const t=Pe.get(e);if(!(!t||t.ws.readyState!==WebSocket.OPEN))try{t.ws.send(JSON.stringify({type:"agent-review-ack"}))}catch{}}function HC(e,t,n){const r=Pe.get(e);if(!(!r||r.ws.readyState!==WebSocket.OPEN))try{r.ws.send(JSON.stringify({type:"flow-control",paused:t,reason:n}))}catch{}}async function $C(e,t,n,r){Number.isFinite(t)&&Number.isFinite(n)&&t>=1&&n>=1&&(sr.delete(e),sr.set(e,{cols:Math.floor(t),rows:Math.floor(n)}),sr.size>256&&sr.delete(sr.keys().next().value));const o=Pe.get(e);if(o&&o.ws.readyState===WebSocket.OPEN)try{o.ws.send(JSON.stringify({type:"resize",cols:t,rows:n,seq:r}));return}catch{}const i=await re(),s=await fetch(`/api/terminal/${e}/resize`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":i},body:JSON.stringify({cols:t,rows:n,seq:r})});if(!s.ok){const c=await s.json().catch(()=>({error:"Failed to resize terminal"}));throw new Error(c.error||"Failed to resize terminal")}const a=await s.json().catch(()=>({success:!0}));if(a?.success===!1||a?.ok===!1)throw new Error(a?.error||"Failed to resize terminal")}async function qC(e,t){const n=Pe.get(e);if(n&&n.ws.readyState===WebSocket.OPEN)return t.action==="scroll"?(n.ws.send(JSON.stringify({type:"tmux",...t})),{success:!0}):new Promise((i,s)=>{const a=Math.random().toString(36).substring(7);Eo.set(a,{resolve:i,reject:s,connection:n.ws}),n.ws.send(JSON.stringify({type:"tmux",reqId:a,...t})),setTimeout(()=>{Eo.has(a)&&(Eo.delete(a),s(new Error("Tmux action timed out")))},3e4)});const r=await re(),o=await fetch(`/api/terminal/${e}/tmux`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(t)});if(!o.ok){const i=await o.json().catch(()=>({error:"Failed to execute tmux action"}));throw new Se(i.error||"Failed to execute tmux action",o.status,i.code)}return o.json()}async function KC(e){const t=await re(),n=await fetch(`/api/terminal/${e}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok&&n.status!==404){const o=await n.json().catch(()=>({error:"Failed to close terminal"}));throw new Error(o.error||"Failed to close terminal")}Pe.get(e)?.disconnect()}async function zC(e,t){const n=Pe.get(e);if(n){n.retryState.isClosed=!0;try{n.ws.close()}catch{}Pe.delete(e)}const r=await re(),o=await fetch(`/api/terminal/${e}/restart`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify({...t.cwd?{cwd:t.cwd}:{},cols:t.cols??80,rows:t.rows??24,mode:t.mode,tmuxSessionName:t.tmuxSessionName})});if(!o.ok){const i=await o.json().catch(()=>({error:"Failed to restart terminal"}));throw new Error(i.error||"Failed to restart terminal session")}return o.json()}async function VC(e){const t=await Te(`/api/terminal/${e}/health`,{method:"GET"},cm,"Terminal health check timed out");if(!t.ok){if(t.status===404)return{healthy:!1,sessionId:e};const n=await _r(t,Dr,"Terminal health error response timed out").catch(()=>({error:"Failed to check terminal health"}));throw new Error(n.error||"Failed to check terminal health")}return _r(t,Dr,"Terminal health response timed out")}async function WC(e){const t=await re(),n=await Te("/api/terminal/force-kill",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)},uC,"Terminal force-kill request timed out");if(!n.ok){const r=await _r(n,Dr,"Terminal force-kill error response timed out").catch(()=>({error:"Failed to force kill terminal"}));throw new Error(r.error||"Failed to force kill terminal")}}async function GC(){const e=await fetch("/api/terminal/tmux/sessions",{method:"GET"});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to list tmux sessions"}));throw new Error(n.error||"Failed to list tmux sessions")}const t=await e.json();return Array.isArray(t.sessions)?t.sessions:[]}async function XC(){const e=await fetch("/api/terminal/tmux/status",{method:"GET"});if(!e.ok){const t=await e.json().catch(()=>({error:"Failed to get tmux status"}));throw new Error(t.error||"Failed to get tmux status")}return e.json()}async function YC(e){const t=e.trim();if(!t)throw new Error("tmux session name is required");const n=await re(),r=await fetch(`/api/terminal/tmux/sessions/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":n}});if(!r.ok){const i=await r.json().catch(()=>({error:"Failed to kill tmux session"}));throw new Error(i.error||"Failed to kill tmux session")}const o=await r.json();return{cleanedSessions:Array.isArray(o.cleanedSessions)?o.cleanedSessions:[],alreadyGone:!!o.alreadyGone}}async function ZC(e){const t=await re(),n=`ui-restore:${e??"current"}:${Date.now()}:${Math.random().toString(36).slice(2)}`,r=await fetch("/api/terminal/tmux/recovery/restore-all",{method:"POST",headers:{"X-XSRF-TOKEN":t,"Content-Type":"application/json"},body:JSON.stringify({idempotencyKey:n})}),o=await r.json().catch(()=>({}));if(!r.ok)throw new Se(o.error||"Failed to restore tmux Agent sessions",r.status);return o}async function JC(e,t){const n=await re(),r=await fetch(`/api/terminal/tmux/recovery/operations/${encodeURIComponent(e)}/${t?"pause":"resume"}`,{method:"POST",headers:{"X-XSRF-TOKEN":n}});if(!r.ok)throw new Se("Failed to update recovery operation",r.status)}async function QC(){const e=await re(),t=await fetch("/api/terminal/tmux/recovery",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Se("Failed to dismiss tmux recovery",t.status)}const fi=new Map;function ek(e){return JSON.stringify({preferredFrontendSessionId:e.preferredFrontendSessionId??null,mode:e.mode??null,tmuxSessionName:e.tmuxSessionName??null,cwd:e.cwd??null,termType:e.termType??null,createIfEmpty:e.createIfEmpty===!0,requireExisting:e.requireExisting===!0})}async function wm(){const e=await fetch("/api/terminal/session-inventory",{method:"GET"});if(!e.ok){const t=await e.json().catch(()=>({error:"Failed to load session inventory"}));throw new Error(t.error||"Failed to load session inventory")}return e.json()}async function ym(e){const t=ek(e),n=fi.get(t);if(n)return n;const r=await re(),o=Te("/api/terminal/session-inventory/open",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(e)},lm,"Terminal session open request timed out").then(async i=>{if(!i.ok){const s=await _r(i,Dr,"Terminal session open error response timed out").catch(()=>({error:"Failed to open session"}));throw new Se(s.error||"Failed to open session",i.status,typeof s.code=="string"?s.code:void 0)}return _r(i,Dr,"Terminal session open response timed out")}).finally(()=>{fi.get(t)===o&&fi.delete(t)});return fi.set(t,o),o}async function Ri(e,t){const n=await re(),r=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify(t)});if(!r.ok){const o=await r.json().catch(()=>({error:"Failed to update session"}));throw new Error(o.error||"Failed to update session")}return r.json()}async function bm(e){const t=await re(),n=await fetch("/api/terminal/session-inventory/reorder",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({sessionIds:e})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to reorder sessions"}));throw new Error(r.error||"Failed to reorder sessions")}return n.json()}async function vm(e){const t=await re(),n=await fetch(`/api/terminal/session-inventory/sessions/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to remove session"}));throw new Error(r.error||"Failed to remove session")}}async function Sm(){const e=await re(),t=await fetch("/api/terminal/session-inventory/sessions",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok){const n=await t.json().catch(()=>({error:"Failed to clear sessions"}));throw new Error(n.error||"Failed to clear sessions")}}async function tk(){const e=await fetch("/api/terminal/toolbar-presets",{method:"GET"});if(!e.ok){const t=await e.json().catch(()=>({error:"Failed to load toolbar presets"}));throw new Error(t.error||"Failed to load toolbar presets")}return e.json()}async function nk(e){const t=await re(),n=await fetch("/api/terminal/toolbar-presets",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to save toolbar presets"})),o=new Error(r.error||"Failed to save toolbar presets");throw o.current=r.current,o.code=r.code,o}return n.json()}let Yr=null,fo=null;const xm=1500;function fn(){return fo&&Date.now()-fo.readAt<xm?Promise.resolve(fo.value):Yr||(Yr=(async()=>{const e=await fetch("/api/terminal/settings",{method:"GET"});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to load settings"}));throw new Error(n.error||"Failed to load settings")}const t=await e.json();return fo={value:t,readAt:Date.now()},t})().finally(()=>{Yr=null}),Yr)}async function at(e){const t=await re(),n=await fetch("/api/terminal/settings",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok){const o=await n.json().catch(()=>({error:"Failed to update settings"}));throw new Error(o.error||"Failed to update settings")}const r=await n.json();return fo={value:r,readAt:Date.now()},r}async function rk(e=!1){const t=await fetch(`/api/terminal/auto-title/catalog${e?"?refresh=1":""}`);if(!t.ok)throw new Error("Failed to discover title models");const n=await t.json();return Array.isArray(n?.namers)?n.namers:[]}let Zr=null,ho=null;function ok(){return ho&&Date.now()-ho.readAt<xm?Promise.resolve(ho.value):Zr||(Zr=(async()=>{const e=await fetch("/api/terminal/context-draft",{method:"GET"});if(!e.ok){const n=await e.json().catch(()=>({error:"Failed to load context draft"}));throw new Error(n.error||"Failed to load context draft")}const t=await e.json();return ho={value:t,readAt:Date.now()},t})().finally(()=>{Zr=null}),Zr)}async function ik(e,t){const n=await re(),r=await fetch("/api/terminal/context-draft",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":n},body:JSON.stringify({text:e,origin:t})});if(!r.ok){const i=await r.json().catch(()=>({error:"Failed to update context draft"}));throw new Error(i.error||"Failed to update context draft")}const o=await r.json();return ho={value:o,readAt:Date.now()},o}async function Em(e){let t;try{t=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:e})})}catch(r){const o=_s(r);return{ok:!1,reason:Vu(o.code),error:o.message}}if(t.ok)return td(),{ok:!0};const n=await t.json().catch(()=>null);return t.status===429?{ok:!1,reason:"rateLimited",rateLimited:!0,retryAfterMs:typeof n?.retryAfterMs=="number"?n.retryAfterMs:void 0,error:n?.error||"Too many failed attempts. Please wait and try again."}:{ok:!1,reason:Vu(n?.code)||(t.status===401?"invalidPassword":"unavailable"),error:n?.error||"Login failed"}}async function sk(){Jl(),rm();const e=await re();await fetch("/api/auth/logout",{method:"POST",headers:{"X-XSRF-TOKEN":e}}),td()}async function ak(){const e=await fetch("/api/terminal/agent-launchers");if(!e.ok)throw new Error("Failed to detect agent launchers");const t=await e.json();return Array.isArray(t?.agents)?t.agents:[]}async function ck(){const e=await fetch("/api/terminal/agent-hooks");if(!e.ok)throw new Error("Failed to get agent hooks");const t=await e.json();return Array.isArray(t?.agents)?t.agents:[]}async function lk(e){const t=await re(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(e)}/install`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to install agent hooks");return{summary:r.summary??"Installed",devMode:r.devMode===!0}}async function dk(e){const t=await re(),n=await fetch(`/api/terminal/agent-hooks/${encodeURIComponent(e)}/uninstall`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to uninstall agent hooks");return r.summary??"Removed"}class od extends Error{constructor(t,n,r){super(t),this.code=n,this.migration=r,this.name="AgentPluginManifestError"}code;migration}async function uk(){const e=await fetch("/api/terminal/agent-plugins");if(!e.ok)throw new Error("Failed to get agent plugins");return await e.json()}async function fk(e){const t=await re(),n=await fetch("/api/terminal/agent-plugins",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)}),r=await n.json().catch(()=>({}));if(!n.ok)throw new od(r.error||"Failed to create agent plugin",r.code,r.migration);return r}async function hk(e){const t=await re(),n=await fetch("/api/terminal/agent-plugins/install",{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify({source:e})}),r=await n.json().catch(()=>({}));if(!n.ok)throw new od(r.error||"Failed to install agent plugin",r.code,r.migration);return r}async function pk(e){const t=await re(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}/check-update`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to check plugin updates");return r}async function gk(e){const t=await re(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}/update`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to update plugin");return r}async function mk(e){const t=await re(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}/doctor`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error||"Failed to diagnose plugin");return r}async function wk(e){const t=await re(),n=await fetch(`/api/terminal/agent-plugins/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||"Failed to delete agent plugin")}}async function yk(e){const t=await re(),n=await fetch(`/api/terminal/${encodeURIComponent(e)}/agent-resume`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Se(r.error||"Failed to resume agent session",n.status,typeof r.code=="string"?r.code:void 0);return{command:r.command??""}}async function bk(){const e=await fetch("/api/terminal/agent-resume-history",{method:"GET"});if(!e.ok)throw new Error("Failed to load Agent resume history");const t=await e.json().catch(()=>({entries:[]}));return Array.isArray(t.entries)?t.entries:[]}async function vk(e){const t=await re(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(e)}/prepare`,{method:"POST",headers:{"X-XSRF-TOKEN":t}}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Se(r.error||"Failed to prepare Agent session resume",n.status,typeof r.code=="string"?r.code:void 0);return r}async function Sk(e){const t=await re(),n=await fetch(`/api/terminal/agent-resume-history/${encodeURIComponent(e)}`,{method:"DELETE",headers:{"X-XSRF-TOKEN":t}});if(!n.ok&&n.status!==404)throw new Error("Failed to remove Agent resume history")}async function xk(e){const t=await re(),n=await fetch("/api/terminal/program-rules",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to update program rules"}));throw new Error(r.error||"Failed to update program rules")}return n.json()}async function Ek(){const e=await re(),t=await fetch("/api/terminal/program-rules",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Error("Failed to reset program rules");return t.json()}async function Ak(){const e=await fetch("/api/terminal/program-detection");if(!e.ok)throw new Error("Failed to get program detection config");return e.json()}async function Ck(e){const t=await re(),n=await fetch("/api/terminal/program-detection",{method:"PUT",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":t},body:JSON.stringify(e)});if(!n.ok)throw new Error("Failed to save program detection config");return n.json()}async function kk(){const e=await re(),t=await fetch("/api/terminal/program-detection",{method:"DELETE",headers:{"X-XSRF-TOKEN":e}});if(!t.ok)throw new Error("Failed to reset program detection config");return t.json()}const Ik={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".bmp":"image/bmp",".ico":"image/x-icon",".svg":"image/svg+xml",".heic":"image/heic",".heif":"image/heif"};function Ms(e){const t=e.lastIndexOf(".");return t<0?null:Ik[e.slice(t).toLowerCase()]??null}function Rk(e){return Ms(e)!==null}function Am(e){const t=Ms(e);return t==="image/heic"||t==="image/heif"}const Tk={".mp4":"video/mp4",".m4v":"video/x-m4v",".webm":"video/webm",".mov":"video/quicktime",".ogv":"video/ogg",".mpeg":"video/mpeg",".mpg":"video/mpeg"};function Cm(e){const t=e.lastIndexOf(".");return t<0?null:Tk[e.slice(t).toLowerCase()]??null}function Pk(e){return Cm(e)!==null}function Nk(e){return`/api/terminal/fs/video?path=${encodeURIComponent(e)}&action=view_file`}const km=[".stl",".glb",".gltf"];function id(e){const t=e.lastIndexOf(".");if(t<0)return null;const n=e.slice(t).toLowerCase();return km.includes(n)?n:null}function Lk(e){return id(e)!==null}function sd(e){const t=e.toLowerCase();return t.endsWith(".kicad_sch")?".kicad_sch":t.endsWith(".kicad_pcb")?".kicad_pcb":null}function Bk(e){return sd(e)!==null}function Dk(e){return sd(e)===".kicad_pcb"?"pcb-front":"schematic"}const Im=[".html",".htm"];function _k(e){const t=e.lastIndexOf(".");if(t<0)return!1;const n=e.slice(t).toLowerCase();return Im.includes(n)}function Ok(e){return`/api/terminal/fs/preview/${e.split(/[\\/]+/).filter(Boolean).map(n=>encodeURIComponent(n)).join("/")}`}const Fk={".stl":"model/stl",".glb":"model/gltf-binary",".gltf":"model/gltf+json"};async function Mk(e,t,n,r="list_directory",o,i="name",s){const a=new URLSearchParams({path:e});n&&a.set("showHidden","true"),i!=="name"&&a.set("sort",i),s&&a.set("gitIgnoreRoot",s),a.set("action",r),o&&a.set("requestSlotId",o);const c=await Te(`/api/terminal/fs/list?${a}`,{signal:t},Kn,"Directory listing took too long. The folder may be on slow storage or blocked by another process.");if(!c.ok){const l=await c.json().catch(()=>({error:"Failed to list directory"}));throw new Error(l.error||"Failed to list directory")}return c.json()}async function jk(e,t,n,r,o,i="name",s,a={}){const c=new URLSearchParams({path:e,query:t,stream:"true"});o&&c.set("showHidden","true"),i==="content"&&c.set("mode","content"),s&&c.set("requestSlotId",s);for(const g of a.excludePatterns??[])c.append("exclude",g);a.caseSensitive&&c.set("caseSensitive","true"),a.wholeWord&&c.set("wholeWord","true"),a.regex&&c.set("regex","true");const l=await fetch(`/api/terminal/fs/search?${c}`,{signal:r});if(!l.ok||!l.body){const g=await l.json().catch(()=>({error:"Failed to search files"}));throw new Error(g.error||"Failed to search files")}const d=l.body.getReader(),u=new TextDecoder;let f="";const h=g=>{if(!g.trim())return;const m=JSON.parse(g);if(m.type==="meta")n({path:m.path,query:m.query,engine:m.engine,mode:m.mode,limited:m.limited});else if(m.type==="batch")n({entries:m.entries??[]});else if(m.type==="content-batch")n({contentEntries:m.contentEntries??[]});else{if(m.type==="error")throw new Error(m.message||"Search failed");m.type==="done"&&n({total:m.total,truncated:m.truncated,limited:m.limited,engine:m.engine,mode:m.mode,done:!0})}};for(;;){const{value:g,done:m}=await d.read();if(m)break;f+=u.decode(g,{stream:!0});let v=f.indexOf(`
|
|
3
3
|
`);for(;v>=0;)h(f.slice(0,v)),f=f.slice(v+1),v=f.indexOf(`
|
|
4
4
|
`)}f+=u.decode(),h(f)}async function Uk(e,t,n){const r=new URLSearchParams;for(const d of e)r.append("root",d);const o=await fetch(`/api/terminal/fs/watch?${r}`,{signal:n});if(!o.ok||!o.body){const d=await o.json().catch(()=>({error:"Failed to watch files"}));throw new Error(d.error||"Failed to watch files")}const i=o.body.getReader(),s=new TextDecoder;let a="",c=null;const l=d=>{if(!d.trim())return;const u=JSON.parse(d);if(u.type==="events"&&u.events?.length){t(u.events);const f=u.events.find(h=>h.type==="rescan-required"&&h.reason!=="event-storm"&&h.reason!=="reconnected"&&h.reason!=="directory-rescan"&&h.reason!=="polling-fallback");f?.reason&&(c=f.reason)}};for(;;){const{value:d,done:u}=await i.read();if(u)break;a+=s.decode(d,{stream:!0});let f=a.indexOf(`
|
|
5
5
|
`);for(;f>=0;)l(a.slice(0,f)),a=a.slice(f+1),f=a.indexOf(`
|
|
@@ -32,4 +32,4 @@ ${e.stack}`:"",t?`
|
|
|
32
32
|
React component stack:
|
|
33
33
|
${t.trim()}`:""].filter(Boolean).join(`
|
|
34
34
|
`)}async function yT(e){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch{}const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();try{return document.execCommand("copy")}catch{return!1}finally{t.remove()}}function bT({error:e,componentStack:t}){const{t:n}=Mr(),[r,o]=lt.useState("idle"),i=async()=>{const s=wT(e,t,{url:window.location.href,userAgent:navigator.userAgent,capturedAt:new Date().toISOString()});o(await yT(s)?"copied":"failed")};return p.jsx("div",{className:"flex h-full items-center justify-center p-4",children:p.jsxs("div",{className:"flex flex-col items-center gap-3 text-center max-w-md",children:[p.jsx("div",{className:"w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center",children:p.jsx("svg",{className:"w-6 h-6 text-destructive",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:p.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),p.jsxs("div",{className:"space-y-1",children:[p.jsx("h3",{className:"font-medium text-foreground",children:n("errorBoundary.title")}),p.jsx("p",{className:"text-sm text-muted-foreground",children:e?.message||n("errorBoundary.unexpected")})]}),p.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-center gap-2",children:[p.jsx("button",{type:"button",onClick:()=>{i()},className:"rounded-full bg-surface-2 px-5 py-2.5 text-sm font-medium text-foreground ring-1 ring-border/15 transition hover:bg-surface-elevated active:scale-[0.97]",children:n(r==="copied"?"errorBoundary.copied":r==="failed"?"errorBoundary.copyFailed":"errorBoundary.copyDetails")}),p.jsx("button",{type:"button",onClick:()=>window.location.reload(),className:"rounded-full bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground shadow-sm transition-all hover:bg-primary/90 active:scale-[0.97]",children:n("errorBoundary.retry")})]})]})})}class vT extends lt.Component{state={hasError:!1,error:null,componentStack:""};static getDerivedStateFromError(t){return{hasError:!0,error:t,componentStack:""}}componentDidCatch(t,n){console.error("Terminal error caught by boundary:",t,n),this.setState({componentStack:n.componentStack??""})}render(){return this.state.hasError?this.props.fallback?this.props.fallback:p.jsx(bT,{error:this.state.error,componentStack:this.state.componentStack}):this.props.children}}function ve(){try{if(window.parent!==window&&location.pathname==="/workspace.html"&&window.parent.location.origin===location.origin&&window.parent.__termdockWorkspaceHost)return window.parent}catch{}return window}const ST="debug",xT="termdock:debug";function Qf(e){return e?new Set(e.split(",").map(t=>t.trim().toLowerCase()).filter(Boolean)):new Set}function ET(){if(typeof window>"u")return new Set;const e=Qf(new URLSearchParams(window.location.search).get(ST));let t=new Set;try{t=Qf(window.localStorage.getItem(xT))}catch{t=new Set}const n=new Set([...e,...t]);return n.has("1")||n.has("true")||n.has("*")||n.has("all")?new Set(["*"]):n}function AT(e){const t=ET();return t.has("*")||t.has(e)}function CT(e){const t=AT(e);return(...n)=>{t&&console.log(`[debug:${e}]`,...n)}}function gd(){return typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}function Ym(){if(typeof window>"u")return!1;const e=ve(),t=e.navigator.maxTouchPoints>0||"ontouchstart"in e;return gd()||t&&Math.min(e.innerWidth,e.innerHeight)<768}const eh=80,kT=60,IT="termdock:viewport-keyboard-change",RT="termdock:viewport-layout-change",Wt=240,th=640,nh=360,TT=1500;function PT({measuredHeight:e,documentVisible:t,editableFocused:n}){return t&&n&&e>0}function Qa(){if(typeof document>"u")return!1;const e=document.activeElement;return e instanceof HTMLElement&&e.matches('input:not([type="hidden"]), textarea, select, [contenteditable]:not([contenteditable="false"])')}const ps=e=>{const t=typeof e=="number"?e:Number.parseFloat(typeof e=="string"?e:"0");return Number.isFinite(t)&&t>0?Math.round(t):0},Zm=(e,t)=>{const n=e.map(ps).filter(r=>r>0);return n.find(r=>r>=Wt)??n[0]??t},Co=()=>typeof window>"u"?th:Zm([ve().innerHeight,document.documentElement?.clientHeight,document.body?.clientHeight,ve().visualViewport?.height,window.screen?.availHeight,window.screen?.height],th),Jm=()=>typeof window>"u"?nh:Zm([ve().innerWidth,document.documentElement?.clientWidth,document.body?.clientWidth,ve().visualViewport?.width,window.screen?.availWidth,window.screen?.width],nh),ln=e=>{const t=Number.parseFloat(e||"0");return Number.isFinite(t)?Math.max(0,Math.round(t)):0},Qm=gd,ew=()=>typeof window>"u"?!1:ve().navigator.standalone===!0||ve().matchMedia?.("(display-mode: standalone)").matches===!0,tw=()=>{if(typeof window>"u"||!Qm()||!ew())return{top:0,right:0,bottom:0,left:0};const e=Co()>=Jm(),t=window.screen?.width||window.innerWidth,n=window.screen?.height||window.innerHeight,r=Math.min(t,n),o=Math.max(t,n);return r>=700?{top:ve().document.documentElement.dataset.termdockPwaStatusBar==="default"?0:20,right:0,bottom:20,left:0}:e?o<780?{top:20,right:0,bottom:0,left:0}:{top:o>=852?59:o>=844?47:44,right:0,bottom:34,left:0}:{top:0,right:0,bottom:0,left:0}};function NT(e="--app-vh"){if(typeof window>"u"||typeof document>"u")return;document.documentElement.dataset.termdockTouchViewport=String(Ym()||ve().innerWidth<=768),document.documentElement.dataset.termdockIpadPwa=String(document.documentElement.dataset.termdockPwaStatusBar==="default"&&ew());const t=ps(ve().visualViewport?.height),n=Math.max(0,Math.round(ve().visualViewport?.offsetTop??0)),r=Co(),i=t>=Wt?Math.min(r,t+n):r,s=Math.max(r,i),a=document.documentElement.style;a.setProperty(e,`${Math.max(i,Wt)}px`),a.setProperty("--app-base-vh",`${Math.max(s,Wt)}px`),a.setProperty("--app-visible-vh",`${Math.max(i,Wt)}px`),a.setProperty("--app-vv-offset-top",`${n}px`),a.setProperty("--kb-translate-y","0px"),a.setProperty("--kb-margin-top","0px"),a.setProperty("--kb-height","0px");const c=tw();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 g2(e={}){const{cssVarName:t="--app-vh"}=e,n=lt.useMemo(()=>CT("viewport"),[]),r=lt.useCallback(()=>{if(typeof window>"u")return 0;const d=ve().visualViewport,u=Co();if(!d)return u;const f=ps(d.height);if(f<Wt&&u>=Wt)return u;const h=d.offsetTop,m=f<u-1&&h>0&&h<=96?f+h:f,v=Math.max(0,Math.min(u,m));return v>0?Math.round(v):u},[]),[o,i]=lt.useState(r),s=lt.useRef(0),a=lt.useRef(0),c=lt.useRef(0),l=lt.useRef(!1);return lt.useEffect(()=>{if(typeof window>"u")return;let d=null,u=0,f=null,h="",g=null;const m=()=>{if(g?.isConnected)return g;try{return g=document.createElement("div"),g.setAttribute("aria-hidden","true"),g.style.cssText=["position:fixed","top:0","left:0","width:0","height:0","visibility:hidden","pointer-events:none","padding-top:constant(safe-area-inset-top)","padding-top:env(safe-area-inset-top,0px)","padding-right:constant(safe-area-inset-right)","padding-right:env(safe-area-inset-right,0px)","padding-bottom:constant(safe-area-inset-bottom)","padding-bottom:env(safe-area-inset-bottom,0px)","padding-left:constant(safe-area-inset-left)","padding-left:env(safe-area-inset-left,0px)"].join(";"),(document.body||document.documentElement).appendChild(g),g}catch{}return null},v=()=>{let D={top:0,right:0,bottom:0,left:0};try{const U=m();if(U){const _=getComputedStyle(U);D={top:ln(_.paddingTop),right:ln(_.paddingRight),bottom:ln(_.paddingBottom),left:ln(_.paddingLeft)}}}catch{}const F=ve();if(F!==window){const U=F.getComputedStyle(F.document.documentElement);D={top:Math.max(D.top,ln(U.getPropertyValue("--safe-top-inset"))),right:Math.max(D.right,ln(U.getPropertyValue("--safe-right-inset"))),bottom:Math.max(D.bottom,ln(U.getPropertyValue("--safe-bottom-inset"))),left:Math.max(D.left,ln(U.getPropertyValue("--safe-left-inset")))}}const j=tw(),M={top:Math.max(D.top,j.top),right:Math.max(D.right,j.right),bottom:Math.max(D.bottom,j.bottom),left:Math.max(D.left,j.left)};return document.documentElement.style.setProperty("--safe-top-inset",`${M.top}px`),document.documentElement.style.setProperty("--safe-right-inset",`${M.right}px`),document.documentElement.style.setProperty("--safe-bottom-inset",`${M.bottom}px`),document.documentElement.style.setProperty("--safe-left-inset",`${M.left}px`),M},w=(D,F,j,M)=>{const U=Math.max(F,j);if(s.current===0){s.current=U,a.current=D,document.documentElement.style.setProperty("--app-base-vh",`${U}px`);return}const _=Math.abs(D-a.current),O=M<=eh;(_>kT||O)&&(s.current=U,a.current=D,document.documentElement.style.setProperty("--app-base-vh",`${U}px`))},S=(D="event")=>{d=null,document.documentElement.dataset.termdockTouchViewport=String(Ym()||ve().innerWidth<=768);const F=r(),j=Math.round(ve().visualViewport?.offsetTop??0),M=ps(ve().visualViewport?.height),U=M>=Wt?M:F,_=Co(),O=Jm(),H=Math.max(0,U+j),V=v(),z=V.bottom,W=Math.max(0,s.current-H-z);w(O,_,H,W),i(ge=>ge===F?ge:F);const X=Number.parseInt(document.documentElement.style.getPropertyValue(t)||"0",10);document.documentElement.style.setProperty(t,`${F}px`),document.documentElement.style.setProperty("--app-vv-offset-top",`${j}px`);const G=s.current,Y=Math.min(F,U),ie=Math.max(0,Math.min(G,H)),se=Math.max(0,Math.round(G-Y-z)),K=Qa(),ne=PT({measuredHeight:se,documentVisible:document.visibilityState==="visible",editableFocused:K}),q=ne?se:0,Z=q>=eh,oe=-q,Q=q;document.documentElement.style.setProperty("--kb-translate-y",`${oe}px`),document.documentElement.style.setProperty("--kb-margin-top",`${Q}px`),document.documentElement.style.setProperty("--kb-height",`${q}px`),document.documentElement.style.setProperty("--app-visible-vh",`${ie}px`);const ee=Math.abs(q-c.current)>1,te=Z!==l.current;(ee||te)&&(c.current=q,l.current=Z,document.dispatchEvent(new CustomEvent(IT,{detail:{baseHeight:G,visibleHeight:ie,visualViewportHeight:U,offsetTop:j,keyboardHeight:q,isOpen:Z,source:D}}))),(X!==F||j>0||ee||te)&&n("sync",{cssVarName:t,innerHeight:_,baseHeight:G,rawViewportHeight:U,offsetTop:j,visibleHeight:ie,rawHeight:F,appliedHeight:F,keyboardViewportHeight:Y,measuredKeyboardHeight:se,editableFocused:K,applyKeyboardInset:ne,keyboardHeight:q,isKeyboardOpen:Z,safeAreaInsets:V,source:D}),document.dispatchEvent(new CustomEvent(RT,{detail:{height:F,baseHeight:G,visibleHeight:ie,offsetTop:j,source:D}}))},y=()=>{d===null&&(d=window.requestAnimationFrame(()=>{d=null;const D=ve(),F=D.visualViewport,j=[D.innerWidth,D.innerHeight,F?.width,F?.height,F?.offsetTop,F?.offsetLeft,document.visibilityState,Qa()].join(":"),M=f;f=null,(M||j!==h)&&(h=j,S(M||"viewport.settle")),performance.now()<u&&y()}))},A=(D="event")=>{(D.includes("visibilitychange")||D.includes("pageshow"))&&n("schedule",{source:D}),f=D,Qm()&&document.visibilityState==="visible"&&(u=performance.now()+TT),y()};A("mount");const R=()=>A("resize"),E=()=>A("orientationchange"),C=()=>A("visualViewport.resize"),k=()=>A("visualViewport.scroll"),b=()=>A("focusin"),x=()=>A("focusout"),T=D=>{u=0;const F=document.activeElement;F instanceof HTMLElement&&Qa()&&F.blur(),c.current=0,l.current=!1;const j=Math.max(s.current,Co(),Wt),M=document.documentElement.style;M.setProperty(t,`${j}px`),M.setProperty("--app-visible-vh",`${j}px`),M.setProperty("--app-vv-offset-top","0px"),M.setProperty("--kb-translate-y","0px"),M.setProperty("--kb-margin-top","0px"),M.setProperty("--kb-height","0px"),i(U=>U===j?U:j),n("keyboard session reset",{source:D,baseHeight:j})};window.addEventListener("resize",R),window.addEventListener("orientationchange",E),ve().visualViewport?.addEventListener("resize",C),ve().visualViewport?.addEventListener("scroll",k),document.addEventListener("focusin",b),document.addEventListener("focusout",x);const L=D=>{n("resume",{source:D,innerHeight:Math.round(window.innerHeight),visualViewport:ve().visualViewport?{width:Math.round(ve().visualViewport.width),height:Math.round(ve().visualViewport.height),offsetTop:Math.round(ve().visualViewport.offsetTop)}:null,hidden:document.hidden}),A(D)},I=()=>{document.hidden?T("visibilitychange:hidden"):L("visibilitychange")},P=()=>L("pageshow"),B=()=>T("pagehide");return document.addEventListener("visibilitychange",I),window.addEventListener("pageshow",P),window.addEventListener("pagehide",B),()=>{window.removeEventListener("resize",R),window.removeEventListener("orientationchange",E),ve().visualViewport?.removeEventListener("resize",C),ve().visualViewport?.removeEventListener("scroll",k),document.removeEventListener("focusin",b),document.removeEventListener("focusout",x),document.removeEventListener("visibilitychange",I),window.removeEventListener("pageshow",P),window.removeEventListener("pagehide",B),d!==null&&window.cancelAnimationFrame(d),g?.remove()}},[t,n,r]),o}const LT=1e3,BT=2e4,DT=9e4,_T=5e3,de={ws:null,listeners:new Set,reconnectAttempt:0,reconnectTimer:null,idleCloseTimer:null,closing:!1};let yi=0,Cr=null;function OT(){return typeof window>"u"?null:`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/api/control/ws`}function nw(){de.idleCloseTimer&&(clearTimeout(de.idleCloseTimer),de.idleCloseTimer=null)}function FT(){nw(),!(de.ws&&de.ws.readyState===WebSocket.OPEN)&&(de.idleCloseTimer=setTimeout(()=>{de.idleCloseTimer=null,de.listeners.size===0&&MT()},_T))}function MT(){if(de.ws){try{de.ws.close()}catch{}de.ws=null}Cr&&(clearInterval(Cr),Cr=null)}function rh(){if(de.reconnectTimer)return;const e=Math.min(LT*Math.pow(2,de.reconnectAttempt),BT);de.reconnectAttempt+=1,de.reconnectTimer=setTimeout(()=>{de.reconnectTimer=null,rw()},e)}function rw(){const e=OT();if(!e||de.ws&&de.ws.readyState===WebSocket.OPEN)return;let t;try{t=Ug(e)}catch{rh();return}de.ws=t,t.onopen=()=>{de.reconnectAttempt=0,yi=Date.now(),Cr||(Cr=setInterval(()=>{if(!(!de.ws||de.ws.readyState!==WebSocket.OPEN)&&yi>0&&Date.now()-yi>DT)try{de.ws.close()}catch{}},3e4),Cr.unref?.())},t.onmessage=n=>{yi=Date.now();let r=null;try{r=JSON.parse(n.data)}catch{return}if(!r)return;if(r.type==="session-notice"){if(typeof r.id!="string"||typeof r.sessionId!="string"||typeof r.sessionName!="string"||typeof r.message!="string"||!r.message.trim()||r.message.length>4e3||r.title!==void 0&&(typeof r.title!="string"||r.title.length>120)||typeof r.createdAt!="number")return;const s=r;for(const a of de.listeners)try{a(s)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type==="update-state"){const s=r.state;if(!s||typeof s.status!="string"||typeof s.currentVersion!="string")return;const a={type:"update-state",state:s};for(const c of de.listeners)try{c(a)}catch(l){console.error("[clientStateSync] listener threw:",l)}return}if(r.type==="server-health"){const s=r.state;if(!s||typeof s.attention!="boolean"||typeof s.supervised!="boolean")return;const a={type:"server-health",state:s};for(const c of de.listeners)try{c(a)}catch(l){console.error("[clientStateSync] listener threw:",l)}return}if(r.type==="context-draft"){if(typeof r.text!="string")return;const s={type:"context-draft",text:r.text,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const a of de.listeners)try{a(s)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type==="pinned-explorer-roots"){if(!r.pinnedExplorerRoots||typeof r.pinnedExplorerRoots!="object"||Array.isArray(r.pinnedExplorerRoots))return;const s={type:"pinned-explorer-roots",pinnedExplorerRoots:r.pinnedExplorerRoots,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),origin:typeof r.origin=="string"?r.origin:null};for(const a of de.listeners)try{a(s)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type==="config-updated"){if(r.key!=="toolbar-presets"&&r.key!=="agent-rules"&&r.key!=="program-detection")return;const s={type:"config-updated",key:r.key,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:void 0};for(const a of de.listeners)try{a(s)}catch(c){console.error("[clientStateSync] listener threw:",c)}return}if(r.type!=="client-state"||!r.state)return;const o=r.state,i={type:"client-state",clientState:{sessions:Array.isArray(o.sessions)?o.sessions:[],updatedAt:typeof o.updatedAt=="number"?o.updatedAt:Date.now()},inventory:r.inventory,seq:typeof r.seq=="number"?r.seq:void 0};for(const s of de.listeners)try{s(i)}catch(a){console.error("[clientStateSync] listener threw:",a)}},t.onclose=()=>{de.ws===t&&(de.ws=null),de.listeners.size>0&&rh()},t.onerror=()=>{}}function ow(e){return de.listeners.add(e),nw(),de.ws||rw(),()=>{de.listeners.delete(e),de.listeners.size===0&&FT()}}const ec=Fs(e=>({unread:{},viewing:null,receive:(t,n)=>e(r=>{const o=r.unread[t]??[];return r.viewing===t||o.includes(n)?r:{unread:{...r.unread,[t]:[...o,n]}}}),view:t=>e(n=>{if(!t||!n.unread[t])return n.viewing===t?n:{viewing:t};const r={...n.unread};return delete r[t],{viewing:t,unread:r}})})),iw=new Set(["bash","zsh","fish","sh","dash","ksh","tcsh","csh","nu"]);function po(e){if(!e)return null;if(e==="/")return"/";const t=e.replace(/\/+$/,"").split("/");return t[t.length-1]||e}function jT(e,t,n,r=iw,o=null,i=null){if(e.customName)return{primary:e.name,secondary:po(n)};if(o){const a=po(n),c=o===n||o===a;if(i!=="idle"&&!r.has(o)&&!c)return{primary:o,secondary:a}}if(t&&!r.has(t))return{primary:t,secondary:po(n)};const s=po(n);return s?{primary:s,secondary:null}:{primary:e.name,secondary:null}}function UT(e,t,n,r=iw,o=null,i=null){return jT(e,t,n,r,o,i).primary}function HT(e,t,n){const r=e.findIndex(o=>n(o)===t);return r<0?null:e[r+1]?n(e[r+1]):r>0?n(e[r-1]):null}const sw="termdock-session-fonts-v1",oh=8,$T=32;function aw(e){return Number.isFinite(e)?Math.max(oh,Math.min($T,Math.round(e))):oh}function md(){if(typeof window>"u")return{};try{const e=window.localStorage.getItem(sw);if(!e)return{};const t=JSON.parse(e);if(typeof t!="object"||t===null)return{};const n={};for(const[r,o]of Object.entries(t))typeof o=="number"&&Number.isFinite(o)&&(n[r]=aw(o));return n}catch{return{}}}function cw(e){if(!(typeof window>"u"))try{window.localStorage.setItem(sw,JSON.stringify(e))}catch{}}function m2(e){return md()[e]??null}function w2(e,t){if(typeof window>"u")return;const n=md(),r=t===null?null:aw(t);r===null?delete n[e]:n[e]=r,cw(n),window.dispatchEvent(new CustomEvent("termfontchange",{detail:{sessionId:e,fontSize:r}}))}function qT(e){if(typeof window>"u")return;const t=md();e in t&&(delete t[e],cw(t))}const tc="termdock-sessions",il="termdock-active-session",wd="termdock-sessions-cache";function sl(){try{const e=localStorage.getItem(il);return e&&e.trim().length>0?e:null}catch{return null}}function rr(e){try{e?localStorage.setItem(il,e):localStorage.removeItem(il)}catch{}}function lw(){if(typeof window>"u")return null;try{const e=localStorage.getItem(wd);if(!e)return null;const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&typeof n.sessionId=="string"&&typeof n.name=="string"):null}catch{return null}}function xn(e){if(!(typeof window>"u"))try{localStorage.setItem(wd,JSON.stringify(e))}catch{}}function ih(){if(!(typeof window>"u"))try{localStorage.removeItem(wd)}catch{}}const KT=["backendSessionId","mode","tmuxSessionName","lastActivity","connected","live","restorable","activeProgram","cwd","shellTitle","agent"];function dw(e){return e.map(t=>({...t,mode:t.mode==="tmux"?"tmux":"shell",tmuxSessionName:t.tmuxSessionName??null,customName:t.customName===!0}))}function sh(e){return dw(e.map(t=>({sessionId:t.sessionId,name:t.name,customName:t.customName===!0,backendSessionId:t.backendSessionId,mode:t.mode,tmuxSessionName:t.tmuxSessionName,createdAt:t.createdAt,lastActivity:t.lastActivity}))).map((t,n)=>({...t,activeProgram:e[n]?.activeProgram??null,cwd:e[n]?.cwd??null,shellTitle:e[n]?.shellTitle??null,agent:e[n]?.agent}))}function ah(e){return e.map(t=>`${t.sessionId}:${t.name}:${t.customName}:${t.backendSessionId}:${t.mode}:${t.tmuxSessionName}:${t.lastActivity}:${t.activeProgram??""}:${t.cwd??""}:${t.shellTitle??""}:${JSON.stringify(t.agent)??""}`).join("|")}function al(e,t){return e.length===0?null:t&&e.some(n=>n.sessionId===t)?t:e[0]?.sessionId??null}function zT(){const e=lw()??[];return{sessions:e,activeSessionId:al(e,sl())}}function y2(){const e=N.useRef(lw()).current,t=N.useRef(sl()).current,[n,r]=N.useState(e??[]),[o,i]=N.useState(null),[s,a]=N.useState(e&&e.length>0?al(e,t):t),[c,l]=N.useState(e===null),d=N.useRef(!1),u=N.useRef(s),f=N.useRef(n),h=N.useRef(null),g=N.useRef(0),m=N.useRef(0),v=N.useRef(new Map),w=N.useRef(0),S=N.useRef(e===null),y=N.useRef(0),A=N.useRef(new Set),R=N.useRef(0);N.useEffect(()=>{S.current=c},[c]),N.useEffect(()=>{u.current=s},[s]);const E=N.useCallback(O=>{const H=al(O,u.current??sl());return a(V=>V===H?V:H),rr(H),u.current=H,H},[]),C=N.useCallback((O,H)=>{const V=O.filter(z=>!A.current.has(z.sessionId));f.current=V,++g.current,r(z=>ah(z)===ah(V)?z:V),xn(V),H?.reconcileActive&&E(V)},[E]),k=N.useCallback((O,H,V)=>{const z=v.current.get(O.sessionId);if(z&&(H<z.updatedAt||H===z.updatedAt&&V!==void 0&&z.revision>V))return{...O,...z.facts};const W=Object.fromEntries(KT.filter(Y=>Y in O).map(Y=>[Y,O[Y]])),G={...z?.facts.backendSessionId===O.backendSessionId?z?.facts:{connected:!1,live:!1,restorable:!1},...W};return v.current.set(O.sessionId,{updatedAt:H,revision:++m.current,facts:G}),{...O,...G}},[]),b=N.useCallback((O,H)=>{if(!H?.mergedLocally&&h.current&&O.updatedAt<h.current.updatedAt)return;const V=A.current.size===0?O:{...O,clientSessions:O.clientSessions.filter(W=>!A.current.has(W.sessionId))},z=H?.mergedLocally?V:{...V,clientSessions:V.clientSessions.map(W=>k(W,O.updatedAt,H?.backendBaseRevision))};h.current=z,i(z),C(sh(z.clientSessions),{...H})},[C,k]),x=N.useCallback(O=>{C(O(f.current))},[C]),T=N.useCallback(()=>typeof window>"u"?[]:localStorage.getItem(tc)?(localStorage.removeItem(tc),ih(),rr(null),f.current=[],u.current=null,r([]),a(null),console.info("[session-persist] discarded legacy local session cache"),[]):[],[]),L=N.useCallback(async()=>{if(typeof window>"u")return[];const O=R.current,H=m.current;try{const V=await wm(),z=sh(V.clientSessions);return O!==R.current?(console.info("[session-inventory] ignored restore snapshot superseded by a local mutation"),z.filter(W=>!A.current.has(W.sessionId))):(b(V,{reconcileActive:!0,backendBaseRevision:H}),z.length>0?z:T())}catch(V){console.error("Failed to restore sessions from server:",V);try{return T()}catch(z){console.error("Failed to discard legacy local sessions:",z)}}finally{l(!1)}return[]},[b,T]),I=N.useCallback(async(O,H)=>{const V=++R.current,z=w.current,W=g.current,X=m.current,G=await ym(O),Y=v.current.get(G.session.sessionId),ie=Y!==void 0&&(Y.updatedAt>G.inventory.updatedAt||Y.updatedAt===G.inventory.updatedAt&&Y.revision>X);if(V===R.current&&W===g.current)b(G.inventory,{backendBaseRevision:X});else{const Z=h.current,oe=new Map(Z?.clientSessions.map(ee=>[ee.sessionId,ee])),Q=f.current.map(ee=>({frontendSessionId:ee.sessionId,connected:!1,live:!1,restorable:!1,...oe.get(ee.sessionId),...ee}));if(!A.current.has(G.session.sessionId)){const ee=k(G.session,G.inventory.updatedAt,X),te=Q.findIndex(le=>le.sessionId===ee.sessionId);if(te<0)Q.push(ee);else{const le=Q[te];Q[te]={...ee,name:le.name,customName:le.customName,createdAt:le.createdAt}}}b({...Z??G.inventory,clientSessions:Q},{mergedLocally:!0})}const se=h.current?.clientSessions.find(Z=>Z.sessionId===G.session.sessionId)??G.session,K=A.current.has(G.session.sessionId)||se.backendSessionId===null;V===R.current&&z===w.current&&!K&&(H?.shouldActivate?.()??!0)&&(u.current=G.session.sessionId,a(G.session.sessionId),rr(G.session.sessionId));const q=se.backendSessionId===G.terminalSession.sessionId&&!ie;return{...G,inventory:h.current??G.inventory,session:se,terminalSession:{...q?G.terminalSession:{cols:O.cols??80,rows:O.rows??24},sessionId:se.backendSessionId??G.terminalSession.sessionId,mode:se.mode,tmuxSessionName:se.tmuxSessionName,activeProgram:se.activeProgram!==void 0?se.activeProgram:q?G.terminalSession.activeProgram:null,cwd:se.cwd!==void 0?se.cwd:q?G.terminalSession.cwd:null},discarded:K}},[b,k]),P=N.useCallback(async(O,H)=>{++R.current,A.current.add(O),qT(O),x(V=>{const z=V.filter(G=>G.sessionId!==O),W=H!=null&&z.some(G=>G.sessionId===H),X=u.current===O?W?H:HT(V,O,G=>G.sessionId):u.current;return a(X),u.current=X,rr(X),xn(z),z});try{await vm(O)}catch(V){console.error("Failed to remove session from inventory:",V)}},[x]),B=N.useCallback(O=>{const H=Date.now();x(V=>{const z=V.map(W=>W.sessionId===O?{...W,lastActivity:H}:W);return xn(z),z})},[x]),D=N.useCallback(O=>{++w.current,u.current=O,a(O),rr(O)},[]),F=N.useCallback(async(O,H)=>{const V=H.trim();if(!V)return;const z=++R.current,W=m.current;x(X=>{const G=X.map(Y=>Y.sessionId===O?{...Y,name:V,customName:!0}:Y);return xn(G),G});try{const X=await Ri(O,{name:V,customName:!0});z===R.current&&b(X,{backendBaseRevision:W})}catch(X){console.error("Failed to rename session in inventory:",X)}},[b,x]),j=N.useCallback(async O=>{const H=++R.current,V=m.current;x(z=>{const W=z.map(X=>X.sessionId===O?{...X,customName:!1}:X);return xn(W),W});try{const z=await Ri(O,{customName:!1});H===R.current&&b(z,{backendBaseRevision:V})}catch(z){console.error("Failed to reset session name in inventory:",z)}},[b,x]),M=N.useCallback(async O=>{const H=++R.current,V=m.current;x(z=>{const W=new Map(z.map(se=>[se.sessionId,se])),X=O.map(se=>W.get(se)).filter(se=>se!==void 0),G=new Set(O),Y=z.filter(se=>!G.has(se.sessionId)),ie=[...X,...Y];return xn(ie),ie});try{const z=await bm(O);H===R.current&&b(z,{backendBaseRevision:V})}catch(z){console.error("Failed to reorder sessions in inventory:",z)}},[b,x]),U=N.useCallback(async()=>{++R.current;for(const O of f.current)A.current.add(O.sessionId);C([]),h.current=null,i(null),a(null),u.current=null,rr(null),ih(),typeof window<"u"&&localStorage.removeItem(tc);try{await Sm()}catch(O){console.error("Failed to clear session inventory:",O)}},[C]),_=N.useCallback(async(O,H)=>{const V=++R.current,z=m.current;x(W=>{const X=W.map(G=>G.sessionId===O?{...G,backendSessionId:H}:G);return xn(X),X});try{const W=await Ri(O,{backendSessionId:H});V===R.current&&b(W,{backendBaseRevision:z})}catch(W){console.error("Failed to update session backend in inventory:",W)}},[b,x]);return N.useEffect(()=>{d.current||(d.current=!0,L())},[L]),N.useEffect(()=>ow(H=>{if(H.type!=="client-state"||S.current)return;const V=typeof H.seq=="number"?H.seq:null;if(V!==null){if(V<y.current){console.warn("[session-inventory] ignored stale control snapshot",{seq:V,latestSeq:y.current});return}y.current=V}if(H.inventory){b(H.inventory,{reconcileActive:!0});return}const z=dw(H.clientState.sessions||[]).map(W=>k(W,H.clientState.updatedAt));h.current&&H.clientState.updatedAt<h.current.updatedAt||C(z,{reconcileActive:!0})}),[b,C,k]),{sessions:n,inventory:o,activeSessionId:s,isLoading:c,openSession:I,removeSession:P,updateSessionActivity:B,setActiveSession:D,updateSessionBackendId:_,renameSession:F,resetSessionCustomName:j,reorderSessions:M,clearAllSessions:U,restoreSessions:L}}const VT=256*1024,WT=256*1024,GT=128;function ch(e,t=VT){if(!e)return[];if(e.length<=t)return[e];const n=[];let r=0;for(;r<e.length;){let o=Math.min(r+t,e.length);if(o<e.length){const i=e.lastIndexOf(`
|
|
35
|
-
`,o);i>r&&(o=i+1)}n.push(e.slice(r,o)),r=o}return n}function XT(e,t=WT,n=GT){const r=new Map;let o=0,i=0;for(const s of[...e.keys()]){const a=e.get(s);if(!a||a.length===0){e.delete(s);continue}const c=[];for(;a.length>0;){const l=a[0];if(i>0&&(i>=n||o+l.length>t))break;a.shift(),c.push(l),o+=l.length,i+=1}if(c.length>0&&r.set(s,c),e.delete(s),a.length>0&&e.set(s,a),i>=n||o>=t)break}return r}async function uw(e,t=!1,n="termdock-encrypted-background"){const r=await new Promise((o,i)=>{const s=indexedDB.open(n,1);s.onupgradeneeded=()=>s.result.createObjectStore("state"),s.onsuccess=()=>o(s.result),s.onerror=()=>i(s.error)});try{return await new Promise((o,i)=>{const s=r.transaction("state",t?"readwrite":"readonly"),a=e(s.objectStore("state"));s.oncomplete=()=>o(a.result),s.onabort=s.onerror=()=>i(s.error)})}finally{r.close()}}const YT=e=>uw(t=>t.put(e,e.targetPeerId),!0),ZT=e=>uw(t=>t.delete(e),!0),fw="termdock-pwa-notifications-enabled",hw="termdock-pwa-ai-notifications-enabled",pw="termdock-pwa-exit-notifications-enabled",gw="termdock-pwa-notification-alert-style",JT="termdock-notification-claim:",cl=5e3,QT=1500,ll="termdock-push-last-sync",lh=360*60*1e3,eP=10080*60*1e3,ko=new Map;function yd(){return it()?!0:typeof window<"u"&&typeof Notification<"u"&&"serviceWorker"in navigator&&window.isSecureContext}function tP(){if(typeof navigator>"u")return!1;const e=navigator.userAgent;return/iPad|iPhone|iPod/.test(e)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}function nP(){return typeof window>"u"?!1:!!(window.matchMedia("(display-mode: standalone)").matches||"standalone"in navigator&&navigator.standalone===!0)}function rP(){return it()?!0:!(!yd()||tP()&&!nP())}function b2(){return it()?"granted":typeof Notification>"u"?"unsupported":Notification.permission}function bd(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(fw)==="true"}catch{return!1}}function v2(e){if(!(typeof window>"u"))try{window.localStorage.setItem(fw,String(e))}catch{}}function gs(){if(typeof window>"u")return!0;try{const e=window.localStorage.getItem(hw);return e===null?!0:e==="true"}catch{return!0}}function S2(e){if(!(typeof window>"u"))try{window.localStorage.setItem(hw,String(e))}catch{}}function dl(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(pw)==="true"}catch{return!1}}function x2(e){if(!(typeof window>"u"))try{window.localStorage.setItem(pw,String(e))}catch{}}function _o(){if(typeof window>"u")return"normal";try{const e=window.localStorage.getItem(gw);if(e==="quiet"||e==="persistent")return e}catch{}return"normal"}function E2(e){if(!(typeof window>"u"))try{window.localStorage.setItem(gw,e)}catch{}}async function A2(){return it()?"granted":yd()?Notification.permission==="default"?Notification.requestPermission():Notification.permission:"unsupported"}function oP(){return typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus()}function iP(e){for(const[t,n]of ko)e-n>cl&&ko.delete(t)}function sP(e){return e.dedupKey?.trim()?e.dedupKey.trim():e.tag?.trim()?e.tag.trim():[e.data?.sessionId,e.title,e.body].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim()).join("|")}function aP(e){const t=sP(e);if(!t)return!0;const n=Date.now();iP(n);const r=ko.get(t)??0;if(n-r<cl)return!1;try{if(typeof window<"u"&&window.localStorage){const o=`${JT}${t}`,i=Number(window.localStorage.getItem(o)??"0");if(Number.isFinite(i)&&n-i<cl)return ko.set(t,i),!1;Number.isFinite(i)&&i>0&&window.localStorage.removeItem(o),window.localStorage.setItem(o,String(n))}}catch{}return ko.set(t,n),!0}async function js(){if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;try{const e=await navigator.serviceWorker.getRegistration()??null;return e?.active?e:await Promise.race([navigator.serviceWorker.ready,new Promise(n=>{window.setTimeout(()=>n(null),QT)})])??e}catch{return null}}function cP(e){const t="=".repeat((4-e.length%4)%4),n=(e+t).replace(/-/g,"+").replace(/_/g,"/"),r=window.atob(n),o=new Uint8Array(new ArrayBuffer(r.length));for(let i=0;i<r.length;i+=1)o[i]=r.charCodeAt(i);return o}async function vd(e,t){const n=await fetch("/api/csrf-token");if(!n.ok)throw new Error("Unable to get notification security token");const{csrfToken:r}=await n.json();return fetch(`/api/notifications/${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(t)})}async function lP(e=!1,t=!1){if(it())return!0;if(!bd()||!rP()||Notification.permission!=="granted")return!1;const n=await js();if(!n?.pushManager)return!1;try{const r=await fetch("/api/notifications/status");if(!r.ok)return!1;const o=await r.json();let i=await n.pushManager.getSubscription();const s=!!(i?.expirationTime&&i.expirationTime-Date.now()<eP);if(!i)try{i=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:cP(o.publicKey)})}catch(d){return console.warn(`[PWA notifications] Push subscription missing; re-subscribe failed${t?" (user gesture)":""}:`,d),!1}const a=Number(window.localStorage.getItem(ll)??"0"),c=!o.subscription||o.subscription.endpoint!==i.endpoint||Date.now()-(o.subscription.updatedAt??0)>=lh;if(e||c||Date.now()-a>=lh||s){if(!(await vd("subscribe",{subscription:i.toJSON(),aiEnabled:gs(),exitEnabled:dl(),alertStyle:_o(),locale:navigator.language})).ok)return!1;window.localStorage.setItem(ll,String(Date.now()))}const l=ce();return l&&await YT({targetPeerId:l.targetPeerId,addresses:yn(l),routes:At(l),publicKey:o.publicKey,preferences:{aiEnabled:gs(),exitEnabled:dl(),alertStyle:_o(),locale:navigator.language}}),!0}catch(r){return console.warn("[PWA notifications] Push subscription sync failed:",r),!1}}async function C2(){if(it())return;const t=await(await js())?.pushManager?.getSubscription();try{await vd("unsubscribe",{endpoint:t?.endpoint})}finally{const n=ce();n&&await ZT(n.targetPeerId),await t?.unsubscribe();try{window.localStorage.removeItem(ll)}catch{}}}async function k2(){if(it()||!bd())return;(await vd("preferences",{aiEnabled:gs(),exitEnabled:dl(),alertStyle:_o(),locale:navigator.language})).status===404&&await lP(!0)}async function I2(){if(!it())try{const e=navigator;typeof e.clearAppBadge=="function"&&await e.clearAppBadge()}catch{}}async function R2(e){if(!it())try{const t=await js();if(!t||typeof t.getNotifications!="function")return;const n=`agent:${e}`,r=await t.getNotifications({tag:n});for(const i of r)i.close();const o=navigator;if(typeof o.setAppBadge=="function"){const i=await t.getNotifications();await o.setAppBadge(i.length)}}catch{}}async function nc(e){if(!bd()||!yd())return!1;if(e.requireHidden!==!1&&oP())return!0;const t=it();if(t){const i=e.alertStyle??_o(),s=await t.showNotification({title:e.title,body:e.body,tag:e.tag,sessionId:e.data?.sessionId,silent:i==="quiet",persistent:i==="persistent"});return t.notificationDeliveryConfirmation===!0&&s}if(Notification.permission!=="granted")return!1;const n=await js();if(e.deferToPush&&await n?.pushManager?.getSubscription())return!0;if(e.requireHidden!==!1){if(await n?.pushManager?.getSubscription())return!0}if(!aP(e))return!0;const r=e.alertStyle??_o(),o={body:e.body,tag:e.tag,icon:"/pwa-192x192.png",badge:"/maskable-icon-512x512.png",requireInteraction:r==="persistent",renotify:r==="persistent"?!!e.tag:!1,silent:r==="quiet",vibrate:r==="quiet"?[]:[80,40,80],data:{url:e.data?.url??"/",sessionId:e.data?.sessionId}};try{if(n&&typeof n.showNotification=="function")return await n.showNotification(e.title,o),!0;const i=new Notification(e.title,o);return i.onclick=()=>{window.focus(),e.data?.url&&window.location.href!==e.data.url&&window.location.assign(e.data.url),i.close()},!0}catch(i){if(i instanceof DOMException&&i.name==="NotSupportedError"&&o.renotify)try{const s={...o,renotify:!1};return n&&typeof n.showNotification=="function"?await n.showNotification(e.title,s):new Notification(e.title,s),!0}catch(s){return console.warn("[PWA notifications] Failed to show notification (renotify fallback):",s),!1}return console.warn("[PWA notifications] Failed to show notification:",i),!1}}function dP(){try{return localStorage.getItem("termdock:locale")||"en"}catch{return"en"}}function uP(e,t){return e==="zh"?{waitingTitle:`${t} 需要你的处理`,waitingBody:`${t} 需要你的处理。`,doneTitle:`${t} 已完成`,doneBody:`${t} 已完成,点按查看结果。`,exitedTitle:`${t} 已退出`,exitedBody:`${t} 已退出,点按查看结果。`}:{waitingTitle:`${t} needs your input`,waitingBody:`${t} is waiting for your input.`,doneTitle:`${t} finished`,doneBody:"Tap to see the result.",exitedTitle:`${t} exited`,exitedBody:"Tap to see the result."}}const dh=1e6;function Nt(e){return{sessionId:e,directory:"",terminalSessionId:null,mode:"shell",tmuxSessionName:null,activeProgram:null,activeProgramRaw:null,activeProgramSource:null,cwd:null,inCopyMode:!1,isConnecting:!1,agentStatus:null,agentIndicator:null,agentStatusDetail:null,agent:null,agentMessage:null,agentNativeSessionId:null,agentResumeRecovered:!1,agentRich:!1,agentActivity:0,agentCwd:null,agentNeedsReview:!1,shellTitle:null,promptState:null,shellExitCode:null,tuiProgress:null,gitStatus:null,bufferChunks:[],bufferLength:0,lastOutputAt:null,updatedAt:Date.now()}}const Us="termdock-shell-titles-v1";function Hs(){if(typeof window>"u")return{};try{const e=localStorage.getItem(Us);if(!e)return{};const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{}}catch{return{}}}function fP(e){return Hs()[e]??null}function hP(e,t){if(!(typeof window>"u"))try{const n=Hs();t?n[e]=t:delete n[e],localStorage.setItem(Us,JSON.stringify(n))}catch{}}function pP(e){if(!(typeof window>"u"))try{const t=Hs();delete t[e],localStorage.setItem(Us,JSON.stringify(t))}catch{}}const $s="termdock-agent-cache-v1";function Sd(){if(typeof window>"u")return{};try{const e=localStorage.getItem($s);if(!e)return{};const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{}}catch{return{}}}function uh(e,t){if(!(typeof window>"u"))try{const n=Sd();t?n[e]=t:delete n[e],localStorage.setItem($s,JSON.stringify(n))}catch{}}function gP(e){if(!(typeof window>"u"))try{const t=Sd();delete t[e],localStorage.setItem($s,JSON.stringify(t))}catch{}}function mP(){if(!(typeof window>"u"))try{localStorage.removeItem($s)}catch{}}function wP(e){return Sd()[e]??null}function yP(){if(!(typeof window>"u"))try{localStorage.removeItem(Us)}catch{}}const rc=Fs((e,t)=>{const n={pendingChunksBySession:new Map,activitySessionIds:new Set,batchFlushRafRef:null},r=(s,a)=>{const c=new Map;return e(l=>{const d=new Map(l.sessions);let u=l.nextChunkId;const f=Date.now();for(const[h,g]of s){const m=d.get(h)??Nt(h);let v=m.bufferChunks.length>0?[...m.bufferChunks]:[],w=m.bufferLength;for(const S of g){const y=u++;v.push({id:y,data:S}),c.set(h,y),w+=S.length}for(;w>dh&&v.length>1;){const S=v.shift();if(!S)break;w-=S.data.length}d.set(h,{...m,bufferChunks:v,bufferLength:w,lastOutputAt:a.has(h)?f:m.lastOutputAt,updatedAt:f})}return{sessions:d,nextChunkId:u}}),c},o=()=>{if(n.batchFlushRafRef===null){if(typeof window>"u"){i();return}n.batchFlushRafRef=window.requestAnimationFrame(()=>{n.batchFlushRafRef=null,i()})}},i=()=>{if(n.pendingChunksBySession.size===0)return;const s=XT(n.pendingChunksBySession),a=new Set([...s.keys()].filter(c=>n.activitySessionIds.has(c)));for(const c of s.keys())n.pendingChunksBySession.has(c)||n.activitySessionIds.delete(c);r(s,a),n.pendingChunksBySession.size>0&&o()};return{sessions:new Map,nextChunkId:1,activeSessionId:null,getTerminalSession:s=>t().sessions.get(s),setActiveSessionId:s=>{if(e({activeSessionId:s}),s){const a=t().sessions.get(s);if(a?.agentNeedsReview){const c=new Map(t().sessions);c.set(s,{...a,agentNeedsReview:!1,updatedAt:Date.now()}),e({sessions:c}),a.terminalSessionId&&zc(a.terminalSessionId)}}},setTerminalSession:(s,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(s),f=!d||d.terminalSessionId!==a.sessionId?Nt(s):d??Nt(s),h=a.history??d?.history??[];return l.set(s,{...f,terminalSessionId:a.sessionId,mode:a.mode??f.mode,tmuxSessionName:a.tmuxSessionName??f.tmuxSessionName,activeProgram:a.activeProgram??d?.activeProgram??f.activeProgram,activeProgramRaw:a.activeProgramRaw??d?.activeProgramRaw??f.activeProgramRaw,activeProgramSource:a.activeProgramSource??d?.activeProgramSource??f.activeProgramSource,cwd:a.cwd??d?.cwd??f.cwd,agent:d?.agent??wP(s)??f.agent,agentResumeRecovered:d?.agentResumeRecovered??f.agentResumeRecovered,shellTitle:d?.shellTitle??Hs()[s]??f.shellTitle,sessionId:s,isConnecting:!1,history:h,updatedAt:Date.now()}),{sessions:l}})},setSessionHistory:(s,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(s)??Nt(s);return l.set(s,{...d,history:a,updatedAt:Date.now()}),{sessions:l}})},setSessionActiveProgram:(s,a,c=null,l=null)=>{e(d=>{const u=new Map(d.sessions),f=u.get(s)??Nt(s);return u.set(s,{...f,activeProgram:a,activeProgramRaw:l,activeProgramSource:c,updatedAt:Date.now()}),{sessions:u}})},setSessionCwd:(s,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(s)??Nt(s);return l.set(s,{...d,cwd:a,updatedAt:Date.now()}),{sessions:l}})},setSessionShellTitle:(s,a)=>{e(c=>{const l=c.sessions.get(s)??Nt(s);if(l.shellTitle===a)return c;const d=new Map(c.sessions);return d.set(s,{...l,shellTitle:a,updatedAt:Date.now()}),{sessions:d}}),hP(s,a)},setSessionPromptState:(s,a,c)=>{e(l=>{const d=l.sessions.get(s);if(!d||d.promptState===a)return l;const u=new Map(l.sessions);return u.set(s,{...d,promptState:a,shellExitCode:c??d.shellExitCode,updatedAt:Date.now()}),{sessions:u}})},setSessionTuiProgress:(s,a)=>{e(c=>{const l=c.sessions.get(s);if(!l)return c;const d=a?.state==="remove"?null:a;if(l.tuiProgress?.state===d?.state&&l.tuiProgress?.progress===d?.progress)return c;const u=new Map(c.sessions);return u.set(s,{...l,tuiProgress:d,updatedAt:Date.now()}),{sessions:u}})},setSessionGitStatus:(s,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(s);return!d||JSON.stringify(d.gitStatus)===JSON.stringify(a)?c:(l.set(s,{...d,gitStatus:a,updatedAt:Date.now()}),{sessions:l})})},setSessionCopyMode:(s,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(s);return!d||d.inCopyMode===a?c:(l.set(s,{...d,inCopyMode:a,updatedAt:Date.now()}),{sessions:l})})},setSessionAgentIdentity:(s,a)=>{uh(s,a),e(c=>{const l=c.sessions.get(s)??Nt(s);if(JSON.stringify(l.agent)===JSON.stringify(a))return c;const d=new Map(c.sessions);return d.set(s,{...l,agent:a,updatedAt:Date.now()}),{sessions:d}})},setSessionAgentStatus:(s,a)=>{const c=t(),l=c.sessions.get(s);if(!l)return;const d=a.agentStatus??null,u=d&&d!=="idle"?a.agentIndicator??l.agentIndicator??null:null,f=d&&d!=="idle"?a.agentStatusDetail??null:null,h=a.agent!==void 0?a.agent:l.agent,g=a.agentMessage!==void 0?a.agentMessage:d?l.agentMessage:null,m=a.agentNativeSessionId!==void 0?a.agentNativeSessionId:l.agentNativeSessionId,v=a.agentResumeRecovered!==void 0?a.agentResumeRecovered:l.agentResumeRecovered,w=a.agentRich??l.agentRich,S=a.agentActivity??l.agentActivity,y=a.agentCwd!==void 0?a.agentCwd:l.agentCwd,A=c.activeSessionId!==s,R=l.agentStatus==="working"||l.agentStatus==="waiting"||l.agentStatus==="done",E=a.reviewed===!1||a.reviewed===null&&d===null&&R&&A;if(l.agentStatus===d&&l.agentIndicator===u&&l.agentStatusDetail===f&&l.agent===h&&l.agentMessage===g&&l.agentNativeSessionId===m&&l.agentResumeRecovered===v&&l.agentRich===w&&l.agentActivity===S&&l.agentCwd===y&&l.agentNeedsReview===E)return;const C=new Map(c.sessions);if(C.set(s,{...l,agentStatus:d,agentIndicator:u,agentStatusDetail:f,agent:h,agentMessage:g,agentNativeSessionId:m,agentResumeRecovered:v,agentRich:w,agentActivity:S,agentCwd:y,agentNeedsReview:E,updatedAt:Date.now()}),e({sessions:C}),h&&uh(s,h),!gs())return;const k=h?.displayName??l.agent?.displayName??"Agent",b=dP(),x=uP(b,k);if(d==="waiting"&&l.agentStatus!=="waiting"&&A){nc({title:x.waitingTitle,body:g??x.waitingBody,tag:`agent:${s}`,dedupKey:`agent:${s}:waiting:${S}`,data:{url:"/",sessionId:s},deferToPush:!0});return}if(d==="done"&&l.agentStatus!=="done"&&A){nc({title:x.doneTitle,body:x.doneBody,tag:`agent:${s}`,dedupKey:`agent:${s}:done:${S}`,data:{url:"/",sessionId:s},deferToPush:!0});return}d===null&&(l.agentStatus==="working"||l.agentStatus==="waiting")&&A&&nc({title:x.exitedTitle,body:x.exitedBody,tag:`agent:${s}`,dedupKey:`agent:${s}:exited:${S}`,data:{url:"/",sessionId:s},deferToPush:!0})},setAgentResumeRecovered:(s,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(s)??Nt(s);return d.agentResumeRecovered===a?c:(l.set(s,{...d,agentResumeRecovered:a,updatedAt:Date.now()}),{sessions:l})})},clearAgentNeedsReview:s=>{const a=t().sessions.get(s);a?.agentNeedsReview&&(e(c=>{const l=new Map(c.sessions),d=l.get(s);return!d||!d.agentNeedsReview?c:(l.set(s,{...d,agentNeedsReview:!1,updatedAt:Date.now()}),{sessions:l})}),a.terminalSessionId&&zc(a.terminalSessionId))},setConnecting:(s,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(s)??Nt(s);return l.set(s,{...d,isConnecting:a,updatedAt:Date.now()}),{sessions:l}})},appendToBuffer:(s,a,c)=>{if(!a)return;let l=n.pendingChunksBySession.get(s);l||(l=[],n.pendingChunksBySession.set(s,l)),l.push(...ch(a)),c?.markActivity!==!1&&n.activitySessionIds.add(s),o()},hasPendingBufferWrites:s=>(n.pendingChunksBySession.get(s)?.length??0)>0,flushPendingBufferWrites:s=>{const a=n.pendingChunksBySession.get(s);if(!a?.length)return t().sessions.get(s)?.bufferChunks.at(-1)?.id??null;n.pendingChunksBySession.delete(s);const c=n.activitySessionIds.delete(s);return n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),r(new Map([[s,a]]),c?new Set([s]):new Set).get(s)??null},replaceBuffer:(s,a)=>{n.pendingChunksBySession.delete(s),n.activitySessionIds.delete(s),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null);let c=null;return e(l=>{const d=new Map(l.sessions),u=d.get(s);if(!u)return l;if(!a||a.length===0)return d.set(s,{...u,bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:d};let f=l.nextChunkId;const h=[];let g=0;for(const m of a)if(m)for(const v of ch(m)){const w=f++;h.push({id:w,data:v}),c=w,g+=v.length}for(;g>dh&&h.length>1;){const m=h.shift();if(!m)break;g-=m.data.length}return d.set(s,{...u,bufferChunks:h,bufferLength:g,updatedAt:Date.now()}),{sessions:d,nextChunkId:f}}),c},clearTerminalSession:s=>{n.pendingChunksBySession.delete(s),n.activitySessionIds.delete(s),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),e(a=>{const c=new Map(a.sessions),l=c.get(s);return l&&c.set(s,{...l,terminalSessionId:null,isConnecting:!1,agentStatus:null,agentIndicator:null,agentStatusDetail:null,agent:null,agentMessage:null,agentNeedsReview:!1,updatedAt:Date.now()}),{sessions:c}})},clearBuffer:s=>{n.pendingChunksBySession.delete(s),n.activitySessionIds.delete(s),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),e(a=>{const c=new Map(a.sessions),l=c.get(s);return l?(c.set(s,{...l,bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:c}):a})},removeTerminalSession:s=>{n.pendingChunksBySession.delete(s),n.activitySessionIds.delete(s),e(a=>{const c=new Map(a.sessions);return c.delete(s),{sessions:c}}),pP(s),gP(s)},clearAllTerminalSessions:()=>{n.pendingChunksBySession.clear(),n.activitySessionIds.clear(),n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),e({sessions:new Map,nextChunkId:1}),yP(),mP()}}}),ul="termdock:session-notice";function bP(){return N.useEffect(()=>{const e=()=>ec.getState().view(!document.hidden&&Ei()?rc.getState().activeSessionId:null);e();const t=rc.subscribe((n,r)=>{n.activeSessionId!==r.activeSessionId&&e()});return document.addEventListener("visibilitychange",e),window.addEventListener(Bo,e),()=>{t(),document.removeEventListener("visibilitychange",e),window.removeEventListener(Bo,e),ec.getState().view(null)}},[]),N.useEffect(()=>ow(e=>{if(e.type!=="session-notice")return;ec.getState().receive(e.sessionId,e.id);const t=ce()?.targetPeerId,n=Bt(),r=window.parent,o=zT().sessions.find(u=>u.sessionId===e.sessionId),i=rc.getState().sessions.get(e.sessionId),s=i?.shellTitle??fP(e.sessionId),a=s===i?.cwd||s===po(i?.cwd??null)?null:s,c=UT(o??{name:e.sessionName},i?.activeProgram??null,null,void 0,a,i?.promptState??null),l={...e,sessionName:c,key:`${t??"local"}:${e.id}`,open:()=>t&&n?n.focusSession(t,e.sessionId):(window.dispatchEvent(new CustomEvent("termdock:focus-session",{detail:e.sessionId})),!0)},d=r.document.createEvent("CustomEvent");d.initCustomEvent(ul,!1,!1,l),r.dispatchEvent(d)}),[]),null}function vP(){const{locale:e}=Mr(),t=e==="zh",[n,r]=N.useState([]);N.useEffect(()=>{const s=a=>{const c=a.detail;r(l=>l.some(d=>d.key===c.key)?l:[...l,c])};return window.addEventListener(ul,s),()=>window.removeEventListener(ul,s)},[]);const o=N.useCallback(s=>{r(a=>a.filter(c=>c.key!==s))},[]),i=n[0];return i?ms.createPortal(p.jsx(SP,{notice:i,remaining:n.length-1,chinese:t,onDismiss:o},i.key),document.body):null}function SP({notice:e,remaining:t,chinese:n,onDismiss:r}){const[o,i]=N.useState(!1);return p.jsxs("section",{"aria-label":n?"关键进展提醒":"Progress reminder",className:"fixed left-3 right-3 top-[calc(var(--safe-top-inset,0px)+0.75rem)] z-toast overflow-hidden rounded-xl bg-surface text-foreground shadow-lg ring-1 ring-inset ring-border/15 animate-fade-in md:left-auto md:right-4 md:w-[360px]",children:[p.jsxs("button",{type:"button","aria-label":n?"查看 Session":"Open session",className:"group flex w-full items-start gap-2.5 p-3.5 pr-11 text-left transition-colors hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",onClick:()=>{e.open()?r(e.key):i(!0)},children:[p.jsx(Kg,{size:16,className:"mt-0.5 shrink-0 text-primary","aria-hidden":"true"}),p.jsxs("span",{className:"min-w-0 flex-1",role:"status","aria-live":"polite","aria-atomic":"true",children:[p.jsxs("span",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium",title:e.sessionName,children:e.sessionName}),p.jsx(W1,{size:13,className:"shrink-0 text-muted-foreground/60 transition-colors group-hover:text-primary","aria-hidden":"true"})]}),e.title&&p.jsx("span",{className:"mt-1 block truncate text-[11px] text-muted-foreground",children:e.title}),p.jsx("span",{className:"mt-1.5 line-clamp-3 whitespace-pre-wrap break-words text-[13px] leading-relaxed text-foreground/85",title:e.message,children:e.message}),t>0&&p.jsx("span",{className:"mt-2 block text-[10px] text-muted-foreground",children:n?`还有 ${t} 条`:`${t} more`}),o&&p.jsx("span",{role:"alert",className:"mt-2 block text-xs text-warning",children:n?"暂时无法打开该服务,请重试。":"Unable to open the service. Please retry."})]})]}),p.jsx("button",{type:"button","aria-label":n?"关闭提醒":"Dismiss reminder",className:"absolute right-0 top-0 flex h-11 w-11 items-center justify-center rounded-tr-xl text-muted-foreground/60 transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",onClick:()=>r(e.key),children:p.jsx(Yg,{size:14})})]})}const fh=5*6e4;let fl,mw=!1,ww=!1,hh=!1;const hl=new Set;function ph(){mw=!0,hl.forEach(e=>e())}function xP(){return N.useSyncExternalStore(e=>(hl.add(e),()=>{hl.delete(e)}),()=>mw,()=>!1)}function EP(){window.dispatchEvent(new Event("termdock:before-update")),ww=!0,fl?.waiting?fl.waiting.postMessage({type:"SKIP_WAITING"}):window.location.reload()}function AP(e,t){let n=e;return()=>{if(!n){n=!0;return}t()}}function CP(){if(hh||typeof window>"u"||!("serviceWorker"in navigator))return;hh=!0,navigator.serviceWorker.addEventListener("controllerchange",AP(!!navigator.serviceWorker.controller,()=>{ww?window.location.reload():ph()}));const e=()=>{navigator.serviceWorker.register("/sw.js",{scope:"/",updateViaCache:"none"}).then(t=>{fl=t;const n=()=>{t.waiting&&ph()},r=()=>{const s=t.installing;s?.addEventListener("statechange",()=>{s.state==="installed"&&navigator.serviceWorker.controller&&n()})};t.addEventListener("updatefound",r),r(),n();let o=0;const i=()=>{document.visibilityState!=="visible"||Date.now()-o<fh||(o=Date.now(),t.update().then(n).catch(()=>{}))};i(),window.setInterval(i,fh),document.addEventListener("visibilitychange",i)}).catch(()=>{})};document.readyState==="complete"?e():window.addEventListener("load",e,{once:!0})}function kP(){const e=xP(),[t,n]=N.useState(!1),{locale:r}=Mr();if(!e||t)return null;const o=r==="zh";return p.jsxs("div",{role:"status",className:"fixed bottom-16 left-1/2 z-toast flex max-w-[calc(100%-2rem)] -translate-x-1/2 items-center gap-3 rounded-lg border border-border bg-background px-4 py-3 text-sm text-foreground shadow-lg",children:[p.jsx("span",{children:o?"新版本已就绪":"An update is ready"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-primary",onClick:EP,children:o?"重新加载":"Reload"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-muted-foreground",onClick:()=>n(!0),children:o?"稍后":"Later"})]})}let go=[],oc=!1;function IP(e,t,n={}){typeof window>"u"||(go.push(JSON.stringify({level:e,message:t,data:{ts:Date.now(),...n}})),RP())}async function RP(){if(!oc){oc=!0;try{for(;go.length>0;){const e=go[0];try{await fetch("/api/client-log",{method:"POST",headers:{"Content-Type":"application/json"},body:e,keepalive:!0}),go.shift()}catch{go=[];break}}}finally{oc=!1}}}function TP(){const e=N.useRef(null),t=navigator.standalone===!0||window.matchMedia?.("(display-mode: standalone)").matches===!0,n=window.parent===window&&gd()&&t;return N.useEffect(()=>{if(!n)return;const r=()=>{const o=e.current;if(!o)return;const i=o.getBoundingClientRect(),s=getComputedStyle(o);IP("info","PWA_STATUS_BAR_SURFACE",{revision:"ipad-default-status-bar",statusBarStyle:document.querySelector('meta[name="apple-mobile-web-app-status-bar-style"]')?.getAttribute("content"),entry:document.querySelector('script[type="module"][src]')?.getAttribute("src"),parent:o.parentElement?.tagName,rect:{x:i.x,y:i.y,width:i.width,height:i.height},background:s.backgroundColor,clip:s.backgroundClip,zIndex:s.zIndex,safeTop:getComputedStyle(document.documentElement).getPropertyValue("--safe-top-inset"),viewport:{width:window.innerWidth,height:window.innerHeight,offsetTop:window.visualViewport?.offsetTop},screen:{width:window.screen.width,height:window.screen.height}})};return window.addEventListener("termdock:initial-viewport-presented",r,{once:!0}),()=>window.removeEventListener("termdock:initial-viewport-presented",r)},[n]),n?ms.createPortal(p.jsx("div",{ref:e,"data-pwa-status-bar-surface":!0,"aria-hidden":"true",className:"pwa-status-bar-surface pointer-events-none fixed inset-x-0 top-0 z-popover app-chrome-bg"}),document.body):null}function yw(e){const t=document.querySelector('meta[name="theme-color"]');t&&t.setAttribute("content",e==="light"?"#FFFCF0":"#1C1B1A")}const bw=N.createContext(void 0);function T2({children:e}){const t=N.useContext(bw),n=t===void 0?typeof document>"u"?null:document.body:t;return n?ms.createPortal(e,n):null}const PP={activeKey:"root",items:[]},NP=()=>()=>{},LP=()=>PP;function BP({host:e,item:t,visible:n,active:r}){const o=N.useRef(null);return N.useEffect(()=>{o.current?.toggleAttribute("inert",!r)},[r]),N.useLayoutEffect(()=>{const i=o.current;return()=>{try{const s=i?.contentWindow,a=s?.document.createEvent("Event");a&&(a.initEvent("termdock:before-update",!1,!1),s?.dispatchEvent(a))}catch{}e.attach(t.key,null)}},[e,t.key]),p.jsx("iframe",{ref:o,title:t.service?.label||"服务工作区","data-workspace-key":t.key,src:`/workspace.html?${Bg}=${encodeURIComponent(t.key)}`,className:"fixed inset-0 w-full border-0 bg-[var(--chrome-bg)]",style:{height:"var(--app-base-vh, 100%)",visibility:n?"visible":"hidden",pointerEvents:r?"auto":"none"},"aria-hidden":!r,tabIndex:r?0:-1,allow:"clipboard-read; clipboard-write; fullscreen"})}function DP({children:e}){const t=window.parent===window?Bt():void 0,n=N.useSyncExternalStore(t?.subscribe||NP,t?.snapshot||LP),[r,o]=N.useState(null),[i,s]=N.useState(()=>n.activeKey==="root"?"root":null),[a,c]=N.useState(),[l,d]=N.useState(!1),[u,f]=N.useState(),h=n.items.find(y=>y.key===n.activeKey),g=h?.rendered||a===n.activeKey?n.activeKey:i,m=g!==n.activeKey,v=m&&i===null;N.useLayoutEffect(()=>{if(!m||v){f(void 0);return}const y=()=>{const A=Array.from(document.querySelectorAll("iframe[data-workspace-key]")).find(T=>T.dataset.workspaceKey===i),k=(i==="root"?r:A?.contentDocument)?.querySelector('nav[aria-label="切换服务"]')?.closest("[data-sidebar-gesture-ignore]")?.getBoundingClientRect();if(!k||k.width===0||k.right<=0){f(void 0);return}const b=A?.getBoundingClientRect(),x=k.top+(b?.top??0)>=160;f({left:k.left+(b?.left??0)+12,top:(x?k.top-8:k.bottom+8)+(b?.top??0),width:Math.max(0,k.width-24),transform:x?"translateY(-100%)":"none"})};return y(),window.addEventListener("resize",y),()=>window.removeEventListener("resize",y)},[m,v,i,r]),N.useLayoutEffect(()=>{t?.present(g),m||s(g),r?.toggleAttribute("inert",g!=="root"||m)},[t,r,g,m]),N.useEffect(()=>{if(d(!1),!m)return;const y=setTimeout(()=>d(!0),8e3);return()=>clearTimeout(y)},[n.activeKey,m]),N.useEffect(()=>{c(void 0)},[n.activeKey]);const w=n.items.find(y=>y.key===i),S=h?.phase==="offline"?"网络已断开,等待恢复…":h?.phase==="reconnecting"?"连接暂未恢复,正在重试…":l?"连接时间较长,仍在等待服务…":v?"正在恢复服务…":"正在切换服务…";return N.useEffect(()=>{if(!t)return;const y=()=>{try{const A=JSON.parse(localStorage.getItem("termdock-color-theme")||"null");(A==="dark"||A==="light")&&(document.documentElement.dataset.theme=A,yw(A))}catch{}};return window.addEventListener("storage",y),()=>window.removeEventListener("storage",y)},[t]),N.useEffect(()=>{if(!t||!("serviceWorker"in navigator))return;const y=E=>{if(E.source!==navigator.serviceWorker.controller)return;const C=E.data;C?.type==="termdock:focus-session"&&typeof C.targetPeerId=="string"&&typeof C.sessionId=="string"&&t.focusSession(C.targetPeerId,C.sessionId)&&(E.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),E.stopImmediatePropagation())},A=async()=>{if("caches"in window)try{const E=await caches.open("termdock-notification-target-v1"),C=await E.match("/__termdock-notification-target");if(!C)return;const k=await C.json();typeof k.targetPeerId=="string"&&typeof k.sessionId=="string"&&Date.now()-k.clickedAt<3e4&&t.focusSession(k.targetPeerId,k.sessionId)&&await E.delete("/__termdock-notification-target")}catch{}},R=()=>{document.hidden||A()};return navigator.serviceWorker.addEventListener("message",y),document.addEventListener("visibilitychange",R),A(),()=>{navigator.serviceWorker.removeEventListener("message",y),document.removeEventListener("visibilitychange",R)}},[t]),t?p.jsxs("div",{className:"relative h-full w-full overflow-hidden bg-[var(--chrome-bg)]",children:[p.jsx("div",{ref:o,className:"isolate h-full w-full","aria-hidden":g!=="root"||m,style:{visibility:g==="root"?"visible":"hidden"},children:p.jsx(bw.Provider,{value:r,children:e})}),n.items.filter(y=>y.key!=="root").map(y=>p.jsx(BP,{host:t,item:y,visible:g===y.key,active:!m&&g===y.key},y.key)),v&&p.jsx(pd,{className:"z-modal-panel",status:S,detail:l||h?.phase==="offline"||h?.phase==="reconnecting"?h?.service?.label:void 0,actionLabel:l||h?.phase==="offline"||h?.phase==="reconnecting"?"查看连接页面":void 0,onAction:()=>c(n.activeKey)}),m&&!v&&p.jsx("div",{className:"fixed inset-0 z-modal-panel flex items-end justify-center px-3 pb-[calc(env(safe-area-inset-bottom)+96px)]",role:"dialog","aria-modal":"true","aria-label":"切换服务",onKeyDown:y=>{if(y.key==="Escape"&&w?.service&&(y.preventDefault(),t.activate(w.service)),y.key==="Tab"){const A=Array.from(y.currentTarget.querySelectorAll("button")),R=A[0],E=A[A.length-1];y.shiftKey&&document.activeElement===R?(y.preventDefault(),E?.focus()):!y.shiftKey&&document.activeElement===E&&(y.preventDefault(),R?.focus())}},children:p.jsxs("div",{style:u?{position:"absolute",...u}:void 0,className:"flex w-full max-w-sm flex-wrap items-center gap-x-2 gap-y-1 rounded-xl border border-border bg-surface-elevated px-3 py-1.5 text-foreground shadow-lg",children:[p.jsxs("div",{role:"status","aria-live":"polite",className:"flex min-w-0 flex-1 items-center gap-2",children:[p.jsx(et,{size:16,className:"shrink-0 animate-spin text-primary motion-reduce:animate-none","aria-hidden":"true"}),p.jsxs("div",{className:"min-w-0",children:[p.jsx("div",{className:"truncate text-sm font-medium",children:h?.service?.label||"服务工作区"}),p.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:S})]})]}),p.jsxs("div",{className:"flex items-center justify-end gap-1",children:[l&&p.jsx("button",{type:"button",className:"min-h-11 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2",onClick:()=>c(n.activeKey),children:"查看连接页面"}),w?.service&&p.jsx("button",{type:"button",autoFocus:!0,"aria-label":"取消切换",className:"min-h-11 shrink-0 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>t.activate(w.service),children:"取消"})]})]})})]}):e}const _P=N.lazy(()=>wn(()=>import("./App-B1lqBSPB.js").then(e=>e.d),__vite__mapDeps([4,2,1,5,6,3,7,8]))),OP=N.lazy(()=>wn(()=>import("./DagPlayground-nUK9xIql.js"),__vite__mapDeps([9,10,2,1,11,7,3])).then(e=>({default:e.DagPlayground}))),FP=N.lazy(()=>wn(()=>import("./DiffLab-D6XhZtPW.js"),__vite__mapDeps([12,2,1,13,8,14,3])).then(e=>({default:e.DiffLab}))),MP=N.lazy(()=>wn(()=>import("./DiffReviewLab-CvNWVrbl.js"),__vite__mapDeps([15,2,1,16,5,6,11,13,8,14,3])).then(e=>({default:e.DiffReviewLab})));NT();C1();L1();window.parent===window&&CP();const mo=ce();mo&&wn(()=>import("./App-B1lqBSPB.js").then(e=>e.d),__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")&&f1(mo?{...mo,id:mo.targetPeerId,label:mo.serviceName||location.host}:void 0);try{const e=JSON.parse(window.localStorage.getItem("termdock-color-theme")||"null");(e==="dark"||e==="light")&&(document.documentElement.dataset.theme=e,yw(e))}catch{}_1.createRoot(document.getElementById("root")).render(p.jsxs(lt.StrictMode,{children:[p.jsx(TP,{}),p.jsx(pT,{}),p.jsxs(VI,{children:[window.parent===window&&p.jsxs(p.Fragment,{children:[p.jsx(kP,{}),p.jsx(vP,{})]}),p.jsx(vT,{children:p.jsx(N.Suspense,{fallback:p.jsx(pd,{}),children:(()=>{const e=new URLSearchParams(window.location.search);return e.get("dag-playground")==="1"?p.jsx(OP,{}):e.get("diff-review-lab")==="1"?p.jsx(MP,{}):e.get("diff-lab")==="1"?p.jsx(FP,{}):p.jsx(DP,{children:p.jsxs(mT,{children:[p.jsx(bP,{}),p.jsx(_P,{})]})})})()})})]})]}));export{u2 as $,od as A,Kg as B,cs as C,iw as D,sm as E,UI as F,XP as G,wR as H,Ok as I,Nk as J,Ml as K,et as L,a1 as M,Hk as N,t1 as O,FR as P,pk as Q,kS as R,h1 as S,dA as T,Vc as U,RT as V,Bo as W,Yg as X,tC as Y,VC as Z,wn as _,qg as a,oC as a$,Nn as a0,lI as a1,cI as a2,I2 as a3,IP as a4,KC as a5,o2 as a6,ls as a7,i2 as a8,KA as a9,gt as aA,DA as aB,ck as aC,ak as aD,uk as aE,NC as aF,aI as aG,oI as aH,wP as aI,fP as aJ,rI as aK,mI as aL,iI as aM,ok as aN,re as aO,po as aP,Dk as aQ,eI as aR,hI as aS,qk as aT,uI as aU,nI as aV,Zk as aW,Ak as aX,b2 as aY,sI as aZ,hs as a_,nC as aa,BC as ab,ZP as ac,Fs as ad,fk as ae,wI as af,CT as ag,qe as ah,LC as ai,ca as aj,bt as ak,wk as al,Xk as am,R2 as an,iC as ao,QC as ap,mk as aq,Gk as ar,rC as as,$I as at,IA as au,om as av,sC as aw,DR as ax,AA as ay,WC as az,z1 as b,p2 as b$,jT as b0,UT as b1,m2 as b2,fn as b3,gs as b4,dl as b5,_o as b6,bd as b7,it as b8,eC as b9,p as bA,YP as bB,YC as bC,bI as bD,bk as bE,ld as bF,_I as bG,gI as bH,Mk as bI,jI as bJ,GC as bK,sk as bL,NI as bM,Jk as bN,_m as bO,ym as bP,HT as bQ,vk as bR,MI as bS,_C as bT,_n as bU,kt as bV,zT as bW,zk as bX,$k as bY,Kk as bZ,Wk as b_,gC as ba,AR as bb,rk as bc,XC as bd,tk as be,dI as bf,Cm as bg,Bt as bh,Qa as bi,Up as bj,sg as bk,Vk as bl,lk as bm,hk as bn,_g as bo,Am as bp,BA as bq,n2 as br,Bk as bs,_k as bt,Rk as bu,Lk as bv,Pk as bw,rP as bx,yd as by,Ei as bz,W1 as c,FC as c$,h2 as c0,s2 as c1,OC as c2,aC as c3,e2 as c4,lo as c5,EI as c6,Sk as c7,kI as c8,DI as c9,Qe as cA,OI as cB,HC as cC,MC as cD,DC as cE,UC as cF,qC as cG,xI as cH,TI as cI,RI as cJ,BI as cK,w2 as cL,S2 as cM,x2 as cN,E2 as cO,v2 as cP,mm as cQ,PC as cR,JC as cS,la as cT,d2 as cU,nc as cV,LI as cW,ow as cX,AI as cY,t2 as cZ,$P as c_,Ck as ca,xk as cb,nk as cc,or as cd,A2 as ce,kk as cf,Ek as cg,$C as ch,f2 as ci,zC as cj,ZC as ck,II as cl,HI as cm,yk as cn,CI as co,WP as cp,CA as cq,SI as cr,fI as cs,vI as ct,PI as cu,Rm as cv,ce as cw,jk as cx,FI as cy,Ug as cz,zg as d,GP as d0,k2 as d1,lP as d2,yw as d3,VP as d4,dk as d5,C2 as d6,gk as d7,yI as d8,ik as d9,Ri as da,at as db,Yk as dc,Jg as dd,JP as de,Mr as df,_A as dg,r2 as dh,c2 as di,ec as dj,y2 as dk,De as dl,rc as dm,g2 as dn,Ym as dp,ve as dq,Uk as dr,Ds as ds,ot as dt,l2 as du,a2 as dv,Un as e,Q1 as f,Vg as g,Wg as h,vT as i,QP as j,im as k,rA as l,iA as m,Gg as n,dt as o,Os as p,LR as q,Xg as r,pd as s,Se as t,T2 as u,jC as v,ss as w,Fl as x,Qt as y,pI as z};
|
|
35
|
+
`,o);i>r&&(o=i+1)}n.push(e.slice(r,o)),r=o}return n}function XT(e,t=WT,n=GT){const r=new Map;let o=0,i=0;for(const s of[...e.keys()]){const a=e.get(s);if(!a||a.length===0){e.delete(s);continue}const c=[];for(;a.length>0;){const l=a[0];if(i>0&&(i>=n||o+l.length>t))break;a.shift(),c.push(l),o+=l.length,i+=1}if(c.length>0&&r.set(s,c),e.delete(s),a.length>0&&e.set(s,a),i>=n||o>=t)break}return r}async function uw(e,t=!1,n="termdock-encrypted-background"){const r=await new Promise((o,i)=>{const s=indexedDB.open(n,1);s.onupgradeneeded=()=>s.result.createObjectStore("state"),s.onsuccess=()=>o(s.result),s.onerror=()=>i(s.error)});try{return await new Promise((o,i)=>{const s=r.transaction("state",t?"readwrite":"readonly"),a=e(s.objectStore("state"));s.oncomplete=()=>o(a.result),s.onabort=s.onerror=()=>i(s.error)})}finally{r.close()}}const YT=e=>uw(t=>t.put(e,e.targetPeerId),!0),ZT=e=>uw(t=>t.delete(e),!0),fw="termdock-pwa-notifications-enabled",hw="termdock-pwa-ai-notifications-enabled",pw="termdock-pwa-exit-notifications-enabled",gw="termdock-pwa-notification-alert-style",JT="termdock-notification-claim:",cl=5e3,QT=1500,ll="termdock-push-last-sync",lh=360*60*1e3,eP=10080*60*1e3,ko=new Map;function yd(){return it()?!0:typeof window<"u"&&typeof Notification<"u"&&"serviceWorker"in navigator&&window.isSecureContext}function tP(){if(typeof navigator>"u")return!1;const e=navigator.userAgent;return/iPad|iPhone|iPod/.test(e)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}function nP(){return typeof window>"u"?!1:!!(window.matchMedia("(display-mode: standalone)").matches||"standalone"in navigator&&navigator.standalone===!0)}function rP(){return it()?!0:!(!yd()||tP()&&!nP())}function b2(){return it()?"granted":typeof Notification>"u"?"unsupported":Notification.permission}function bd(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(fw)==="true"}catch{return!1}}function v2(e){if(!(typeof window>"u"))try{window.localStorage.setItem(fw,String(e))}catch{}}function gs(){if(typeof window>"u")return!0;try{const e=window.localStorage.getItem(hw);return e===null?!0:e==="true"}catch{return!0}}function S2(e){if(!(typeof window>"u"))try{window.localStorage.setItem(hw,String(e))}catch{}}function dl(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(pw)==="true"}catch{return!1}}function x2(e){if(!(typeof window>"u"))try{window.localStorage.setItem(pw,String(e))}catch{}}function _o(){if(typeof window>"u")return"normal";try{const e=window.localStorage.getItem(gw);if(e==="quiet"||e==="persistent")return e}catch{}return"normal"}function E2(e){if(!(typeof window>"u"))try{window.localStorage.setItem(gw,e)}catch{}}async function A2(){return it()?"granted":yd()?Notification.permission==="default"?Notification.requestPermission():Notification.permission:"unsupported"}function oP(){return typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus()}function iP(e){for(const[t,n]of ko)e-n>cl&&ko.delete(t)}function sP(e){return e.dedupKey?.trim()?e.dedupKey.trim():e.tag?.trim()?e.tag.trim():[e.data?.sessionId,e.title,e.body].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim()).join("|")}function aP(e){const t=sP(e);if(!t)return!0;const n=Date.now();iP(n);const r=ko.get(t)??0;if(n-r<cl)return!1;try{if(typeof window<"u"&&window.localStorage){const o=`${JT}${t}`,i=Number(window.localStorage.getItem(o)??"0");if(Number.isFinite(i)&&n-i<cl)return ko.set(t,i),!1;Number.isFinite(i)&&i>0&&window.localStorage.removeItem(o),window.localStorage.setItem(o,String(n))}}catch{}return ko.set(t,n),!0}async function js(){if(typeof navigator>"u"||!("serviceWorker"in navigator))return null;try{const e=await navigator.serviceWorker.getRegistration()??null;return e?.active?e:await Promise.race([navigator.serviceWorker.ready,new Promise(n=>{window.setTimeout(()=>n(null),QT)})])??e}catch{return null}}function cP(e){const t="=".repeat((4-e.length%4)%4),n=(e+t).replace(/-/g,"+").replace(/_/g,"/"),r=window.atob(n),o=new Uint8Array(new ArrayBuffer(r.length));for(let i=0;i<r.length;i+=1)o[i]=r.charCodeAt(i);return o}async function vd(e,t){const n=await fetch("/api/csrf-token");if(!n.ok)throw new Error("Unable to get notification security token");const{csrfToken:r}=await n.json();return fetch(`/api/notifications/${e}`,{method:"POST",headers:{"Content-Type":"application/json","X-XSRF-TOKEN":r},body:JSON.stringify(t)})}async function lP(e=!1,t=!1){if(it())return!0;if(!bd()||!rP()||Notification.permission!=="granted")return!1;const n=await js();if(!n?.pushManager)return!1;try{const r=await fetch("/api/notifications/status");if(!r.ok)return!1;const o=await r.json();let i=await n.pushManager.getSubscription();const s=!!(i?.expirationTime&&i.expirationTime-Date.now()<eP);if(!i)try{i=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:cP(o.publicKey)})}catch(d){return console.warn(`[PWA notifications] Push subscription missing; re-subscribe failed${t?" (user gesture)":""}:`,d),!1}const a=Number(window.localStorage.getItem(ll)??"0"),c=!o.subscription||o.subscription.endpoint!==i.endpoint||Date.now()-(o.subscription.updatedAt??0)>=lh;if(e||c||Date.now()-a>=lh||s){if(!(await vd("subscribe",{subscription:i.toJSON(),aiEnabled:gs(),exitEnabled:dl(),alertStyle:_o(),locale:navigator.language})).ok)return!1;window.localStorage.setItem(ll,String(Date.now()))}const l=ce();return l&&await YT({targetPeerId:l.targetPeerId,addresses:yn(l),routes:At(l),publicKey:o.publicKey,preferences:{aiEnabled:gs(),exitEnabled:dl(),alertStyle:_o(),locale:navigator.language}}),!0}catch(r){return console.warn("[PWA notifications] Push subscription sync failed:",r),!1}}async function C2(){if(it())return;const t=await(await js())?.pushManager?.getSubscription();try{await vd("unsubscribe",{endpoint:t?.endpoint})}finally{const n=ce();n&&await ZT(n.targetPeerId),await t?.unsubscribe();try{window.localStorage.removeItem(ll)}catch{}}}async function k2(){if(it()||!bd())return;(await vd("preferences",{aiEnabled:gs(),exitEnabled:dl(),alertStyle:_o(),locale:navigator.language})).status===404&&await lP(!0)}async function I2(){if(!it())try{const e=navigator;typeof e.clearAppBadge=="function"&&await e.clearAppBadge()}catch{}}async function R2(e){if(!it())try{const t=await js();if(!t||typeof t.getNotifications!="function")return;const n=`agent:${e}`,r=await t.getNotifications({tag:n});for(const i of r)i.close();const o=navigator;if(typeof o.setAppBadge=="function"){const i=await t.getNotifications();await o.setAppBadge(i.length)}}catch{}}async function nc(e){if(!bd()||!yd())return!1;if(e.requireHidden!==!1&&oP())return!0;const t=it();if(t){const i=e.alertStyle??_o(),s=await t.showNotification({title:e.title,body:e.body,tag:e.tag,sessionId:e.data?.sessionId,silent:i==="quiet",persistent:i==="persistent"});return t.notificationDeliveryConfirmation===!0&&s}if(Notification.permission!=="granted")return!1;const n=await js();if(e.deferToPush&&await n?.pushManager?.getSubscription())return!0;if(e.requireHidden!==!1){if(await n?.pushManager?.getSubscription())return!0}if(!aP(e))return!0;const r=e.alertStyle??_o(),o={body:e.body,tag:e.tag,icon:"/pwa-192x192.png",badge:"/maskable-icon-512x512.png",requireInteraction:r==="persistent",renotify:r==="persistent"?!!e.tag:!1,silent:r==="quiet",vibrate:r==="quiet"?[]:[80,40,80],data:{url:e.data?.url??"/",sessionId:e.data?.sessionId}};try{if(n&&typeof n.showNotification=="function")return await n.showNotification(e.title,o),!0;const i=new Notification(e.title,o);return i.onclick=()=>{window.focus(),e.data?.url&&window.location.href!==e.data.url&&window.location.assign(e.data.url),i.close()},!0}catch(i){if(i instanceof DOMException&&i.name==="NotSupportedError"&&o.renotify)try{const s={...o,renotify:!1};return n&&typeof n.showNotification=="function"?await n.showNotification(e.title,s):new Notification(e.title,s),!0}catch(s){return console.warn("[PWA notifications] Failed to show notification (renotify fallback):",s),!1}return console.warn("[PWA notifications] Failed to show notification:",i),!1}}function dP(){try{return localStorage.getItem("termdock:locale")||"en"}catch{return"en"}}function uP(e,t){return e==="zh"?{waitingTitle:`${t} 需要你的处理`,waitingBody:`${t} 需要你的处理。`,doneTitle:`${t} 已完成`,doneBody:`${t} 已完成,点按查看结果。`,exitedTitle:`${t} 已退出`,exitedBody:`${t} 已退出,点按查看结果。`}:{waitingTitle:`${t} needs your input`,waitingBody:`${t} is waiting for your input.`,doneTitle:`${t} finished`,doneBody:"Tap to see the result.",exitedTitle:`${t} exited`,exitedBody:"Tap to see the result."}}const dh=1e6;function Nt(e){return{sessionId:e,directory:"",terminalSessionId:null,mode:"shell",tmuxSessionName:null,activeProgram:null,activeProgramRaw:null,activeProgramSource:null,cwd:null,inCopyMode:!1,isConnecting:!1,agentStatus:null,agentIndicator:null,agentStatusDetail:null,agent:null,agentMessage:null,agentNativeSessionId:null,agentResumeRecovered:!1,agentRich:!1,agentActivity:0,agentCwd:null,agentNeedsReview:!1,shellTitle:null,promptState:null,shellExitCode:null,tuiProgress:null,gitStatus:null,bufferChunks:[],bufferLength:0,lastOutputAt:null,updatedAt:Date.now()}}const Us="termdock-shell-titles-v1";function Hs(){if(typeof window>"u")return{};try{const e=localStorage.getItem(Us);if(!e)return{};const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{}}catch{return{}}}function fP(e){return Hs()[e]??null}function hP(e,t){if(!(typeof window>"u"))try{const n=Hs();t?n[e]=t:delete n[e],localStorage.setItem(Us,JSON.stringify(n))}catch{}}function pP(e){if(!(typeof window>"u"))try{const t=Hs();delete t[e],localStorage.setItem(Us,JSON.stringify(t))}catch{}}const $s="termdock-agent-cache-v1";function Sd(){if(typeof window>"u")return{};try{const e=localStorage.getItem($s);if(!e)return{};const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{}}catch{return{}}}function uh(e,t){if(!(typeof window>"u"))try{const n=Sd();t?n[e]=t:delete n[e],localStorage.setItem($s,JSON.stringify(n))}catch{}}function gP(e){if(!(typeof window>"u"))try{const t=Sd();delete t[e],localStorage.setItem($s,JSON.stringify(t))}catch{}}function mP(){if(!(typeof window>"u"))try{localStorage.removeItem($s)}catch{}}function wP(e){return Sd()[e]??null}function yP(){if(!(typeof window>"u"))try{localStorage.removeItem(Us)}catch{}}const rc=Fs((e,t)=>{const n={pendingChunksBySession:new Map,activitySessionIds:new Set,batchFlushRafRef:null},r=(s,a)=>{const c=new Map;return e(l=>{const d=new Map(l.sessions);let u=l.nextChunkId;const f=Date.now();for(const[h,g]of s){const m=d.get(h)??Nt(h);let v=m.bufferChunks.length>0?[...m.bufferChunks]:[],w=m.bufferLength;for(const S of g){const y=u++;v.push({id:y,data:S}),c.set(h,y),w+=S.length}for(;w>dh&&v.length>1;){const S=v.shift();if(!S)break;w-=S.data.length}d.set(h,{...m,bufferChunks:v,bufferLength:w,lastOutputAt:a.has(h)?f:m.lastOutputAt,updatedAt:f})}return{sessions:d,nextChunkId:u}}),c},o=()=>{if(n.batchFlushRafRef===null){if(typeof window>"u"){i();return}n.batchFlushRafRef=window.requestAnimationFrame(()=>{n.batchFlushRafRef=null,i()})}},i=()=>{if(n.pendingChunksBySession.size===0)return;const s=XT(n.pendingChunksBySession),a=new Set([...s.keys()].filter(c=>n.activitySessionIds.has(c)));for(const c of s.keys())n.pendingChunksBySession.has(c)||n.activitySessionIds.delete(c);r(s,a),n.pendingChunksBySession.size>0&&o()};return{sessions:new Map,nextChunkId:1,activeSessionId:null,getTerminalSession:s=>t().sessions.get(s),setActiveSessionId:s=>{if(e({activeSessionId:s}),s){const a=t().sessions.get(s);if(a?.agentNeedsReview){const c=new Map(t().sessions);c.set(s,{...a,agentNeedsReview:!1,updatedAt:Date.now()}),e({sessions:c}),a.terminalSessionId&&zc(a.terminalSessionId)}}},setTerminalSession:(s,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(s),f=!d||d.terminalSessionId!==a.sessionId?Nt(s):d??Nt(s),h=a.history??d?.history??[];return l.set(s,{...f,terminalSessionId:a.sessionId,mode:a.mode??f.mode,tmuxSessionName:a.tmuxSessionName??f.tmuxSessionName,activeProgram:a.activeProgram??d?.activeProgram??f.activeProgram,activeProgramRaw:a.activeProgramRaw??d?.activeProgramRaw??f.activeProgramRaw,activeProgramSource:a.activeProgramSource??d?.activeProgramSource??f.activeProgramSource,cwd:a.cwd??d?.cwd??f.cwd,agent:d?.agent??wP(s)??f.agent,agentResumeRecovered:d?.agentResumeRecovered??f.agentResumeRecovered,shellTitle:d?.shellTitle??Hs()[s]??f.shellTitle,sessionId:s,isConnecting:!1,history:h,updatedAt:Date.now()}),{sessions:l}})},setSessionHistory:(s,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(s)??Nt(s);return l.set(s,{...d,history:a,updatedAt:Date.now()}),{sessions:l}})},setSessionActiveProgram:(s,a,c=null,l=null)=>{e(d=>{const u=new Map(d.sessions),f=u.get(s)??Nt(s);return u.set(s,{...f,activeProgram:a,activeProgramRaw:l,activeProgramSource:c,updatedAt:Date.now()}),{sessions:u}})},setSessionCwd:(s,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(s)??Nt(s);return l.set(s,{...d,cwd:a,updatedAt:Date.now()}),{sessions:l}})},setSessionShellTitle:(s,a)=>{e(c=>{const l=c.sessions.get(s)??Nt(s);if(l.shellTitle===a)return c;const d=new Map(c.sessions);return d.set(s,{...l,shellTitle:a,updatedAt:Date.now()}),{sessions:d}}),hP(s,a)},setSessionPromptState:(s,a,c)=>{e(l=>{const d=l.sessions.get(s);if(!d||d.promptState===a)return l;const u=new Map(l.sessions);return u.set(s,{...d,promptState:a,shellExitCode:c??d.shellExitCode,updatedAt:Date.now()}),{sessions:u}})},setSessionTuiProgress:(s,a)=>{e(c=>{const l=c.sessions.get(s);if(!l)return c;const d=a?.state==="remove"?null:a;if(l.tuiProgress?.state===d?.state&&l.tuiProgress?.progress===d?.progress)return c;const u=new Map(c.sessions);return u.set(s,{...l,tuiProgress:d,updatedAt:Date.now()}),{sessions:u}})},setSessionGitStatus:(s,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(s);return!d||JSON.stringify(d.gitStatus)===JSON.stringify(a)?c:(l.set(s,{...d,gitStatus:a,updatedAt:Date.now()}),{sessions:l})})},setSessionCopyMode:(s,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(s);return!d||d.inCopyMode===a?c:(l.set(s,{...d,inCopyMode:a,updatedAt:Date.now()}),{sessions:l})})},setSessionAgentIdentity:(s,a)=>{uh(s,a),e(c=>{const l=c.sessions.get(s)??Nt(s);if(JSON.stringify(l.agent)===JSON.stringify(a))return c;const d=new Map(c.sessions);return d.set(s,{...l,agent:a,updatedAt:Date.now()}),{sessions:d}})},setSessionAgentStatus:(s,a)=>{const c=t(),l=c.sessions.get(s);if(!l)return;const d=a.agentStatus??null,u=d&&d!=="idle"?a.agentIndicator??l.agentIndicator??null:null,f=d&&d!=="idle"?a.agentStatusDetail??null:null,h=a.agent!==void 0?a.agent:l.agent,g=a.agentMessage!==void 0?a.agentMessage:d?l.agentMessage:null,m=a.agentNativeSessionId!==void 0?a.agentNativeSessionId:l.agentNativeSessionId,v=a.agentResumeRecovered!==void 0?a.agentResumeRecovered:l.agentResumeRecovered,w=a.agentRich??l.agentRich,S=a.agentActivity??l.agentActivity,y=a.agentCwd!==void 0?a.agentCwd:l.agentCwd,A=c.activeSessionId!==s,R=l.agentStatus==="working"||l.agentStatus==="waiting"||l.agentStatus==="done",E=a.reviewed===!1||a.reviewed===null&&d===null&&R&&A;if(l.agentStatus===d&&l.agentIndicator===u&&l.agentStatusDetail===f&&l.agent===h&&l.agentMessage===g&&l.agentNativeSessionId===m&&l.agentResumeRecovered===v&&l.agentRich===w&&l.agentActivity===S&&l.agentCwd===y&&l.agentNeedsReview===E)return;const C=new Map(c.sessions);if(C.set(s,{...l,agentStatus:d,agentIndicator:u,agentStatusDetail:f,agent:h,agentMessage:g,agentNativeSessionId:m,agentResumeRecovered:v,agentRich:w,agentActivity:S,agentCwd:y,agentNeedsReview:E,updatedAt:Date.now()}),e({sessions:C}),h&&uh(s,h),!gs())return;const k=h?.displayName??l.agent?.displayName??"Agent",b=dP(),x=uP(b,k);if(d==="waiting"&&l.agentStatus!=="waiting"&&A){nc({title:x.waitingTitle,body:g??x.waitingBody,tag:`agent:${s}`,dedupKey:`agent:${s}:waiting:${S}`,data:{url:"/",sessionId:s},deferToPush:!0});return}if(d==="done"&&l.agentStatus!=="done"&&A){nc({title:x.doneTitle,body:x.doneBody,tag:`agent:${s}`,dedupKey:`agent:${s}:done:${S}`,data:{url:"/",sessionId:s},deferToPush:!0});return}d===null&&(l.agentStatus==="working"||l.agentStatus==="waiting")&&A&&nc({title:x.exitedTitle,body:x.exitedBody,tag:`agent:${s}`,dedupKey:`agent:${s}:exited:${S}`,data:{url:"/",sessionId:s},deferToPush:!0})},setAgentResumeRecovered:(s,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(s)??Nt(s);return d.agentResumeRecovered===a?c:(l.set(s,{...d,agentResumeRecovered:a,updatedAt:Date.now()}),{sessions:l})})},clearAgentNeedsReview:s=>{const a=t().sessions.get(s);a?.agentNeedsReview&&(e(c=>{const l=new Map(c.sessions),d=l.get(s);return!d||!d.agentNeedsReview?c:(l.set(s,{...d,agentNeedsReview:!1,updatedAt:Date.now()}),{sessions:l})}),a.terminalSessionId&&zc(a.terminalSessionId))},setConnecting:(s,a)=>{e(c=>{const l=new Map(c.sessions),d=l.get(s)??Nt(s);return l.set(s,{...d,isConnecting:a,updatedAt:Date.now()}),{sessions:l}})},appendToBuffer:(s,a,c)=>{if(!a)return;let l=n.pendingChunksBySession.get(s);l||(l=[],n.pendingChunksBySession.set(s,l)),l.push(...ch(a)),c?.markActivity!==!1&&n.activitySessionIds.add(s),o()},hasPendingBufferWrites:s=>(n.pendingChunksBySession.get(s)?.length??0)>0,flushPendingBufferWrites:s=>{const a=n.pendingChunksBySession.get(s);if(!a?.length)return t().sessions.get(s)?.bufferChunks.at(-1)?.id??null;n.pendingChunksBySession.delete(s);const c=n.activitySessionIds.delete(s);return n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),r(new Map([[s,a]]),c?new Set([s]):new Set).get(s)??null},replaceBuffer:(s,a)=>{n.pendingChunksBySession.delete(s),n.activitySessionIds.delete(s),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null);let c=null;return e(l=>{const d=new Map(l.sessions),u=d.get(s);if(!u)return l;if(!a||a.length===0)return d.set(s,{...u,bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:d};let f=l.nextChunkId;const h=[];let g=0;for(const m of a)if(m)for(const v of ch(m)){const w=f++;h.push({id:w,data:v}),c=w,g+=v.length}for(;g>dh&&h.length>1;){const m=h.shift();if(!m)break;g-=m.data.length}return d.set(s,{...u,bufferChunks:h,bufferLength:g,updatedAt:Date.now()}),{sessions:d,nextChunkId:f}}),c},clearTerminalSession:s=>{n.pendingChunksBySession.delete(s),n.activitySessionIds.delete(s),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),e(a=>{const c=new Map(a.sessions),l=c.get(s);return l&&c.set(s,{...l,terminalSessionId:null,isConnecting:!1,agentStatus:null,agentIndicator:null,agentStatusDetail:null,agent:null,agentMessage:null,agentNeedsReview:!1,updatedAt:Date.now()}),{sessions:c}})},clearBuffer:s=>{n.pendingChunksBySession.delete(s),n.activitySessionIds.delete(s),n.pendingChunksBySession.size===0&&n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),e(a=>{const c=new Map(a.sessions),l=c.get(s);return l?(c.set(s,{...l,bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:c}):a})},removeTerminalSession:s=>{n.pendingChunksBySession.delete(s),n.activitySessionIds.delete(s),e(a=>{const c=new Map(a.sessions);return c.delete(s),{sessions:c}}),pP(s),gP(s)},clearAllTerminalSessions:()=>{n.pendingChunksBySession.clear(),n.activitySessionIds.clear(),n.batchFlushRafRef!==null&&(window.cancelAnimationFrame(n.batchFlushRafRef),n.batchFlushRafRef=null),e({sessions:new Map,nextChunkId:1}),yP(),mP()}}}),ul="termdock:session-notice";function bP(){return N.useEffect(()=>{const e=()=>ec.getState().view(!document.hidden&&Ei()?rc.getState().activeSessionId:null);e();const t=rc.subscribe((n,r)=>{n.activeSessionId!==r.activeSessionId&&e()});return document.addEventListener("visibilitychange",e),window.addEventListener(Bo,e),()=>{t(),document.removeEventListener("visibilitychange",e),window.removeEventListener(Bo,e),ec.getState().view(null)}},[]),N.useEffect(()=>ow(e=>{if(e.type!=="session-notice")return;ec.getState().receive(e.sessionId,e.id);const t=ce()?.targetPeerId,n=Bt(),r=window.parent,o=zT().sessions.find(u=>u.sessionId===e.sessionId),i=rc.getState().sessions.get(e.sessionId),s=i?.shellTitle??fP(e.sessionId),a=s===i?.cwd||s===po(i?.cwd??null)?null:s,c=UT(o??{name:e.sessionName},i?.activeProgram??null,null,void 0,a,i?.promptState??null),l={...e,sessionName:c,key:`${t??"local"}:${e.id}`,open:()=>t&&n?n.focusSession(t,e.sessionId):(window.dispatchEvent(new CustomEvent("termdock:focus-session",{detail:e.sessionId})),!0)},d=r.document.createEvent("CustomEvent");d.initCustomEvent(ul,!1,!1,l),r.dispatchEvent(d)}),[]),null}function vP(){const{locale:e}=Mr(),t=e==="zh",[n,r]=N.useState([]);N.useEffect(()=>{const s=a=>{const c=a.detail;r(l=>l.some(d=>d.key===c.key)?l:[...l,c])};return window.addEventListener(ul,s),()=>window.removeEventListener(ul,s)},[]);const o=N.useCallback(s=>{r(a=>a.filter(c=>c.key!==s))},[]),i=n[0];return i?ms.createPortal(p.jsx(SP,{notice:i,remaining:n.length-1,chinese:t,onDismiss:o},i.key),document.body):null}function SP({notice:e,remaining:t,chinese:n,onDismiss:r}){const[o,i]=N.useState(!1);return p.jsxs("section",{"aria-label":n?"关键进展提醒":"Progress reminder",className:"fixed left-3 right-3 top-[calc(var(--safe-top-inset,0px)+0.75rem)] z-toast overflow-hidden rounded-xl bg-surface text-foreground shadow-lg ring-1 ring-inset ring-border/15 animate-fade-in md:left-auto md:right-4 md:w-[360px]",children:[p.jsxs("button",{type:"button","aria-label":n?"查看 Session":"Open session",className:"group flex w-full items-start gap-2.5 p-3.5 pr-11 text-left transition-colors hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",onClick:()=>{e.open()?r(e.key):i(!0)},children:[p.jsx(Kg,{size:16,className:"mt-0.5 shrink-0 text-primary","aria-hidden":"true"}),p.jsxs("span",{className:"min-w-0 flex-1",role:"status","aria-live":"polite","aria-atomic":"true",children:[p.jsxs("span",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] font-medium",title:e.sessionName,children:e.sessionName}),p.jsx(W1,{size:13,className:"shrink-0 text-muted-foreground/60 transition-colors group-hover:text-primary","aria-hidden":"true"})]}),e.title&&p.jsx("span",{className:"mt-1 block truncate text-[11px] text-muted-foreground",children:e.title}),p.jsx("span",{className:"mt-1.5 line-clamp-3 whitespace-pre-wrap break-words text-[13px] leading-relaxed text-foreground/85",title:e.message,children:e.message}),t>0&&p.jsx("span",{className:"mt-2 block text-[10px] text-muted-foreground",children:n?`还有 ${t} 条`:`${t} more`}),o&&p.jsx("span",{role:"alert",className:"mt-2 block text-xs text-warning",children:n?"暂时无法打开该服务,请重试。":"Unable to open the service. Please retry."})]})]}),p.jsx("button",{type:"button","aria-label":n?"关闭提醒":"Dismiss reminder",className:"absolute right-0 top-0 flex h-11 w-11 items-center justify-center rounded-tr-xl text-muted-foreground/60 transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",onClick:()=>r(e.key),children:p.jsx(Yg,{size:14})})]})}const fh=5*6e4;let fl,mw=!1,ww=!1,hh=!1;const hl=new Set;function ph(){mw=!0,hl.forEach(e=>e())}function xP(){return N.useSyncExternalStore(e=>(hl.add(e),()=>{hl.delete(e)}),()=>mw,()=>!1)}function EP(){window.dispatchEvent(new Event("termdock:before-update")),ww=!0,fl?.waiting?fl.waiting.postMessage({type:"SKIP_WAITING"}):window.location.reload()}function AP(e,t){let n=e;return()=>{if(!n){n=!0;return}t()}}function CP(){if(hh||typeof window>"u"||!("serviceWorker"in navigator))return;hh=!0,navigator.serviceWorker.addEventListener("controllerchange",AP(!!navigator.serviceWorker.controller,()=>{ww?window.location.reload():ph()}));const e=()=>{navigator.serviceWorker.register("/sw.js",{scope:"/",updateViaCache:"none"}).then(t=>{fl=t;const n=()=>{t.waiting&&ph()},r=()=>{const s=t.installing;s?.addEventListener("statechange",()=>{s.state==="installed"&&navigator.serviceWorker.controller&&n()})};t.addEventListener("updatefound",r),r(),n();let o=0;const i=()=>{document.visibilityState!=="visible"||Date.now()-o<fh||(o=Date.now(),t.update().then(n).catch(()=>{}))};i(),window.setInterval(i,fh),document.addEventListener("visibilitychange",i)}).catch(()=>{})};document.readyState==="complete"?e():window.addEventListener("load",e,{once:!0})}function kP(){const e=xP(),[t,n]=N.useState(!1),{locale:r}=Mr();if(!e||t)return null;const o=r==="zh";return p.jsxs("div",{role:"status",className:"fixed bottom-16 left-1/2 z-toast flex max-w-[calc(100%-2rem)] -translate-x-1/2 items-center gap-3 rounded-lg border border-border bg-background px-4 py-3 text-sm text-foreground shadow-lg",children:[p.jsx("span",{children:o?"新版本已就绪":"An update is ready"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-primary",onClick:EP,children:o?"重新加载":"Reload"}),p.jsx("button",{type:"button",className:"whitespace-nowrap text-muted-foreground",onClick:()=>n(!0),children:o?"稍后":"Later"})]})}let go=[],oc=!1;function IP(e,t,n={}){typeof window>"u"||(go.push(JSON.stringify({level:e,message:t,data:{ts:Date.now(),...n}})),RP())}async function RP(){if(!oc){oc=!0;try{for(;go.length>0;){const e=go[0];try{await fetch("/api/client-log",{method:"POST",headers:{"Content-Type":"application/json"},body:e,keepalive:!0}),go.shift()}catch{go=[];break}}}finally{oc=!1}}}function TP(){const e=N.useRef(null),t=navigator.standalone===!0||window.matchMedia?.("(display-mode: standalone)").matches===!0,n=window.parent===window&&gd()&&t;return N.useEffect(()=>{if(!n)return;const r=()=>{const o=e.current;if(!o)return;const i=o.getBoundingClientRect(),s=getComputedStyle(o);IP("info","PWA_STATUS_BAR_SURFACE",{revision:"ipad-default-status-bar",statusBarStyle:document.querySelector('meta[name="apple-mobile-web-app-status-bar-style"]')?.getAttribute("content"),entry:document.querySelector('script[type="module"][src]')?.getAttribute("src"),parent:o.parentElement?.tagName,rect:{x:i.x,y:i.y,width:i.width,height:i.height},background:s.backgroundColor,clip:s.backgroundClip,zIndex:s.zIndex,safeTop:getComputedStyle(document.documentElement).getPropertyValue("--safe-top-inset"),viewport:{width:window.innerWidth,height:window.innerHeight,offsetTop:window.visualViewport?.offsetTop},screen:{width:window.screen.width,height:window.screen.height}})};return window.addEventListener("termdock:initial-viewport-presented",r,{once:!0}),()=>window.removeEventListener("termdock:initial-viewport-presented",r)},[n]),n?ms.createPortal(p.jsx("div",{ref:e,"data-pwa-status-bar-surface":!0,"aria-hidden":"true",className:"pwa-status-bar-surface pointer-events-none fixed inset-x-0 top-0 z-popover app-chrome-bg"}),document.body):null}function yw(e){const t=document.querySelector('meta[name="theme-color"]');t&&t.setAttribute("content",e==="light"?"#FFFCF0":"#1C1B1A")}const bw=N.createContext(void 0);function T2({children:e}){const t=N.useContext(bw),n=t===void 0?typeof document>"u"?null:document.body:t;return n?ms.createPortal(e,n):null}const PP={activeKey:"root",items:[]},NP=()=>()=>{},LP=()=>PP;function BP({host:e,item:t,visible:n,active:r}){const o=N.useRef(null);return N.useEffect(()=>{o.current?.toggleAttribute("inert",!r)},[r]),N.useLayoutEffect(()=>{const i=o.current;return()=>{try{const s=i?.contentWindow,a=s?.document.createEvent("Event");a&&(a.initEvent("termdock:before-update",!1,!1),s?.dispatchEvent(a))}catch{}e.attach(t.key,null)}},[e,t.key]),p.jsx("iframe",{ref:o,title:t.service?.label||"服务工作区","data-workspace-key":t.key,src:`/workspace.html?${Bg}=${encodeURIComponent(t.key)}`,className:"fixed inset-0 w-full border-0 bg-[var(--chrome-bg)]",style:{height:"var(--app-base-vh, 100%)",visibility:n?"visible":"hidden",pointerEvents:r?"auto":"none"},"aria-hidden":!r,tabIndex:r?0:-1,allow:"clipboard-read; clipboard-write; fullscreen"})}function DP({children:e}){const t=window.parent===window?Bt():void 0,n=N.useSyncExternalStore(t?.subscribe||NP,t?.snapshot||LP),[r,o]=N.useState(null),[i,s]=N.useState(()=>n.activeKey==="root"?"root":null),[a,c]=N.useState(),[l,d]=N.useState(!1),[u,f]=N.useState(),h=n.items.find(y=>y.key===n.activeKey),g=h?.rendered||a===n.activeKey?n.activeKey:i,m=g!==n.activeKey,v=m&&i===null;N.useLayoutEffect(()=>{if(!m||v){f(void 0);return}const y=()=>{const A=Array.from(document.querySelectorAll("iframe[data-workspace-key]")).find(T=>T.dataset.workspaceKey===i),k=(i==="root"?r:A?.contentDocument)?.querySelector('nav[aria-label="切换服务"]')?.closest("[data-sidebar-gesture-ignore]")?.getBoundingClientRect();if(!k||k.width===0||k.right<=0){f(void 0);return}const b=A?.getBoundingClientRect(),x=k.top+(b?.top??0)>=160;f({left:k.left+(b?.left??0)+12,top:(x?k.top-8:k.bottom+8)+(b?.top??0),width:Math.max(0,k.width-24),transform:x?"translateY(-100%)":"none"})};return y(),window.addEventListener("resize",y),()=>window.removeEventListener("resize",y)},[m,v,i,r]),N.useLayoutEffect(()=>{t?.present(g),m||s(g),r?.toggleAttribute("inert",g!=="root"||m)},[t,r,g,m]),N.useEffect(()=>{if(d(!1),!m)return;const y=setTimeout(()=>d(!0),8e3);return()=>clearTimeout(y)},[n.activeKey,m]),N.useEffect(()=>{c(void 0)},[n.activeKey]);const w=n.items.find(y=>y.key===i),S=h?.phase==="offline"?"网络已断开,等待恢复…":h?.phase==="reconnecting"?"连接暂未恢复,正在重试…":l?"连接时间较长,仍在等待服务…":v?"正在恢复服务…":"正在切换服务…";return N.useEffect(()=>{if(!t)return;const y=()=>{try{const A=JSON.parse(localStorage.getItem("termdock-color-theme")||"null");(A==="dark"||A==="light")&&(document.documentElement.dataset.theme=A,yw(A))}catch{}};return window.addEventListener("storage",y),()=>window.removeEventListener("storage",y)},[t]),N.useEffect(()=>{if(!t||!("serviceWorker"in navigator))return;const y=E=>{if(E.source!==navigator.serviceWorker.controller)return;const C=E.data;C?.type==="termdock:focus-session"&&typeof C.targetPeerId=="string"&&typeof C.sessionId=="string"&&t.focusSession(C.targetPeerId,C.sessionId)&&(E.ports[0]?.postMessage({type:"termdock:focus-session-ack"}),E.stopImmediatePropagation())},A=async()=>{if("caches"in window)try{const E=await caches.open("termdock-notification-target-v1"),C=await E.match("/__termdock-notification-target");if(!C)return;const k=await C.json();typeof k.targetPeerId=="string"&&typeof k.sessionId=="string"&&Date.now()-k.clickedAt<3e4&&t.focusSession(k.targetPeerId,k.sessionId)&&await E.delete("/__termdock-notification-target")}catch{}},R=()=>{document.hidden||A()};return navigator.serviceWorker.addEventListener("message",y),document.addEventListener("visibilitychange",R),A(),()=>{navigator.serviceWorker.removeEventListener("message",y),document.removeEventListener("visibilitychange",R)}},[t]),t?p.jsxs("div",{className:"relative h-full w-full overflow-hidden bg-[var(--chrome-bg)]",children:[p.jsx("div",{ref:o,className:"isolate h-full w-full","aria-hidden":g!=="root"||m,style:{visibility:g==="root"?"visible":"hidden"},children:p.jsx(bw.Provider,{value:r,children:e})}),n.items.filter(y=>y.key!=="root").map(y=>p.jsx(BP,{host:t,item:y,visible:g===y.key,active:!m&&g===y.key},y.key)),v&&p.jsx(pd,{className:"z-modal-panel",status:S,detail:l||h?.phase==="offline"||h?.phase==="reconnecting"?h?.service?.label:void 0,actionLabel:l||h?.phase==="offline"||h?.phase==="reconnecting"?"查看连接页面":void 0,onAction:()=>c(n.activeKey)}),m&&!v&&p.jsx("div",{className:"fixed inset-0 z-modal-panel flex items-end justify-center px-3 pb-[calc(env(safe-area-inset-bottom)+96px)]",role:"dialog","aria-modal":"true","aria-label":"切换服务",onKeyDown:y=>{if(y.key==="Escape"&&w?.service&&(y.preventDefault(),t.activate(w.service)),y.key==="Tab"){const A=Array.from(y.currentTarget.querySelectorAll("button")),R=A[0],E=A[A.length-1];y.shiftKey&&document.activeElement===R?(y.preventDefault(),E?.focus()):!y.shiftKey&&document.activeElement===E&&(y.preventDefault(),R?.focus())}},children:p.jsxs("div",{style:u?{position:"absolute",...u}:void 0,className:"flex w-full max-w-sm flex-wrap items-center gap-x-2 gap-y-1 rounded-xl border border-border bg-surface-elevated px-3 py-1.5 text-foreground shadow-lg",children:[p.jsxs("div",{role:"status","aria-live":"polite",className:"flex min-w-0 flex-1 items-center gap-2",children:[p.jsx(et,{size:16,className:"shrink-0 animate-spin text-primary motion-reduce:animate-none","aria-hidden":"true"}),p.jsxs("div",{className:"min-w-0",children:[p.jsx("div",{className:"truncate text-sm font-medium",children:h?.service?.label||"服务工作区"}),p.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:S})]})]}),p.jsxs("div",{className:"flex items-center justify-end gap-1",children:[l&&p.jsx("button",{type:"button",className:"min-h-11 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2",onClick:()=>c(n.activeKey),children:"查看连接页面"}),w?.service&&p.jsx("button",{type:"button",autoFocus:!0,"aria-label":"取消切换",className:"min-h-11 shrink-0 rounded-lg px-3 text-xs text-muted-foreground hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>t.activate(w.service),children:"取消"})]})]})})]}):e}const _P=N.lazy(()=>wn(()=>import("./App-DhHRFEY2.js").then(e=>e.d),__vite__mapDeps([4,2,1,5,6,3,7,8]))),OP=N.lazy(()=>wn(()=>import("./DagPlayground-CiCwopwo.js"),__vite__mapDeps([9,10,2,1,11,7,3])).then(e=>({default:e.DagPlayground}))),FP=N.lazy(()=>wn(()=>import("./DiffLab-C8ItelM8.js"),__vite__mapDeps([12,2,1,13,8,14,3])).then(e=>({default:e.DiffLab}))),MP=N.lazy(()=>wn(()=>import("./DiffReviewLab-CXlrQWLJ.js"),__vite__mapDeps([15,2,1,16,5,6,11,13,8,14,3])).then(e=>({default:e.DiffReviewLab})));NT();C1();L1();window.parent===window&&CP();const mo=ce();mo&&wn(()=>import("./App-DhHRFEY2.js").then(e=>e.d),__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")&&f1(mo?{...mo,id:mo.targetPeerId,label:mo.serviceName||location.host}:void 0);try{const e=JSON.parse(window.localStorage.getItem("termdock-color-theme")||"null");(e==="dark"||e==="light")&&(document.documentElement.dataset.theme=e,yw(e))}catch{}_1.createRoot(document.getElementById("root")).render(p.jsxs(lt.StrictMode,{children:[p.jsx(TP,{}),p.jsx(pT,{}),p.jsxs(VI,{children:[window.parent===window&&p.jsxs(p.Fragment,{children:[p.jsx(kP,{}),p.jsx(vP,{})]}),p.jsx(vT,{children:p.jsx(N.Suspense,{fallback:p.jsx(pd,{}),children:(()=>{const e=new URLSearchParams(window.location.search);return e.get("dag-playground")==="1"?p.jsx(OP,{}):e.get("diff-review-lab")==="1"?p.jsx(MP,{}):e.get("diff-lab")==="1"?p.jsx(FP,{}):p.jsx(DP,{children:p.jsxs(mT,{children:[p.jsx(bP,{}),p.jsx(_P,{})]})})})()})})]})]}));export{u2 as $,od as A,Kg as B,cs as C,iw as D,sm as E,UI as F,XP as G,wR as H,Ok as I,Nk as J,Ml as K,et as L,a1 as M,Hk as N,t1 as O,FR as P,pk as Q,kS as R,h1 as S,dA as T,Vc as U,RT as V,Bo as W,Yg as X,tC as Y,VC as Z,wn as _,qg as a,oC as a$,Nn as a0,lI as a1,cI as a2,I2 as a3,IP as a4,KC as a5,o2 as a6,ls as a7,i2 as a8,KA as a9,gt as aA,DA as aB,ck as aC,ak as aD,uk as aE,NC as aF,aI as aG,oI as aH,wP as aI,fP as aJ,rI as aK,mI as aL,iI as aM,ok as aN,re as aO,po as aP,Dk as aQ,eI as aR,hI as aS,qk as aT,uI as aU,nI as aV,Zk as aW,Ak as aX,b2 as aY,sI as aZ,hs as a_,nC as aa,BC as ab,ZP as ac,Fs as ad,fk as ae,wI as af,CT as ag,qe as ah,LC as ai,ca as aj,bt as ak,wk as al,Xk as am,R2 as an,iC as ao,QC as ap,mk as aq,Gk as ar,rC as as,$I as at,IA as au,om as av,sC as aw,DR as ax,AA as ay,WC as az,z1 as b,p2 as b$,jT as b0,UT as b1,m2 as b2,fn as b3,gs as b4,dl as b5,_o as b6,bd as b7,it as b8,eC as b9,p as bA,YP as bB,YC as bC,bI as bD,bk as bE,ld as bF,_I as bG,gI as bH,Mk as bI,jI as bJ,GC as bK,sk as bL,NI as bM,Jk as bN,_m as bO,ym as bP,HT as bQ,vk as bR,MI as bS,_C as bT,_n as bU,kt as bV,zT as bW,zk as bX,$k as bY,Kk as bZ,Wk as b_,gC as ba,AR as bb,rk as bc,XC as bd,tk as be,dI as bf,Cm as bg,Bt as bh,Qa as bi,Up as bj,sg as bk,Vk as bl,lk as bm,hk as bn,_g as bo,Am as bp,BA as bq,n2 as br,Bk as bs,_k as bt,Rk as bu,Lk as bv,Pk as bw,rP as bx,yd as by,Ei as bz,W1 as c,FC as c$,h2 as c0,s2 as c1,OC as c2,aC as c3,e2 as c4,lo as c5,EI as c6,Sk as c7,kI as c8,DI as c9,Qe as cA,OI as cB,HC as cC,MC as cD,DC as cE,UC as cF,qC as cG,xI as cH,TI as cI,RI as cJ,BI as cK,w2 as cL,S2 as cM,x2 as cN,E2 as cO,v2 as cP,mm as cQ,PC as cR,JC as cS,la as cT,d2 as cU,nc as cV,LI as cW,ow as cX,AI as cY,t2 as cZ,$P as c_,Ck as ca,xk as cb,nk as cc,or as cd,A2 as ce,kk as cf,Ek as cg,$C as ch,f2 as ci,zC as cj,ZC as ck,II as cl,HI as cm,yk as cn,CI as co,WP as cp,CA as cq,SI as cr,fI as cs,vI as ct,PI as cu,Rm as cv,ce as cw,jk as cx,FI as cy,Ug as cz,zg as d,GP as d0,k2 as d1,lP as d2,yw as d3,VP as d4,dk as d5,C2 as d6,gk as d7,yI as d8,ik as d9,Ri as da,at as db,Yk as dc,Jg as dd,JP as de,Mr as df,_A as dg,r2 as dh,c2 as di,ec as dj,y2 as dk,De as dl,rc as dm,g2 as dn,Ym as dp,ve as dq,Uk as dr,Ds as ds,ot as dt,l2 as du,a2 as dv,Un as e,Q1 as f,Vg as g,Wg as h,vT as i,QP as j,im as k,rA as l,iA as m,Gg as n,dt as o,Os as p,LR as q,Xg as r,pd as s,Se as t,T2 as u,jC as v,ss as w,Fl as x,Qt as y,pI as z};
|