All your machines, one app. For you and your AI agents: agent sessions, desktops, files, logs and GitHub across your Macs, Linux and Windows machines, with an MCP server.
Share a session by link, peer to peer (#32)
Adib Hannac7841b33d2fe
diff --git a/Cargo.lock b/Cargo.lockindex 7d122d0..6aaa9c6 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -8,6 +8,16 @@ version = "2.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"+[[package]]+name = "aead"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"+dependencies = [+ "crypto-common 0.1.7",+ "generic-array",+]+[[package]]name = "aes"version = "0.8.4"@@ -262,6 +272,73 @@ dependencies = ["zbus",]+[[package]]+name = "asn1-rs"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5493c3bedbacf7fd7382c6346bbd66687d12bbaad3a89a2d2c303ee6cf20b048"+dependencies = [+ "asn1-rs-derive 0.5.1",+ "asn1-rs-impl",+ "displaydoc",+ "nom 7.1.3",+ "num-traits",+ "rusticata-macros",+ "thiserror 1.0.69",+ "time",+]++[[package]]+name = "asn1-rs"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8"+dependencies = [+ "asn1-rs-derive 0.6.0",+ "asn1-rs-impl",+ "displaydoc",+ "nom 7.1.3",+ "num-traits",+ "rusticata-macros",+ "thiserror 2.0.21",+ "time",+]++[[package]]+name = "asn1-rs-derive"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "965c2d33e53cb6b267e148a4cb0760bc01f4904c1cd4bb4002a085bb016d1490"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+ "synstructure 0.13.2",+]++[[package]]+name = "asn1-rs-derive"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+ "synstructure 0.13.2",+]++[[package]]+name = "asn1-rs-impl"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "async-broadcast"version = "0.7.2"@@ -577,6 +654,54 @@ dependencies = ["pkg-config",]+[[package]]+name = "axum"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"+dependencies = [+ "axum-core",+ "bytes",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-util",+ "itoa",+ "matchit",+ "memchr",+ "mime",+ "percent-encoding",+ "pin-project-lite",+ "serde_core",+ "serde_json",+ "serde_path_to_error",+ "sync_wrapper",+ "tokio",+ "tower",+ "tower-layer",+ "tower-service",+]++[[package]]+name = "axum-core"+version = "0.5.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"+dependencies = [+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "http-body-util",+ "mime",+ "pin-project-lite",+ "sync_wrapper",+ "tower-layer",+ "tower-service",+]+[[package]]name = "base64"version = "0.22.1"@@ -615,7 +740,7 @@ version = "0.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"dependencies = [- "bit-vec",+ "bit-vec 0.8.0",][[package]]@@ -624,6 +749,15 @@ version = "0.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"+[[package]]+name = "bit-vec"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"+dependencies = [+ "serde",+]+[[package]]name = "bit_field"version = "0.10.3"@@ -789,6 +923,29 @@ version = "3.20.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"+[[package]]+name = "bytecheck"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26333eeac754f0ad8a6bcd0eb0ac012156302e4e16b852b72ee399aea4f12c29"+dependencies = [+ "bytecheck_derive",+ "ptr_meta",+ "rancor",+ "simdutf8",+]++[[package]]+name = "bytecheck_derive"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "46d07918caa9eeaaf06b7873925c53a61daac173539b4f7715090745e44e4e69"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]+[[package]]name = "bytemuck"version = "1.25.2"@@ -892,6 +1049,18 @@ dependencies = ["shlex 2.0.1",]+[[package]]+name = "ccm"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ae3c82e4355234767756212c570e29833699ab63e6ffd161887314cc5b43847"+dependencies = [+ "aead",+ "cipher",+ "ctr",+ "subtle",+]+[[package]]name = "cexpr"version = "0.6.0"@@ -1368,6 +1537,30 @@ dependencies = ["libc",]+[[package]]+name = "crc"+version = "3.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d"+dependencies = [+ "crc-catalog",+]++[[package]]+name = "crc-catalog"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"++[[package]]+name = "crc32c"+version = "0.6.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47"+dependencies = [+ "rustc_version",+]+[[package]]name = "crc32fast"version = "1.5.2"@@ -1453,12 +1646,27 @@ version = "0.0.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e2931af7e13dc045d8e9d26afccc6fa115d64e115c9c84b1166288b46f6782c2"+[[package]]+name = "ctr"+version = "0.9.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"+dependencies = [+ "cipher",+]+[[package]]name = "cursor-icon"version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"+[[package]]+name = "data-encoding"+version = "2.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"+[[package]]name = "data-url"version = "0.3.2"@@ -1471,6 +1679,34 @@ version = "0.1.12"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2"+[[package]]+name = "der-parser"+version = "9.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5cd0a5c643689626bec213c4d8bd4d96acc8ffdb4ad4bb6bc16abf27d5f4b553"+dependencies = [+ "asn1-rs 0.6.2",+ "displaydoc",+ "nom 7.1.3",+ "num-bigint",+ "num-traits",+ "rusticata-macros",+]++[[package]]+name = "der-parser"+version = "10.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6"+dependencies = [+ "asn1-rs 0.7.2",+ "displaydoc",+ "nom 7.1.3",+ "num-bigint",+ "num-traits",+ "rusticata-macros",+]+[[package]]name = "deranged"version = "0.5.8"@@ -2737,6 +2973,12 @@ version = "1.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"+[[package]]+name = "httpdate"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"+[[package]]name = "hybrid-array"version = "0.4.15"@@ -2760,6 +3002,7 @@ dependencies = ["http","http-body","httparse",+ "httpdate","itoa","pin-project-lite","smallvec",@@ -3416,6 +3659,12 @@ dependencies = ["regex-automata",]+[[package]]+name = "matchit"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"+[[package]]name = "maybe-rayon"version = "0.1.1"@@ -3575,9 +3824,29 @@ version = "1.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"+[[package]]+name = "munge"+version = "0.4.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e17401f259eba956ca16491461b6e8f72913a0a114e39736ce404410f915a0c"+dependencies = [+ "munge_macro",+]++[[package]]+name = "munge_macro"+version = "0.4.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4568f25ccbd45ab5d5603dc34318c1ec56b117531781260002151b8530a9f931"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "muxen-agent"-version = "0.2.8"+version = "0.2.9"dependencies = ["alacritty_terminal","anyhow",@@ -3587,7 +3856,7 @@ dependencies = ["libc","portable-pty","quinn",- "rcgen",+ "rcgen 0.13.2","ring","rustls","serde_json",@@ -3603,7 +3872,9 @@ version = "0.5.9"dependencies = ["alacritty_terminal","anyhow",+ "async-trait","base64 0.22.1",+ "bytes","chrono","clap","cocoa 0.26.0",@@ -3616,9 +3887,10 @@ dependencies = ["objc","quinn","raw-window-handle",- "rcgen",+ "rcgen 0.13.2","reqwest","ring",+ "rtc","rustls","security-framework","serde",@@ -3631,10 +3903,24 @@ dependencies = ["tracing","tracing-subscriber","unicode-segmentation",+ "webrtc","windows-sys 0.61.2","winresource",]+[[package]]+name = "muxin-share-server"+version = "0.1.0"+dependencies = [+ "axum",+ "base64 0.22.1",+ "ring",+ "serde_json",+ "tokio",+ "tracing",+ "tracing-subscriber",+]+[[package]]name = "naga"version = "25.0.1"@@ -3709,6 +3995,7 @@ dependencies = ["cfg-if","cfg_aliases 0.2.2","libc",+ "memoffset",][[package]]@@ -4017,6 +4304,24 @@ dependencies = ["memchr",]+[[package]]+name = "oid-registry"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8d8034d9489cdaf79228eb9f6a3b8d7bb32ba00d6645ebd48eef4077ceb5bd9"+dependencies = [+ "asn1-rs 0.6.2",+]++[[package]]+name = "oid-registry"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7"+dependencies = [+ "asn1-rs 0.7.2",+]+[[package]]name = "once_cell"version = "1.21.4"@@ -4166,6 +4471,26 @@ dependencies = ["hmac",]+[[package]]+name = "pem"+version = "3.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be"+dependencies = [+ "base64 0.22.1",+ "serde_core",+]++[[package]]+name = "pem"+version = "4.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120"+dependencies = [+ "base64 0.23.1",+ "serde_core",+]+[[package]]name = "percent-encoding"version = "2.3.2"@@ -4414,6 +4739,26 @@ dependencies = ["cc",]+[[package]]+name = "ptr_meta"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "743da816b98c921cdbe8628ef7381b76f25ecf4da599fc80aca90eae7ef70cc0"+dependencies = [+ "ptr_meta_derive",+]++[[package]]+name = "ptr_meta_derive"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c8d9ca532f185d5d4db7a7c9d51420b452168ea1c2b913953281bd6fe1fcbd0"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]+[[package]]name = "pulp"version = "0.22.3"@@ -4477,7 +4822,7 @@ dependencies = ["cfg_aliases 0.2.2","pin-project-lite","quinn-proto",- "quinn-udp",+ "quinn-udp 0.5.16","rustc-hash 2.1.3","rustls","socket2",@@ -4525,10 +4870,23 @@ dependencies = [][[package]]-name = "quote"-version = "1.0.47"+name = "quinn-udp"+version = "0.6.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+checksum = "47091c86514c2e11452cb228dee77037334b99d92a23e4c69aa5982261f39247"+dependencies = [+ "cfg_aliases 0.2.2",+ "libc",+ "log",+ "socket2",+ "windows-sys 0.61.2",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"dependencies = ["proc-macro2",]@@ -4545,6 +4903,15 @@ version = "6.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"+[[package]]+name = "rancor"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b534442d0fcdb55d66f373d9cac6d33b6293a2335bc2136dbd06ce0e87d2572"+dependencies = [+ "ptr_meta",+]+[[package]]name = "rand"version = "0.8.8"@@ -4742,7 +5109,21 @@ dependencies = ["ring","rustls-pki-types","time",- "yasna",+ "yasna 0.5.2",+]++[[package]]+name = "rcgen"+version = "0.14.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8"+dependencies = [+ "pem 4.0.0",+ "ring",+ "rustls-pki-types",+ "time",+ "x509-parser 0.18.1",+ "yasna 0.6.0",][[package]]@@ -4850,6 +5231,15 @@ version = "0.8.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"+[[package]]+name = "rend"+version = "0.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "663ba70707f96e871406fe10d68128412e619b06d1d47cb91c3a4c6501176240"+dependencies = [+ "bytecheck",+]+[[package]]name = "reqwest"version = "0.13.5"@@ -4927,12 +5317,302 @@ dependencies = ["windows-sys 0.52.0",]+[[package]]+name = "rkyv"+version = "0.8.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9776093b7ca170454ab1406954f7b7d97a57c51dc6c0642957fb2ef25c2d399"+dependencies = [+ "bytecheck",+ "bytes",+ "hashbrown 0.17.1",+ "indexmap",+ "munge",+ "ptr_meta",+ "rancor",+ "rend",+ "rkyv_derive",+ "tinyvec",+ "uuid",+]++[[package]]+name = "rkyv_derive"+version = "0.8.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c25ef604ac7dd839d44d64648952ea23c97866f124ff671b0ed2cf3ad9bb06e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]+[[package]]name = "roxmltree"version = "0.20.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"+[[package]]+name = "rtc"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e2ca201de5ccc83aa3c08d49a2f08d7ed0aeeb2052fb1ccc517a8b77a6927ce"+dependencies = [+ "bytes",+ "hex",+ "log",+ "pem 3.0.6",+ "rand 0.10.3",+ "rcgen 0.14.10",+ "rtc-crypto",+ "rtc-datachannel",+ "rtc-dtls",+ "rtc-ice",+ "rtc-interceptor",+ "rtc-mdns",+ "rtc-media",+ "rtc-rtcp",+ "rtc-rtp",+ "rtc-sctp",+ "rtc-sdp",+ "rtc-shared",+ "rtc-srtp",+ "rtc-stun",+ "rtc-turn",+ "rustls",+ "sansio",+ "serde",+ "serde_json",+ "unicase",+ "url",+ "x509-parser 0.16.0",+]++[[package]]+name = "rtc-crypto"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "404ea28682271626739dfb1f3a04e96c596490b948d7629d9e4651dd4ba6aaf3"+dependencies = [+ "aes",+ "ccm",+ "ctr",+ "hmac",+ "md-5",+ "rand 0.10.3",+ "ring",+ "sha1",+ "subtle",+ "thiserror 2.0.21",+ "zeroize",+]++[[package]]+name = "rtc-datachannel"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8d93dd81014535ff0134c0f19dbccfbae4d5ceb6010cf917c1a6056ea2c0d9bb"+dependencies = [+ "bytes",+ "log",+ "rtc-sctp",+ "rtc-shared",+ "sansio",+]++[[package]]+name = "rtc-dtls"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0a2fe5767d6caf61018d52189b3b8e37075799eeb81cd5ab452307c7e7ebd97e"+dependencies = [+ "bytecheck",+ "byteorder",+ "bytes",+ "der-parser 9.0.0",+ "log",+ "pem 3.0.6",+ "rcgen 0.14.10",+ "rkyv",+ "rtc-crypto",+ "rtc-shared",+ "rustls",+ "x509-parser 0.16.0",+]++[[package]]+name = "rtc-ice"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "099984f1be120b2e5692f232f8cbb82e53f6b4261c5c2eeda5be6223ba1adaa9"+dependencies = [+ "bytes",+ "crc",+ "log",+ "rtc-crypto",+ "rtc-mdns",+ "rtc-shared",+ "rtc-stun",+ "sansio",+ "serde",+ "url",+ "uuid",+]++[[package]]+name = "rtc-interceptor"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "43e7df85d7aacf6e3f69bb922a6c9f83b2a29461038d06285df7642206df64cf"+dependencies = [+ "log",+ "rand 0.10.3",+ "rtc-rtcp",+ "rtc-rtp",+ "rtc-shared",+ "sansio",+]++[[package]]+name = "rtc-mdns"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d86ac3cafd411bef81d70aff9d59d9520331b29970f7e361180da99e7a8b5a0d"+dependencies = [+ "bytes",+ "log",+ "rtc-shared",+ "sansio",+ "socket2",+]++[[package]]+name = "rtc-media"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a76840ad2aff52efeb16a613db26c16981841a6cf50907bff950884f00f9d9a9"+dependencies = [+ "byteorder",+ "bytes",+ "rand 0.10.3",+ "rtc-rtp",+ "rtc-shared",+ "thiserror 2.0.21",+]++[[package]]+name = "rtc-rtcp"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "485aa259bdb68e550363c40c8dc30c1c453ddd80f0cf7224dd2d72dffd5e01c2"+dependencies = [+ "bytes",+ "rtc-shared",+]++[[package]]+name = "rtc-rtp"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a640f266927139a899a3a93b5cf4aa3626594ee2e5d26202b60930bb42cb445"+dependencies = [+ "bytes",+ "memchr",+ "rand 0.10.3",+ "rtc-shared",+ "serde",+]++[[package]]+name = "rtc-sctp"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2eb430b379d90e7984306036d1646454a26b300c9c3256009eb8f7e0615e90b9"+dependencies = [+ "bytes",+ "crc32c",+ "log",+ "rand 0.10.3",+ "rtc-shared",+ "rustc-hash 2.1.3",+ "slab",+ "thiserror 2.0.21",+]++[[package]]+name = "rtc-sdp"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd69b1ea06978e045f374ec19eb34177ee4e4f8349cc7d9c0b183683fa7b2d1f"+dependencies = [+ "rand 0.10.3",+ "rtc-shared",+ "url",+]++[[package]]+name = "rtc-shared"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1250e81796ac6d3d67bd04ecdb891b8371ff97c8a2ce0a5a1c1321f2e12b657b"+dependencies = [+ "bitflags 1.3.2",+ "bytes",+ "nix 0.31.3",+ "rand 0.10.3",+ "serde",+ "substring",+ "thiserror 2.0.21",+ "url",+ "winapi",+]++[[package]]+name = "rtc-srtp"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cbb71f476c84763db0435bc47a598acb31abc5fdc6ca3fc84dcb274ed9b70155"+dependencies = [+ "byteorder",+ "bytes",+ "rtc-crypto",+ "rtc-rtcp",+ "rtc-rtp",+ "rtc-shared",+]++[[package]]+name = "rtc-stun"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e59e5c70b7900f537ded24cfee5fa476e8fdc186b90ced528611e441f4063b4"+dependencies = [+ "base64 0.22.1",+ "bytes",+ "crc",+ "lazy_static",+ "rand 0.10.3",+ "rtc-crypto",+ "rtc-shared",+ "sansio",+ "url",+]++[[package]]+name = "rtc-turn"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c53078a0696df5a3a5e4947bc550c5e903b59803b252f1d39062d637ebd3d17e"+dependencies = [+ "bytes",+ "log",+ "rtc-crypto",+ "rtc-shared",+ "rtc-stun",+ "sansio",+]+[[package]]name = "rust-embed"version = "8.13.0"@@ -4990,6 +5670,15 @@ dependencies = ["semver",]+[[package]]+name = "rusticata-macros"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"+dependencies = [+ "nom 7.1.3",+]+[[package]]name = "rustix"version = "0.38.44"@@ -5168,6 +5857,12 @@ dependencies = ["winapi-util",]+[[package]]+name = "sansio"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c62751faa8bc286982334a082fe125184a29fc89d17775766e4f891b7d726980"+[[package]]name = "schannel"version = "0.1.29"@@ -5356,6 +6051,17 @@ dependencies = ["serde",]+[[package]]+name = "serde_path_to_error"+version = "0.1.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"+dependencies = [+ "itoa",+ "serde",+ "serde_core",+]+[[package]]name = "serde_repr"version = "0.1.21"@@ -5408,6 +6114,17 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "sha1"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"+dependencies = [+ "cfg-if",+ "cpufeatures 0.2.17",+ "digest 0.10.7",+]+[[package]]name = "sha1_smol"version = "1.0.1"@@ -5736,6 +6453,15 @@ dependencies = ["syn 2.0.119",]+[[package]]+name = "substring"+version = "1.4.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42ee6433ecef213b2e72f587ef64a2f5943e7cd16fbd82dbe8bc07486c534c86"+dependencies = [+ "autocfg",+]+[[package]]name = "subtle"version = "2.6.1"@@ -5890,6 +6616,17 @@ dependencies = ["futures-core",]+[[package]]+name = "synstructure"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "synstructure"version = "0.14.0"@@ -5993,7 +6730,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"dependencies = ["fastrand 2.5.0",- "getrandom 0.3.4",+ "getrandom 0.4.3","once_cell","rustix 1.1.5","windows-sys 0.61.2",@@ -6093,6 +6830,7 @@ dependencies = ["powerfmt","serde_core","time-core",+ "time-macros",][[package]]@@ -6101,6 +6839,16 @@ version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"+[[package]]+name = "time-macros"+version = "0.2.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"+dependencies = [+ "num-conv",+ "time-core",+]+[[package]]name = "tiny-keccak"version = "2.0.2"@@ -6948,6 +7696,24 @@ dependencies = ["rustls-pki-types",]+[[package]]+name = "webrtc"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b621e736302bef784948cc8d8099fd0a8fdb5757693c80a344ffbe38c49387d2"+dependencies = [+ "async-broadcast",+ "async-channel 2.5.0",+ "async-trait",+ "bytes",+ "event-listener 5.4.2",+ "futures",+ "log",+ "quinn-udp 0.6.3",+ "rtc",+ "tokio",+]+[[package]]name = "weezl"version = "0.1.12"@@ -7589,6 +8355,41 @@ version = "0.13.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"+[[package]]+name = "x509-parser"+version = "0.16.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fcbc162f30700d6f3f82a24bf7cc62ffe7caea42c0b2cba8bf7f3ae50cf51f69"+dependencies = [+ "asn1-rs 0.6.2",+ "data-encoding",+ "der-parser 9.0.0",+ "lazy_static",+ "nom 7.1.3",+ "oid-registry 0.7.1",+ "rusticata-macros",+ "thiserror 1.0.69",+ "time",+]++[[package]]+name = "x509-parser"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202"+dependencies = [+ "asn1-rs 0.7.2",+ "data-encoding",+ "der-parser 10.0.0",+ "lazy_static",+ "nom 7.1.3",+ "oid-registry 0.8.1",+ "ring",+ "rusticata-macros",+ "thiserror 2.0.21",+ "time",+]+[[package]]name = "xattr"version = "0.2.3"@@ -7673,6 +8474,16 @@ dependencies = ["time",]+[[package]]+name = "yasna"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282"+dependencies = [+ "bit-vec 0.9.1",+ "time",+]+[[package]]name = "yazi"version = "0.2.1"@@ -7710,7 +8521,7 @@ dependencies = ["proc-macro2","quote","syn 3.0.6",- "synstructure",+ "synstructure 0.14.0",][[package]]@@ -7952,7 +8763,7 @@ dependencies = ["proc-macro2","quote","syn 3.0.6",- "synstructure",+ "synstructure 0.14.0",][[package]]diff --git a/Cargo.toml b/Cargo.tomlindex e836569..6345fad 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -40,6 +40,12 @@ ring = "0.17"# Bigger UDP buffers for those connections (macOS's defaults choke a copy).socket2 = "0.6"mdns-sd = "0.21"+# Sharing a session by link (src/share): WebRTC data channels, peer to peer+# with the guest's browser or Muxin, introduced through muxin.dev.+webrtc = { version = "0.21", default-features = false, features = ["runtime-tokio", "crypto-ring"] }+rtc = { version = "0.21", default-features = false, features = ["crypto-ring"] }+async-trait = "0.1"+bytes = "1"[target.'cfg(target_os = "macos")'.dependencies]# Already part of GPUI's dependency tree; used to set the Dock icon when running@@ -67,7 +73,7 @@ windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_raw-window-handle = { version = "0.6", optional = true }[workspace]-members = [".", "agent"]+members = [".", "agent", "share-server"][features]default = ["gui"]diff --git a/README.md b/README.mdindex 1073be9..a59753d 100644--- a/README.md+++ b/README.md@@ -403,6 +403,20 @@ muxin session stop beelink/claude-3f9aBuild the agent for every platform with `scripts/build-agents.sh` (needs `cargo-zigbuild` and Zig for the Linux builds); `scripts/bundle-macos.sh` runs it and ships the builds inside the app.+## Sharing a session++Show someone a session, or let them type in it, straight from your computer. They join from Muxin or from any browser; nothing to install.++- **Share.** On a session's page, click **Share**: the link is made and copied, ready to paste anywhere (`https://muxin.dev/s#1.…`). By default you let each person in, they can only watch, and it lasts an hour; change any of that in the same window, while it runs: let them type, let anyone with the link watch without asking, or make it last longer.+- **Let people in.** When someone opens it, a card over the terminal shows their name and a 6-digit code; they see the same code. Ask them to read it out, then **Let in**. A link that leaked shows a code nobody reads to you.+- **While you share.** The header says who's there (**Shared · Sam watching**). Click it to let someone type or stop them, remove them, copy the link, add an hour, or stop sharing. A shared session has an eye in the sidebar; a dot means someone is waiting.+- **Joining.** The link opens a page that asks for their name, then joins right there in the browser (or in Muxin, if they have it). In Muxin, ⇧⌘P › **Join a shared session…** takes a link too. Shared sessions are listed under **Shared with you**, shown at the size the sharer's terminal is.+- **Peer to peer.** The two computers connect directly (WebRTC): over your network or Tailscale when they share one, across the internet otherwise, and through an encrypted relay only when nothing direct works. muxin.dev only introduces them, with two short messages: the part of the link after `#` (the share's secret) never reaches it, and the guest checks that it reached the sharing computer's own certificate, so the site can't listen in or join.+- **What a guest can do.** Watch the one session shared, and type in it only while you let them. Muxin enforces it on your computer, and the agent on the machine attaches a watcher that can't type or resize. Guests never reach the machine, its other sessions, files or a shell.+- **It ends** when its time runs out, when you **Stop sharing**, or when you quit Muxin. The link stops working then, for good.++To introduce them through a server of your own instead (`share-server/` in this repository), set `[settings.share] server = "https://share.example.com"` in `config.toml`.+## Connections and desktopsMuxin first reaches a machine with `ssh`, installs its small agent there, and from then on talks to that agent over **one live connection** instead of a new ssh connection per request: requests take milliseconds instead of ~0.4 s, terminals open instantly, and the sidebar updates the moment a session changes.@@ -601,6 +615,7 @@ cargo run -- status --demo --jsonSource layout:- `agent/`: the agent that runs on each machine (sessions, the live link, direct connections, desktops, files, clipboard).+- `src/share`: sharing sessions by link (the host's gateway, joining, WebRTC); `share-server/`: the server that introduces the two sides and serves the browser's join page.- `src/fleet`: the engine and snapshot model; `link.rs` and `direct.rs` (connections), `tailscale.rs` and `engine/roaming.rs` (moving between networks), `files.rs`, `clipboard.rs`, `discover.rs` (machines on this network).- `src/probe`: machine checks.- `src/github`: the GitHub API client.diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 7a9e4ab..9408561 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -18,6 +18,8 @@ must ship with every copy of Muxin.| Agent logos (`assets/icons/agent-*.svg`), SVGs from LobeHub Icons | MIT | <https://github.com/lobehub/lobe-icons> || Pi logo (`assets/icons/agent-pi.svg`), from Pi's press kit (Earendil) | trademark of its owner | <https://pi.dev/press-kit> || DigitalOcean logo (`assets/icons/brand-digitalocean.svg`), SVG from Simple Icons | CC0-1.0 (the SVG); trademark of DigitalOcean | <https://simpleicons.org> |+| xterm.js 5.5.0 (the share server's join page, `share-server/web/vendor/`) | MIT | `share-server/web/vendor/XTERM-LICENSE` |+| webrtc-rs (`webrtc`, `rtc`: sharing sessions peer to peer) | MIT or Apache-2.0 | <https://github.com/webrtc-rs/webrtc> || Rust crates listed in `Cargo.lock` | MIT and/or Apache-2.0 (mostly), see each crate | Generate the full list before each release, e.g. with `cargo about generate` |The agent logos are trademarks of their owners (Anthropic, OpenAI, Google,diff --git a/agent/Cargo.toml b/agent/Cargo.tomlindex aab6a70..6073265 100644--- a/agent/Cargo.toml+++ b/agent/Cargo.toml@@ -1,6 +1,6 @@[package]name = "muxen-agent"-version = "0.2.8"+version = "0.2.9"edition = "2024"description = "Runs on each machine Muxen manages: keeps agent sessions alive and lets the app attach to them"license = "Apache-2.0"diff --git a/agent/src/daemon.rs b/agent/src/daemon.rsindex 9baad63..65bc7fd 100644--- a/agent/src/daemon.rs+++ b/agent/src/daemon.rs@@ -83,7 +83,7 @@ struct Inner {writer: Option<Box<dyn Write + Send>>,master: Option<Box<dyn MasterPty + Send>>,child: Option<Box<dyn Child + Send + Sync>>,- clients: Vec<(u64, Stream)>,+ clients: Vec<Client>,cols: u16,rows: u16,exit: Option<i32>,@@ -92,6 +92,16 @@ struct Inner {generation: u64,}+/// An attached terminal.+struct Client {+ id: u64,+ stream: Stream,+ /// Only watches: what it sends is ignored (a shared session's guest).+ watch_only: bool,+ /// Wants SIZE frames, to draw at the session's size rather than set it.+ sizes: bool,+}+impl Inner {fn resize(&mut self, cols: u16, rows: u16) {let (cols, rows) = (cols.clamp(10, 1000), rows.clamp(4, 500));@@ -104,10 +114,17 @@ impl Inner {if let Some(m) = &self.master {let _ = m.resize(PtySize { rows, cols, pixel_width: 0, pixel_height: 0 });}+ let size = self.size_frame();+ self.clients.retain_mut(|c| !c.sizes || proto::write_frame(&mut c.stream, proto::SIZE, &size).is_ok());+ }++ fn size_frame(&self) -> [u8; 4] {+ let (c, r) = (self.cols.to_be_bytes(), self.rows.to_be_bytes());+ [c[0], c[1], r[0], r[1]]}fn broadcast(&mut self, kind: u8, payload: &[u8]) {- self.clients.retain_mut(|(_, c)| proto::write_frame(c, kind, payload).is_ok());+ self.clients.retain_mut(|c| proto::write_frame(&mut c.stream, kind, payload).is_ok());}}@@ -374,10 +391,11 @@ fn pump(state: &State, s: &Session, mut reader: Box<dyn Read + Send>, generationlet bells = i.listener.bells.load(Ordering::Relaxed);i.parser.advance(&mut i.term, bytes);i.last_output = now();- // Attached terminals answer queries themselves; without one, answer- // here so programs waiting on a reply don't hang.+ // Attached terminals answer queries themselves; without one that+ // can (watchers' answers are ignored), answer here so programs+ // waiting on a reply don't hang.let replies = std::mem::take(&mut *i.listener.replies.lock().unwrap());- if i.clients.is_empty() {+ if i.clients.iter().all(|c| c.watch_only) {if let Some(w) = i.writer.as_mut() {for r in replies {let _ = w.write_all(r.as_bytes());@@ -510,7 +528,9 @@ fn read(state: &State, req: &Value) -> Result<Value, String> {}/// Connects a client terminal: resize to it, send the current screen, then-/// stream both ways until it goes away.+/// stream both ways until it goes away. `"watch_only": true` attaches one+/// whose keys and size are ignored (it keeps the session's size), and+/// `"sizes": true` sends it the size as it changes (SIZE frames).fn attach(state: &State, mut stream: Stream, req: &Value) {let name = str_of(req, "name");let Some(s) = state.find(name) else {@@ -518,13 +538,20 @@ fn attach(state: &State, mut stream: Stream, req: &Value) {return;};let id = state.next_client.fetch_add(1, Ordering::Relaxed);+ let watch_only = req["watch_only"].as_bool() == Some(true);+ let sizes = req["sizes"].as_bool() == Some(true);{let mut i = s.inner.lock().unwrap();// The newest terminal sets the size, like tmux's window-size latest.- let cols = req["cols"].as_u64().unwrap_or(i.cols as u64) as u16;- let rows = req["rows"].as_u64().unwrap_or(i.rows as u64) as u16;- i.resize(cols, rows);- if proto::write_line(&mut stream, &json!({ "ok": true })).is_err() {+ if !watch_only {+ let cols = req["cols"].as_u64().unwrap_or(i.cols as u64) as u16;+ let rows = req["rows"].as_u64().unwrap_or(i.rows as u64) as u16;+ i.resize(cols, rows);+ }+ if proto::write_line(&mut stream, &json!({ "ok": true, "cols": i.cols, "rows": i.rows })).is_err() {+ return;+ }+ if sizes && proto::write_frame(&mut stream, proto::SIZE, &i.size_frame()).is_err() {return;}let redraw = screen::redraw(&i.term);@@ -533,10 +560,11 @@ fn attach(state: &State, mut stream: Stream, req: &Value) {}let Ok(out) = stream.try_clone() else { return };let _ = out.set_write_timeout(Some(CLIENT_WRITE_TIMEOUT));- i.clients.push((id, out));+ i.clients.push(Client { id, stream: out, watch_only, sizes });}loop {match proto::read_frame(&mut stream) {+ Ok(_) if watch_only => {}Ok((proto::DATA, bytes)) => {let mut i = s.inner.lock().unwrap();if let Some(w) = i.writer.as_mut() {@@ -552,7 +580,7 @@ fn attach(state: &State, mut stream: Stream, req: &Value) {Err(_) => break,}}- s.inner.lock().unwrap().clients.retain(|(c, _)| *c != id);+ s.inner.lock().unwrap().clients.retain(|c| c.id != id);}#[cfg(test)]diff --git a/agent/src/link.rs b/agent/src/link.rsindex 37c37a1..d0b23b1 100644--- a/agent/src/link.rs+++ b/agent/src/link.rs@@ -344,7 +344,8 @@ fn run_script(req: &Value) -> Value {json!({ "ok": true, "status": status, "stdout": text(stdout), "stderr": text(stderr), "timed_out": timed_out })}-/// Connects a channel to a session, as `muxen-agent attach` does for a terminal.+/// Connects a channel to a session, as `muxen-agent attach` does for a+/// terminal (`watch_only` and `sizes` as the session server takes them).fn attach(req: &Value, out: &Out, attached: &Attached) -> Value {let channel = req["channel"].as_u64().unwrap_or(0) as u32;if channel == CONTROL {@@ -354,15 +355,15 @@ fn attach(req: &Value, out: &Out, attached: &Attached) -> Value {Ok(s) => s,Err(_) => return json!({ "ok": false, "error": "no sessions are running on this machine" }),};- let request = json!({ "op": "attach", "name": req["name"], "cols": req["cols"], "rows": req["rows"] });+ let request = json!({ "op": "attach", "name": req["name"], "cols": req["cols"], "rows": req["rows"], "watch_only": req["watch_only"], "sizes": req["sizes"] });if let Err(e) = proto::write_line(&mut stream, &request) {return json!({ "ok": false, "error": e.to_string() });}- match proto::read_line(&mut stream) {- Ok(v) if v["ok"].as_bool() == Some(true) => {}+ let size = match proto::read_line(&mut stream) {+ Ok(v) if v["ok"].as_bool() == Some(true) => json!({ "cols": v["cols"], "rows": v["rows"] }),Ok(v) => return json!({ "ok": false, "error": v["error"].as_str().unwrap_or("can't attach") }),Err(e) => return json!({ "ok": false, "error": e.to_string() }),- }+ };let Ok(mut reader) = stream.try_clone() else { return json!({ "ok": false, "error": "can't attach" }) };attached.lock().unwrap().insert(channel, Sink::Session(stream));// The session's output, and its end, to the app.@@ -385,7 +386,7 @@ fn attach(req: &Value, out: &Out, attached: &Attached) -> Value {let _ = send(&out, channel, CLOSE, &[]);}});- json!({ "ok": true })+ json!({ "ok": true, "cols": size["cols"], "rows": size["rows"] })}/// Starts streaming the desktop on a channel: `{"op": "desktop", "channel",diff --git a/agent/src/proto.rs b/agent/src/proto.rsindex 14d6080..ee639c3 100644--- a/agent/src/proto.rs+++ b/agent/src/proto.rs@@ -12,6 +12,9 @@ pub const DATA: u8 = 0;pub const RESIZE: u8 = 1;/// Server to client: the session was ended; `[code: i32 BE]`.pub const EXIT: u8 = 2;+/// Server to client, for clients that ask (`"sizes": true`): the session's+/// size, `[cols: u16 BE][rows: u16 BE]`, on attach and whenever it changes.+pub const SIZE: u8 = 3;const MAX_FRAME: usize = 16 << 20;diff --git a/assets/icons/eye.svg b/assets/icons/eye.svgnew file mode 100644index 0000000..322eb10--- /dev/null+++ b/assets/icons/eye.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-eye"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0" />+ <circle cx="12" cy="12" r="3" />+</svg>diff --git a/assets/icons/link.svg b/assets/icons/link.svgnew file mode 100644index 0000000..b53991c--- /dev/null+++ b/assets/icons/link.svg@@ -0,0 +1,16 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-link"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />+ <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />+</svg>diff --git a/assets/icons/user-check.svg b/assets/icons/user-check.svgnew file mode 100644index 0000000..7bdd110--- /dev/null+++ b/assets/icons/user-check.svg@@ -0,0 +1,17 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-user-check"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="m16 11 2 2 4-4" />+ <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />+ <circle cx="9" cy="7" r="4" />+</svg>diff --git a/assets/icons/user-x.svg b/assets/icons/user-x.svgnew file mode 100644index 0000000..7a0fd52--- /dev/null+++ b/assets/icons/user-x.svg@@ -0,0 +1,18 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-user-x"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />+ <circle cx="9" cy="7" r="4" />+ <line x1="17" x2="22" y1="8" y2="13" />+ <line x1="22" x2="17" y1="8" y2="13" />+</svg>diff --git a/assets/icons/users.svg b/assets/icons/users.svgnew file mode 100644index 0000000..a140b2f--- /dev/null+++ b/assets/icons/users.svg@@ -0,0 +1,18 @@+<!-- @license lucide-static v1.53.0 - ISC -->+<svg+ class="lucide lucide-users"+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.6"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />+ <path d="M16 3.128a4 4 0 0 1 0 7.744" />+ <path d="M22 21v-2a4 4 0 0 0-3-3.87" />+ <circle cx="9" cy="7" r="4" />+</svg>diff --git a/assets/linux/muxin.desktop b/assets/linux/muxin.desktopindex 1e0e17c..30483c9 100644--- a/assets/linux/muxin.desktop+++ b/assets/linux/muxin.desktop@@ -3,9 +3,10 @@ Type=ApplicationName=MuxinGenericName=MachinesComment=All your machines, one app-Exec=muxin+Exec=muxin %uIcon=muxinTerminal=falseStartupWMClass=muxinCategories=Development;Network;RemoteAccess;Keywords=ssh;servers;agents;runners;+MimeType=x-scheme-handler/muxin;diff --git a/scripts/bundle-macos.sh b/scripts/bundle-macos.shindex e987984..3f58eca 100755--- a/scripts/bundle-macos.sh+++ b/scripts/bundle-macos.sh@@ -68,6 +68,11 @@ cat > "$app/Contents/Info.plist" <<PLIST<key>LSMinimumSystemVersion</key><string>12.0</string><key>LSApplicationCategoryType</key><string>public.app-category.developer-tools</string><key>NSHighResolutionCapable</key><true/>+ <key>CFBundleURLTypes</key>+ <array><dict>+ <key>CFBundleURLName</key><string>Muxin share link</string>+ <key>CFBundleURLSchemes</key><array><string>muxin</string></array>+ </dict></array><key>NSHumanReadableCopyright</key><string>© Lumary Labs LLC</string><key>NSLocalNetworkUsageDescription</key><string>Muxin connects straight to your machines on your local network: faster than going through ssh or a VPN, and needed to show their desktops smoothly.</string></dict>diff --git a/scripts/muxin.iss b/scripts/muxin.issindex fc0451b..719ffc9 100644--- a/scripts/muxin.iss+++ b/scripts/muxin.iss@@ -59,6 +59,13 @@ Type: files; Name: "{app}\muxen.exe"Type: files; Name: "{autoprograms}\Muxen.lnk"Type: files; Name: "{autodesktop}\Muxen.lnk"+; Share links (muxin://join...) open in Muxin.+[Registry]+Root: HKCU; Subkey: "Software\Classes\muxin"; ValueType: string; ValueName: ""; ValueData: "URL:Muxin share link"; Flags: uninsdeletekey+Root: HKCU; Subkey: "Software\Classes\muxin"; ValueType: string; ValueName: "URL Protocol"; ValueData: ""+Root: HKCU; Subkey: "Software\Classes\muxin\DefaultIcon"; ValueType: string; ValueName: ""; ValueData: "{app}\muxin.exe,0"+Root: HKCU; Subkey: "Software\Classes\muxin\shell\open\command"; ValueType: string; ValueName: ""; ValueData: """{app}\muxin.exe"" ""%1"""+[Icons]Name: "{autoprograms}\Muxin"; Filename: "{app}\muxin.exe"Name: "{autodesktop}\Muxin"; Filename: "{app}\muxin.exe"; Tasks: desktopicondiff --git a/share-server/Cargo.toml b/share-server/Cargo.tomlnew file mode 100644index 0000000..6734065--- /dev/null+++ b/share-server/Cargo.toml@@ -0,0 +1,16 @@+[package]+name = "muxin-share-server"+version = "0.1.0"+edition = "2024"+description = "Introduces the two sides of a Muxin share (signaling) and serves the page that joins one from a browser"+license = "Apache-2.0"+publish = false++[dependencies]+axum = { version = "0.8", default-features = false, features = ["http1", "tokio", "json"] }+base64 = "0.22"+ring = "0.17"+serde_json = "1"+tokio = { version = "1", features = ["rt-multi-thread", "net", "macros", "time", "sync", "signal"] }+tracing = "0.1"+tracing-subscriber = { version = "0.3", features = ["env-filter"] }diff --git a/share-server/README.md b/share-server/README.mdnew file mode 100644index 0000000..493d506--- /dev/null+++ b/share-server/README.md@@ -0,0 +1,59 @@+# Muxin share server++Introduces the two sides of a shared session (WebRTC signaling) and serves+the page that joins one from a browser. muxin.dev does the same for+everyone; this is for running your own, and for tests. It never sees+what's shared: the share's secret is after the `#` in the link, which+browsers don't send, and both sides check each other's certificates end to+end. The interface (a few JSON calls) is described in `src/share/signal.rs`.++```sh+cargo run -p muxin-share-server # http://127.0.0.1:8787+MUXIN_SHARE_SERVER=http://127.0.0.1:8787 cargo run # Muxin, sharing through it+```++## Running it for real++Browsers need https, so put it behind a proxy with TLS. With Caddy:++```+share.example.com {+ reverse_proxy 127.0.0.1:8787+}+```++Most connections are direct. For the rest (strict NATs, some corporate+networks), run a TURN relay such as coturn and tell the server about it:++```+# /etc/turnserver.conf+use-auth-secret+static-auth-secret=<a long random secret>+realm=share.example.com+listening-port=3478+fingerprint+no-cli+```++```sh+MUXIN_SHARE_LISTEN=127.0.0.1:8787 \+MUXIN_SHARE_STUN=stun:share.example.com:3478 \+MUXIN_SHARE_TURN=turn:share.example.com:3478 \+MUXIN_SHARE_TURN_SECRET=<the same secret> \+muxin-share-server+```++Each side gets TURN credentials of its own that last a day (coturn's REST+scheme). The relay only ever carries encrypted traffic.++## Endpoints++- `/s`: the join page (the link is `https://<server>/s#1.<ticket>`), with its files under `/share/`.+- `/share/v1/...`: the introductions (see `src/share/signal.rs`).+- `/healthz`: `ok`.++## muxin.dev++The website serves the same page from its own repository (`public/share/`+and `resources/views/share/join.blade.php`) and the same interface+(`app/Share`). Copy changes to `web/` there too.diff --git a/share-server/src/main.rs b/share-server/src/main.rsnew file mode 100644index 0000000..e9fda44--- /dev/null+++ b/share-server/src/main.rs@@ -0,0 +1,355 @@+//! The share server: introduces the two sides of a Muxin share, and serves+//! the page that joins one from a browser. muxin.dev runs the same thing+//! (its own code, the same interface); this one is for running your own,+//! and for tests.+//!+//! It never sees what's shared. A share's link carries its secret after the+//! `#`, which browsers don't send; the page reads it and talks to the+//! sharing computer itself, over WebRTC. Here, each share is a room named+//! by its id: the sharing app checks in every couple of seconds with its+//! key and picks up the guests' offers; a guest leaves an offer and waits+//! for the answer. Both sides check each other end to end, so a server that+//! lies can stop a share from working but can't join one or listen in. The+//! interface is described in src/share/signal.rs.+//!+//! Configuration, from the environment:+//!+//! - `MUXIN_SHARE_LISTEN`: where to listen (`127.0.0.1:8787`). Put TLS in+//! front (Caddy, nginx); browsers need https.+//! - `MUXIN_SHARE_STUN`: STUN servers, comma-separated (`stun:host:3478`).+//! - `MUXIN_SHARE_TURN`: TURN servers, comma-separated (`turn:host:3478`),+//! with `MUXIN_SHARE_TURN_SECRET` (coturn's `static-auth-secret`): each+//! side gets short-lived credentials for the relay.++use std::collections::HashMap;+use std::net::SocketAddr;+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};++use axum::Router;+use axum::extract::{Path, State};+use axum::http::{HeaderMap, HeaderValue, StatusCode, header};+use axum::response::{IntoResponse, Response};+use axum::routing::{get, post};+use base64::Engine as _;+use serde_json::{Value, json};++/// A room is open while its host checked in this recently.+const HOST_FRESH: Duration = Duration::from_secs(20);+/// Another key may take a room whose host has been gone this long.+const HOST_GONE: Duration = Duration::from_secs(60);+const ROOM_TTL: Duration = Duration::from_secs(15 * 60);+const OFFER_TTL: Duration = Duration::from_secs(120);+/// Offers waiting for one host.+const MAX_PENDING: usize = 32;+/// A description is a few KB.+const MAX_SDP: usize = 16 << 10;+/// How long TURN credentials last.+const TURN_TTL: Duration = Duration::from_secs(24 * 3600);++struct Room {+ /// SHA-256 of the host's key.+ host: String,+ seen: Instant,+ closed: bool,+ pending: Vec<String>,+}++struct Offer {+ room: String,+ sdp: String,+ answer: Option<String>,+ at: Instant,+}++#[derive(Default)]+struct Rooms {+ rooms: HashMap<String, Room>,+ offers: HashMap<String, Offer>,+}++struct App {+ state: Mutex<Rooms>,+ stun: Vec<String>,+ turn: Vec<String>,+ turn_secret: Option<String>,+}++type Shared = State<Arc<App>>;++#[tokio::main]+async fn main() {+ tracing_subscriber::fmt().with_env_filter(tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into())).init();+ let list = |k: &str| -> Vec<String> { std::env::var(k).unwrap_or_default().split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect() };+ let app = Arc::new(App {+ state: Mutex::new(Rooms::default()),+ stun: list("MUXIN_SHARE_STUN"),+ turn: list("MUXIN_SHARE_TURN"),+ turn_secret: std::env::var("MUXIN_SHARE_TURN_SECRET").ok().filter(|s| !s.is_empty()),+ });+ if !app.turn.is_empty() && app.turn_secret.is_none() {+ tracing::warn!("MUXIN_SHARE_TURN is set without MUXIN_SHARE_TURN_SECRET: the relay won't be offered");+ }+ // Rooms and offers nobody came back for.+ let sweeping = app.clone();+ tokio::spawn(async move {+ loop {+ tokio::time::sleep(Duration::from_secs(30)).await;+ let mut st = sweeping.state.lock().unwrap();+ st.rooms.retain(|_, r| r.seen.elapsed() < ROOM_TTL);+ st.offers.retain(|_, o| o.at.elapsed() < OFFER_TTL);+ }+ });+ let addr: SocketAddr = std::env::var("MUXIN_SHARE_LISTEN").unwrap_or_else(|_| "127.0.0.1:8787".into()).parse().expect("MUXIN_SHARE_LISTEN: an address like 127.0.0.1:8787");+ let router = Router::new()+ .route("/", get(home))+ .route("/s", get(page))+ .route("/share/join.js", get(|| asset("join.js")))+ .route("/share/join.css", get(|| asset("join.css")))+ .route("/share/vendor/xterm.js", get(|| asset("vendor/xterm.js")))+ .route("/share/vendor/xterm.css", get(|| asset("vendor/xterm.css")))+ .route("/healthz", get(|| async { "ok" }))+ .route("/share/v1/rooms/{room}", get(room).delete(close))+ .route("/share/v1/rooms/{room}/host", post(check_in))+ .route("/share/v1/rooms/{room}/offers", post(offer))+ .route("/share/v1/rooms/{room}/offers/{id}", get(answer_to))+ .route("/share/v1/rooms/{room}/offers/{id}/answer", post(answer))+ .with_state(app);+ let listener = tokio::net::TcpListener::bind(addr).await.expect("can't listen");+ tracing::info!("muxin share server on http://{addr}");+ axum::serve(listener, router)+ .with_graceful_shutdown(async {+ let _ = tokio::signal::ctrl_c().await;+ })+ .await+ .expect("server");+}++// ---------------------------------------------------------------------------+// The page++/// The page's files, built in.+fn file(name: &str) -> Option<(&'static [u8], &'static str)> {+ Some(match name {+ "index.html" => (include_bytes!("../web/index.html"), "text/html; charset=utf-8"),+ "join.js" => (include_bytes!("../web/join.js"), "text/javascript; charset=utf-8"),+ "join.css" => (include_bytes!("../web/join.css"), "text/css; charset=utf-8"),+ "vendor/xterm.js" => (include_bytes!("../web/vendor/xterm.js"), "text/javascript; charset=utf-8"),+ "vendor/xterm.css" => (include_bytes!("../web/vendor/xterm.css"), "text/css; charset=utf-8"),+ _ => return None,+ })+}++/// Headers the page gets: nothing from anywhere else, no framing, no+/// referrer. (xterm.js sets styles from script, hence 'unsafe-inline' for+/// styles only.)+fn secure(mut res: Response) -> Response {+ let h = res.headers_mut();+ let csp = "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";+ h.insert(header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(csp));+ h.insert(header::REFERRER_POLICY, HeaderValue::from_static("no-referrer"));+ h.insert(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));+ h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));+ h.insert("cross-origin-opener-policy", HeaderValue::from_static("same-origin"));+ h.insert("permissions-policy", HeaderValue::from_static("camera=(), microphone=(), geolocation=(), clipboard-read=()"));+ res+}++async fn home() -> Response {+ secure((StatusCode::OK, [(header::CONTENT_TYPE, "text/plain; charset=utf-8")], "Muxin share server. Open a share link to join.\n").into_response())+}++async fn page() -> Response {+ let (body, kind) = file("index.html").expect("built in");+ secure(([(header::CONTENT_TYPE, kind), (header::CACHE_CONTROL, "no-store")], body).into_response())+}++async fn asset(name: &'static str) -> Response {+ match file(name) {+ Some((body, kind)) => secure(([(header::CONTENT_TYPE, kind), (header::CACHE_CONTROL, "public, max-age=300")], body).into_response()),+ None => StatusCode::NOT_FOUND.into_response(),+ }+}++// ---------------------------------------------------------------------------+// Introductions++fn reply(status: StatusCode, body: Value) -> Response {+ let mut res = (status, axum::Json(body)).into_response();+ res.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));+ res+}++fn error(status: StatusCode, why: &str) -> Response {+ reply(status, json!({ "error": why }))+}++/// A room id: a share's 16-byte id in base64url.+fn valid_room(room: &str) -> bool {+ room.len() == 22 && room.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')+}++fn valid_id(id: &str) -> bool {+ id.len() == 16 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')+}++/// The host's key, from `X-Muxin-Host`, as kept (its SHA-256).+fn host_key(headers: &HeaderMap) -> Option<String> {+ let key = headers.get("x-muxin-host")?.to_str().ok()?;+ if key.len() < 32 || key.len() > 128 {+ return None;+ }+ Some(ring::digest::digest(&ring::digest::SHA256, key.as_bytes()).as_ref().iter().map(|b| format!("{b:02x}")).collect())+}++/// A description from the request, when it looks like one.+fn sdp(body: &Value) -> Option<String> {+ let sdp = body["sdp"].as_str()?;+ (sdp.len() <= MAX_SDP && sdp.starts_with("v=0")).then(|| sdp.to_string())+}++fn open(r: &Room) -> bool {+ !r.closed && r.seen.elapsed() < HOST_FRESH+}++async fn check_in(State(app): Shared, Path(room): Path<String>, headers: HeaderMap) -> Response {+ if !valid_room(&room) {+ return error(StatusCode::NOT_FOUND, "That isn't a share.");+ }+ let Some(key) = host_key(&headers) else { return error(StatusCode::UNAUTHORIZED, "Say which computer this is.") };+ let offers = {+ let mut st = app.state.lock().unwrap();+ let st = &mut *st;+ let r = st.rooms.entry(room.clone()).or_insert_with(|| Room { host: key.clone(), seen: Instant::now(), closed: false, pending: Vec::new() });+ if r.host != key {+ if !r.closed && r.seen.elapsed() < HOST_GONE {+ return error(StatusCode::CONFLICT, "That share is open on another computer.");+ }+ *r = Room { host: key, seen: Instant::now(), closed: false, pending: Vec::new() };+ }+ r.seen = Instant::now();+ r.closed = false;+ let ids = std::mem::take(&mut r.pending);+ ids.into_iter().filter_map(|id| st.offers.get(&id).map(|o| json!({ "id": id, "sdp": o.sdp }))).collect::<Vec<_>>()+ };+ reply(StatusCode::OK, json!({ "ice": app.ice(&room), "offers": offers }))+}++async fn answer(State(app): Shared, Path((room, id)): Path<(String, String)>, headers: HeaderMap, axum::Json(body): axum::Json<Value>) -> Response {+ let Some(key) = host_key(&headers) else { return error(StatusCode::UNAUTHORIZED, "Say which computer this is.") };+ let Some(sdp) = sdp(&body) else { return error(StatusCode::UNPROCESSABLE_ENTITY, "That isn't a description.") };+ let mut st = app.state.lock().unwrap();+ if st.rooms.get(&room).is_none_or(|r| r.host != key) {+ return error(StatusCode::FORBIDDEN, "That isn't your share.");+ }+ match st.offers.get_mut(&id).filter(|o| o.room == room) {+ Some(o) => {+ o.answer = Some(sdp);+ reply(StatusCode::OK, json!({ "ok": true }))+ }+ None => error(StatusCode::NOT_FOUND, "That offer is gone."),+ }+}++async fn close(State(app): Shared, Path(room): Path<String>, headers: HeaderMap) -> Response {+ let Some(key) = host_key(&headers) else { return error(StatusCode::UNAUTHORIZED, "Say which computer this is.") };+ let mut st = app.state.lock().unwrap();+ match st.rooms.get_mut(&room) {+ Some(r) if r.host == key => {+ r.closed = true;+ r.pending.clear();+ reply(StatusCode::OK, json!({ "ok": true }))+ }+ _ => error(StatusCode::NOT_FOUND, "That share isn't open."),+ }+}++async fn room(State(app): Shared, Path(room): Path<String>) -> Response {+ if !valid_room(&room) {+ return error(StatusCode::NOT_FOUND, "That isn't a share.");+ }+ let is_open = app.state.lock().unwrap().rooms.get(&room).is_some_and(open);+ reply(StatusCode::OK, json!({ "open": is_open, "ice": app.ice(&room) }))+}++async fn offer(State(app): Shared, Path(room): Path<String>, axum::Json(body): axum::Json<Value>) -> Response {+ let Some(sdp) = sdp(&body) else { return error(StatusCode::UNPROCESSABLE_ENTITY, "That isn't a description.") };+ let id = {+ let mut bytes = [0u8; 12];+ let _ = ring::rand::SecureRandom::fill(&ring::rand::SystemRandom::new(), &mut bytes);+ base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)+ };+ let mut st = app.state.lock().unwrap();+ let st = &mut *st;+ let Some(r) = st.rooms.get_mut(&room).filter(|r| open(r)) else {+ return error(StatusCode::NOT_FOUND, "That share isn't open right now. It may have ended.");+ };+ if r.pending.len() >= MAX_PENDING {+ return error(StatusCode::TOO_MANY_REQUESTS, "Too many people are joining this share right now. Try again in a minute.");+ }+ r.pending.push(id.clone());+ st.offers.insert(id.clone(), Offer { room, sdp, answer: None, at: Instant::now() });+ reply(StatusCode::CREATED, json!({ "id": id }))+}++async fn answer_to(State(app): Shared, Path((room, id)): Path<(String, String)>) -> Response {+ if !valid_id(&id) {+ return error(StatusCode::NOT_FOUND, "That offer is gone.");+ }+ let st = app.state.lock().unwrap();+ let is_open = st.rooms.get(&room).is_some_and(open);+ match st.offers.get(&id).filter(|o| o.room == room) {+ Some(o) => reply(StatusCode::OK, json!({ "answer": o.answer, "open": is_open })),+ None => error(StatusCode::NOT_FOUND, "That offer is gone."),+ }+}++impl App {+ /// The STUN and TURN servers to give a side, with TURN credentials of+ /// its own (coturn's REST scheme: `expiry:room`, HMAC-SHA1 of it).+ fn ice(&self, room: &str) -> Value {+ let mut ice = Vec::new();+ if !self.stun.is_empty() {+ ice.push(json!({ "urls": self.stun }));+ }+ if let (false, Some(secret)) = (self.turn.is_empty(), &self.turn_secret) {+ let expiry = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) + TURN_TTL.as_secs();+ let username = format!("{expiry}:{}", &room[..8.min(room.len())]);+ let key = ring::hmac::Key::new(ring::hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, secret.as_bytes());+ let credential = base64::engine::general_purpose::STANDARD.encode(ring::hmac::sign(&key, username.as_bytes()).as_ref());+ ice.push(json!({ "urls": self.turn, "username": username, "credential": credential }));+ }+ Value::Array(ice)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn rooms_are_share_ids() {+ assert!(valid_room("AQEBAQEBAQEBAQEBAQEBAQ"));+ assert!(!valid_room("short"));+ assert!(!valid_room("AQEBAQEBAQEBAQEBAQEB/Q"));+ assert!(valid_id("AQEBAQEBAQEBAQEB"));+ assert!(!valid_id("../../etc/passwd"));+ }++ #[test]+ fn turn_credentials_follow_coturn() {+ let app = App {+ state: Mutex::new(Rooms::default()),+ stun: vec!["stun:s.example.com:3478".into()],+ turn: vec!["turn:t.example.com:3478".into()],+ turn_secret: Some("secret".into()),+ };+ let ice = app.ice("AQEBAQEBAQEBAQEBAQEBAQ");+ assert_eq!(ice[0]["urls"][0], "stun:s.example.com:3478");+ let user = ice[1]["username"].as_str().unwrap();+ let key = ring::hmac::Key::new(ring::hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, b"secret");+ let want = base64::engine::general_purpose::STANDARD.encode(ring::hmac::sign(&key, user.as_bytes()).as_ref());+ assert_eq!(ice[1]["credential"], want);+ assert!(user.ends_with(":AQEBAQEB"));+ }+}diff --git a/share-server/web/index.html b/share-server/web/index.htmlnew file mode 100644index 0000000..740387c--- /dev/null+++ b/share-server/web/index.html@@ -0,0 +1,77 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<meta name="referrer" content="no-referrer">+<title>Muxin share</title>+<link rel="stylesheet" href="/share/vendor/xterm.css">+<link rel="stylesheet" href="/share/join.css">+<script src="/share/vendor/xterm.js" defer></script>+<script src="/share/join.js" defer></script>+</head>+<body>+<header class="bar">+ <span class="brand"><span class="logo" aria-hidden="true"></span>Muxin</span>+ <span id="session" class="session" hidden>+ <span class="session-title" id="session-title"></span>+ <span class="session-sub" id="session-sub"></span>+ </span>+ <span id="session-actions" class="session-actions" hidden>+ <span class="pill" id="mode-pill">Watching</span>+ <span class="muted" id="time-left"></span>+ <button type="button" id="leave" class="secondary">Leave</button>+ </span>+</header>++<main>+ <section id="start" class="center" hidden>+ <form id="join-form" class="card stack">+ <h1>Join a shared session</h1>+ <p class="muted">Right here in your browser. Nothing to install.</p>+ <label for="name">Your name</label>+ <input id="name" name="name" maxlength="40" autocomplete="name" placeholder="Sam" required>+ <p id="name-error" class="error small" hidden>Enter your name first.</p>+ <button type="submit" id="join-button" class="primary wide">Join</button>+ <p class="muted small center-text">Have Muxin? <a id="open-app" href="#">Open it in Muxin</a></p>+ </form>+ </section>++ <section id="wait" class="center" hidden>+ <div class="card stack">+ <h2 id="wait-title">Connecting…</h2>+ <p id="wait-sub" class="muted"></p>+ <ul id="facts" class="facts" hidden>+ <li id="fact-can"></li>+ <li id="fact-ends"></li>+ <li id="fact-name"></li>+ </ul>+ <div id="code-box" class="code-box" hidden>+ <span class="muted small">Your code</span>+ <span id="code" class="code"></span>+ <span id="code-help" class="muted small"></span>+ </div>+ <div class="row">+ <span id="wait-status" class="status"></span>+ <button type="button" id="cancel" class="secondary">Cancel</button>+ </div>+ </div>+ </section>++ <section id="watch" class="watch" hidden>+ <div id="term" class="term"></div>+ <div class="term-bar">+ <span id="term-note">You're watching.</span>+ <span class="muted" id="term-path">Peer to peer · encrypted</span>+ </div>+ </section>++ <section id="done" class="center" hidden>+ <div class="stack narrow">+ <h1 id="done-title">The share ended</h1>+ <p id="done-sub" class="lead"></p>+ </div>+ </section>+</main>+</body>+</html>diff --git a/share-server/web/join.css b/share-server/web/join.cssnew file mode 100644index 0000000..45d0784--- /dev/null+++ b/share-server/web/join.css@@ -0,0 +1,117 @@+:root {+ --ground: #12152e;+ --sidebar: #151834;+ --canvas: #1a1e3c;+ --surface: #20254a;+ --elevated: #272d56;+ --border: #363d6e;+ --border-soft: #2b3160;+ --text: #eeecfb;+ --muted: #aeb0d8;+ --accent: #a66bf2;+ --accent-soft: #2f2a63;+ --accent-text: #c9a6ff;+ --orange: #e8734a;+ --green: #52d6ad;+ --red: #ff6e86;+ --yellow: #f2c94c;+ color-scheme: dark;+}++* { box-sizing: border-box; }+[hidden] { display: none !important; }++html, body { height: 100%; }+body {+ margin: 0;+ background: var(--ground);+ color: var(--text);+ font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif;+ display: flex;+ flex-direction: column;+}++a { color: var(--orange); }+a:hover { color: #f0956f; }++.bar {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 12px 16px;+ padding: 14px 24px;+ border-bottom: 1px solid var(--border-soft);+ background: var(--sidebar);+}+.brand { display: flex; align-items: center; gap: 10px; font-weight: 600; }+.logo { width: 24px; height: 24px; border-radius: 7px; background: linear-gradient(135deg, var(--accent), var(--orange)); }+.session { display: flex; flex-direction: column; flex: 1 1 260px; min-width: 0; padding-left: 16px; border-left: 1px solid var(--border); }+.session-title { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.session-sub { font-size: 12px; color: var(--muted); }+.session-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; font-size: 14px; }+.pill { border: 1px solid var(--accent); background: var(--accent-soft); border-radius: 999px; padding: 4px 12px; }++main { flex: 1; display: flex; flex-direction: column; min-height: 0; }+.center { flex: 1; display: flex; align-items: center; justify-content: center; padding: 32px 16px 64px; }+.stack { display: flex; flex-direction: column; gap: 16px; }+.narrow { width: 100%; max-width: 520px; text-align: center; align-items: center; }+h1 { margin: 0; font-size: 32px; line-height: 1.2; font-weight: 600; }+h2 { margin: 0; font-size: 20px; font-weight: 600; }+.lead { margin: 0; font-size: 17px; color: var(--muted); }+.muted { color: var(--muted); }+.small { font-size: 13px; margin: 0; }+.note { border: 1px solid var(--border-soft); border-radius: 10px; padding: 8px 14px; color: var(--muted); }+.error { color: var(--red); }++.choices { width: 100%; display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; text-align: left; }+.choice {+ display: flex; flex-direction: column; gap: 4px; padding: 18px; border-radius: 12px;+ border: 1px solid var(--border); background: var(--elevated); color: var(--text);+ text-decoration: none; font: inherit; cursor: pointer; text-align: left;+}+.choice:hover { border-color: var(--accent); color: var(--text); }+.primary-choice { border: 0; background: linear-gradient(135deg, #8f55df, #c95f39); color: #fff; }+.primary-choice:hover { color: #fff; filter: brightness(1.08); }+.choice-title { font-size: 16px; font-weight: 600; }+.choice-sub { font-size: 13px; opacity: 0.92; }++.card {+ width: 100%; max-width: 500px; background: var(--elevated); border: 1px solid var(--border);+ border-radius: 14px; padding: 28px;+}+label { font-size: 13px; color: var(--muted); }+input {+ width: 100%; padding: 10px 12px; border-radius: 9px; border: 1px solid var(--border);+ background: var(--canvas); color: var(--text); font: inherit;+}+input:focus { outline: 2px solid var(--accent); outline-offset: 1px; }+.row { display: flex; align-items: center; gap: 12px; }+.row.end { justify-content: flex-end; }+button {+ font: inherit; color: inherit; cursor: pointer; border-radius: 9px; padding: 9px 18px; min-height: 40px;+}+button.primary { border: 0; background: linear-gradient(90deg, #8f55df, #c95f39); color: #fff; font-weight: 500; }+button.wide { width: 100%; min-height: 44px; font-size: 16px; }+.center-text { text-align: center; }+.card h1 { font-size: 24px; }+button.secondary { border: 1px solid var(--border); background: var(--surface); }+button:disabled { opacity: 0.6; cursor: default; }++.facts { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; font-size: 14px; }+.code-box {+ display: flex; flex-direction: column; align-items: center; gap: 6px; padding: 20px;+ border-radius: 12px; background: var(--canvas); border: 1px solid var(--border); text-align: center;+}+.code { font: 500 36px/1.2 ui-monospace, "SF Mono", Menlo, monospace; letter-spacing: 4px; }+.status { flex: 1; font-size: 14px; color: var(--accent-text); }++.watch { flex: 1; display: flex; flex-direction: column; align-items: center; gap: 10px; padding: 20px 16px; min-height: 0; }+.term {+ width: 100%; max-width: 1200px; flex: 1; min-height: 320px; overflow: auto;+ border: 1px solid var(--border-soft); border-radius: 10px; padding: 12px; background: var(--canvas);+}+.term-bar {+ width: 100%; max-width: 1200px; display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: center;+ padding: 10px 14px; border-radius: 10px; background: var(--surface); font-size: 13px;+}+.term-bar > :first-child { flex: 1 1 220px; }diff --git a/share-server/web/join.js b/share-server/web/join.jsnew file mode 100644index 0000000..ed6352e--- /dev/null+++ b/share-server/web/join.js@@ -0,0 +1,330 @@+// Joins a Muxin share from the browser: the link's ticket (after the #)+// names the share, its secret and its certificate. This page connects to+// the sharing computer over WebRTC, refuses any other certificate, proves+// it has the link, then shows the session. See src/share in Muxin.+"use strict";++(() => {+ const JSON_KIND = 10, DATA = 0, EXIT = 2, SIZE = 3, CLOSE = 11;+ const SESSION = 1;+ const $ = (id) => document.getElementById(id);+ const enc = new TextEncoder();+ const dec = new TextDecoder();++ // The ticket, out of the address bar (kept for this tab only, so a reload+ // works and a screenshot of the page doesn't show it).+ function readTicket() {+ let fragment = location.hash.slice(1);+ if (fragment) {+ try { sessionStorage.setItem("muxin-share", fragment); } catch (_) {}+ history.replaceState(null, "", location.pathname);+ } else {+ try { fragment = sessionStorage.getItem("muxin-share") || ""; } catch (_) {}+ }+ const [version, data] = fragment.split(".");+ if (version !== "1" || !data) return null;+ let bytes;+ try {+ const b64 = data.replace(/-/g, "+").replace(/_/g, "/");+ bytes = Uint8Array.from(atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4)), (c) => c.charCodeAt(0));+ } catch (_) { return null; }+ if (bytes.length !== 80) return null;+ return { fragment, id: bytes.slice(0, 16), secret: bytes.slice(16, 48), fingerprint: hex(bytes.slice(48, 80)) };+ }++ const hex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");+ const room = (id) => btoa(String.fromCharCode(...id)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");++ // The one SHA-256 fingerprint in an SDP (null when none, or several differ).+ function fingerprint(sdp) {+ let found = null;+ for (const line of sdp.split(/\r?\n/)) {+ const m = /^a=fingerprint:(\S+) (.+)$/.exec(line.trim());+ if (!m) continue;+ if (m[1].toLowerCase() !== "sha-256") return null;+ const value = m[2].trim().replace(/:/g, "").toLowerCase();+ if (value.length !== 64 || (found && found !== value)) return null;+ found = value;+ }+ return found;+ }++ async function hmac(secret, text) {+ const key = await crypto.subtle.importKey("raw", secret, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);+ return new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(text)));+ }++ function frame(channel, kind, payload) {+ const f = new Uint8Array(5 + payload.length);+ new DataView(f.buffer).setUint32(0, channel);+ f[4] = kind;+ f.set(payload, 5);+ return f;+ }++ const sections = ["start", "wait", "watch", "done"];+ function show(name) {+ for (const s of sections) $(s).hidden = s !== name;+ }++ function finish(title, sub) {+ state.over = true;+ if (state.pc) try { state.pc.close(); } catch (_) {}+ clearInterval(state.clock);+ $("session-actions").hidden = true;+ $("done-title").textContent = title;+ $("done-sub").textContent = sub || "";+ show("done");+ }++ const state = { over: false, pc: null, dc: null, term: null, canType: false, info: null, clock: 0, name: "" };++ function minutesLeft(endsAt) {+ const s = endsAt - Date.now() / 1000;+ if (s <= 0) return "Ending";+ if (s < 3600) return `${Math.max(1, Math.round(s / 60))} min left`;+ const h = Math.round(s / 3600);+ return `${h} hour${h === 1 ? "" : "s"} left`;+ }++ const agents = { claude: "Claude Code", codex: "Codex", opencode: "OpenCode", gemini: "Gemini CLI", amp: "Amp", pi: "Pi", shell: "Shell" };++ function showInfo(info) {+ state.info = info;+ const what = agents[info.agent] || "A session";+ $("session-title").textContent = info.title || what;+ $("session-sub").textContent = `${what} on ${info.machine} · shared by ${info.by}`;+ $("session").hidden = false;+ $("wait-title").textContent = `Join ${info.title || what}`;+ $("wait-sub").textContent = `${what} on ${info.machine} · shared by ${info.by}`;+ $("fact-can").textContent = info.can_type ? "You can watch and type" : "You can watch";+ $("fact-ends").textContent = `Ends in ${minutesLeft(info.ends_at).replace(" left", "")}`;+ $("fact-name").textContent = `Joining as ${state.name}`;+ $("facts").hidden = false;+ $("code-help").textContent = `Read it to ${info.by} so they know it's you.`;+ clearInterval(state.clock);+ state.clock = setInterval(() => { $("time-left").textContent = minutesLeft(info.ends_at); }, 15000);+ $("time-left").textContent = minutesLeft(info.ends_at);+ }++ function setTyping(allowed) {+ state.canType = allowed;+ $("mode-pill").textContent = allowed ? "Typing" : "Watching";+ const by = state.info ? state.info.by : "they";+ $("term-note").textContent = allowed ? "You can type. Keys go to their session." : `You're watching. Only ${by} can type.`;+ if (state.term) state.term.options.disableStdin = !allowed;+ }++ function openTerminal() {+ show("watch");+ $("session-actions").hidden = false;+ const term = new window.Terminal({+ cols: 80, rows: 24, scrollback: 5000, convertEol: false, cursorBlink: true, disableStdin: true,+ fontFamily: 'ui-monospace, "SF Mono", Menlo, Consolas, monospace', fontSize: 13,+ theme: { background: "#1a1e3c", foreground: "#eeecfb", cursor: "#eeecfb", selectionBackground: "#3d3a7a" },+ });+ term.open($("term"));+ term.onData((data) => {+ if (state.canType && state.dc && state.dc.readyState === "open") state.dc.send(frame(SESSION, DATA, enc.encode(data)));+ });+ term.onBinary((data) => {+ if (!state.canType || !state.dc || state.dc.readyState !== "open") return;+ state.dc.send(frame(SESSION, DATA, Uint8Array.from(data, (c) => c.charCodeAt(0) & 255)));+ });+ state.term = term;+ setTyping(state.canType);+ }++ function send(obj) {+ if (state.dc && state.dc.readyState === "open") state.dc.send(frame(0, JSON_KIND, enc.encode(JSON.stringify(obj))));+ }++ function onFrame(buf) {+ const bytes = new Uint8Array(buf);+ if (bytes.length < 5) return;+ const channel = new DataView(bytes.buffer, bytes.byteOffset).getUint32(0);+ const kind = bytes[4];+ const body = bytes.subarray(5);+ if (channel === SESSION) {+ if (!state.term) return;+ if (kind === DATA) state.term.write(body);+ else if (kind === SIZE && body.length === 4) {+ const v = new DataView(body.buffer, body.byteOffset);+ state.term.resize(Math.max(10, v.getUint16(0)), Math.max(4, v.getUint16(2)));+ } else if (kind === EXIT) finish("The session ended", "");+ else if (kind === CLOSE) finish("The session ended", "");+ return;+ }+ if (channel !== 0 || kind !== JSON_KIND) return;+ let m;+ try { m = JSON.parse(dec.decode(body)); } catch (_) { return; }+ const clean = (s, n) => String(s || "").replace(/[\u0000-\u001f\u007f-\u009f]/g, "").slice(0, n);+ switch (m.event) {+ case "share":+ showInfo({ title: clean(m.title, 120), agent: clean(m.agent, 40), machine: clean(m.machine, 80), by: clean(m.by, 80), can_type: !!m.can_type, ends_at: Number(m.ends_at) || 0 });+ break;+ case "waiting":+ $("wait-status").textContent = `Waiting for ${state.info ? state.info.by : "them"} to let you in…`;+ break;+ case "admitted":+ state.canType = !!m.can_type;+ openTerminal();+ send({ op: "watch", channel: SESSION });+ break;+ case "typing":+ setTyping(!!m.allowed);+ break;+ case "denied":+ finish("You weren't let in", "Ask them for a new link if that wasn't meant to happen.");+ break;+ case "ended":+ finish(m.why === "removed" ? "You were removed" : "The share ended", m.why === "expired" ? "Its time ran out." : "");+ break;+ case "error":+ finish("Couldn't join", clean(m.error, 200));+ break;+ }+ }++ // The share server (this page's own): it only passes the offer and the+ // answer between the two sides.+ async function api(method, path, body) {+ const res = await fetch(`/share/v1${path}`, {+ method,+ headers: { "Content-Type": "application/json", Accept: "application/json" },+ body: body ? JSON.stringify(body) : undefined,+ cache: "no-store",+ credentials: "omit",+ referrerPolicy: "no-referrer",+ });+ let data = {};+ try { data = await res.json(); } catch (_) {}+ if (!res.ok) throw new Error(data.error || "The share server couldn't be reached.");+ return data;+ }++ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++ // The addresses that matter, in the description (no trickling: one offer,+ // one answer): this computer's, its public one when there's a STUN+ // server, the relay's when there's a relay. They come within moments;+ // the end of gathering can take much longer.+ function gathered(pc, ice) {+ const urls = ice.flatMap((s) => [].concat(s.urls || []));+ const wantPublic = urls.some((u) => u.startsWith("stun:"));+ const wantRelay = urls.some((u) => u.startsWith("turn:") || u.startsWith("turns:"));+ const seen = new Set();+ return new Promise((resolve) => {+ let done = false;+ const finish = () => { if (!done) { done = true; resolve(); } };+ const check = () => {+ if (seen.has("host") && (!wantPublic || seen.has("srflx")) && (!wantRelay || seen.has("relay"))) setTimeout(finish, 100);+ };+ pc.addEventListener("icecandidate", (e) => {+ if (!e.candidate) return finish();+ const m = / typ (\w+)/.exec(e.candidate.candidate);+ if (m) seen.add(m[1]);+ check();+ });+ pc.addEventListener("icegatheringstatechange", () => { if (pc.iceGatheringState === "complete") finish(); });+ setTimeout(finish, 2500);+ });+ }++ async function connect(ticket) {+ show("wait");+ $("wait-status").textContent = "Connecting…";+ const id = room(ticket.id);+ try {+ const r = await api("GET", `/rooms/${id}`);+ if (!r.open) return finish("The share ended", "It isn't open right now.");+ const pc = new RTCPeerConnection({ iceServers: Array.isArray(r.ice) ? r.ice : [] });+ state.pc = pc;+ const dc = pc.createDataChannel("muxin");+ dc.binaryType = "arraybuffer";+ state.dc = dc;+ pc.onconnectionstatechange = () => {+ if (pc.connectionState === "failed" && !state.over) finish("Couldn't connect", "No way through to the computer sharing it.");+ if (pc.connectionState === "connected") {+ pc.getStats().then((stats) => {+ stats.forEach((p) => {+ if (p.type === "candidate-pair" && p.state === "succeeded" && p.nominated) {+ const local = stats.get(p.localCandidateId), remote = stats.get(p.remoteCandidateId);+ const relayed = (local && local.candidateType === "relay") || (remote && remote.candidateType === "relay");+ $("term-path").textContent = relayed ? "Through the relay · encrypted" : "Peer to peer · encrypted";+ }+ });+ }).catch(() => {});+ }+ };+ dc.onopen = async () => {+ const mine = fingerprint(pc.localDescription.sdp);+ if (!mine) return finish("Couldn't join", "This browser didn't offer a certificate.");+ const proof = hex(await hmac(ticket.secret, `muxin-share-v1\n${ticket.fingerprint}\n${mine}`));+ const tag = await hmac(ticket.secret, `muxin-share-code-v1\n${mine}`);+ const code = String(new DataView(tag.buffer).getUint32(0) % 1000000).padStart(6, "0");+ $("code").textContent = `${code.slice(0, 3)} ${code.slice(3)}`;+ $("code-box").hidden = false;+ $("wait-status").textContent = "Asking to join…";+ send({ op: "hello", v: 1, name: state.name, client: "browser", proof });+ };+ dc.onmessage = (e) => onFrame(e.data);+ dc.onclose = () => { if (!state.over) finish("The share ended", "The connection closed."); };+ const iceReady = gathered(pc, Array.isArray(r.ice) ? r.ice : []);+ await pc.setLocalDescription(await pc.createOffer());+ await iceReady;+ const offer = await api("POST", `/rooms/${id}/offers`, { sdp: pc.localDescription.sdp });+ // The answer, once the sharing computer picks the offer up.+ const until = Date.now() + 30000;+ while (!state.over) {+ if (Date.now() > until) return finish("Couldn't connect", "The computer sharing it didn't answer.");+ await sleep(700);+ const a = await api("GET", `/rooms/${id}/offers/${offer.id}`);+ if (!a.open) return finish("The share ended", "It isn't open right now.");+ if (!a.answer) continue;+ // Only the share's own certificate: the server can't stand in.+ if (fingerprint(a.answer) !== ticket.fingerprint) return finish("Couldn't join", "That share's connection couldn't be verified.");+ await pc.setRemoteDescription({ type: "answer", sdp: a.answer });+ break;+ }+ } catch (e) {+ if (!state.over) finish("Couldn't join", e.message || "The share server couldn't be reached.");+ return;+ }+ setTimeout(() => {+ if (!state.over && (!state.dc || state.dc.readyState !== "open")) finish("Couldn't connect", "The computer sharing it didn't answer.");+ }, 25000);+ }++ function start() {+ const ticket = readTicket();+ if (!ticket || !window.RTCPeerConnection || !crypto.subtle) {+ $("done-title").textContent = ticket ? "This browser can't join" : "That link isn't complete";+ $("done-sub").textContent = ticket ? "Try a current Chrome, Safari, Firefox or Edge." : "Ask for the link again, and copy all of it.";+ show("done");+ return;+ }+ $("open-app").href = `muxin://join?server=${encodeURIComponent(location.origin)}#${ticket.fragment}`;+ show("start");+ try { $("name").value = localStorage.getItem("muxin-name") || ""; } catch (_) {}+ $("name").focus();+ $("name").addEventListener("input", () => { $("name-error").hidden = true; });+ $("join-form").addEventListener("submit", (e) => {+ e.preventDefault();+ const name = $("name").value.trim();+ if (!name) { $("name-error").hidden = false; return; }+ state.name = name.slice(0, 40);+ try { localStorage.setItem("muxin-name", state.name); } catch (_) {}+ connect(ticket);+ });+ $("cancel").addEventListener("click", () => { send({ op: "bye" }); finish("You left", ""); });+ $("leave").addEventListener("click", () => { send({ op: "bye" }); finish("You left", ""); });+ }++ // Another link opened in this tab: start over with it.+ window.addEventListener("hashchange", () => {+ if (location.hash.length > 1) location.reload();+ });++ start();+})();diff --git a/share-server/web/vendor/XTERM-LICENSE b/share-server/web/vendor/XTERM-LICENSEnew file mode 100644index 0000000..4472336--- /dev/null+++ b/share-server/web/vendor/XTERM-LICENSE@@ -0,0 +1,21 @@+Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)+Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com)+Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/)++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in+all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+THE SOFTWARE.diff --git a/share-server/web/vendor/xterm.css b/share-server/web/vendor/xterm.cssnew file mode 100644index 0000000..e97b643--- /dev/null+++ b/share-server/web/vendor/xterm.css@@ -0,0 +1,218 @@+/**+ * Copyright (c) 2014 The xterm.js authors. All rights reserved.+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)+ * https://github.com/chjj/term.js+ * @license MIT+ *+ * Permission is hereby granted, free of charge, to any person obtaining a copy+ * of this software and associated documentation files (the "Software"), to deal+ * in the Software without restriction, including without limitation the rights+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+ * copies of the Software, and to permit persons to whom the Software is+ * furnished to do so, subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be included in+ * all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+ * THE SOFTWARE.+ *+ * Originally forked from (with the author's permission):+ * Fabrice Bellard's javascript vt100 for jslinux:+ * http://bellard.org/jslinux/+ * Copyright (c) 2011 Fabrice Bellard+ * The original design remains. The terminal itself+ * has been extended to include xterm CSI codes, among+ * other features.+ */++/**+ * Default styles for xterm.js+ */++.xterm {+ cursor: text;+ position: relative;+ user-select: none;+ -ms-user-select: none;+ -webkit-user-select: none;+}++.xterm.focus,+.xterm:focus {+ outline: none;+}++.xterm .xterm-helpers {+ position: absolute;+ top: 0;+ /**+ * The z-index of the helpers must be higher than the canvases in order for+ * IMEs to appear on top.+ */+ z-index: 5;+}++.xterm .xterm-helper-textarea {+ padding: 0;+ border: 0;+ margin: 0;+ /* Move textarea out of the screen to the far left, so that the cursor is not visible */+ position: absolute;+ opacity: 0;+ left: -9999em;+ top: 0;+ width: 0;+ height: 0;+ z-index: -5;+ /** Prevent wrapping so the IME appears against the textarea at the correct position */+ white-space: nowrap;+ overflow: hidden;+ resize: none;+}++.xterm .composition-view {+ /* TODO: Composition position got messed up somewhere */+ background: #000;+ color: #FFF;+ display: none;+ position: absolute;+ white-space: nowrap;+ z-index: 1;+}++.xterm .composition-view.active {+ display: block;+}++.xterm .xterm-viewport {+ /* On OS X this is required in order for the scroll bar to appear fully opaque */+ background-color: #000;+ overflow-y: scroll;+ cursor: default;+ position: absolute;+ right: 0;+ left: 0;+ top: 0;+ bottom: 0;+}++.xterm .xterm-screen {+ position: relative;+}++.xterm .xterm-screen canvas {+ position: absolute;+ left: 0;+ top: 0;+}++.xterm .xterm-scroll-area {+ visibility: hidden;+}++.xterm-char-measure-element {+ display: inline-block;+ visibility: hidden;+ position: absolute;+ top: 0;+ left: -9999em;+ line-height: normal;+}++.xterm.enable-mouse-events {+ /* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */+ cursor: default;+}++.xterm.xterm-cursor-pointer,+.xterm .xterm-cursor-pointer {+ cursor: pointer;+}++.xterm.column-select.focus {+ /* Column selection mode */+ cursor: crosshair;+}++.xterm .xterm-accessibility:not(.debug),+.xterm .xterm-message {+ position: absolute;+ left: 0;+ top: 0;+ bottom: 0;+ right: 0;+ z-index: 10;+ color: transparent;+ pointer-events: none;+}++.xterm .xterm-accessibility-tree:not(.debug) *::selection {+ color: transparent;+}++.xterm .xterm-accessibility-tree {+ user-select: text;+ white-space: pre;+}++.xterm .live-region {+ position: absolute;+ left: -9999px;+ width: 1px;+ height: 1px;+ overflow: hidden;+}++.xterm-dim {+ /* Dim should not apply to background, so the opacity of the foreground color is applied+ * explicitly in the generated class and reset to 1 here */+ opacity: 1 !important;+}++.xterm-underline-1 { text-decoration: underline; }+.xterm-underline-2 { text-decoration: double underline; }+.xterm-underline-3 { text-decoration: wavy underline; }+.xterm-underline-4 { text-decoration: dotted underline; }+.xterm-underline-5 { text-decoration: dashed underline; }++.xterm-overline {+ text-decoration: overline;+}++.xterm-overline.xterm-underline-1 { text-decoration: overline underline; }+.xterm-overline.xterm-underline-2 { text-decoration: overline double underline; }+.xterm-overline.xterm-underline-3 { text-decoration: overline wavy underline; }+.xterm-overline.xterm-underline-4 { text-decoration: overline dotted underline; }+.xterm-overline.xterm-underline-5 { text-decoration: overline dashed underline; }++.xterm-strikethrough {+ text-decoration: line-through;+}++.xterm-screen .xterm-decoration-container .xterm-decoration {+ z-index: 6;+ position: absolute;+}++.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer {+ z-index: 7;+}++.xterm-decoration-overview-ruler {+ z-index: 8;+ position: absolute;+ top: 0;+ right: 0;+ pointer-events: none;+}++.xterm-decoration-top {+ z-index: 2;+ position: relative;+}diff --git a/share-server/web/vendor/xterm.js b/share-server/web/vendor/xterm.jsnew file mode 100644index 0000000..7ca75f8--- /dev/null+++ b/share-server/web/vendor/xterm.js@@ -0,0 +1,2 @@+!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i=t();for(var s in i)("object"==typeof exports?exports:e)[s]=i[s]}}(globalThis,(()=>(()=>{"use strict";var e={4567:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.AccessibilityManager=void 0;const n=i(9042),o=i(9924),a=i(844),h=i(4725),c=i(2585),l=i(3656);let d=t.AccessibilityManager=class extends a.Disposable{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new o.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((e=>this._handleResize(e.rows)))),this.register(this._terminal.onRender((e=>this._refreshRows(e.start,e.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((e=>this._handleChar(e)))),this.register(this._terminal.onLineFeed((()=>this._handleChar("\n")))),this.register(this._terminal.onA11yTab((e=>this._handleTab(e)))),this.register(this._terminal.onKey((e=>this._handleKey(e.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,l.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,a.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,"\n"===e&&(this._liveRegionLineCount++,21===this._liveRegionLineCount&&(this._liveRegion.textContent+=n.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){const i=this._terminal.buffer,s=i.lines.length.toString();for(let r=e;r<=t;r++){const e=i.lines.get(i.ydisp+r),t=[],n=e?.translateToString(!0,void 0,void 0,t)||"",o=(i.ydisp+r+1).toString(),a=this._rowElements[r];a&&(0===n.length?(a.innerText=" ",this._rowColumns.set(a,[0,1])):(a.textContent=n,this._rowColumns.set(a,t)),a.setAttribute("aria-posinset",o),a.setAttribute("aria-setsize",s))}this._announceCharacters()}_announceCharacters(){0!==this._charsToAnnounce.length&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){const i=e.target,s=this._rowElements[0===t?1:this._rowElements.length-2];if(i.getAttribute("aria-posinset")===(0===t?"1":`${this._terminal.buffer.lines.length}`))return;if(e.relatedTarget!==s)return;let r,n;if(0===t?(r=i,n=this._rowElements.pop(),this._rowContainer.removeChild(n)):(r=this._rowElements.shift(),n=i,this._rowContainer.removeChild(r)),r.removeEventListener("focus",this._topBoundaryFocusListener),n.removeEventListener("focus",this._bottomBoundaryFocusListener),0===t){const e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement("afterbegin",e)}else{const e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(0===t?-1:1),this._rowElements[0===t?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(0===this._rowElements.length)return;const e=document.getSelection();if(!e)return;if(e.isCollapsed)return void(this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection());if(!e.anchorNode||!e.focusNode)return void console.error("anchorNode and/or focusNode are null");let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;const s=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:s,offset:s.textContent?.length??0}),!this._rowContainer.contains(i.node))return;const r=({node:e,offset:t})=>{const i=e instanceof Text?e.parentNode:e;let s=parseInt(i?.getAttribute("aria-posinset"),10)-1;if(isNaN(s))return console.warn("row is invalid. Race condition?"),null;const r=this._rowColumns.get(i);if(!r)return console.warn("columns is null. Race condition?"),null;let n=t<r.length?r[t]:r.slice(-1)[0]+1;return n>=this._terminal.cols&&(++s,n=0),{row:s,column:n}},n=r(t),o=r(i);if(n&&o){if(n.row>o.row||n.row===o.row&&n.column>=o.column)throw new Error("invalid range");this._terminal.select(n.column,n.row,(o.row-n.row)*this._terminal.cols-n.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}};t.AccessibilityManager=d=s([r(1,c.IInstantiationService),r(2,h.ICoreBrowserService),r(3,h.IRenderService)],d)},3614:(e,t)=>{function i(e){return e.replace(/\r?\n/g,"\r")}function s(e,t){return t?"[200~"+e+"[201~":e}function r(e,t,r,n){e=s(e=i(e),r.decPrivateModes.bracketedPasteMode&&!0!==n.rawOptions.ignoreBracketedPasteMode),r.triggerDataEvent(e,!0),t.value=""}function n(e,t,i){const s=i.getBoundingClientRect(),r=e.clientX-s.left-10,n=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${r}px`,t.style.top=`${n}px`,t.style.zIndex="1000",t.focus()}Object.defineProperty(t,"__esModule",{value:!0}),t.rightClickHandler=t.moveTextAreaUnderMouseCursor=t.paste=t.handlePasteEvent=t.copyHandler=t.bracketTextForPaste=t.prepareTextForTerminal=void 0,t.prepareTextForTerminal=i,t.bracketTextForPaste=s,t.copyHandler=function(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()},t.handlePasteEvent=function(e,t,i,s){e.stopPropagation(),e.clipboardData&&r(e.clipboardData.getData("text/plain"),t,i,s)},t.paste=r,t.moveTextAreaUnderMouseCursor=n,t.rightClickHandler=function(e,t,i,s,r){n(e,t,i),r&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}},7239:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorContrastCache=void 0;const s=i(1505);t.ColorContrastCache=class{constructor(){this._color=new s.TwoKeyMap,this._css=new s.TwoKeyMap}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}}},3656:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addDisposableDomListener=void 0,t.addDisposableDomListener=function(e,t,i,s){e.addEventListener(t,i,s);let r=!1;return{dispose:()=>{r||(r=!0,e.removeEventListener(t,i,s))}}}},3551:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.Linkifier=void 0;const n=i(3656),o=i(8460),a=i(844),h=i(2585),c=i(4725);let l=t.Linkifier=class extends a.Disposable{get currentLink(){return this._currentLink}constructor(e,t,i,s,r){super(),this._element=e,this._mouseService=t,this._renderService=i,this._bufferService=s,this._linkProviderService=r,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new o.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new o.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,a.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,a.toDisposable)((()=>{this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,n.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,n.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,n.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,n.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(e){this._lastMouseEvent=e;const t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;const i=e.composedPath();for(let e=0;e<i.length;e++){const t=i[e];if(t.classList.contains("xterm"))break;if(t.classList.contains("xterm-hover"))return}this._lastBufferCell&&t.x===this._lastBufferCell.x&&t.y===this._lastBufferCell.y||(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){if(this._activeLine!==e.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(e,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){this._activeProviderReplies&&t||(this._activeProviderReplies?.forEach((e=>{e?.forEach((e=>{e.link.dispose&&e.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(const[s,r]of this._linkProviderService.linkProviders.entries())if(t){const t=this._activeProviderReplies?.get(s);t&&(i=this._checkLinkProviderResult(s,e,i))}else r.provideLinks(e.y,(t=>{if(this._isMouseOut)return;const r=t?.map((e=>({link:e})));this._activeProviderReplies?.set(s,r),i=this._checkLinkProviderResult(s,e,i),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)}))}_removeIntersectingLinks(e,t){const i=new Set;for(let s=0;s<t.size;s++){const r=t.get(s);if(r)for(let t=0;t<r.length;t++){const s=r[t],n=s.link.range.start.y<e?0:s.link.range.start.x,o=s.link.range.end.y>e?this._bufferService.cols:s.link.range.end.x;for(let e=n;e<=o;e++){if(i.has(e)){r.splice(t--,1);break}i.add(e)}}}}_checkLinkProviderResult(e,t,i){if(!this._activeProviderReplies)return i;const s=this._activeProviderReplies.get(e);let r=!1;for(let t=0;t<e;t++)this._activeProviderReplies.has(t)&&!this._activeProviderReplies.get(t)||(r=!0);if(!r&&s){const e=s.find((e=>this._linkAtPosition(e.link,t)));e&&(i=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let e=0;e<this._activeProviderReplies.size;e++){const s=this._activeProviderReplies.get(e)?.find((e=>this._linkAtPosition(e.link,t)));if(s){i=!0,this._handleNewLink(s);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;const t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){this._currentLink&&this._lastMouseEvent&&(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,a.disposeArray)(this._linkCacheDisposables))}_handleNewLink(e){if(!this._lastMouseEvent)return;const t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:void 0===e.link.decorations||e.link.decorations.underline,pointerCursor:void 0===e.link.decorations||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((e=>{if(!this._currentLink)return;const t=0===e.start?0:e.start+1+this._bufferService.buffer.ydisp,i=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=i&&(this._clearCurrentLink(t,i),this._lastMouseEvent)){const e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}}))))}_linkHover(e,t,i){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){const i=e.range,s=this._bufferService.buffer.ydisp,r=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(r)}_linkLeave(e,t,i){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){const i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,r=t.y*this._bufferService.cols+t.x;return i<=r&&r<=s}_positionFromMouseEvent(e,t,i){const s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,r){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:r}}};t.Linkifier=l=s([r(1,c.IMouseService),r(2,c.IRenderService),r(3,h.IBufferService),r(4,c.ILinkProviderService)],l)},9042:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.tooMuchOutput=t.promptLabel=void 0,t.promptLabel="Terminal input",t.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OscLinkProvider=void 0;const n=i(511),o=i(2585);let a=t.OscLinkProvider=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){const i=this._bufferService.buffer.lines.get(e-1);if(!i)return void t(void 0);const s=[],r=this._optionsService.rawOptions.linkHandler,o=new n.CellData,a=i.getTrimmedLength();let c=-1,l=-1,d=!1;for(let t=0;t<a;t++)if(-1!==l||i.hasContent(t)){if(i.loadCell(t,o),o.hasExtendedAttrs()&&o.extended.urlId){if(-1===l){l=t,c=o.extended.urlId;continue}d=o.extended.urlId!==c}else-1!==l&&(d=!0);if(d||-1!==l&&t===a-1){const i=this._oscLinkService.getLinkData(c)?.uri;if(i){const n={start:{x:l+1,y:e},end:{x:t+(d||t!==a-1?0:1),y:e}};let o=!1;if(!r?.allowNonHttpProtocols)try{const e=new URL(i);["http:","https:"].includes(e.protocol)||(o=!0)}catch(e){o=!0}o||s.push({text:i,range:n,activate:(e,t)=>r?r.activate(e,t,n):h(0,t),hover:(e,t)=>r?.hover?.(e,t,n),leave:(e,t)=>r?.leave?.(e,t,n)})}d=!1,o.hasExtendedAttrs()&&o.extended.urlId?(l=t,c=o.extended.urlId):(l=-1,c=-1)}}t(s)}};function h(e,t){if(confirm(`Do you want to navigate to ${t}?\n\nWARNING: This link could potentially be dangerous`)){const e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}t.OscLinkProvider=a=s([r(0,o.IBufferService),r(1,o.IOptionsService),r(2,o.IOscLinkService)],a)},6193:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RenderDebouncer=void 0,t.RenderDebouncer=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh()))),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=void 0!==e?e:0,t=void 0!==t?t:this._rowCount-1,this._rowStart=void 0!==this._rowStart?Math.min(this._rowStart,e):e,this._rowEnd=void 0!==this._rowEnd?Math.max(this._rowEnd,t):t,this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh())))}_innerRefresh(){if(this._animationFrame=void 0,void 0===this._rowStart||void 0===this._rowEnd||void 0===this._rowCount)return void this._runRefreshCallbacks();const e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}}},3236:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Terminal=void 0;const s=i(3614),r=i(3656),n=i(3551),o=i(9042),a=i(3730),h=i(1680),c=i(3107),l=i(5744),d=i(2950),_=i(1296),u=i(428),f=i(4269),v=i(5114),p=i(8934),g=i(3230),m=i(9312),S=i(4725),C=i(6731),b=i(8055),w=i(8969),y=i(8460),E=i(844),k=i(6114),L=i(8437),D=i(2584),R=i(7399),x=i(5941),A=i(9074),B=i(2585),T=i(5435),M=i(4567),O=i(779);class P extends w.CoreTerminal{get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}constructor(e={}){super(e),this.browser=k,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this.register(new E.MutableDisposable),this._onCursorMove=this.register(new y.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this.register(new y.EventEmitter),this.onKey=this._onKey.event,this._onRender=this.register(new y.EventEmitter),this.onRender=this._onRender.event,this._onSelectionChange=this.register(new y.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this.register(new y.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this.register(new y.EventEmitter),this.onBell=this._onBell.event,this._onFocus=this.register(new y.EventEmitter),this._onBlur=this.register(new y.EventEmitter),this._onA11yCharEmitter=this.register(new y.EventEmitter),this._onA11yTabEmitter=this.register(new y.EventEmitter),this._onWillOpen=this.register(new y.EventEmitter),this._setup(),this._decorationService=this._instantiationService.createInstance(A.DecorationService),this._instantiationService.setService(B.IDecorationService,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(O.LinkProviderService),this._instantiationService.setService(S.ILinkProviderService,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(a.OscLinkProvider)),this.register(this._inputHandler.onRequestBell((()=>this._onBell.fire()))),this.register(this._inputHandler.onRequestRefreshRows(((e,t)=>this.refresh(e,t)))),this.register(this._inputHandler.onRequestSendFocus((()=>this._reportFocus()))),this.register(this._inputHandler.onRequestReset((()=>this.reset()))),this.register(this._inputHandler.onRequestWindowsOptionsReport((e=>this._reportWindowsOptions(e)))),this.register(this._inputHandler.onColor((e=>this._handleColorEvent(e)))),this.register((0,y.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,y.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,y.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,y.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this.register(this._bufferService.onResize((e=>this._afterResize(e.cols,e.rows)))),this.register((0,E.toDisposable)((()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)})))}_handleColorEvent(e){if(this._themeService)for(const t of e){let e,i="";switch(t.index){case 256:e="foreground",i="10";break;case 257:e="background",i="11";break;case 258:e="cursor",i="12";break;default:e="ansi",i="4;"+t.index}switch(t.type){case 0:const s=b.color.toColorRGB("ansi"===e?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${D.C0.ESC}]${i};${(0,x.toRgbString)(s)}${D.C1_ESCAPED.ST}`);break;case 1:if("ansi"===e)this._themeService.modifyColors((e=>e.ansi[t.index]=b.channels.toColor(...t.color)));else{const i=e;this._themeService.modifyColors((e=>e[i]=b.channels.toColor(...t.color)))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(M.AccessibilityManager,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(D.C0.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(D.C0.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;const e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;const i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,r=t.getWidth(i),n=this._renderService.dimensions.css.cell.width*r,o=this.buffer.y*this._renderService.dimensions.css.cell.height,a=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=a+"px",this.textarea.style.top=o+"px",this.textarea.style.width=n+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this.register((0,r.addDisposableDomListener)(this.element,"copy",(e=>{this.hasSelection()&&(0,s.copyHandler)(e,this._selectionService)})));const e=e=>(0,s.handlePasteEvent)(e,this.textarea,this.coreService,this.optionsService);this.register((0,r.addDisposableDomListener)(this.textarea,"paste",e)),this.register((0,r.addDisposableDomListener)(this.element,"paste",e)),k.isFirefox?this.register((0,r.addDisposableDomListener)(this.element,"mousedown",(e=>{2===e.button&&(0,s.rightClickHandler)(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))):this.register((0,r.addDisposableDomListener)(this.element,"contextmenu",(e=>{(0,s.rightClickHandler)(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))),k.isLinux&&this.register((0,r.addDisposableDomListener)(this.element,"auxclick",(e=>{1===e.button&&(0,s.moveTextAreaUnderMouseCursor)(e,this.textarea,this.screenElement)})))}_bindKeys(){this.register((0,r.addDisposableDomListener)(this.textarea,"keyup",(e=>this._keyUp(e)),!0)),this.register((0,r.addDisposableDomListener)(this.textarea,"keydown",(e=>this._keyDown(e)),!0)),this.register((0,r.addDisposableDomListener)(this.textarea,"keypress",(e=>this._keyPress(e)),!0)),this.register((0,r.addDisposableDomListener)(this.textarea,"compositionstart",(()=>this._compositionHelper.compositionstart()))),this.register((0,r.addDisposableDomListener)(this.textarea,"compositionupdate",(e=>this._compositionHelper.compositionupdate(e)))),this.register((0,r.addDisposableDomListener)(this.textarea,"compositionend",(()=>this._compositionHelper.compositionend()))),this.register((0,r.addDisposableDomListener)(this.textarea,"input",(e=>this._inputEvent(e)),!0)),this.register(this.onRender((()=>this._compositionHelper.updateCompositionElements())))}open(e){if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService)return void(this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView));this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);const t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this._viewportScrollArea=this._document.createElement("div"),this._viewportScrollArea.classList.add("xterm-scroll-area"),this._viewportElement.appendChild(this._viewportScrollArea),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this.register((0,r.addDisposableDomListener)(this.screenElement,"mousemove",(e=>this.updateCursorStyle(e)))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement),this.textarea=this._document.createElement("textarea"),this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",o.promptLabel),k.isChromeOS||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._coreBrowserService=this.register(this._instantiationService.createInstance(v.CoreBrowserService,this.textarea,e.ownerDocument.defaultView??window,this._document??"undefined"!=typeof window?window.document:null)),this._instantiationService.setService(S.ICoreBrowserService,this._coreBrowserService),this.register((0,r.addDisposableDomListener)(this.textarea,"focus",(e=>this._handleTextAreaFocus(e)))),this.register((0,r.addDisposableDomListener)(this.textarea,"blur",(()=>this._handleTextAreaBlur()))),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(u.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(S.ICharSizeService,this._charSizeService),this._themeService=this._instantiationService.createInstance(C.ThemeService),this._instantiationService.setService(S.IThemeService,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(f.CharacterJoinerService),this._instantiationService.setService(S.ICharacterJoinerService,this._characterJoinerService),this._renderService=this.register(this._instantiationService.createInstance(g.RenderService,this.rows,this.screenElement)),this._instantiationService.setService(S.IRenderService,this._renderService),this.register(this._renderService.onRenderedViewportChange((e=>this._onRender.fire(e)))),this.onResize((e=>this._renderService.resize(e.cols,e.rows))),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(d.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(p.MouseService),this._instantiationService.setService(S.IMouseService,this._mouseService),this.linkifier=this.register(this._instantiationService.createInstance(n.Linkifier,this.screenElement)),this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this.viewport=this._instantiationService.createInstance(h.Viewport,this._viewportElement,this._viewportScrollArea),this.viewport.onRequestScrollLines((e=>this.scrollLines(e.amount,e.suppressScrollEvent,1))),this.register(this._inputHandler.onRequestSyncScrollBar((()=>this.viewport.syncScrollArea()))),this.register(this.viewport),this.register(this.onCursorMove((()=>{this._renderService.handleCursorMove(),this._syncTextArea()}))),this.register(this.onResize((()=>this._renderService.handleResize(this.cols,this.rows)))),this.register(this.onBlur((()=>this._renderService.handleBlur()))),this.register(this.onFocus((()=>this._renderService.handleFocus()))),this.register(this._renderService.onDimensionsChange((()=>this.viewport.syncScrollArea()))),this._selectionService=this.register(this._instantiationService.createInstance(m.SelectionService,this.element,this.screenElement,this.linkifier)),this._instantiationService.setService(S.ISelectionService,this._selectionService),this.register(this._selectionService.onRequestScrollLines((e=>this.scrollLines(e.amount,e.suppressScrollEvent)))),this.register(this._selectionService.onSelectionChange((()=>this._onSelectionChange.fire()))),this.register(this._selectionService.onRequestRedraw((e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode)))),this.register(this._selectionService.onLinuxMouseSelection((e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()}))),this.register(this._onScroll.event((e=>{this.viewport.syncScrollArea(),this._selectionService.refresh()}))),this.register((0,r.addDisposableDomListener)(this._viewportElement,"scroll",(()=>this._selectionService.refresh()))),this.register(this._instantiationService.createInstance(c.BufferDecorationRenderer,this.screenElement)),this.register((0,r.addDisposableDomListener)(this.element,"mousedown",(e=>this._selectionService.handleMouseDown(e)))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(M.AccessibilityManager,this)),this.register(this.optionsService.onSpecificOptionChange("screenReaderMode",(e=>this._handleScreenReaderModeOptionChange(e)))),this.options.overviewRulerWidth&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(l.OverviewRulerRenderer,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRulerWidth",(e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(l.OverviewRulerRenderer,this._viewportElement,this.screenElement)))})),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(_.DomRenderer,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){const e=this,t=this.element;function i(t){const i=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!i)return!1;let s,r;switch(t.overrideType||t.type){case"mousemove":r=32,void 0===t.buttons?(s=3,void 0!==t.button&&(s=t.button<3?t.button:3)):s=1&t.buttons?0:4&t.buttons?1:2&t.buttons?2:3;break;case"mouseup":r=0,s=t.button<3?t.button:3;break;case"mousedown":r=1,s=t.button<3?t.button:3;break;case"wheel":if(e._customWheelEventHandler&&!1===e._customWheelEventHandler(t))return!1;if(0===e.viewport.getLinesScrolled(t))return!1;r=t.deltaY<0?0:1,s=4;break;default:return!1}return!(void 0===r||void 0===s||s>4)&&e.coreMouseService.triggerMouseEvent({col:i.col,row:i.row,x:i.x,y:i.y,button:s,action:r,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}const s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},n={mouseup:e=>(i(e),e.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(e)),wheel:e=>(i(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&i(e)},mousemove:e=>{e.buttons||i(e)}};this.register(this.coreMouseService.onProtocolChange((e=>{e?("debug"===this.optionsService.rawOptions.logLevel&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(e)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),8&e?s.mousemove||(t.addEventListener("mousemove",n.mousemove),s.mousemove=n.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),16&e?s.wheel||(t.addEventListener("wheel",n.wheel,{passive:!1}),s.wheel=n.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),2&e?s.mouseup||(s.mouseup=n.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),4&e?s.mousedrag||(s.mousedrag=n.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)}))),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this.register((0,r.addDisposableDomListener)(t,"mousedown",(e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return i(e),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(e)}))),this.register((0,r.addDisposableDomListener)(t,"wheel",(e=>{if(!s.wheel){if(this._customWheelEventHandler&&!1===this._customWheelEventHandler(e))return!1;if(!this.buffer.hasScrollback){const t=this.viewport.getLinesScrolled(e);if(0===t)return;const i=D.C0.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(e.deltaY<0?"A":"B");let s="";for(let e=0;e<Math.abs(t);e++)s+=i;return this.coreService.triggerDataEvent(s,!0),this.cancel(e,!0)}return this.viewport.handleWheel(e)?this.cancel(e):void 0}}),{passive:!1})),this.register((0,r.addDisposableDomListener)(t,"touchstart",(e=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchStart(e),this.cancel(e)}),{passive:!0})),this.register((0,r.addDisposableDomListener)(t,"touchmove",(e=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchMove(e)?void 0:this.cancel(e)}),{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t,i=0){1===i?(super.scrollLines(e,t,i),this.refresh(0,this.rows-1)):this.viewport?.scrollLines(e)}paste(e){(0,s.paste)(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");const t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;const t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(),!1;t||"Dead"!==e.key&&"AltGraph"!==e.key||(this._unprocessedDeadKey=!0);const i=(0,R.evaluateKeyboardEvent)(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),3===i.type||2===i.type){const t=this.rows-1;return this.scrollLines(2===i.type?-t:t),this.cancel(e,!0)}return 1===i.type&&this.selectAll(),!!this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key||!!(e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&1===e.key.length&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):(i.key!==D.C0.ETX&&i.key!==D.C0.CR||(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey?this.cancel(e,!0):void(this._keyDownHandled=!0))))}_isThirdLevelShift(e,t){const i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return"keypress"===t.type?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e)||(function(e){return 16===e.keyCode||17===e.keyCode||18===e.keyCode}(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled)return!1;if(this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(null===e.which||void 0===e.which)t=e.keyCode;else{if(0===e.which||0===e.charCode)return!1;t=e.which}return!(!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)||(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,0))}_inputEvent(e){if(e.data&&"insertText"===e.inputType&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;const t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e!==this.cols||t!==this.rows?super.resize(e,t):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(e,t){this._charSizeService?.measure(),this.viewport?.syncScrollArea(!0)}clear(){if(0!==this.buffer.ybase||0!==this.buffer.y){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(L.DEFAULT_ATTR_DATA));this._onScroll.fire({position:this.buffer.ydisp,source:0}),this.viewport?.reset(),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;const e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this.viewport?.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains("focus")?this.coreService.triggerDataEvent(D.C0.ESC+"[I"):this.coreService.triggerDataEvent(D.C0.ESC+"[O")}_reportWindowsOptions(e){if(this._renderService)switch(e){case T.WindowsOptionsReportType.GET_WIN_SIZE_PIXELS:const e=this._renderService.dimensions.css.canvas.width.toFixed(0),t=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${D.C0.ESC}[4;${t};${e}t`);break;case T.WindowsOptionsReportType.GET_CELL_SIZE_PIXELS:const i=this._renderService.dimensions.css.cell.width.toFixed(0),s=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${D.C0.ESC}[6;${s};${i}t`)}}cancel(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1}}t.Terminal=P},9924:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeBasedDebouncer=void 0,t.TimeBasedDebouncer=class{constructor(e,t=1e3){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,i){this._rowCount=i,e=void 0!==e?e:0,t=void 0!==t?t:this._rowCount-1,this._rowStart=void 0!==this._rowStart?Math.min(this._rowStart,e):e,this._rowEnd=void 0!==this._rowEnd?Math.max(this._rowEnd,t):t;const s=Date.now();if(s-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){const e=s-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout((()=>{this._lastRefreshMs=Date.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0}),t)}}_innerRefresh(){if(void 0===this._rowStart||void 0===this._rowEnd||void 0===this._rowCount)return;const e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}}},1680:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.Viewport=void 0;const n=i(3656),o=i(4725),a=i(8460),h=i(844),c=i(2585);let l=t.Viewport=class extends h.Disposable{constructor(e,t,i,s,r,o,h,c){super(),this._viewportElement=e,this._scrollArea=t,this._bufferService=i,this._optionsService=s,this._charSizeService=r,this._renderService=o,this._coreBrowserService=h,this.scrollBarWidth=0,this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._wheelPartialScroll=0,this._refreshAnimationFrame=null,this._ignoreNextScrollEvent=!1,this._smoothScrollState={startTime:0,origin:-1,target:-1},this._onRequestScrollLines=this.register(new a.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this.scrollBarWidth=this._viewportElement.offsetWidth-this._scrollArea.offsetWidth||15,this.register((0,n.addDisposableDomListener)(this._viewportElement,"scroll",this._handleScroll.bind(this))),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((e=>this._activeBuffer=e.activeBuffer))),this._renderDimensions=this._renderService.dimensions,this.register(this._renderService.onDimensionsChange((e=>this._renderDimensions=e))),this._handleThemeChange(c.colors),this.register(c.onChangeColors((e=>this._handleThemeChange(e)))),this.register(this._optionsService.onSpecificOptionChange("scrollback",(()=>this.syncScrollArea()))),setTimeout((()=>this.syncScrollArea()))}_handleThemeChange(e){this._viewportElement.style.backgroundColor=e.background.css}reset(){this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._coreBrowserService.window.requestAnimationFrame((()=>this.syncScrollArea()))}_refresh(e){if(e)return this._innerRefresh(),void(null!==this._refreshAnimationFrame&&this._coreBrowserService.window.cancelAnimationFrame(this._refreshAnimationFrame));null===this._refreshAnimationFrame&&(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh())))}_innerRefresh(){if(this._charSizeService.height>0){this._currentRowHeight=this._renderDimensions.device.cell.height/this._coreBrowserService.dpr,this._currentDeviceCellHeight=this._renderDimensions.device.cell.height,this._lastRecordedViewportHeight=this._viewportElement.offsetHeight;const e=Math.round(this._currentRowHeight*this._lastRecordedBufferLength)+(this._lastRecordedViewportHeight-this._renderDimensions.css.canvas.height);this._lastRecordedBufferHeight!==e&&(this._lastRecordedBufferHeight=e,this._scrollArea.style.height=this._lastRecordedBufferHeight+"px")}const e=this._bufferService.buffer.ydisp*this._currentRowHeight;this._viewportElement.scrollTop!==e&&(this._ignoreNextScrollEvent=!0,this._viewportElement.scrollTop=e),this._refreshAnimationFrame=null}syncScrollArea(e=!1){if(this._lastRecordedBufferLength!==this._bufferService.buffer.lines.length)return this._lastRecordedBufferLength=this._bufferService.buffer.lines.length,void this._refresh(e);this._lastRecordedViewportHeight===this._renderService.dimensions.css.canvas.height&&this._lastScrollTop===this._activeBuffer.ydisp*this._currentRowHeight&&this._renderDimensions.device.cell.height===this._currentDeviceCellHeight||this._refresh(e)}_handleScroll(e){if(this._lastScrollTop=this._viewportElement.scrollTop,!this._viewportElement.offsetParent)return;if(this._ignoreNextScrollEvent)return this._ignoreNextScrollEvent=!1,void this._onRequestScrollLines.fire({amount:0,suppressScrollEvent:!0});const t=Math.round(this._lastScrollTop/this._currentRowHeight)-this._bufferService.buffer.ydisp;this._onRequestScrollLines.fire({amount:t,suppressScrollEvent:!0})}_smoothScroll(){if(this._isDisposed||-1===this._smoothScrollState.origin||-1===this._smoothScrollState.target)return;const e=this._smoothScrollPercent();this._viewportElement.scrollTop=this._smoothScrollState.origin+Math.round(e*(this._smoothScrollState.target-this._smoothScrollState.origin)),e<1?this._coreBrowserService.window.requestAnimationFrame((()=>this._smoothScroll())):this._clearSmoothScrollState()}_smoothScrollPercent(){return this._optionsService.rawOptions.smoothScrollDuration&&this._smoothScrollState.startTime?Math.max(Math.min((Date.now()-this._smoothScrollState.startTime)/this._optionsService.rawOptions.smoothScrollDuration,1),0):1}_clearSmoothScrollState(){this._smoothScrollState.startTime=0,this._smoothScrollState.origin=-1,this._smoothScrollState.target=-1}_bubbleScroll(e,t){const i=this._viewportElement.scrollTop+this._lastRecordedViewportHeight;return!(t<0&&0!==this._viewportElement.scrollTop||t>0&&i<this._lastRecordedBufferHeight)||(e.cancelable&&e.preventDefault(),!1)}handleWheel(e){const t=this._getPixelsScrolled(e);return 0!==t&&(this._optionsService.rawOptions.smoothScrollDuration?(this._smoothScrollState.startTime=Date.now(),this._smoothScrollPercent()<1?(this._smoothScrollState.origin=this._viewportElement.scrollTop,-1===this._smoothScrollState.target?this._smoothScrollState.target=this._viewportElement.scrollTop+t:this._smoothScrollState.target+=t,this._smoothScrollState.target=Math.max(Math.min(this._smoothScrollState.target,this._viewportElement.scrollHeight),0),this._smoothScroll()):this._clearSmoothScrollState()):this._viewportElement.scrollTop+=t,this._bubbleScroll(e,t))}scrollLines(e){if(0!==e)if(this._optionsService.rawOptions.smoothScrollDuration){const t=e*this._currentRowHeight;this._smoothScrollState.startTime=Date.now(),this._smoothScrollPercent()<1?(this._smoothScrollState.origin=this._viewportElement.scrollTop,this._smoothScrollState.target=this._smoothScrollState.origin+t,this._smoothScrollState.target=Math.max(Math.min(this._smoothScrollState.target,this._viewportElement.scrollHeight),0),this._smoothScroll()):this._clearSmoothScrollState()}else this._onRequestScrollLines.fire({amount:e,suppressScrollEvent:!1})}_getPixelsScrolled(e){if(0===e.deltaY||e.shiftKey)return 0;let t=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_LINE?t*=this._currentRowHeight:e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(t*=this._currentRowHeight*this._bufferService.rows),t}getBufferElements(e,t){let i,s="";const r=[],n=t??this._bufferService.buffer.lines.length,o=this._bufferService.buffer.lines;for(let t=e;t<n;t++){const e=o.get(t);if(!e)continue;const n=o.get(t+1)?.isWrapped;if(s+=e.translateToString(!n),!n||t===o.length-1){const e=document.createElement("div");e.textContent=s,r.push(e),s.length>0&&(i=e),s=""}}return{bufferElements:r,cursorElement:i}}getLinesScrolled(e){if(0===e.deltaY||e.shiftKey)return 0;let t=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(t/=this._currentRowHeight+0,this._wheelPartialScroll+=t,t=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(t*=this._bufferService.rows),t}_applyScrollModifier(e,t){const i=this._optionsService.rawOptions.fastScrollModifier;return"alt"===i&&t.altKey||"ctrl"===i&&t.ctrlKey||"shift"===i&&t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}handleTouchStart(e){this._lastTouchY=e.touches[0].pageY}handleTouchMove(e){const t=this._lastTouchY-e.touches[0].pageY;return this._lastTouchY=e.touches[0].pageY,0!==t&&(this._viewportElement.scrollTop+=t,this._bubbleScroll(e,t))}};t.Viewport=l=s([r(2,c.IBufferService),r(3,c.IOptionsService),r(4,o.ICharSizeService),r(5,o.IRenderService),r(6,o.ICoreBrowserService),r(7,o.IThemeService)],l)},3107:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.BufferDecorationRenderer=void 0;const n=i(4725),o=i(844),a=i(2585);let h=t.BufferDecorationRenderer=class extends o.Disposable{constructor(e,t,i,s,r){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=s,this._renderService=r,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this.register(this._renderService.onRenderedViewportChange((()=>this._doRefreshDecorations()))),this.register(this._renderService.onDimensionsChange((()=>{this._dimensionsChanged=!0,this._queueRefresh()}))),this.register(this._coreBrowserService.onDprChange((()=>this._queueRefresh()))),this.register(this._bufferService.buffers.onBufferActivate((()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt}))),this.register(this._decorationService.onDecorationRegistered((()=>this._queueRefresh()))),this.register(this._decorationService.onDecorationRemoved((e=>this._removeDecoration(e)))),this.register((0,o.toDisposable)((()=>{this._container.remove(),this._decorationElements.clear()})))}_queueRefresh(){void 0===this._animationFrame&&(this._animationFrame=this._renderService.addRefreshCallback((()=>{this._doRefreshDecorations(),this._animationFrame=void 0})))}_doRefreshDecorations(){for(const e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){const t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer","top"===e?.options?.layer),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=(e.options.height||1)*this._renderService.dimensions.css.cell.height+"px",t.style.top=(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+"px",t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;const i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){const t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose((()=>{this._decorationElements.delete(e),i.remove()}))),i.style.top=t*this._renderService.dimensions.css.cell.height+"px",i.style.display=this._altBufferIsActive?"none":"block",e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;const i=e.options.x??0;"right"===(e.options.anchor||"left")?t.style.right=i?i*this._renderService.dimensions.css.cell.width+"px":"":t.style.left=i?i*this._renderService.dimensions.css.cell.width+"px":""}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};t.BufferDecorationRenderer=h=s([r(1,a.IBufferService),r(2,n.ICoreBrowserService),r(3,a.IDecorationService),r(4,n.IRenderService)],h)},5871:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorZoneStore=void 0,t.ColorZoneStore=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(const t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position))return void this._addLineToZone(t,e.marker.line)}if(this._zonePoolIndex<this._zonePool.length)return this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,void this._zones.push(this._zonePool[this._zonePoolIndex++]);this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}}},5744:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OverviewRulerRenderer=void 0;const n=i(5871),o=i(4725),a=i(844),h=i(2585),c={full:0,left:0,center:0,right:0},l={full:0,left:0,center:0,right:0},d={full:0,left:0,center:0,right:0};let _=t.OverviewRulerRenderer=class extends a.Disposable{get _width(){return this._optionsService.options.overviewRulerWidth||0}constructor(e,t,i,s,r,o,h){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=s,this._renderService=r,this._optionsService=o,this._coreBrowserService=h,this._colorZoneStore=new n.ColorZoneStore,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement);const c=this._canvas.getContext("2d");if(!c)throw new Error("Ctx cannot be null");this._ctx=c,this._registerDecorationListeners(),this._registerBufferChangeListeners(),this._registerDimensionChangeListeners(),this.register((0,a.toDisposable)((()=>{this._canvas?.remove()})))}_registerDecorationListeners(){this.register(this._decorationService.onDecorationRegistered((()=>this._queueRefresh(void 0,!0)))),this.register(this._decorationService.onDecorationRemoved((()=>this._queueRefresh(void 0,!0))))}_registerBufferChangeListeners(){this.register(this._renderService.onRenderedViewportChange((()=>this._queueRefresh()))),this.register(this._bufferService.buffers.onBufferActivate((()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"}))),this.register(this._bufferService.onScroll((()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})))}_registerDimensionChangeListeners(){this.register(this._renderService.onRender((()=>{this._containerHeight&&this._containerHeight===this._screenElement.clientHeight||(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)}))),this.register(this._optionsService.onSpecificOptionChange("overviewRulerWidth",(()=>this._queueRefresh(!0)))),this.register(this._coreBrowserService.onDprChange((()=>this._queueRefresh(!0)))),this._queueRefresh(!0)}_refreshDrawConstants(){const e=Math.floor(this._canvas.width/3),t=Math.ceil(this._canvas.width/3);l.full=this._canvas.width,l.left=e,l.center=t,l.right=e,this._refreshDrawHeightConstants(),d.full=0,d.left=0,d.center=l.left,d.right=l.left+l.center}_refreshDrawHeightConstants(){c.full=Math.round(2*this._coreBrowserService.dpr);const e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);c.left=t,c.center=t,c.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*c.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*c.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*c.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*c.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(const e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1;const e=this._colorZoneStore.zones;for(const t of e)"full"!==t.position&&this._renderColorZone(t);for(const t of e)"full"===t.position&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(d[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-c[e.position||"full"]/2),l[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+c[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,void 0===this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>{this._refreshDecorations(),this._animationFrame=void 0})))}};t.OverviewRulerRenderer=_=s([r(2,h.IBufferService),r(3,h.IDecorationService),r(4,o.IRenderService),r(5,h.IOptionsService),r(6,o.ICoreBrowserService)],_)},2950:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CompositionHelper=void 0;const n=i(4725),o=i(2585),a=i(2584);let h=t.CompositionHelper=class{get isComposing(){return this._isComposing}constructor(e,t,i,s,r,n){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=r,this._renderService=n,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout((()=>{this._compositionPosition.end=this._textarea.value.length}),0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(229===e.keyCode)return!1;if(16===e.keyCode||17===e.keyCode||18===e.keyCode)return!1;this._finalizeComposition(!1)}return 229!==e.keyCode||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){const e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout((()=>{if(this._isSendingComposition){let t;this._isSendingComposition=!1,e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,e.end):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}}),0)}else{this._isSendingComposition=!1;const e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){const e=this._textarea.value;setTimeout((()=>{if(!this._isComposing){const t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.length<e.length?this._coreService.triggerDataEvent(`${a.C0.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}}),0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){const e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,i=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,s=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=s+"px",this._compositionView.style.top=i+"px",this._compositionView.style.height=t+"px",this._compositionView.style.lineHeight=t+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";const r=this._compositionView.getBoundingClientRect();this._textarea.style.left=s+"px",this._textarea.style.top=i+"px",this._textarea.style.width=Math.max(r.width,1)+"px",this._textarea.style.height=Math.max(r.height,1)+"px",this._textarea.style.lineHeight=r.height+"px"}e||setTimeout((()=>this.updateCompositionElements(!0)),0)}}};t.CompositionHelper=h=s([r(2,o.IBufferService),r(3,o.IOptionsService),r(4,o.ICoreService),r(5,n.IRenderService)],h)},9806:(e,t)=>{function i(e,t,i){const s=i.getBoundingClientRect(),r=e.getComputedStyle(i),n=parseInt(r.getPropertyValue("padding-left")),o=parseInt(r.getPropertyValue("padding-top"));return[t.clientX-s.left-n,t.clientY-s.top-o]}Object.defineProperty(t,"__esModule",{value:!0}),t.getCoords=t.getCoordsRelativeToElement=void 0,t.getCoordsRelativeToElement=i,t.getCoords=function(e,t,s,r,n,o,a,h,c){if(!o)return;const l=i(e,t,s);return l?(l[0]=Math.ceil((l[0]+(c?a/2:0))/a),l[1]=Math.ceil(l[1]/h),l[0]=Math.min(Math.max(l[0],1),r+(c?1:0)),l[1]=Math.min(Math.max(l[1],1),n),l):void 0}},9504:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.moveToCellSequence=void 0;const s=i(2584);function r(e,t,i,s){const r=e-n(e,i),a=t-n(t,i),l=Math.abs(r-a)-function(e,t,i){let s=0;const r=e-n(e,i),a=t-n(t,i);for(let n=0;n<Math.abs(r-a);n++){const a="A"===o(e,t)?-1:1,h=i.buffer.lines.get(r+a*n);h?.isWrapped&&s++}return s}(e,t,i);return c(l,h(o(e,t),s))}function n(e,t){let i=0,s=t.buffer.lines.get(e),r=s?.isWrapped;for(;r&&e>=0&&e<t.rows;)i++,s=t.buffer.lines.get(--e),r=s?.isWrapped;return i}function o(e,t){return e>t?"A":"B"}function a(e,t,i,s,r,n){let o=e,a=t,h="";for(;o!==i||a!==s;)o+=r?1:-1,r&&o>n.cols-1?(h+=n.buffer.translateBufferLineToString(a,!1,e,o),o=0,e=0,a++):!r&&o<0&&(h+=n.buffer.translateBufferLineToString(a,!1,0,e+1),o=n.cols-1,e=o,a--);return h+n.buffer.translateBufferLineToString(a,!1,e,o)}function h(e,t){const i=t?"O":"[";return s.C0.ESC+i+e}function c(e,t){e=Math.floor(e);let i="";for(let s=0;s<e;s++)i+=t;return i}t.moveToCellSequence=function(e,t,i,s){const o=i.buffer.x,l=i.buffer.y;if(!i.buffer.hasScrollback)return function(e,t,i,s,o,l){return 0===r(t,s,o,l).length?"":c(a(e,t,e,t-n(t,o),!1,o).length,h("D",l))}(o,l,0,t,i,s)+r(l,t,i,s)+function(e,t,i,s,o,l){let d;d=r(t,s,o,l).length>0?s-n(s,o):t;const _=s,u=function(e,t,i,s,o,a){let h;return h=r(i,s,o,a).length>0?s-n(s,o):t,e<i&&h<=s||e>=i&&h<s?"C":"D"}(e,t,i,s,o,l);return c(a(e,d,i,_,"C"===u,o).length,h(u,l))}(o,l,e,t,i,s);let d;if(l===t)return d=o>e?"D":"C",c(Math.abs(o-e),h(d,s));d=l>t?"D":"C";const _=Math.abs(l-t);return c(function(e,t){return t.cols-e}(l>t?e:o,i)+(_-1)*i.cols+1+((l>t?o:e)-1),h(d,s))}},1296:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.DomRenderer=void 0;const n=i(3787),o=i(2550),a=i(2223),h=i(6171),c=i(6052),l=i(4725),d=i(8055),_=i(8460),u=i(844),f=i(2585),v="xterm-dom-renderer-owner-",p="xterm-rows",g="xterm-fg-",m="xterm-bg-",S="xterm-focus",C="xterm-selection";let b=1,w=t.DomRenderer=class extends u.Disposable{constructor(e,t,i,s,r,a,l,d,f,g,m,S,w){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=s,this._viewportElement=r,this._helperContainer=a,this._linkifier2=l,this._charSizeService=f,this._optionsService=g,this._bufferService=m,this._coreBrowserService=S,this._themeService=w,this._terminalClass=b++,this._rowElements=[],this._selectionRenderModel=(0,c.createSelectionRenderModel)(),this.onRequestRedraw=this.register(new _.EventEmitter).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(p),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(C),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=(0,h.createRenderDimensions)(),this._updateDimensions(),this.register(this._optionsService.onOptionChange((()=>this._handleOptionsChanged()))),this.register(this._themeService.onChangeColors((e=>this._injectCss(e)))),this._injectCss(this._themeService.colors),this._rowFactory=d.createInstance(n.DomRendererRowFactory,document),this._element.classList.add(v+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this.register(this._linkifier2.onShowLinkUnderline((e=>this._handleLinkHover(e)))),this.register(this._linkifier2.onHideLinkUnderline((e=>this._handleLinkLeave(e)))),this.register((0,u.toDisposable)((()=>{this._element.classList.remove(v+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()}))),this._widthCache=new o.WidthCache(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){const e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(const e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));const t=`${this._terminalSelector} .${p} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${p} { color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${p} .xterm-dim { color: ${d.color.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;const i=`blink_underline_${this._terminalClass}`,s=`blink_bar_${this._terminalClass}`,r=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${s} { 50% { box-shadow: none; }}`,t+=`@keyframes ${r} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${p}.${S} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${p}.${S} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${p}.${S} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${p} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${p} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${p} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${p} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${p} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${C} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${C} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${C} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(const[i,s]of e.ansi.entries())t+=`${this._terminalSelector} .${g}${i} { color: ${s.css}; }${this._terminalSelector} .${g}${i}.xterm-dim { color: ${d.color.multiplyOpacity(s,.5).css}; }${this._terminalSelector} .${m}${i} { background-color: ${s.css}; }`;t+=`${this._terminalSelector} .${g}${a.INVERTED_DEFAULT_COLOR} { color: ${d.color.opaque(e.background).css}; }${this._terminalSelector} .${g}${a.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${d.color.multiplyOpacity(d.color.opaque(e.background),.5).css}; }${this._terminalSelector} .${m}${a.INVERTED_DEFAULT_COLOR} { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){const e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){const e=this._document.createElement("div");this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(S),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(S),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t)return;this._selectionRenderModel.update(this._terminal,e,t,i);const s=this._selectionRenderModel.viewportStartRow,r=this._selectionRenderModel.viewportEndRow,n=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow;if(n>=this._bufferService.rows||o<0)return;const a=this._document.createDocumentFragment();if(i){const i=e[0]>t[0];a.appendChild(this._createSelectionElement(n,i?t[0]:e[0],i?e[0]:t[0],o-n+1))}else{const i=s===n?e[0]:0,h=n===r?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(n,i,h));const c=o-n-1;if(a.appendChild(this._createSelectionElement(n+1,0,this._bufferService.cols,c)),n!==o){const e=r===o?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(a)}_createSelectionElement(e,t,i,s=1){const r=this._document.createElement("div"),n=t*this.dimensions.css.cell.width;let o=this.dimensions.css.cell.width*(i-t);return n+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-n),r.style.height=s*this.dimensions.css.cell.height+"px",r.style.top=e*this.dimensions.css.cell.height+"px",r.style.left=`${n}px`,r.style.width=`${o}px`,r}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(const e of this._rowElements)e.replaceChildren()}renderRows(e,t){const i=this._bufferService.buffer,s=i.ybase+i.y,r=Math.min(i.x,this._bufferService.cols-1),n=this._optionsService.rawOptions.cursorBlink,o=this._optionsService.rawOptions.cursorStyle,a=this._optionsService.rawOptions.cursorInactiveStyle;for(let h=e;h<=t;h++){const e=h+i.ydisp,t=this._rowElements[h],c=i.lines.get(e);if(!t||!c)break;t.replaceChildren(...this._rowFactory.createRow(c,e,e===s,o,a,r,n,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${v}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,r,n){i<0&&(e=0),s<0&&(t=0);const o=this._bufferService.rows-1;i=Math.max(Math.min(i,o),0),s=Math.max(Math.min(s,o),0),r=Math.min(r,this._bufferService.cols);const a=this._bufferService.buffer,h=a.ybase+a.y,c=Math.min(a.x,r-1),l=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,_=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=i;o<=s;++o){const u=o+a.ydisp,f=this._rowElements[o],v=a.lines.get(u);if(!f||!v)break;f.replaceChildren(...this._rowFactory.createRow(v,u,u===h,d,_,c,l,this.dimensions.css.cell.width,this._widthCache,n?o===i?e:0:-1,n?(o===s?t:r)-1:-1))}}};t.DomRenderer=w=s([r(7,f.IInstantiationService),r(8,l.ICharSizeService),r(9,f.IOptionsService),r(10,f.IBufferService),r(11,l.ICoreBrowserService),r(12,l.IThemeService)],w)},3787:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.DomRendererRowFactory=void 0;const n=i(2223),o=i(643),a=i(511),h=i(2585),c=i(8055),l=i(4725),d=i(4269),_=i(6171),u=i(3734);let f=t.DomRendererRowFactory=class{constructor(e,t,i,s,r,n,o){this._document=e,this._characterJoinerService=t,this._optionsService=i,this._coreBrowserService=s,this._coreService=r,this._decorationService=n,this._themeService=o,this._workCell=new a.CellData,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,i){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=i}createRow(e,t,i,s,r,a,h,l,_,f,p){const g=[],m=this._characterJoinerService.getJoinedCharacters(t),S=this._themeService.colors;let C,b=e.getNoBgTrimmedLength();i&&b<a+1&&(b=a+1);let w=0,y="",E=0,k=0,L=0,D=!1,R=0,x=!1,A=0;const B=[],T=-1!==f&&-1!==p;for(let M=0;M<b;M++){e.loadCell(M,this._workCell);let b=this._workCell.getWidth();if(0===b)continue;let O=!1,P=M,I=this._workCell;if(m.length>0&&M===m[0][0]){O=!0;const t=m.shift();I=new d.JoinedCellData(this._workCell,e.translateToString(!0,t[0],t[1]),t[1]-t[0]),P=t[1]-1,b=I.getWidth()}const H=this._isCellInSelection(M,t),F=i&&M===a,W=T&&M>=f&&M<=p;let U=!1;this._decorationService.forEachDecorationAtCell(M,t,void 0,(e=>{U=!0}));let N=I.getChars()||o.WHITESPACE_CELL_CHAR;if(" "===N&&(I.isUnderline()||I.isOverline())&&(N=" "),A=b*l-_.get(N,I.isBold(),I.isItalic()),C){if(w&&(H&&x||!H&&!x&&I.bg===E)&&(H&&x&&S.selectionForeground||I.fg===k)&&I.extended.ext===L&&W===D&&A===R&&!F&&!O&&!U){I.isInvisible()?y+=o.WHITESPACE_CELL_CHAR:y+=N,w++;continue}w&&(C.textContent=y),C=this._document.createElement("span"),w=0,y=""}else C=this._document.createElement("span");if(E=I.bg,k=I.fg,L=I.extended.ext,D=W,R=A,x=H,O&&a>=M&&a<=P&&(a=M),!this._coreService.isCursorHidden&&F&&this._coreService.isCursorInitialized)if(B.push("xterm-cursor"),this._coreBrowserService.isFocused)h&&B.push("xterm-cursor-blink"),B.push("bar"===s?"xterm-cursor-bar":"underline"===s?"xterm-cursor-underline":"xterm-cursor-block");else if(r)switch(r){case"outline":B.push("xterm-cursor-outline");break;case"block":B.push("xterm-cursor-block");break;case"bar":B.push("xterm-cursor-bar");break;case"underline":B.push("xterm-cursor-underline")}if(I.isBold()&&B.push("xterm-bold"),I.isItalic()&&B.push("xterm-italic"),I.isDim()&&B.push("xterm-dim"),y=I.isInvisible()?o.WHITESPACE_CELL_CHAR:I.getChars()||o.WHITESPACE_CELL_CHAR,I.isUnderline()&&(B.push(`xterm-underline-${I.extended.underlineStyle}`)," "===y&&(y=" "),!I.isUnderlineColorDefault()))if(I.isUnderlineColorRGB())C.style.textDecorationColor=`rgb(${u.AttributeData.toColorRGB(I.getUnderlineColor()).join(",")})`;else{let e=I.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&I.isBold()&&e<8&&(e+=8),C.style.textDecorationColor=S.ansi[e].css}I.isOverline()&&(B.push("xterm-overline")," "===y&&(y=" ")),I.isStrikethrough()&&B.push("xterm-strikethrough"),W&&(C.style.textDecoration="underline");let $=I.getFgColor(),j=I.getFgColorMode(),z=I.getBgColor(),K=I.getBgColorMode();const q=!!I.isInverse();if(q){const e=$;$=z,z=e;const t=j;j=K,K=t}let V,G,X,J=!1;switch(this._decorationService.forEachDecorationAtCell(M,t,void 0,(e=>{"top"!==e.options.layer&&J||(e.backgroundColorRGB&&(K=50331648,z=e.backgroundColorRGB.rgba>>8&16777215,V=e.backgroundColorRGB),e.foregroundColorRGB&&(j=50331648,$=e.foregroundColorRGB.rgba>>8&16777215,G=e.foregroundColorRGB),J="top"===e.options.layer)})),!J&&H&&(V=this._coreBrowserService.isFocused?S.selectionBackgroundOpaque:S.selectionInactiveBackgroundOpaque,z=V.rgba>>8&16777215,K=50331648,J=!0,S.selectionForeground&&(j=50331648,$=S.selectionForeground.rgba>>8&16777215,G=S.selectionForeground)),J&&B.push("xterm-decoration-top"),K){case 16777216:case 33554432:X=S.ansi[z],B.push(`xterm-bg-${z}`);break;case 50331648:X=c.channels.toColor(z>>16,z>>8&255,255&z),this._addStyle(C,`background-color:#${v((z>>>0).toString(16),"0",6)}`);break;default:q?(X=S.foreground,B.push(`xterm-bg-${n.INVERTED_DEFAULT_COLOR}`)):X=S.background}switch(V||I.isDim()&&(V=c.color.multiplyOpacity(X,.5)),j){case 16777216:case 33554432:I.isBold()&&$<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&($+=8),this._applyMinimumContrast(C,X,S.ansi[$],I,V,void 0)||B.push(`xterm-fg-${$}`);break;case 50331648:const e=c.channels.toColor($>>16&255,$>>8&255,255&$);this._applyMinimumContrast(C,X,e,I,V,G)||this._addStyle(C,`color:#${v($.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(C,X,S.foreground,I,V,G)||q&&B.push(`xterm-fg-${n.INVERTED_DEFAULT_COLOR}`)}B.length&&(C.className=B.join(" "),B.length=0),F||O||U?C.textContent=y:w++,A!==this.defaultSpacing&&(C.style.letterSpacing=`${A}px`),g.push(C),M=P}return C&&w&&(C.textContent=y),g}_applyMinimumContrast(e,t,i,s,r,n){if(1===this._optionsService.rawOptions.minimumContrastRatio||(0,_.treatGlyphAsBackgroundColor)(s.getCode()))return!1;const o=this._getContrastCache(s);let a;if(r||n||(a=o.getColor(t.rgba,i.rgba)),void 0===a){const e=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);a=c.color.ensureContrastRatio(r||t,n||i,e),o.setColor((r||t).rgba,(n||i).rgba,a??null)}return!!a&&(this._addStyle(e,`color:${a.css}`),!0)}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){const i=this._selectionStart,s=this._selectionEnd;return!(!i||!s)&&(this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e<s[0]&&t<=s[1]:e<i[0]&&t>=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t<s[1]||i[1]===s[1]&&t===i[1]&&e>=i[0]&&e<s[0]||i[1]<s[1]&&t===s[1]&&e<s[0]||i[1]<s[1]&&t===i[1]&&e>=i[0])}};function v(e,t,i){for(;e.length<i;)e=t+e;return e}t.DomRendererRowFactory=f=s([r(1,l.ICharacterJoinerService),r(2,h.IOptionsService),r(3,l.ICoreBrowserService),r(4,h.ICoreService),r(5,h.IDecorationService),r(6,l.IThemeService)],f)},2550:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WidthCache=void 0,t.WidthCache=class{constructor(e,t){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=e.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";const i=e.createElement("span");i.classList.add("xterm-char-measure-element");const s=e.createElement("span");s.classList.add("xterm-char-measure-element"),s.style.fontWeight="bold";const r=e.createElement("span");r.classList.add("xterm-char-measure-element"),r.style.fontStyle="italic";const n=e.createElement("span");n.classList.add("xterm-char-measure-element"),n.style.fontWeight="bold",n.style.fontStyle="italic",this._measureElements=[i,s,r,n],this._container.appendChild(i),this._container.appendChild(s),this._container.appendChild(r),this._container.appendChild(n),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,i,s){e===this._font&&t===this._fontSize&&i===this._weight&&s===this._weightBold||(this._font=e,this._fontSize=t,this._weight=i,this._weightBold=s,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${i}`,this._measureElements[1].style.fontWeight=`${s}`,this._measureElements[2].style.fontWeight=`${i}`,this._measureElements[3].style.fontWeight=`${s}`,this.clear())}get(e,t,i){let s=0;if(!t&&!i&&1===e.length&&(s=e.charCodeAt(0))<256){if(-9999!==this._flat[s])return this._flat[s];const t=this._measure(e,0);return t>0&&(this._flat[s]=t),t}let r=e;t&&(r+="B"),i&&(r+="I");let n=this._holey.get(r);if(void 0===n){let s=0;t&&(s|=1),i&&(s|=2),n=this._measure(e,s),n>0&&this._holey.set(r,n)}return n}_measure(e,t){const i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}}},2223:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TEXT_BASELINE=t.DIM_OPACITY=t.INVERTED_DEFAULT_COLOR=void 0;const s=i(6114);t.INVERTED_DEFAULT_COLOR=257,t.DIM_OPACITY=.5,t.TEXT_BASELINE=s.isFirefox||s.isLegacyEdge?"bottom":"ideographic"},6171:(e,t)=>{function i(e){return 57508<=e&&e<=57558}function s(e){return e>=128512&&e<=128591||e>=127744&&e<=128511||e>=128640&&e<=128767||e>=9728&&e<=9983||e>=9984&&e<=10175||e>=65024&&e<=65039||e>=129280&&e<=129535||e>=127462&&e<=127487}Object.defineProperty(t,"__esModule",{value:!0}),t.computeNextVariantOffset=t.createRenderDimensions=t.treatGlyphAsBackgroundColor=t.allowRescaling=t.isEmoji=t.isRestrictedPowerlineGlyph=t.isPowerlineGlyph=t.throwIfFalsy=void 0,t.throwIfFalsy=function(e){if(!e)throw new Error("value must not be falsy");return e},t.isPowerlineGlyph=i,t.isRestrictedPowerlineGlyph=function(e){return 57520<=e&&e<=57527},t.isEmoji=s,t.allowRescaling=function(e,t,r,n){return 1===t&&r>Math.ceil(1.5*n)&&void 0!==e&&e>255&&!s(e)&&!i(e)&&!function(e){return 57344<=e&&e<=63743}(e)},t.treatGlyphAsBackgroundColor=function(e){return i(e)||function(e){return 9472<=e&&e<=9631}(e)},t.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}},t.computeNextVariantOffset=function(e,t,i=0){return(e-(2*Math.round(t)-i))%(2*Math.round(t))}},6052:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createSelectionRenderModel=void 0;class i{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,i,s=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1])return void this.clear();const r=e.buffers.active.ydisp,n=t[1]-r,o=i[1]-r,a=Math.max(n,0),h=Math.min(o,e.rows-1);a>=e.rows||h<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=s,this.viewportStartRow=n,this.viewportEndRow=o,this.viewportCappedStartRow=a,this.viewportCappedEndRow=h,this.startCol=t[0],this.endCol=i[0])}isCellSelected(e,t,i){return!!this.hasSelection&&(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t<this.endCol&&i<=this.viewportCappedEndRow:t<this.startCol&&i>=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&i===this.viewportStartRow&&t>=this.startCol)}}t.createSelectionRenderModel=function(){return new i}},456:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SelectionModel=void 0,t.SelectionModel=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){const e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols==0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){const e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){const e=this.selectionStart,t=this.selectionEnd;return!(!e||!t)&&(e[1]>t[1]||e[1]===t[1]&&e[0]>t[0])}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}}},428:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CharSizeService=void 0;const n=i(2585),o=i(8460),a=i(844);let h=t.CharSizeService=class extends a.Disposable{get hasValidSize(){return this.width>0&&this.height>0}constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this.register(new o.EventEmitter),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this.register(new d(this._optionsService))}catch{this._measureStrategy=this.register(new l(e,t,this._optionsService))}this.register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],(()=>this.measure())))}measure(){const e=this._measureStrategy.measure();e.width===this.width&&e.height===this.height||(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};t.CharSizeService=h=s([r(2,n.IOptionsService)],h);class c extends a.Disposable{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){void 0!==e&&e>0&&void 0!==t&&t>0&&(this._result.width=e,this._result.height=t)}}class l extends c{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}}class d extends c{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");const t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;const e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}}},4269:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CharacterJoinerService=t.JoinedCellData=void 0;const n=i(3734),o=i(643),a=i(511),h=i(2585);class c extends n.AttributeData{constructor(e,t,i){super(),this.content=0,this.combinedData="",this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=i}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t.JoinedCellData=c;let l=t.CharacterJoinerService=class e{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new a.CellData}register(e){const t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(0===this._characterJoiners.length)return[];const t=this._bufferService.buffer.lines.get(e);if(!t||0===t.length)return[];const i=[],s=t.translateToString(!0);let r=0,n=0,a=0,h=t.getFg(0),c=t.getBg(0);for(let e=0;e<t.getTrimmedLength();e++)if(t.loadCell(e,this._workCell),0!==this._workCell.getWidth()){if(this._workCell.fg!==h||this._workCell.bg!==c){if(e-r>1){const e=this._getJoinedRanges(s,a,n,t,r);for(let t=0;t<e.length;t++)i.push(e[t])}r=e,a=n,h=this._workCell.fg,c=this._workCell.bg}n+=this._workCell.getChars().length||o.WHITESPACE_CELL_CHAR.length}if(this._bufferService.cols-r>1){const e=this._getJoinedRanges(s,a,n,t,r);for(let t=0;t<e.length;t++)i.push(e[t])}return i}_getJoinedRanges(t,i,s,r,n){const o=t.substring(i,s);let a=[];try{a=this._characterJoiners[0].handler(o)}catch(e){console.error(e)}for(let t=1;t<this._characterJoiners.length;t++)try{const i=this._characterJoiners[t].handler(o);for(let t=0;t<i.length;t++)e._mergeRanges(a,i[t])}catch(e){console.error(e)}return this._stringRangesToCellRanges(a,r,n),a}_stringRangesToCellRanges(e,t,i){let s=0,r=!1,n=0,a=e[s];if(a){for(let h=i;h<this._bufferService.cols;h++){const i=t.getWidth(h),c=t.getString(h).length||o.WHITESPACE_CELL_CHAR.length;if(0!==i){if(!r&&a[0]<=n&&(a[0]=h,r=!0),a[1]<=n){if(a[1]=h,a=e[++s],!a)break;a[0]<=n?(a[0]=h,r=!0):r=!1}n+=c}}a&&(a[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let i=!1;for(let s=0;s<e.length;s++){const r=e[s];if(i){if(t[1]<=r[0])return e[s-1][1]=t[1],e;if(t[1]<=r[1])return e[s-1][1]=Math.max(t[1],r[1]),e.splice(s,1),e;e.splice(s,1),s--}else{if(t[1]<=r[0])return e.splice(s,0,t),e;if(t[1]<=r[1])return r[0]=Math.min(t[0],r[0]),e;t[0]<r[1]&&(r[0]=Math.min(t[0],r[0]),i=!0)}}return i?e[e.length-1][1]=t[1]:e.push(t),e}};t.CharacterJoinerService=l=s([r(0,h.IBufferService)],l)},5114:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CoreBrowserService=void 0;const s=i(844),r=i(8460),n=i(3656);class o extends s.Disposable{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=new a(this._window),this._onDprChange=this.register(new r.EventEmitter),this.onDprChange=this._onDprChange.event,this._onWindowChange=this.register(new r.EventEmitter),this.onWindowChange=this._onWindowChange.event,this.register(this.onWindowChange((e=>this._screenDprMonitor.setWindow(e)))),this.register((0,r.forwardEvent)(this._screenDprMonitor.onDprChange,this._onDprChange)),this._textarea.addEventListener("focus",(()=>this._isFocused=!0)),this._textarea.addEventListener("blur",(()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return void 0===this._cachedIsFocused&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask((()=>this._cachedIsFocused=void 0))),this._cachedIsFocused}}t.CoreBrowserService=o;class a extends s.Disposable{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this.register(new s.MutableDisposable),this._onDprChange=this.register(new r.EventEmitter),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this.register((0,s.toDisposable)((()=>this.clearListener())))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=(0,n.addDisposableDomListener)(this._parentWindow,"resize",(()=>this._setDprAndFireIfDiffers()))}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){this._resolutionMediaMatchList&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}}},779:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LinkProviderService=void 0;const s=i(844);class r extends s.Disposable{constructor(){super(),this.linkProviders=[],this.register((0,s.toDisposable)((()=>this.linkProviders.length=0)))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{const t=this.linkProviders.indexOf(e);-1!==t&&this.linkProviders.splice(t,1)}}}}t.LinkProviderService=r},8934:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.MouseService=void 0;const n=i(4725),o=i(9806);let a=t.MouseService=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,r){return(0,o.getCoords)(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,r)}getMouseReportCoords(e,t){const i=(0,o.getCoordsRelativeToElement)(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};t.MouseService=a=s([r(0,n.IRenderService),r(1,n.ICharSizeService)],a)},3230:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.RenderService=void 0;const n=i(6193),o=i(4725),a=i(8460),h=i(844),c=i(7226),l=i(2585);let d=t.RenderService=class extends h.Disposable{get dimensions(){return this._renderer.value.dimensions}constructor(e,t,i,s,r,o,l,d){super(),this._rowCount=e,this._charSizeService=s,this._renderer=this.register(new h.MutableDisposable),this._pausedResizeTask=new c.DebouncedIdleTask,this._observerDisposable=this.register(new h.MutableDisposable),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this.register(new a.EventEmitter),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this.register(new a.EventEmitter),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this.register(new a.EventEmitter),this.onRender=this._onRender.event,this._onRefreshRequest=this.register(new a.EventEmitter),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new n.RenderDebouncer(((e,t)=>this._renderRows(e,t)),l),this.register(this._renderDebouncer),this.register(l.onDprChange((()=>this.handleDevicePixelRatioChange()))),this.register(o.onResize((()=>this._fullRefresh()))),this.register(o.buffers.onBufferActivate((()=>this._renderer.value?.clear()))),this.register(i.onOptionChange((()=>this._handleOptionsChanged()))),this.register(this._charSizeService.onCharSizeChange((()=>this.handleCharSizeChanged()))),this.register(r.onDecorationRegistered((()=>this._fullRefresh()))),this.register(r.onDecorationRemoved((()=>this._fullRefresh()))),this.register(i.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],(()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()}))),this.register(i.onMultipleOptionChange(["cursorBlink","cursorStyle"],(()=>this.refreshRows(o.buffer.y,o.buffer.y,!0)))),this.register(d.onChangeColors((()=>this._fullRefresh()))),this._registerIntersectionObserver(l.window,t),this.register(l.onWindowChange((e=>this._registerIntersectionObserver(e,t))))}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){const i=new e.IntersectionObserver((e=>this._handleIntersectionChange(e[e.length-1])),{threshold:0});i.observe(t),this._observerDisposable.value=(0,h.toDisposable)((()=>i.disconnect()))}}_handleIntersectionChange(e){this._isPaused=void 0===e.isIntersecting?0===e.intersectionRatio:!e.isIntersecting,this._isPaused||this._charSizeService.hasValidSize||this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){this._isPaused?this._needsFullRefresh=!0:(i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount))}_renderRows(e,t){this._renderer.value&&(e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0)}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw((e=>this.refreshRows(e.start,e.end,!0))),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set((()=>this._renderer.value?.handleResize(e,t))):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,i){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,this._renderer.value?.handleSelectionChanged(e,t,i)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};t.RenderService=d=s([r(2,l.IOptionsService),r(3,o.ICharSizeService),r(4,l.IDecorationService),r(5,l.IBufferService),r(6,o.ICoreBrowserService),r(7,o.IThemeService)],d)},9312:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.SelectionService=void 0;const n=i(9806),o=i(9504),a=i(456),h=i(4725),c=i(8460),l=i(844),d=i(6114),_=i(4841),u=i(511),f=i(2585),v=String.fromCharCode(160),p=new RegExp(v,"g");let g=t.SelectionService=class extends l.Disposable{constructor(e,t,i,s,r,n,o,h,d){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=r,this._mouseService=n,this._optionsService=o,this._renderService=h,this._coreBrowserService=d,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new u.CellData,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this.register(new c.EventEmitter),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this.register(new c.EventEmitter),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this.register(new c.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this.register(new c.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput((()=>{this.hasSelection&&this.clearSelection()})),this._trimListener=this._bufferService.buffer.lines.onTrim((e=>this._handleTrim(e))),this.register(this._bufferService.buffers.onBufferActivate((e=>this._handleBufferActivate(e)))),this.enable(),this._model=new a.SelectionModel(this._bufferService),this._activeSelectionMode=0,this.register((0,l.toDisposable)((()=>{this._removeMouseDownListeners()})))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){const e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!(!e||!t||e[0]===t[0]&&e[1]===t[1])}get selectionText(){const e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";const i=this._bufferService.buffer,s=[];if(3===this._activeSelectionMode){if(e[0]===t[0])return"";const r=e[0]<t[0]?e[0]:t[0],n=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){const e=i.translateBufferLineToString(o,!0,r,n);s.push(e)}}else{const r=e[1]===t[1]?t[0]:void 0;s.push(i.translateBufferLineToString(e[1],!0,e[0],r));for(let r=e[1]+1;r<=t[1]-1;r++){const e=i.lines.get(r),t=i.translateBufferLineToString(r,!0);e?.isWrapped?s[s.length-1]+=t:s.push(t)}if(e[1]!==t[1]){const e=i.lines.get(t[1]),r=i.translateBufferLineToString(t[1],!0,0,t[0]);e&&e.isWrapped?s[s.length-1]+=r:s.push(r)}}return s.map((e=>e.replace(p," "))).join(d.isWindows?"\r\n":"\n")}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._refresh()))),d.isLinux&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:3===this._activeSelectionMode})}_isClickInSelection(e){const t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!!(i&&s&&t)&&this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){const i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!(!i||!s)&&this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]<i[1]||t[1]===i[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<i[0]||t[1]<i[1]&&e[1]===i[1]&&e[0]<i[0]||t[1]<i[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){const i=this._linkifier.currentLink?.link?.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=(0,_.getRangeLength)(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const s=this._getMouseBufferCoords(e);return!!s&&(this._selectWordAt(s,t),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){const t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=(0,n.getCoordsRelativeToElement)(this._coreBrowserService.window,e,this._screenElement)[1];const i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-50),50),t/=50,t/Math.abs(t)+Math.round(14*t))}shouldForceSelection(e){return d.isMac?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,(2!==e.button||!this.hasSelection)&&0===e.button){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):1===e.detail?this._handleSingleClick(e):2===e.detail?this._handleDoubleClick(e):3===e.detail&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval((()=>this._dragScroll()),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&0===t.hasWidth(this._model.selectionStart[0])&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){const t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(d.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;const t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd)return void this.refresh(!0);2===this._activeSelectionMode?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:1===this._activeSelectionMode&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),3!==this._activeSelectionMode&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const i=this._bufferService.buffer;if(this._model.selectionEnd[1]<i.lines.length){const e=i.lines.get(this._model.selectionEnd[1]);e&&0===e.hasWidth(this._model.selectionEnd[0])&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}t&&t[0]===this._model.selectionEnd[0]&&t[1]===this._model.selectionEnd[1]||this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});const e=this._bufferService.buffer;this._dragScrollAmount>0?(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){const t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<500&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&void 0!==t[0]&&void 0!==t[1]){const e=(0,o.moveToCellSequence)(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,i=!(!e||!t||e[0]===t[0]&&e[1]===t[1]);i?e&&t&&(this._oldSelectionStart&&this._oldSelectionEnd&&e[0]===this._oldSelectionStart[0]&&e[1]===this._oldSelectionStart[1]&&t[0]===this._oldSelectionEnd[0]&&t[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(e,t,i)):this._oldHasSelection&&this._fireOnSelectionChange(e,t,i)}_fireOnSelectionChange(e,t,i){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=i,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim((e=>this._handleTrim(e)))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){const r=e.loadCell(s,this._workCell).getChars().length;0===this._workCell.getWidth()?i--:r>1&&t!==s&&(i+=r-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;const r=this._bufferService.buffer,n=r.lines.get(e[1]);if(!n)return;const o=r.translateBufferLineToString(e[1],!1);let a=this._convertViewportColToCharacterIndex(n,e[0]),h=a;const c=e[0]-a;let l=0,d=0,_=0,u=0;if(" "===o.charAt(a)){for(;a>0&&" "===o.charAt(a-1);)a--;for(;h<o.length&&" "===o.charAt(h+1);)h++}else{let t=e[0],i=e[0];0===n.getWidth(t)&&(l++,t--),2===n.getWidth(i)&&(d++,i++);const s=n.getString(i).length;for(s>1&&(u+=s-1,h+=s-1);t>0&&a>0&&!this._isCharWordSeparator(n.loadCell(t-1,this._workCell));){n.loadCell(t-1,this._workCell);const e=this._workCell.getChars().length;0===this._workCell.getWidth()?(l++,t--):e>1&&(_+=e-1,a-=e-1),a--,t--}for(;i<n.length&&h+1<o.length&&!this._isCharWordSeparator(n.loadCell(i+1,this._workCell));){n.loadCell(i+1,this._workCell);const e=this._workCell.getChars().length;2===this._workCell.getWidth()?(d++,i++):e>1&&(u+=e-1,h+=e-1),h++,i++}}h++;let f=a+c-l+_,v=Math.min(this._bufferService.cols,h-a+l+d-_-u);if(t||""!==o.slice(a,h).trim()){if(i&&0===f&&32!==n.getCodePoint(0)){const t=r.lines.get(e[1]-1);if(t&&n.isWrapped&&32!==t.getCodePoint(this._bufferService.cols-1)){const t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){const e=this._bufferService.cols-t.start;f-=e,v+=e}}}if(s&&f+v===this._bufferService.cols&&32!==n.getCodePoint(this._bufferService.cols-1)){const t=r.lines.get(e[1]+1);if(t?.isWrapped&&32!==t.getCodePoint(0)){const t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(v+=t.length)}}return{start:f,length:v}}}_selectWordAt(e,t){const i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){const t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return 0!==e.getWidth()&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){const t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,_.getRangeLength)(i,this._bufferService.cols)}};t.SelectionService=g=s([r(3,f.IBufferService),r(4,f.ICoreService),r(5,h.IMouseService),r(6,f.IOptionsService),r(7,h.IRenderService),r(8,h.ICoreBrowserService)],g)},4725:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ILinkProviderService=t.IThemeService=t.ICharacterJoinerService=t.ISelectionService=t.IRenderService=t.IMouseService=t.ICoreBrowserService=t.ICharSizeService=void 0;const s=i(8343);t.ICharSizeService=(0,s.createDecorator)("CharSizeService"),t.ICoreBrowserService=(0,s.createDecorator)("CoreBrowserService"),t.IMouseService=(0,s.createDecorator)("MouseService"),t.IRenderService=(0,s.createDecorator)("RenderService"),t.ISelectionService=(0,s.createDecorator)("SelectionService"),t.ICharacterJoinerService=(0,s.createDecorator)("CharacterJoinerService"),t.IThemeService=(0,s.createDecorator)("ThemeService"),t.ILinkProviderService=(0,s.createDecorator)("LinkProviderService")},6731:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.ThemeService=t.DEFAULT_ANSI_COLORS=void 0;const n=i(7239),o=i(8055),a=i(8460),h=i(844),c=i(2585),l=o.css.toColor("#ffffff"),d=o.css.toColor("#000000"),_=o.css.toColor("#ffffff"),u=o.css.toColor("#000000"),f={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117};t.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const e=[o.css.toColor("#2e3436"),o.css.toColor("#cc0000"),o.css.toColor("#4e9a06"),o.css.toColor("#c4a000"),o.css.toColor("#3465a4"),o.css.toColor("#75507b"),o.css.toColor("#06989a"),o.css.toColor("#d3d7cf"),o.css.toColor("#555753"),o.css.toColor("#ef2929"),o.css.toColor("#8ae234"),o.css.toColor("#fce94f"),o.css.toColor("#729fcf"),o.css.toColor("#ad7fa8"),o.css.toColor("#34e2e2"),o.css.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){const s=t[i/36%6|0],r=t[i/6%6|0],n=t[i%6];e.push({css:o.channels.toCss(s,r,n),rgba:o.channels.toRgba(s,r,n)})}for(let t=0;t<24;t++){const i=8+10*t;e.push({css:o.channels.toCss(i,i,i),rgba:o.channels.toRgba(i,i,i)})}return e})());let v=t.ThemeService=class extends h.Disposable{get colors(){return this._colors}constructor(e){super(),this._optionsService=e,this._contrastCache=new n.ColorContrastCache,this._halfContrastCache=new n.ColorContrastCache,this._onChangeColors=this.register(new a.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:l,background:d,cursor:_,cursorAccent:u,selectionForeground:void 0,selectionBackgroundTransparent:f,selectionBackgroundOpaque:o.color.blend(d,f),selectionInactiveBackgroundTransparent:f,selectionInactiveBackgroundOpaque:o.color.blend(d,f),ansi:t.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this.register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",(()=>this._contrastCache.clear()))),this.register(this._optionsService.onSpecificOptionChange("theme",(()=>this._setTheme(this._optionsService.rawOptions.theme))))}_setTheme(e={}){const i=this._colors;if(i.foreground=p(e.foreground,l),i.background=p(e.background,d),i.cursor=p(e.cursor,_),i.cursorAccent=p(e.cursorAccent,u),i.selectionBackgroundTransparent=p(e.selectionBackground,f),i.selectionBackgroundOpaque=o.color.blend(i.background,i.selectionBackgroundTransparent),i.selectionInactiveBackgroundTransparent=p(e.selectionInactiveBackground,i.selectionBackgroundTransparent),i.selectionInactiveBackgroundOpaque=o.color.blend(i.background,i.selectionInactiveBackgroundTransparent),i.selectionForeground=e.selectionForeground?p(e.selectionForeground,o.NULL_COLOR):void 0,i.selectionForeground===o.NULL_COLOR&&(i.selectionForeground=void 0),o.color.isOpaque(i.selectionBackgroundTransparent)){const e=.3;i.selectionBackgroundTransparent=o.color.opacity(i.selectionBackgroundTransparent,e)}if(o.color.isOpaque(i.selectionInactiveBackgroundTransparent)){const e=.3;i.selectionInactiveBackgroundTransparent=o.color.opacity(i.selectionInactiveBackgroundTransparent,e)}if(i.ansi=t.DEFAULT_ANSI_COLORS.slice(),i.ansi[0]=p(e.black,t.DEFAULT_ANSI_COLORS[0]),i.ansi[1]=p(e.red,t.DEFAULT_ANSI_COLORS[1]),i.ansi[2]=p(e.green,t.DEFAULT_ANSI_COLORS[2]),i.ansi[3]=p(e.yellow,t.DEFAULT_ANSI_COLORS[3]),i.ansi[4]=p(e.blue,t.DEFAULT_ANSI_COLORS[4]),i.ansi[5]=p(e.magenta,t.DEFAULT_ANSI_COLORS[5]),i.ansi[6]=p(e.cyan,t.DEFAULT_ANSI_COLORS[6]),i.ansi[7]=p(e.white,t.DEFAULT_ANSI_COLORS[7]),i.ansi[8]=p(e.brightBlack,t.DEFAULT_ANSI_COLORS[8]),i.ansi[9]=p(e.brightRed,t.DEFAULT_ANSI_COLORS[9]),i.ansi[10]=p(e.brightGreen,t.DEFAULT_ANSI_COLORS[10]),i.ansi[11]=p(e.brightYellow,t.DEFAULT_ANSI_COLORS[11]),i.ansi[12]=p(e.brightBlue,t.DEFAULT_ANSI_COLORS[12]),i.ansi[13]=p(e.brightMagenta,t.DEFAULT_ANSI_COLORS[13]),i.ansi[14]=p(e.brightCyan,t.DEFAULT_ANSI_COLORS[14]),i.ansi[15]=p(e.brightWhite,t.DEFAULT_ANSI_COLORS[15]),e.extendedAnsi){const s=Math.min(i.ansi.length-16,e.extendedAnsi.length);for(let r=0;r<s;r++)i.ansi[r+16]=p(e.extendedAnsi[r],t.DEFAULT_ANSI_COLORS[r+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(void 0!==e)switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}else for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e]}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};function p(e,t){if(void 0!==e)try{return o.css.toColor(e)}catch{}return t}t.ThemeService=v=s([r(0,c.IOptionsService)],v)},6349:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CircularList=void 0;const s=i(8460),r=i(844);class n extends r.Disposable{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this.register(new s.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new s.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new s.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;const t=new Array(e);for(let i=0;i<Math.min(e,this.length);i++)t[i]=this._array[this._getCyclicIndex(i)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...i){if(t){for(let i=e;i<this._length-t;i++)this._array[this._getCyclicIndex(i)]=this._array[this._getCyclicIndex(i+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+i.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<i.length;t++)this._array[this._getCyclicIndex(e+t)]=i[t];if(i.length&&this.onInsertEmitter.fire({index:e,amount:i.length}),this._length+i.length>this._maxLength){const e=this._length+i.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let s=t-1;s>=0;s--)this.set(e+s+i,this.get(e+s));const s=e+t+i-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s<t;s++)this.set(e+s+i,this.get(e+s))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}}t.CircularList=n},1439:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.clone=void 0,t.clone=function e(t,i=5){if("object"!=typeof t)return t;const s=Array.isArray(t)?[]:{};for(const r in t)s[r]=i<=1?t[r]:t[r]&&e(t[r],i-1);return s}},8055:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.contrastRatio=t.toPaddedHex=t.rgba=t.rgb=t.css=t.color=t.channels=t.NULL_COLOR=void 0;let i=0,s=0,r=0,n=0;var o,a,h,c,l;function d(e){const t=e.toString(16);return t.length<2?"0"+t:t}function _(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}t.NULL_COLOR={css:"#00000000",rgba:0},function(e){e.toCss=function(e,t,i,s){return void 0!==s?`#${d(e)}${d(t)}${d(i)}${d(s)}`:`#${d(e)}${d(t)}${d(i)}`},e.toRgba=function(e,t,i,s=255){return(e<<24|t<<16|i<<8|s)>>>0},e.toColor=function(t,i,s,r){return{css:e.toCss(t,i,s,r),rgba:e.toRgba(t,i,s,r)}}}(o||(t.channels=o={})),function(e){function t(e,t){return n=Math.round(255*t),[i,s,r]=l.toChannels(e.rgba),{css:o.toCss(i,s,r,n),rgba:o.toRgba(i,s,r,n)}}e.blend=function(e,t){if(n=(255&t.rgba)/255,1===n)return{css:t.css,rgba:t.rgba};const a=t.rgba>>24&255,h=t.rgba>>16&255,c=t.rgba>>8&255,l=e.rgba>>24&255,d=e.rgba>>16&255,_=e.rgba>>8&255;return i=l+Math.round((a-l)*n),s=d+Math.round((h-d)*n),r=_+Math.round((c-_)*n),{css:o.toCss(i,s,r),rgba:o.toRgba(i,s,r)}},e.isOpaque=function(e){return 255==(255&e.rgba)},e.ensureContrastRatio=function(e,t,i){const s=l.ensureContrastRatio(e.rgba,t.rgba,i);if(s)return o.toColor(s>>24&255,s>>16&255,s>>8&255)},e.opaque=function(e){const t=(255|e.rgba)>>>0;return[i,s,r]=l.toChannels(t),{css:o.toCss(i,s,r),rgba:t}},e.opacity=t,e.multiplyOpacity=function(e,i){return n=255&e.rgba,t(e,n*i/255)},e.toColorRGB=function(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}}(a||(t.color=a={})),function(e){let t,a;try{const e=document.createElement("canvas");e.width=1,e.height=1;const i=e.getContext("2d",{willReadFrequently:!0});i&&(t=i,t.globalCompositeOperation="copy",a=t.createLinearGradient(0,0,1,1))}catch{}e.toColor=function(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return i=parseInt(e.slice(1,2).repeat(2),16),s=parseInt(e.slice(2,3).repeat(2),16),r=parseInt(e.slice(3,4).repeat(2),16),o.toColor(i,s,r);case 5:return i=parseInt(e.slice(1,2).repeat(2),16),s=parseInt(e.slice(2,3).repeat(2),16),r=parseInt(e.slice(3,4).repeat(2),16),n=parseInt(e.slice(4,5).repeat(2),16),o.toColor(i,s,r,n);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}const h=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(h)return i=parseInt(h[1]),s=parseInt(h[2]),r=parseInt(h[3]),n=Math.round(255*(void 0===h[5]?1:parseFloat(h[5]))),o.toColor(i,s,r,n);if(!t||!a)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=a,t.fillStyle=e,"string"!=typeof t.fillStyle)throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[i,s,r,n]=t.getImageData(0,0,1,1).data,255!==n)throw new Error("css.toColor: Unsupported css format");return{rgba:o.toRgba(i,s,r,n),css:e}}}(h||(t.css=h={})),function(e){function t(e,t,i){const s=e/255,r=t/255,n=i/255;return.2126*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))}e.relativeLuminance=function(e){return t(e>>16&255,e>>8&255,255&e)},e.relativeLuminance2=t}(c||(t.rgb=c={})),function(e){function t(e,t,i){const s=e>>24&255,r=e>>16&255,n=e>>8&255;let o=t>>24&255,a=t>>16&255,h=t>>8&255,l=_(c.relativeLuminance2(o,a,h),c.relativeLuminance2(s,r,n));for(;l<i&&(o>0||a>0||h>0);)o-=Math.max(0,Math.ceil(.1*o)),a-=Math.max(0,Math.ceil(.1*a)),h-=Math.max(0,Math.ceil(.1*h)),l=_(c.relativeLuminance2(o,a,h),c.relativeLuminance2(s,r,n));return(o<<24|a<<16|h<<8|255)>>>0}function a(e,t,i){const s=e>>24&255,r=e>>16&255,n=e>>8&255;let o=t>>24&255,a=t>>16&255,h=t>>8&255,l=_(c.relativeLuminance2(o,a,h),c.relativeLuminance2(s,r,n));for(;l<i&&(o<255||a<255||h<255);)o=Math.min(255,o+Math.ceil(.1*(255-o))),a=Math.min(255,a+Math.ceil(.1*(255-a))),h=Math.min(255,h+Math.ceil(.1*(255-h))),l=_(c.relativeLuminance2(o,a,h),c.relativeLuminance2(s,r,n));return(o<<24|a<<16|h<<8|255)>>>0}e.blend=function(e,t){if(n=(255&t)/255,1===n)return t;const a=t>>24&255,h=t>>16&255,c=t>>8&255,l=e>>24&255,d=e>>16&255,_=e>>8&255;return i=l+Math.round((a-l)*n),s=d+Math.round((h-d)*n),r=_+Math.round((c-_)*n),o.toRgba(i,s,r)},e.ensureContrastRatio=function(e,i,s){const r=c.relativeLuminance(e>>8),n=c.relativeLuminance(i>>8);if(_(r,n)<s){if(n<r){const n=t(e,i,s),o=_(r,c.relativeLuminance(n>>8));if(o<s){const t=a(e,i,s);return o>_(r,c.relativeLuminance(t>>8))?n:t}return n}const o=a(e,i,s),h=_(r,c.relativeLuminance(o>>8));if(h<s){const n=t(e,i,s);return h>_(r,c.relativeLuminance(n>>8))?o:n}return o}},e.reduceLuminance=t,e.increaseLuminance=a,e.toChannels=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]}}(l||(t.rgba=l={})),t.toPaddedHex=d,t.contrastRatio=_},8969:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CoreTerminal=void 0;const s=i(844),r=i(2585),n=i(4348),o=i(7866),a=i(744),h=i(7302),c=i(6975),l=i(8460),d=i(1753),_=i(1480),u=i(7994),f=i(9282),v=i(5435),p=i(5981),g=i(2660);let m=!1;class S extends s.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new l.EventEmitter),this._onScroll.event((e=>{this._onScrollApi?.fire(e.position)}))),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(const t in e)this.optionsService.options[t]=e[t]}constructor(e){super(),this._windowsWrappingHeuristics=this.register(new s.MutableDisposable),this._onBinary=this.register(new l.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new l.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new l.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new l.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new l.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new l.EventEmitter),this._instantiationService=new n.InstantiationService,this.optionsService=this.register(new h.OptionsService(e)),this._instantiationService.setService(r.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(a.BufferService)),this._instantiationService.setService(r.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(o.LogService)),this._instantiationService.setService(r.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(c.CoreService)),this._instantiationService.setService(r.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(d.CoreMouseService)),this._instantiationService.setService(r.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(_.UnicodeService)),this._instantiationService.setService(r.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(u.CharsetService),this._instantiationService.setService(r.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(g.OscLinkService),this._instantiationService.setService(r.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new v.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,l.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,l.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,l.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,l.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom((()=>this.scrollToBottom()))),this.register(this.coreService.onUserInput((()=>this._writeBuffer.handleUserInput()))),this.register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],(()=>this._handleWindowsPtyOptionChange()))),this.register(this._bufferService.onScroll((e=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this.register(this._inputHandler.onScroll((e=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this._writeBuffer=this.register(new p.WriteBuffer(((e,t)=>this._inputHandler.parse(e,t)))),this.register((0,l.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=r.LogLevelEnum.WARN&&!m&&(this._logService.warn("writeSync is unreliable and will be removed soon."),m=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,a.MINIMUM_COLS),t=Math.max(t,a.MINIMUM_ROWS),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t,i){this._bufferService.scrollLines(e,t,i)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){const t=e-this._bufferService.buffer.ydisp;0!==t&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1;const t=this.optionsService.rawOptions.windowsPty;t&&void 0!==t.buildNumber&&void 0!==t.buildNumber?e=!!("conpty"===t.backend&&t.buildNumber<21376):this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){const e=[];e.push(this.onLineFeed(f.updateWindowsModeWrappedState.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},(()=>((0,f.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,s.toDisposable)((()=>{for(const t of e)t.dispose()}))}}}t.CoreTerminal=S},8460:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.runAndSubscribe=t.forwardEvent=t.EventEmitter=void 0,t.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=e=>(this._listeners.push(e),{dispose:()=>{if(!this._disposed)for(let t=0;t<this._listeners.length;t++)if(this._listeners[t]===e)return void this._listeners.splice(t,1)}})),this._event}fire(e,t){const i=[];for(let e=0;e<this._listeners.length;e++)i.push(this._listeners[e]);for(let s=0;s<i.length;s++)i[s].call(void 0,e,t)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},t.forwardEvent=function(e,t){return e((e=>t.fire(e)))},t.runAndSubscribe=function(e,t){return t(void 0),e((e=>t(e)))}},5435:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.InputHandler=t.WindowsOptionsReportType=void 0;const n=i(2584),o=i(7116),a=i(2015),h=i(844),c=i(482),l=i(8437),d=i(8460),_=i(643),u=i(511),f=i(3734),v=i(2585),p=i(1480),g=i(6242),m=i(6351),S=i(5941),C={"(":0,")":1,"*":2,"+":3,"-":1,".":2},b=131072;function w(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var y;!function(e){e[e.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",e[e.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"}(y||(t.WindowsOptionsReportType=y={}));let E=0;class k extends h.Disposable{getAttrData(){return this._curAttrData}constructor(e,t,i,s,r,h,_,f,v=new a.EscapeSequenceParser){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=s,this._optionsService=r,this._oscLinkService=h,this._coreMouseService=_,this._unicodeService=f,this._parser=v,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new c.StringToUtf32,this._utf8Decoder=new c.Utf8ToUtf32,this._workCell=new u.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=l.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=l.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new d.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new d.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new d.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new d.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new d.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new d.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new d.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new d.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new d.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new d.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new d.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new d.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new d.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new L(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((e=>this._activeBuffer=e.activeBuffer))),this._parser.setCsiHandlerFallback(((e,t)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(e),params:t.toArray()})})),this._parser.setEscHandlerFallback((e=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(e)})})),this._parser.setExecuteHandlerFallback((e=>{this._logService.debug("Unknown EXECUTE code: ",{code:e})})),this._parser.setOscHandlerFallback(((e,t,i)=>{this._logService.debug("Unknown OSC code: ",{identifier:e,action:t,data:i})})),this._parser.setDcsHandlerFallback(((e,t,i)=>{"HOOK"===t&&(i=i.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(e),action:t,payload:i})})),this._parser.setPrintHandler(((e,t,i)=>this.print(e,t,i))),this._parser.registerCsiHandler({final:"@"},(e=>this.insertChars(e))),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(e=>this.scrollLeft(e))),this._parser.registerCsiHandler({final:"A"},(e=>this.cursorUp(e))),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(e=>this.scrollRight(e))),this._parser.registerCsiHandler({final:"B"},(e=>this.cursorDown(e))),this._parser.registerCsiHandler({final:"C"},(e=>this.cursorForward(e))),this._parser.registerCsiHandler({final:"D"},(e=>this.cursorBackward(e))),this._parser.registerCsiHandler({final:"E"},(e=>this.cursorNextLine(e))),this._parser.registerCsiHandler({final:"F"},(e=>this.cursorPrecedingLine(e))),this._parser.registerCsiHandler({final:"G"},(e=>this.cursorCharAbsolute(e))),this._parser.registerCsiHandler({final:"H"},(e=>this.cursorPosition(e))),this._parser.registerCsiHandler({final:"I"},(e=>this.cursorForwardTab(e))),this._parser.registerCsiHandler({final:"J"},(e=>this.eraseInDisplay(e,!1))),this._parser.registerCsiHandler({prefix:"?",final:"J"},(e=>this.eraseInDisplay(e,!0))),this._parser.registerCsiHandler({final:"K"},(e=>this.eraseInLine(e,!1))),this._parser.registerCsiHandler({prefix:"?",final:"K"},(e=>this.eraseInLine(e,!0))),this._parser.registerCsiHandler({final:"L"},(e=>this.insertLines(e))),this._parser.registerCsiHandler({final:"M"},(e=>this.deleteLines(e))),this._parser.registerCsiHandler({final:"P"},(e=>this.deleteChars(e))),this._parser.registerCsiHandler({final:"S"},(e=>this.scrollUp(e))),this._parser.registerCsiHandler({final:"T"},(e=>this.scrollDown(e))),this._parser.registerCsiHandler({final:"X"},(e=>this.eraseChars(e))),this._parser.registerCsiHandler({final:"Z"},(e=>this.cursorBackwardTab(e))),this._parser.registerCsiHandler({final:"`"},(e=>this.charPosAbsolute(e))),this._parser.registerCsiHandler({final:"a"},(e=>this.hPositionRelative(e))),this._parser.registerCsiHandler({final:"b"},(e=>this.repeatPrecedingCharacter(e))),this._parser.registerCsiHandler({final:"c"},(e=>this.sendDeviceAttributesPrimary(e))),this._parser.registerCsiHandler({prefix:">",final:"c"},(e=>this.sendDeviceAttributesSecondary(e))),this._parser.registerCsiHandler({final:"d"},(e=>this.linePosAbsolute(e))),this._parser.registerCsiHandler({final:"e"},(e=>this.vPositionRelative(e))),this._parser.registerCsiHandler({final:"f"},(e=>this.hVPosition(e))),this._parser.registerCsiHandler({final:"g"},(e=>this.tabClear(e))),this._parser.registerCsiHandler({final:"h"},(e=>this.setMode(e))),this._parser.registerCsiHandler({prefix:"?",final:"h"},(e=>this.setModePrivate(e))),this._parser.registerCsiHandler({final:"l"},(e=>this.resetMode(e))),this._parser.registerCsiHandler({prefix:"?",final:"l"},(e=>this.resetModePrivate(e))),this._parser.registerCsiHandler({final:"m"},(e=>this.charAttributes(e))),this._parser.registerCsiHandler({final:"n"},(e=>this.deviceStatus(e))),this._parser.registerCsiHandler({prefix:"?",final:"n"},(e=>this.deviceStatusPrivate(e))),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(e=>this.softReset(e))),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(e=>this.setCursorStyle(e))),this._parser.registerCsiHandler({final:"r"},(e=>this.setScrollRegion(e))),this._parser.registerCsiHandler({final:"s"},(e=>this.saveCursor(e))),this._parser.registerCsiHandler({final:"t"},(e=>this.windowOptions(e))),this._parser.registerCsiHandler({final:"u"},(e=>this.restoreCursor(e))),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(e=>this.insertColumns(e))),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(e=>this.deleteColumns(e))),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(e=>this.selectProtected(e))),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(e=>this.requestMode(e,!0))),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(e=>this.requestMode(e,!1))),this._parser.setExecuteHandler(n.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(n.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(n.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(n.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(n.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(n.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(n.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(n.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(n.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(n.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(n.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(n.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new g.OscHandler((e=>(this.setTitle(e),this.setIconName(e),!0)))),this._parser.registerOscHandler(1,new g.OscHandler((e=>this.setIconName(e)))),this._parser.registerOscHandler(2,new g.OscHandler((e=>this.setTitle(e)))),this._parser.registerOscHandler(4,new g.OscHandler((e=>this.setOrReportIndexedColor(e)))),this._parser.registerOscHandler(8,new g.OscHandler((e=>this.setHyperlink(e)))),this._parser.registerOscHandler(10,new g.OscHandler((e=>this.setOrReportFgColor(e)))),this._parser.registerOscHandler(11,new g.OscHandler((e=>this.setOrReportBgColor(e)))),this._parser.registerOscHandler(12,new g.OscHandler((e=>this.setOrReportCursorColor(e)))),this._parser.registerOscHandler(104,new g.OscHandler((e=>this.restoreIndexedColor(e)))),this._parser.registerOscHandler(110,new g.OscHandler((e=>this.restoreFgColor(e)))),this._parser.registerOscHandler(111,new g.OscHandler((e=>this.restoreBgColor(e)))),this._parser.registerOscHandler(112,new g.OscHandler((e=>this.restoreCursorColor(e)))),this._parser.registerEscHandler({final:"7"},(()=>this.saveCursor())),this._parser.registerEscHandler({final:"8"},(()=>this.restoreCursor())),this._parser.registerEscHandler({final:"D"},(()=>this.index())),this._parser.registerEscHandler({final:"E"},(()=>this.nextLine())),this._parser.registerEscHandler({final:"H"},(()=>this.tabSet())),this._parser.registerEscHandler({final:"M"},(()=>this.reverseIndex())),this._parser.registerEscHandler({final:"="},(()=>this.keypadApplicationMode())),this._parser.registerEscHandler({final:">"},(()=>this.keypadNumericMode())),this._parser.registerEscHandler({final:"c"},(()=>this.fullReset())),this._parser.registerEscHandler({final:"n"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"o"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"|"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"}"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"~"},(()=>this.setgLevel(1))),this._parser.registerEscHandler({intermediates:"%",final:"@"},(()=>this.selectDefaultCharset())),this._parser.registerEscHandler({intermediates:"%",final:"G"},(()=>this.selectDefaultCharset()));for(const e in o.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:e},(()=>this.selectCharset("("+e))),this._parser.registerEscHandler({intermediates:")",final:e},(()=>this.selectCharset(")"+e))),this._parser.registerEscHandler({intermediates:"*",final:e},(()=>this.selectCharset("*"+e))),this._parser.registerEscHandler({intermediates:"+",final:e},(()=>this.selectCharset("+"+e))),this._parser.registerEscHandler({intermediates:"-",final:e},(()=>this.selectCharset("-"+e))),this._parser.registerEscHandler({intermediates:".",final:e},(()=>this.selectCharset("."+e))),this._parser.registerEscHandler({intermediates:"/",final:e},(()=>this.selectCharset("/"+e)));this._parser.registerEscHandler({intermediates:"#",final:"8"},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((e=>(this._logService.error("Parsing error: ",e),e))),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new m.DcsHandler(((e,t)=>this.requestStatusString(e,t))))}_preserveStack(e,t,i,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=v.LogLevelEnum.WARN&&Promise.race([e,new Promise(((e,t)=>setTimeout((()=>t("#SLOW_TIMEOUT")),5e3)))]).catch((e=>{if("#SLOW_TIMEOUT"!==e)throw e;console.warn("async parser handler taking longer than 5000 ms")}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,r=this._activeBuffer.y,n=0;const o=this._parseStack.paused;if(o){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,r=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>b&&(n=this._parseStack.position+b)}if(this._logService.logLevel<=v.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+("string"==typeof e?` "${e}"`:` "${Array.prototype.map.call(e,(e=>String.fromCharCode(e))).join("")}"`),"string"==typeof e?e.split("").map((e=>e.charCodeAt(0))):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<b&&(this._parseBuffer=new Uint32Array(Math.min(e.length,b))),o||this._dirtyRowTracker.clearRange(),e.length>b)for(let t=n;t<e.length;t+=b){const n=t+b<e.length?t+b:e.length,o="string"==typeof e?this._stringDecoder.decode(e.substring(t,n),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,n),this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,o))return this._preserveStack(s,r,o,t),this._logSlowResolvingAsync(i),i}else if(!o){const t="string"==typeof e?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(i=this._parser.parse(this._parseBuffer,t))return this._preserveStack(s,r,t,0),this._logSlowResolvingAsync(i),i}this._activeBuffer.x===s&&this._activeBuffer.y===r||this._onCursorMove.fire();const a=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),h=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);h<this._bufferService.rows&&this._onRequestRefreshRows.fire(Math.min(h,this._bufferService.rows-1),Math.min(a,this._bufferService.rows-1))}print(e,t,i){let s,r;const n=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,a=this._bufferService.cols,h=this._coreService.decPrivateModes.wraparound,d=this._coreService.modes.insertMode,u=this._curAttrData;let f=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&i-t>0&&2===f.getWidth(this._activeBuffer.x-1)&&f.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let v=this._parser.precedingJoinState;for(let g=t;g<i;++g){if(s=e[g],s<127&&n){const e=n[String.fromCharCode(s)];e&&(s=e.charCodeAt(0))}const t=this._unicodeService.charProperties(s,v);r=p.UnicodeService.extractWidth(t);const i=p.UnicodeService.extractShouldJoin(t),m=i?p.UnicodeService.extractWidth(v):0;if(v=t,o&&this._onA11yChar.fire((0,c.stringFromCodePoint)(s)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+r-m>a)if(h){const e=f;let t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),f=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&f instanceof l.BufferLine&&f.copyCellsFrom(e,t,0,m,!1);t<a;)e.setCellFromCodepoint(t++,0,1,u)}else if(this._activeBuffer.x=a-1,2===r)continue;if(i&&this._activeBuffer.x){const e=f.getWidth(this._activeBuffer.x-1)?1:2;f.addCodepointToCell(this._activeBuffer.x-e,s,r);for(let e=r-m;--e>=0;)f.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}else if(d&&(f.insertCells(this._activeBuffer.x,r-m,this._activeBuffer.getNullCell(u)),2===f.getWidth(a-1)&&f.setCellFromCodepoint(a-1,_.NULL_CELL_CODE,_.NULL_CELL_WIDTH,u)),f.setCellFromCodepoint(this._activeBuffer.x++,s,r,u),r>0)for(;--r;)f.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=v,this._activeBuffer.x<a&&i-t>0&&0===f.getWidth(this._activeBuffer.x)&&!f.hasContent(this._activeBuffer.x)&&f.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return"t"!==e.final||e.prefix||e.intermediates?this._parser.registerCsiHandler(e,t):this._parser.registerCsiHandler(e,(e=>!w(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)))}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new m.DcsHandler(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new g.OscHandler(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(0===this._activeBuffer.x&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;const e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){const t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){const t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){const t=e.params[0];return 0===t?delete this._activeBuffer.tabs[this._activeBuffer.x]:3===t&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){const t=e.params[0];return 1===t&&(this._curAttrData.bg|=536870912),2!==t&&0!==t||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,r=!1){const n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),r),s&&(n.isWrapped=!1)}_resetBufferLine(e,t=!1){const i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){let i;switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,0===this._activeBuffer.x,t);i<this._bufferService.rows;i++)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(i);break;case 1:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 3:const e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,0===this._activeBuffer.x,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const i=this._activeBuffer.ybase+this._activeBuffer.y,s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-s+1;for(;t--;)this._activeBuffer.lines.splice(r-1,1),this._activeBuffer.lines.splice(i,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const i=this._activeBuffer.ybase+this._activeBuffer.y;let s;for(s=this._bufferService.rows-1-this._activeBuffer.scrollBottom,s=this._bufferService.rows-1+this._activeBuffer.ybase-s;t--;)this._activeBuffer.lines.splice(i,1),this._activeBuffer.lines.splice(s,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();const t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();const t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(l.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){const i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),i.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){const i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),i.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){const i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),i.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){const i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),i.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();const t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){const t=this._parser.precedingJoinState;if(!t)return!0;const i=e.params[0]||1,s=p.UnicodeService.extractWidth(t),r=this._activeBuffer.x-s,n=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(r),o=new Uint32Array(n.length*i);let a=0;for(let e=0;e<n.length;){const t=n.codePointAt(e)||0;o[a++]=t,e+=t>65535?2:1}let h=a;for(let e=1;e<i;++e)o.copyWithin(h,0,a),h+=a;return this.print(o,0,h),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(n.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(n.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(n.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(n.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(n.C0.ESC+"[>83;40003;0c")),!0}_is(e){return 0===(this._optionsService.rawOptions.termName+"").indexOf(e)}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,o.DEFAULT_CHARSET),this._charsetService.setgCharset(1,o.DEFAULT_CHARSET),this._charsetService.setgCharset(2,o.DEFAULT_CHARSET),this._charsetService.setgCharset(3,o.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),1049===e.params[t]&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1}return!0}requestMode(e,t){const i=this._coreService.decPrivateModes,{activeProtocol:s,activeEncoding:r}=this._coreMouseService,o=this._coreService,{buffers:a,cols:h}=this._bufferService,{active:c,alt:l}=a,d=this._optionsService.rawOptions,_=e=>e?1:2,u=e.params[0];return f=u,v=t?2===u?4:4===u?_(o.modes.insertMode):12===u?3:20===u?_(d.convertEol):0:1===u?_(i.applicationCursorKeys):3===u?d.windowOptions.setWinLines?80===h?2:132===h?1:0:0:6===u?_(i.origin):7===u?_(i.wraparound):8===u?3:9===u?_("X10"===s):12===u?_(d.cursorBlink):25===u?_(!o.isCursorHidden):45===u?_(i.reverseWraparound):66===u?_(i.applicationKeypad):67===u?4:1e3===u?_("VT200"===s):1002===u?_("DRAG"===s):1003===u?_("ANY"===s):1004===u?_(i.sendFocus):1005===u?4:1006===u?_("SGR"===r):1015===u?4:1016===u?_("SGR_PIXELS"===r):1048===u?1:47===u||1047===u||1049===u?_(c===l):2004===u?_(i.bracketedPasteMode):0,o.triggerDataEvent(`${n.C0.ESC}[${t?"":"?"}${f};${v}$y`),!0;var f,v}_updateAttrColor(e,t,i,s,r){return 2===t?(e|=50331648,e&=-16777216,e|=f.AttributeData.fromColorRGB([i,s,r])):5===t&&(e&=-50331904,e|=33554432|255&i),e}_extractColor(e,t,i){const s=[0,0,-1,0,0,0];let r=0,n=0;do{if(s[n+r]=e.params[t+n],e.hasSubParams(t+n)){const i=e.getSubParams(t+n);let o=0;do{5===s[1]&&(r=1),s[n+o+1+r]=i[o]}while(++o<i.length&&o+n+1+r<s.length);break}if(5===s[1]&&n+r>=2||2===s[1]&&n+r>=5)break;s[1]&&(r=1)}while(++n+t<e.length&&n+r<s.length);for(let e=2;e<s.length;++e)-1===s[e]&&(s[e]=0);switch(s[0]){case 38:i.fg=this._updateAttrColor(i.fg,s[1],s[3],s[4],s[5]);break;case 48:i.bg=this._updateAttrColor(i.bg,s[1],s[3],s[4],s[5]);break;case 58:i.extended=i.extended.clone(),i.extended.underlineColor=this._updateAttrColor(i.extended.underlineColor,s[1],s[3],s[4],s[5])}return n}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,0===e&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=l.DEFAULT_ATTR_DATA.fg,e.bg=l.DEFAULT_ATTR_DATA.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(1===e.length&&0===e.params[0])return this._processSGR0(this._curAttrData),!0;const t=e.length;let i;const s=this._curAttrData;for(let r=0;r<t;r++)i=e.params[r],i>=30&&i<=37?(s.fg&=-50331904,s.fg|=16777216|i-30):i>=40&&i<=47?(s.bg&=-50331904,s.bg|=16777216|i-40):i>=90&&i<=97?(s.fg&=-50331904,s.fg|=16777224|i-90):i>=100&&i<=107?(s.bg&=-50331904,s.bg|=16777224|i-100):0===i?this._processSGR0(s):1===i?s.fg|=134217728:3===i?s.bg|=67108864:4===i?(s.fg|=268435456,this._processUnderline(e.hasSubParams(r)?e.getSubParams(r)[0]:1,s)):5===i?s.fg|=536870912:7===i?s.fg|=67108864:8===i?s.fg|=1073741824:9===i?s.fg|=2147483648:2===i?s.bg|=134217728:21===i?this._processUnderline(2,s):22===i?(s.fg&=-134217729,s.bg&=-134217729):23===i?s.bg&=-67108865:24===i?(s.fg&=-268435457,this._processUnderline(0,s)):25===i?s.fg&=-536870913:27===i?s.fg&=-67108865:28===i?s.fg&=-1073741825:29===i?s.fg&=2147483647:39===i?(s.fg&=-67108864,s.fg|=16777215&l.DEFAULT_ATTR_DATA.fg):49===i?(s.bg&=-67108864,s.bg|=16777215&l.DEFAULT_ATTR_DATA.bg):38===i||48===i||58===i?r+=this._extractColor(e,r,s):53===i?s.bg|=1073741824:55===i?s.bg&=-1073741825:59===i?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):100===i?(s.fg&=-67108864,s.fg|=16777215&l.DEFAULT_ATTR_DATA.fg,s.bg&=-67108864,s.bg|=16777215&l.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${n.C0.ESC}[0n`);break;case 6:const e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${n.C0.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(6===e.params[0]){const e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${n.C0.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=l.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){const t=e.params[0]||1;switch(t){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}const i=t%2==1;return this._optionsService.options.cursorBlink=i,!0}setScrollRegion(e){const t=e.params[0]||1;let i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||0===i)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!w(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;const t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:2!==t&&this._onRequestWindowsOptionsReport.fire(y.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(y.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${n.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:0!==t&&2!==t||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),0!==t&&1!==t||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:0!==t&&2!==t||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),0!==t&&1!==t||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){const t=[],i=e.split(";");for(;i.length>1;){const e=i.shift(),s=i.shift();if(/^\d+$/.exec(e)){const i=parseInt(e);if(D(i))if("?"===s)t.push({type:0,index:i});else{const e=(0,S.parseColor)(s);e&&t.push({type:1,index:i,color:e})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){const t=e.split(";");return!(t.length<2)&&(t[1]?this._createHyperlink(t[0],t[1]):!t[0]&&this._finishHyperlink())}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();const i=e.split(":");let s;const r=i.findIndex((e=>e.startsWith("id=")));return-1!==r&&(s=i[r].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){const i=e.split(";");for(let e=0;e<i.length&&!(t>=this._specialColors.length);++e,++t)if("?"===i[e])this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{const s=(0,S.parseColor)(i[e]);s&&this._onColor.fire([{type:1,index:this._specialColors[t],color:s}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;const t=[],i=e.split(";");for(let e=0;e<i.length;++e)if(/^\d+$/.exec(i[e])){const s=parseInt(i[e]);D(s)&&t.push({type:2,index:s})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,o.DEFAULT_CHARSET),!0}selectCharset(e){return 2!==e.length?(this.selectDefaultCharset(),!0):("/"===e[0]||this._charsetService.setgCharset(C[e[0]],o.CHARSETS[e[1]]||o.DEFAULT_CHARSET),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){const e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=l.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=l.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){const e=new u.CellData;e.content=1<<22|"E".charCodeAt(0),e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){const i=this._activeBuffer.ybase+this._activeBuffer.y+t,s=this._activeBuffer.lines.get(i);s&&(s.fill(e),s.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){const i=this._bufferService.buffer,s=this._optionsService.rawOptions;return(e=>(this._coreService.triggerDataEvent(`${n.C0.ESC}${e}${n.C0.ESC}\\`),!0))('"q'===e?`P1$r${this._curAttrData.isProtected()?1:0}"q`:'"p'===e?'P1$r61;1"p':"r"===e?`P1$r${i.scrollTop+1};${i.scrollBottom+1}r`:"m"===e?"P1$r0m":" q"===e?`P1$r${{block:2,underline:4,bar:6}[s.cursorStyle]-(s.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}}t.InputHandler=k;let L=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(E=e,e=t,t=E),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function D(e){return 0<=e&&e<256}L=s([r(0,v.IBufferService)],L)},844:(e,t)=>{function i(e){for(const t of e)t.dispose();e.length=0}Object.defineProperty(t,"__esModule",{value:!0}),t.getDisposeArrayDisposable=t.disposeArray=t.toDisposable=t.MutableDisposable=t.Disposable=void 0,t.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(const e of this._disposables)e.dispose();this._disposables.length=0}register(e){return this._disposables.push(e),e}unregister(e){const t=this._disposables.indexOf(e);-1!==t&&this._disposables.splice(t,1)}},t.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},t.toDisposable=function(e){return{dispose:e}},t.disposeArray=i,t.getDisposeArrayDisposable=function(e){return{dispose:()=>i(e)}}},1505:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FourKeyMap=t.TwoKeyMap=void 0;class i{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}}t.TwoKeyMap=i,t.FourKeyMap=class{constructor(){this._data=new i}set(e,t,s,r,n){this._data.get(e,t)||this._data.set(e,t,new i),this._data.get(e,t).set(s,r,n)}get(e,t,i,s){return this._data.get(e,t)?.get(i,s)}clear(){this._data.clear()}}},6114:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isChromeOS=t.isLinux=t.isWindows=t.isIphone=t.isIpad=t.isMac=t.getSafariVersion=t.isSafari=t.isLegacyEdge=t.isFirefox=t.isNode=void 0,t.isNode="undefined"!=typeof process&&"title"in process;const i=t.isNode?"node":navigator.userAgent,s=t.isNode?"node":navigator.platform;t.isFirefox=i.includes("Firefox"),t.isLegacyEdge=i.includes("Edge"),t.isSafari=/^((?!chrome|android).)*safari/i.test(i),t.getSafariVersion=function(){if(!t.isSafari)return 0;const e=i.match(/Version\/(\d+)/);return null===e||e.length<2?0:parseInt(e[1])},t.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(s),t.isIpad="iPad"===s,t.isIphone="iPhone"===s,t.isWindows=["Windows","Win16","Win32","WinCE"].includes(s),t.isLinux=s.indexOf("Linux")>=0,t.isChromeOS=/\bCrOS\b/.test(i)},6106:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SortedList=void 0;let i=0;t.SortedList=class{constructor(e){this._getKey=e,this._array=[]}clear(){this._array.length=0}insert(e){0!==this._array.length?(i=this._search(this._getKey(e)),this._array.splice(i,0,e)):this._array.push(e)}delete(e){if(0===this._array.length)return!1;const t=this._getKey(e);if(void 0===t)return!1;if(i=this._search(t),-1===i)return!1;if(this._getKey(this._array[i])!==t)return!1;do{if(this._array[i]===e)return this._array.splice(i,1),!0}while(++i<this._array.length&&this._getKey(this._array[i])===t);return!1}*getKeyIterator(e){if(0!==this._array.length&&(i=this._search(e),!(i<0||i>=this._array.length)&&this._getKey(this._array[i])===e))do{yield this._array[i]}while(++i<this._array.length&&this._getKey(this._array[i])===e)}forEachByKey(e,t){if(0!==this._array.length&&(i=this._search(e),!(i<0||i>=this._array.length)&&this._getKey(this._array[i])===e))do{t(this._array[i])}while(++i<this._array.length&&this._getKey(this._array[i])===e)}values(){return[...this._array].values()}_search(e){let t=0,i=this._array.length-1;for(;i>=t;){let s=t+i>>1;const r=this._getKey(this._array[s]);if(r>e)i=s-1;else{if(!(r<e)){for(;s>0&&this._getKey(this._array[s-1])===e;)s--;return s}t=s+1}}return t}}},7226:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DebouncedIdleTask=t.IdleTaskQueue=t.PriorityTaskQueue=void 0;const s=i(6114);class r{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(e){this._idleCallback=void 0;let t=0,i=0,s=e.timeRemaining(),r=0;for(;this._i<this._tasks.length;){if(t=Date.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,Date.now()-t),i=Math.max(t,i),r=e.timeRemaining(),1.5*i>r)return s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),void this._start();s=r}this.clear()}}class n extends r{_requestCallback(e){return setTimeout((()=>e(this._createDeadline(16))))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){const t=Date.now()+e;return{timeRemaining:()=>Math.max(0,t-Date.now())}}}t.PriorityTaskQueue=n,t.IdleTaskQueue=!s.isNode&&"requestIdleCallback"in window?class extends r{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}}:n,t.DebouncedIdleTask=class{constructor(){this._queue=new t.IdleTaskQueue}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}}},9282:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.updateWindowsModeWrappedState=void 0;const s=i(643);t.updateWindowsModeWrappedState=function(e){const t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1),i=t?.get(e.cols-1),r=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);r&&i&&(r.isWrapped=i[s.CHAR_DATA_CODE_INDEX]!==s.NULL_CELL_CODE&&i[s.CHAR_DATA_CODE_INDEX]!==s.WHITESPACE_CELL_CODE)}},3734:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtendedAttrs=t.AttributeData=void 0;class i{constructor(){this.fg=0,this.bg=0,this.extended=new s}static toColorRGB(e){return[e>>>16&255,e>>>8&255,255&e]}static fromColorRGB(e){return(255&e[0])<<16|(255&e[1])<<8|255&e[2]}clone(){const e=new i;return e.fg=this.fg,e.bg=this.bg,e.extended=this.extended.clone(),e}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&0!==this.extended.underlineStyle?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return 50331648==(50331648&this.fg)}isBgRGB(){return 50331648==(50331648&this.bg)}isFgPalette(){return 16777216==(50331648&this.fg)||33554432==(50331648&this.fg)}isBgPalette(){return 16777216==(50331648&this.bg)||33554432==(50331648&this.bg)}isFgDefault(){return 0==(50331648&this.fg)}isBgDefault(){return 0==(50331648&this.bg)}isAttributeDefault(){return 0===this.fg&&0===this.bg}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?50331648==(50331648&this.extended.underlineColor):this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?16777216==(50331648&this.extended.underlineColor)||33554432==(50331648&this.extended.underlineColor):this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?0==(50331648&this.extended.underlineColor):this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}t.AttributeData=i;class s{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(e){this._ext&=-67108864,this._ext|=67108863&e}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){const e=(3758096384&this._ext)>>29;return e<0?4294967288^e:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}clone(){return new s(this._ext,this._urlId)}isEmpty(){return 0===this.underlineStyle&&0===this._urlId}}t.ExtendedAttrs=s},9092:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Buffer=t.MAX_BUFFER_SIZE=void 0;const s=i(6349),r=i(7226),n=i(3734),o=i(8437),a=i(4634),h=i(511),c=i(643),l=i(4863),d=i(7116);t.MAX_BUFFER_SIZE=4294967295,t.Buffer=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=o.DEFAULT_ATTR_DATA.clone(),this.savedCharset=d.DEFAULT_CHARSET,this.markers=[],this._nullCell=h.CellData.fromCharData([0,c.NULL_CELL_CHAR,c.NULL_CELL_WIDTH,c.NULL_CELL_CODE]),this._whitespaceCell=h.CellData.fromCharData([0,c.WHITESPACE_CELL_CHAR,c.WHITESPACE_CELL_WIDTH,c.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new r.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new s.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new n.ExtendedAttrs),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new n.ExtendedAttrs),this._whitespaceCell}getBlankLine(e,t){return new o.BufferLine(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){const e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;const i=e+this._optionsService.rawOptions.scrollback;return i>t.MAX_BUFFER_SIZE?t.MAX_BUFFER_SIZE:i}fillViewportRows(e){if(0===this.lines.length){void 0===e&&(e=o.DEFAULT_ATTR_DATA);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new s.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){const i=this.getNullCell(o.DEFAULT_ATTR_DATA);let s=0;const r=this._getCorrectBufferLength(t);if(r>this.lines.maxLength&&(this.lines.maxLength=r),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)s+=+this.lines.get(t).resize(e,i);let n=0;if(this._rows<t)for(let s=this._rows;s<t;s++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||void 0!==this._optionsService.rawOptions.windowsPty.backend||void 0!==this._optionsService.rawOptions.windowsPty.buildNumber?this.lines.push(new o.BufferLine(e,i)):this.ybase>0&&this.lines.length<=this.ybase+this.y+n+1?(this.ybase--,n++,this.ydisp>0&&this.ydisp--):this.lines.push(new o.BufferLine(e,i)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(r<this.lines.maxLength){const e=this.lines.length-r;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=r}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),n&&(this.y+=n),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)s+=+this.lines.get(t).resize(e,i);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),s>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){const e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&"conpty"===e.backend&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){const i=(0,a.reflowLargerGetLinesToRemove)(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(o.DEFAULT_ATTR_DATA));if(i.length>0){const s=(0,a.reflowLargerCreateNewLayout)(this.lines,i);(0,a.reflowLargerApplyNewLayout)(this.lines,s.layout),this._reflowLargerAdjustViewport(e,t,s.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){const s=this.getNullCell(o.DEFAULT_ATTR_DATA);let r=i;for(;r-- >0;)0===this.ybase?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new o.BufferLine(e,s))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-i,0)}_reflowSmaller(e,t){const i=this.getNullCell(o.DEFAULT_ATTR_DATA),s=[];let r=0;for(let n=this.lines.length-1;n>=0;n--){let h=this.lines.get(n);if(!h||!h.isWrapped&&h.getTrimmedLength()<=e)continue;const c=[h];for(;h.isWrapped&&n>0;)h=this.lines.get(--n),c.unshift(h);const l=this.ybase+this.y;if(l>=n&&l<n+c.length)continue;const d=c[c.length-1].getTrimmedLength(),_=(0,a.reflowSmallerGetNewLineLengths)(c,this._cols,e),u=_.length-c.length;let f;f=0===this.ybase&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+u):Math.max(0,this.lines.length-this.lines.maxLength+u);const v=[];for(let e=0;e<u;e++){const e=this.getBlankLine(o.DEFAULT_ATTR_DATA,!0);v.push(e)}v.length>0&&(s.push({start:n+c.length+r,newLines:v}),r+=v.length),c.push(...v);let p=_.length-1,g=_[p];0===g&&(p--,g=_[p]);let m=c.length-u-1,S=d;for(;m>=0;){const e=Math.min(S,g);if(void 0===c[p])break;if(c[p].copyCellsFrom(c[m],S-e,g-e,e,!0),g-=e,0===g&&(p--,g=_[p]),S-=e,0===S){m--;const e=Math.max(m,0);S=(0,a.getWrappedLineTrimmedLength)(c,e,this._cols)}}for(let t=0;t<c.length;t++)_[t]<e&&c[t].setCell(_[t],i);let C=u-f;for(;C-- >0;)0===this.ybase?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+r)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+u,this.ybase+t-1)}if(s.length>0){const e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));const i=this.lines.length;let n=i-1,o=0,a=s[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+r);let h=0;for(let c=Math.min(this.lines.maxLength-1,i+r-1);c>=0;c--)if(a&&a.start>n+h){for(let e=a.newLines.length-1;e>=0;e--)this.lines.set(c--,a.newLines[e]);c++,e.push({index:n+1,amount:a.newLines.length}),h+=a.newLines.length,a=s[++o]}else this.lines.set(c,t[n--]);let c=0;for(let t=e.length-1;t>=0;t--)e[t].index+=c,this.lines.onInsertEmitter.fire(e[t]),c+=e[t].amount;const l=Math.max(0,i+r-this.lines.maxLength);l>0&&this.lines.onTrimEmitter.fire(l)}}translateBufferLineToString(e,t,i=0,s){const r=this.lines.get(e);return r?r.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+1<this.lines.length&&this.lines.get(i+1).isWrapped;)i++;return{first:t,last:i}}setupTabStops(e){for(null!=e?this.tabs[e]||(e=this.prevStop(e)):(this.tabs={},e=0);e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(null==e&&(e=this.x);!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(null==e&&(e=this.x);!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose(),this.markers.splice(e--,1);this._isClearing=!1}addMarker(e){const t=new l.Marker(e);return this.markers.push(t),t.register(this.lines.onTrim((e=>{t.line-=e,t.line<0&&t.dispose()}))),t.register(this.lines.onInsert((e=>{t.line>=e.index&&(t.line+=e.amount)}))),t.register(this.lines.onDelete((e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)}))),t.register(t.onDispose((()=>this._removeMarker(t)))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}}},8437:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferLine=t.DEFAULT_ATTR_DATA=void 0;const s=i(3734),r=i(511),n=i(643),o=i(482);t.DEFAULT_ATTR_DATA=Object.freeze(new s.AttributeData);let a=0;class h{constructor(e,t,i=!1){this.isWrapped=i,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*e);const s=t||r.CellData.fromCharData([0,n.NULL_CELL_CHAR,n.NULL_CELL_WIDTH,n.NULL_CELL_CODE]);for(let t=0;t<e;++t)this.setCell(t,s);this.length=e}get(e){const t=this._data[3*e+0],i=2097151&t;return[this._data[3*e+1],2097152&t?this._combined[e]:i?(0,o.stringFromCodePoint)(i):"",t>>22,2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):i]}set(e,t){this._data[3*e+1]=t[n.CHAR_DATA_ATTR_INDEX],t[n.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[e]=t[1],this._data[3*e+0]=2097152|e|t[n.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*e+0]=t[n.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|t[n.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(e){return this._data[3*e+0]>>22}hasWidth(e){return 12582912&this._data[3*e+0]}getFg(e){return this._data[3*e+1]}getBg(e){return this._data[3*e+2]}hasContent(e){return 4194303&this._data[3*e+0]}getCodePoint(e){const t=this._data[3*e+0];return 2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):2097151&t}isCombined(e){return 2097152&this._data[3*e+0]}getString(e){const t=this._data[3*e+0];return 2097152&t?this._combined[e]:2097151&t?(0,o.stringFromCodePoint)(2097151&t):""}isProtected(e){return 536870912&this._data[3*e+2]}loadCell(e,t){return a=3*e,t.content=this._data[a+0],t.fg=this._data[a+1],t.bg=this._data[a+2],2097152&t.content&&(t.combinedData=this._combined[e]),268435456&t.bg&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){2097152&t.content&&(this._combined[e]=t.combinedData),268435456&t.bg&&(this._extendedAttrs[e]=t.extended),this._data[3*e+0]=t.content,this._data[3*e+1]=t.fg,this._data[3*e+2]=t.bg}setCellFromCodepoint(e,t,i,s){268435456&s.bg&&(this._extendedAttrs[e]=s.extended),this._data[3*e+0]=t|i<<22,this._data[3*e+1]=s.fg,this._data[3*e+2]=s.bg}addCodepointToCell(e,t,i){let s=this._data[3*e+0];2097152&s?this._combined[e]+=(0,o.stringFromCodePoint)(t):2097151&s?(this._combined[e]=(0,o.stringFromCodePoint)(2097151&s)+(0,o.stringFromCodePoint)(t),s&=-2097152,s|=2097152):s=t|1<<22,i&&(s&=-12582913,s|=i<<22),this._data[3*e+0]=s}insertCells(e,t,i){if((e%=this.length)&&2===this.getWidth(e-1)&&this.setCellFromCodepoint(e-1,0,1,i),t<this.length-e){const s=new r.CellData;for(let i=this.length-e-t-1;i>=0;--i)this.setCell(e+t+i,this.loadCell(e+i,s));for(let s=0;s<t;++s)this.setCell(e+s,i)}else for(let t=e;t<this.length;++t)this.setCell(t,i);2===this.getWidth(this.length-1)&&this.setCellFromCodepoint(this.length-1,0,1,i)}deleteCells(e,t,i){if(e%=this.length,t<this.length-e){const s=new r.CellData;for(let i=0;i<this.length-e-t;++i)this.setCell(e+i,this.loadCell(e+t+i,s));for(let e=this.length-t;e<this.length;++e)this.setCell(e,i)}else for(let t=e;t<this.length;++t)this.setCell(t,i);e&&2===this.getWidth(e-1)&&this.setCellFromCodepoint(e-1,0,1,i),0!==this.getWidth(e)||this.hasContent(e)||this.setCellFromCodepoint(e,0,1,i)}replaceCells(e,t,i,s=!1){if(s)for(e&&2===this.getWidth(e-1)&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,i),t<this.length&&2===this.getWidth(t-1)&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,i);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,i),e++;else for(e&&2===this.getWidth(e-1)&&this.setCellFromCodepoint(e-1,0,1,i),t<this.length&&2===this.getWidth(t-1)&&this.setCellFromCodepoint(t,0,1,i);e<t&&e<this.length;)this.setCell(e++,i)}resize(e,t){if(e===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;const i=3*e;if(e>this.length){if(this._data.buffer.byteLength>=4*i)this._data=new Uint32Array(this._data.buffer,0,i);else{const e=new Uint32Array(i);e.set(this._data),this._data=e}for(let i=this.length;i<e;++i)this.setCell(i,t)}else{this._data=this._data.subarray(0,i);const t=Object.keys(this._combined);for(let i=0;i<t.length;i++){const s=parseInt(t[i],10);s>=e&&delete this._combined[s]}const s=Object.keys(this._extendedAttrs);for(let t=0;t<s.length;t++){const i=parseInt(s[t],10);i>=e&&delete this._extendedAttrs[i]}}return this.length=e,4*i*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){const e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){this.length!==e.length?this._data=new Uint32Array(e._data):this._data.set(e._data),this.length=e.length,this._combined={};for(const t in e._combined)this._combined[t]=e._combined[t];this._extendedAttrs={};for(const t in e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){const e=new h(0);e._data=new Uint32Array(this._data),e.length=this.length;for(const t in this._combined)e._combined[t]=this._combined[t];for(const t in this._extendedAttrs)e._extendedAttrs[t]=this._extendedAttrs[t];return e.isWrapped=this.isWrapped,e}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0])return e+(this._data[3*e+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0]||50331648&this._data[3*e+2])return e+(this._data[3*e+0]>>22);return 0}copyCellsFrom(e,t,i,s,r){const n=e._data;if(r)for(let r=s-1;r>=0;r--){for(let e=0;e<3;e++)this._data[3*(i+r)+e]=n[3*(t+r)+e];268435456&n[3*(t+r)+2]&&(this._extendedAttrs[i+r]=e._extendedAttrs[t+r])}else for(let r=0;r<s;r++){for(let e=0;e<3;e++)this._data[3*(i+r)+e]=n[3*(t+r)+e];268435456&n[3*(t+r)+2]&&(this._extendedAttrs[i+r]=e._extendedAttrs[t+r])}const o=Object.keys(e._combined);for(let s=0;s<o.length;s++){const r=parseInt(o[s],10);r>=t&&(this._combined[r-t+i]=e._combined[r])}}translateToString(e,t,i,s){t=t??0,i=i??this.length,e&&(i=Math.min(i,this.getTrimmedLength())),s&&(s.length=0);let r="";for(;t<i;){const e=this._data[3*t+0],i=2097151&e,a=2097152&e?this._combined[t]:i?(0,o.stringFromCodePoint)(i):n.WHITESPACE_CELL_CHAR;if(r+=a,s)for(let e=0;e<a.length;++e)s.push(t);t+=e>>22||1}return s&&s.push(t),r}}t.BufferLine=h},4841:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getRangeLength=void 0,t.getRangeLength=function(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}},4634:(e,t)=>{function i(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();const s=!e[t].hasContent(i-1)&&1===e[t].getWidth(i-1),r=2===e[t+1].getWidth(0);return s&&r?i-1:i}Object.defineProperty(t,"__esModule",{value:!0}),t.getWrappedLineTrimmedLength=t.reflowSmallerGetNewLineLengths=t.reflowLargerApplyNewLayout=t.reflowLargerCreateNewLayout=t.reflowLargerGetLinesToRemove=void 0,t.reflowLargerGetLinesToRemove=function(e,t,s,r,n){const o=[];for(let a=0;a<e.length-1;a++){let h=a,c=e.get(++h);if(!c.isWrapped)continue;const l=[e.get(a)];for(;h<e.length&&c.isWrapped;)l.push(c),c=e.get(++h);if(r>=a&&r<h){a+=l.length-1;continue}let d=0,_=i(l,d,t),u=1,f=0;for(;u<l.length;){const e=i(l,u,t),r=e-f,o=s-_,a=Math.min(r,o);l[d].copyCellsFrom(l[u],f,_,a,!1),_+=a,_===s&&(d++,_=0),f+=a,f===e&&(u++,f=0),0===_&&0!==d&&2===l[d-1].getWidth(s-1)&&(l[d].copyCellsFrom(l[d-1],s-1,_++,1,!1),l[d-1].setCell(s-1,n))}l[d].replaceCells(_,s,n);let v=0;for(let e=l.length-1;e>0&&(e>d||0===l[e].getTrimmedLength());e--)v++;v>0&&(o.push(a+l.length-v),o.push(v)),a+=l.length-1}return o},t.reflowLargerCreateNewLayout=function(e,t){const i=[];let s=0,r=t[s],n=0;for(let o=0;o<e.length;o++)if(r===o){const i=t[++s];e.onDeleteEmitter.fire({index:o-n,amount:i}),o+=i-1,n+=i,r=t[++s]}else i.push(o);return{layout:i,countRemoved:n}},t.reflowLargerApplyNewLayout=function(e,t){const i=[];for(let s=0;s<t.length;s++)i.push(e.get(t[s]));for(let t=0;t<i.length;t++)e.set(t,i[t]);e.length=t.length},t.reflowSmallerGetNewLineLengths=function(e,t,s){const r=[],n=e.map(((s,r)=>i(e,r,t))).reduce(((e,t)=>e+t));let o=0,a=0,h=0;for(;h<n;){if(n-h<s){r.push(n-h);break}o+=s;const c=i(e,a,t);o>c&&(o-=c,a++);const l=2===e[a].getWidth(o-1);l&&o--;const d=l?s-1:s;r.push(d),h+=d}return r},t.getWrappedLineTrimmedLength=i},5295:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferSet=void 0;const s=i(8460),r=i(844),n=i(9092);class o extends r.Disposable{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this.register(new s.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange("scrollback",(()=>this.resize(this._bufferService.cols,this._bufferService.rows)))),this.register(this._optionsService.onSpecificOptionChange("tabStopWidth",(()=>this.setupTabStops())))}reset(){this._normal=new n.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new n.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}}t.BufferSet=o},511:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CellData=void 0;const s=i(482),r=i(643),n=i(3734);class o extends n.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new n.ExtendedAttrs,this.combinedData=""}static fromCharData(e){const t=new o;return t.setFromCharData(e),t}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,s.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(e){this.fg=e[r.CHAR_DATA_ATTR_INDEX],this.bg=0;let t=!1;if(e[r.CHAR_DATA_CHAR_INDEX].length>2)t=!0;else if(2===e[r.CHAR_DATA_CHAR_INDEX].length){const i=e[r.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=i&&i<=56319){const s=e[r.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=s&&s<=57343?this.content=1024*(i-55296)+s-56320+65536|e[r.CHAR_DATA_WIDTH_INDEX]<<22:t=!0}else t=!0}else this.content=e[r.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|e[r.CHAR_DATA_WIDTH_INDEX]<<22;t&&(this.combinedData=e[r.CHAR_DATA_CHAR_INDEX],this.content=2097152|e[r.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t.CellData=o},643:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WHITESPACE_CELL_CODE=t.WHITESPACE_CELL_WIDTH=t.WHITESPACE_CELL_CHAR=t.NULL_CELL_CODE=t.NULL_CELL_WIDTH=t.NULL_CELL_CHAR=t.CHAR_DATA_CODE_INDEX=t.CHAR_DATA_WIDTH_INDEX=t.CHAR_DATA_CHAR_INDEX=t.CHAR_DATA_ATTR_INDEX=t.DEFAULT_EXT=t.DEFAULT_ATTR=t.DEFAULT_COLOR=void 0,t.DEFAULT_COLOR=0,t.DEFAULT_ATTR=256|t.DEFAULT_COLOR<<9,t.DEFAULT_EXT=0,t.CHAR_DATA_ATTR_INDEX=0,t.CHAR_DATA_CHAR_INDEX=1,t.CHAR_DATA_WIDTH_INDEX=2,t.CHAR_DATA_CODE_INDEX=3,t.NULL_CELL_CHAR="",t.NULL_CELL_WIDTH=1,t.NULL_CELL_CODE=0,t.WHITESPACE_CELL_CHAR=" ",t.WHITESPACE_CELL_WIDTH=1,t.WHITESPACE_CELL_CODE=32},4863:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Marker=void 0;const s=i(8460),r=i(844);class n{get id(){return this._id}constructor(e){this.line=e,this.isDisposed=!1,this._disposables=[],this._id=n._nextId++,this._onDispose=this.register(new s.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,r.disposeArray)(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}}t.Marker=n,n._nextId=1},7116:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_CHARSET=t.CHARSETS=void 0,t.CHARSETS={},t.DEFAULT_CHARSET=t.CHARSETS.B,t.CHARSETS[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},t.CHARSETS.A={"#":"£"},t.CHARSETS.B=void 0,t.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},t.CHARSETS.C=t.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},t.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},t.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},t.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},t.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},t.CHARSETS.E=t.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},t.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},t.CHARSETS.H=t.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},t.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},2584:(e,t)=>{var i,s,r;Object.defineProperty(t,"__esModule",{value:!0}),t.C1_ESCAPED=t.C1=t.C0=void 0,function(e){e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="",e.BS="\b",e.HT="\t",e.LF="\n",e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""}(i||(t.C0=i={})),function(e){e.PAD="",e.HOP="",e.BPH="",e.NBH="",e.IND="",e.NEL=" ",e.SSA="",e.ESA="",e.HTS="",e.HTJ="",e.VTS="",e.PLD="",e.PLU="",e.RI="",e.SS2="",e.SS3="",e.DCS="",e.PU1="",e.PU2="",e.STS="",e.CCH="",e.MW="",e.SPA="",e.EPA="",e.SOS="",e.SGCI="",e.SCI="",e.CSI="",e.ST="",e.OSC="",e.PM="",e.APC=""}(s||(t.C1=s={})),function(e){e.ST=`${i.ESC}\\`}(r||(t.C1_ESCAPED=r={}))},7399:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.evaluateKeyboardEvent=void 0;const s=i(2584),r={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};t.evaluateKeyboardEvent=function(e,t,i,n){const o={type:0,cancel:!1,key:void 0},a=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:"UIKeyInputUpArrow"===e.key?o.key=t?s.C0.ESC+"OA":s.C0.ESC+"[A":"UIKeyInputLeftArrow"===e.key?o.key=t?s.C0.ESC+"OD":s.C0.ESC+"[D":"UIKeyInputRightArrow"===e.key?o.key=t?s.C0.ESC+"OC":s.C0.ESC+"[C":"UIKeyInputDownArrow"===e.key&&(o.key=t?s.C0.ESC+"OB":s.C0.ESC+"[B");break;case 8:o.key=e.ctrlKey?"\b":s.C0.DEL,e.altKey&&(o.key=s.C0.ESC+o.key);break;case 9:if(e.shiftKey){o.key=s.C0.ESC+"[Z";break}o.key=s.C0.HT,o.cancel=!0;break;case 13:o.key=e.altKey?s.C0.ESC+s.C0.CR:s.C0.CR,o.cancel=!0;break;case 27:o.key=s.C0.ESC,e.altKey&&(o.key=s.C0.ESC+s.C0.ESC),o.cancel=!0;break;case 37:if(e.metaKey)break;a?(o.key=s.C0.ESC+"[1;"+(a+1)+"D",o.key===s.C0.ESC+"[1;3D"&&(o.key=s.C0.ESC+(i?"b":"[1;5D"))):o.key=t?s.C0.ESC+"OD":s.C0.ESC+"[D";break;case 39:if(e.metaKey)break;a?(o.key=s.C0.ESC+"[1;"+(a+1)+"C",o.key===s.C0.ESC+"[1;3C"&&(o.key=s.C0.ESC+(i?"f":"[1;5C"))):o.key=t?s.C0.ESC+"OC":s.C0.ESC+"[C";break;case 38:if(e.metaKey)break;a?(o.key=s.C0.ESC+"[1;"+(a+1)+"A",i||o.key!==s.C0.ESC+"[1;3A"||(o.key=s.C0.ESC+"[1;5A")):o.key=t?s.C0.ESC+"OA":s.C0.ESC+"[A";break;case 40:if(e.metaKey)break;a?(o.key=s.C0.ESC+"[1;"+(a+1)+"B",i||o.key!==s.C0.ESC+"[1;3B"||(o.key=s.C0.ESC+"[1;5B")):o.key=t?s.C0.ESC+"OB":s.C0.ESC+"[B";break;case 45:e.shiftKey||e.ctrlKey||(o.key=s.C0.ESC+"[2~");break;case 46:o.key=a?s.C0.ESC+"[3;"+(a+1)+"~":s.C0.ESC+"[3~";break;case 36:o.key=a?s.C0.ESC+"[1;"+(a+1)+"H":t?s.C0.ESC+"OH":s.C0.ESC+"[H";break;case 35:o.key=a?s.C0.ESC+"[1;"+(a+1)+"F":t?s.C0.ESC+"OF":s.C0.ESC+"[F";break;case 33:e.shiftKey?o.type=2:e.ctrlKey?o.key=s.C0.ESC+"[5;"+(a+1)+"~":o.key=s.C0.ESC+"[5~";break;case 34:e.shiftKey?o.type=3:e.ctrlKey?o.key=s.C0.ESC+"[6;"+(a+1)+"~":o.key=s.C0.ESC+"[6~";break;case 112:o.key=a?s.C0.ESC+"[1;"+(a+1)+"P":s.C0.ESC+"OP";break;case 113:o.key=a?s.C0.ESC+"[1;"+(a+1)+"Q":s.C0.ESC+"OQ";break;case 114:o.key=a?s.C0.ESC+"[1;"+(a+1)+"R":s.C0.ESC+"OR";break;case 115:o.key=a?s.C0.ESC+"[1;"+(a+1)+"S":s.C0.ESC+"OS";break;case 116:o.key=a?s.C0.ESC+"[15;"+(a+1)+"~":s.C0.ESC+"[15~";break;case 117:o.key=a?s.C0.ESC+"[17;"+(a+1)+"~":s.C0.ESC+"[17~";break;case 118:o.key=a?s.C0.ESC+"[18;"+(a+1)+"~":s.C0.ESC+"[18~";break;case 119:o.key=a?s.C0.ESC+"[19;"+(a+1)+"~":s.C0.ESC+"[19~";break;case 120:o.key=a?s.C0.ESC+"[20;"+(a+1)+"~":s.C0.ESC+"[20~";break;case 121:o.key=a?s.C0.ESC+"[21;"+(a+1)+"~":s.C0.ESC+"[21~";break;case 122:o.key=a?s.C0.ESC+"[23;"+(a+1)+"~":s.C0.ESC+"[23~";break;case 123:o.key=a?s.C0.ESC+"[24;"+(a+1)+"~":s.C0.ESC+"[24~";break;default:if(!e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)if(i&&!n||!e.altKey||e.metaKey)!i||e.altKey||e.ctrlKey||e.shiftKey||!e.metaKey?e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&1===e.key.length?o.key=e.key:e.key&&e.ctrlKey&&("_"===e.key&&(o.key=s.C0.US),"@"===e.key&&(o.key=s.C0.NUL)):65===e.keyCode&&(o.type=1);else{const t=r[e.keyCode],i=t?.[e.shiftKey?1:0];if(i)o.key=s.C0.ESC+i;else if(e.keyCode>=65&&e.keyCode<=90){const t=e.ctrlKey?e.keyCode-64:e.keyCode+32;let i=String.fromCharCode(t);e.shiftKey&&(i=i.toUpperCase()),o.key=s.C0.ESC+i}else if(32===e.keyCode)o.key=s.C0.ESC+(e.ctrlKey?s.C0.NUL:" ");else if("Dead"===e.key&&e.code.startsWith("Key")){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),o.key=s.C0.ESC+t,o.cancel=!0}}else e.keyCode>=65&&e.keyCode<=90?o.key=String.fromCharCode(e.keyCode-64):32===e.keyCode?o.key=s.C0.NUL:e.keyCode>=51&&e.keyCode<=55?o.key=String.fromCharCode(e.keyCode-51+27):56===e.keyCode?o.key=s.C0.DEL:219===e.keyCode?o.key=s.C0.ESC:220===e.keyCode?o.key=s.C0.FS:221===e.keyCode&&(o.key=s.C0.GS)}return o}},482:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Utf8ToUtf32=t.StringToUtf32=t.utf32ToString=t.stringFromCodePoint=void 0,t.stringFromCodePoint=function(e){return e>65535?(e-=65536,String.fromCharCode(55296+(e>>10))+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)},t.utf32ToString=function(e,t=0,i=e.length){let s="";for(let r=t;r<i;++r){let t=e[r];t>65535?(t-=65536,s+=String.fromCharCode(55296+(t>>10))+String.fromCharCode(t%1024+56320)):s+=String.fromCharCode(t)}return s},t.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){const i=e.length;if(!i)return 0;let s=0,r=0;if(this._interim){const i=e.charCodeAt(r++);56320<=i&&i<=57343?t[s++]=1024*(this._interim-55296)+i-56320+65536:(t[s++]=this._interim,t[s++]=i),this._interim=0}for(let n=r;n<i;++n){const r=e.charCodeAt(n);if(55296<=r&&r<=56319){if(++n>=i)return this._interim=r,s;const o=e.charCodeAt(n);56320<=o&&o<=57343?t[s++]=1024*(r-55296)+o-56320+65536:(t[s++]=r,t[s++]=o)}else 65279!==r&&(t[s++]=r)}return s}},t.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){const i=e.length;if(!i)return 0;let s,r,n,o,a=0,h=0,c=0;if(this.interim[0]){let s=!1,r=this.interim[0];r&=192==(224&r)?31:224==(240&r)?15:7;let n,o=0;for(;(n=63&this.interim[++o])&&o<4;)r<<=6,r|=n;const h=192==(224&this.interim[0])?2:224==(240&this.interim[0])?3:4,l=h-o;for(;c<l;){if(c>=i)return 0;if(n=e[c++],128!=(192&n)){c--,s=!0;break}this.interim[o++]=n,r<<=6,r|=63&n}s||(2===h?r<128?c--:t[a++]=r:3===h?r<2048||r>=55296&&r<=57343||65279===r||(t[a++]=r):r<65536||r>1114111||(t[a++]=r)),this.interim.fill(0)}const l=i-4;let d=c;for(;d<i;){for(;!(!(d<l)||128&(s=e[d])||128&(r=e[d+1])||128&(n=e[d+2])||128&(o=e[d+3]));)t[a++]=s,t[a++]=r,t[a++]=n,t[a++]=o,d+=4;if(s=e[d++],s<128)t[a++]=s;else if(192==(224&s)){if(d>=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(h=(31&s)<<6|63&r,h<128){d--;continue}t[a++]=h}else if(224==(240&s)){if(d>=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,a;if(n=e[d++],128!=(192&n)){d--;continue}if(h=(15&s)<<12|(63&r)<<6|63&n,h<2048||h>=55296&&h<=57343||65279===h)continue;t[a++]=h}else if(240==(248&s)){if(d>=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,a;if(n=e[d++],128!=(192&n)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,this.interim[2]=n,a;if(o=e[d++],128!=(192&o)){d--;continue}if(h=(7&s)<<18|(63&r)<<12|(63&n)<<6|63&o,h<65536||h>1114111)continue;t[a++]=h}}return a}}},225:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeV6=void 0;const s=i(1480),r=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],n=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];let o;t.UnicodeV6=class{constructor(){if(this.version="6",!o){o=new Uint8Array(65536),o.fill(1),o[0]=0,o.fill(0,1,32),o.fill(0,127,160),o.fill(2,4352,4448),o[9001]=2,o[9002]=2,o.fill(2,11904,42192),o[12351]=1,o.fill(2,44032,55204),o.fill(2,63744,64256),o.fill(2,65040,65050),o.fill(2,65072,65136),o.fill(2,65280,65377),o.fill(2,65504,65511);for(let e=0;e<r.length;++e)o.fill(0,r[e][0],r[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?o[e]:function(e,t){let i,s=0,r=t.length-1;if(e<t[0][0]||e>t[r][1])return!1;for(;r>=s;)if(i=s+r>>1,e>t[i][1])s=i+1;else{if(!(e<t[i][0]))return!0;r=i-1}return!1}(e,n)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),r=0===i&&0!==t;if(r){const e=s.UnicodeService.extractWidth(t);0===e?r=!1:e>i&&(i=e)}return s.UnicodeService.createPropertyValue(0,i,r)}}},5981:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WriteBuffer=void 0;const s=i(8460),r=i(844);class n extends r.Disposable{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new s.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(void 0!==t&&this._syncCalls>t)return void(this._syncCalls=0);if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let i;for(this._isSyncWriting=!0;i=this._writeBuffer.shift();){this._action(i);const e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){const i=e||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){const e=this._writeBuffer[this._bufferOffset],s=this._action(e,t);if(s){const e=e=>Date.now()-i>=12?setTimeout((()=>this._innerWrite(0,e))):this._innerWrite(i,e);return void s.catch((e=>(queueMicrotask((()=>{throw e})),Promise.resolve(!1)))).then(e)}const r=this._callbacks[this._bufferOffset];if(r&&r(),this._bufferOffset++,this._pendingData-=e.length,Date.now()-i>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout((()=>this._innerWrite()))):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}t.WriteBuffer=n},5941:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toRgbString=t.parseColor=void 0;const i=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,s=/^[\da-f]+$/;function r(e,t){const i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}t.parseColor=function(e){if(!e)return;let t=e.toLowerCase();if(0===t.indexOf("rgb:")){t=t.slice(4);const e=i.exec(t);if(e){const t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(0===t.indexOf("#")&&(t=t.slice(1),s.exec(t)&&[3,6,9,12].includes(t.length))){const e=t.length/3,i=[0,0,0];for(let s=0;s<3;++s){const r=parseInt(t.slice(e*s,e*s+e),16);i[s]=1===e?r<<4:2===e?r:3===e?r>>4:r>>8}return i}},t.toRgbString=function(e,t=16){const[i,s,n]=e;return`rgb:${r(i,t)}/${r(s,t)}/${r(n,t)}`}},5770:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PAYLOAD_LIMIT=void 0,t.PAYLOAD_LIMIT=1e7},6351:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DcsHandler=t.DcsParser=void 0;const s=i(482),r=i(8742),n=i(5770),o=[];t.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=o,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=o}registerHandler(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);const i=this._handlers[e];return i.push(t),{dispose:()=>{const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=o,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||o,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t);else this._handlerFb(this._ident,"HOOK",t)}put(e,t,i){if(this._active.length)for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i);else this._handlerFb(this._ident,"PUT",(0,s.utf32ToString)(e,t,i))}unhook(e,t=!0){if(this._active.length){let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&!1===i){for(;s>=0&&(i=this._active[s].unhook(e),!0!==i);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}else this._handlerFb(this._ident,"UNHOOK",e);this._active=o,this._ident=0}};const a=new r.Params;a.addParam(0),t.DcsHandler=class{constructor(e){this._handler=e,this._data="",this._params=a,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():a,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=(0,s.utf32ToString)(e,t,i),this._data.length>n.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then((e=>(this._params=a,this._data="",this._hitLimit=!1,e)));return this._params=a,this._data="",this._hitLimit=!1,t}}},2015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EscapeSequenceParser=t.VT500_TRANSITION_TABLE=t.TransitionTable=void 0;const s=i(844),r=i(8742),n=i(6242),o=i(6351);class a{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,s){this.table[t<<8|e]=i<<4|s}addMany(e,t,i,s){for(let r=0;r<e.length;r++)this.table[t<<8|e[r]]=i<<4|s}}t.TransitionTable=a;const h=160;t.VT500_TRANSITION_TABLE=function(){const e=new a(4095),t=Array.apply(null,Array(256)).map(((e,t)=>t)),i=(e,i)=>t.slice(e,i),s=i(32,127),r=i(0,24);r.push(25),r.push.apply(r,i(28,32));const n=i(0,14);let o;for(o in e.setDefault(1,0),e.addMany(s,0,2,0),n)e.addMany([24,26,153,154],o,3,0),e.addMany(i(128,144),o,3,0),e.addMany(i(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(r,0,3,0),e.addMany(r,1,3,1),e.add(127,1,0,1),e.addMany(r,8,0,8),e.addMany(r,3,3,3),e.add(127,3,0,3),e.addMany(r,4,3,4),e.add(127,4,0,4),e.addMany(r,6,3,6),e.addMany(r,5,3,5),e.add(127,5,0,5),e.addMany(r,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(s,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(r,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(r,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(r,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(r,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(r,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(r,13,13,13),e.addMany(s,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(h,0,2,0),e.add(h,8,5,8),e.add(h,6,0,6),e.add(h,11,0,11),e.add(h,13,13,13),e}();class c extends s.Disposable{constructor(e=t.VT500_TRANSITION_TABLE){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new r.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,i)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,s.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this.register(new n.OscParser),this._dcsParser=this.register(new o.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},(()=>!0))}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let t=0;t<e.intermediates.length;++t){const s=e.intermediates.charCodeAt(t);if(32>s||s>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=s}}if(1!==e.final.length)throw new Error("final must be a single byte");const s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){const t=[];for(;e;)t.push(String.fromCharCode(255&e)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){const i=this._identifier(e,[48,126]);void 0===this._escHandlers[i]&&(this._escHandlers[i]=[]);const s=this._escHandlers[i];return s.push(t),{dispose:()=>{const e=s.indexOf(t);-1!==e&&s.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){const i=this._identifier(e);void 0===this._csiHandlers[i]&&(this._csiHandlers[i]=[]);const s=this._csiHandlers[i];return s.push(t),{dispose:()=>{const e=s.indexOf(t);-1!==e&&s.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,0!==this._parseStack.state&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,s,r){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=r}parse(e,t,i){let s,r=0,n=0,o=0;if(this._parseStack.state)if(2===this._parseStack.state)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(void 0===i||1===this._parseStack.state)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const t=this._parseStack.handlers;let n=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(!1===i&&n>-1)for(;n>=0&&(s=t[n](this._params),!0!==s);n--)if(s instanceof Promise)return this._parseStack.handlerPos=n,s;this._parseStack.handlers=[];break;case 4:if(!1===i&&n>-1)for(;n>=0&&(s=t[n](),!0!==s);n--)if(s instanceof Promise)return this._parseStack.handlerPos=n,s;this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],s=this._dcsParser.unhook(24!==r&&26!==r,i),s)return s;27===r&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],s=this._oscParser.end(24!==r&&26!==r,i),s)return s;27===r&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let i=o;i<t;++i){switch(r=e[i],n=this._transitions.table[this.currentState<<8|(r<160?r:h)],n>>4){case 2:for(let s=i+1;;++s){if(s>=t||(r=e[s])<32||r>126&&r<h){this._printHandler(e,i,s),i=s-1;break}if(++s>=t||(r=e[s])<32||r>126&&r<h){this._printHandler(e,i,s),i=s-1;break}if(++s>=t||(r=e[s])<32||r>126&&r<h){this._printHandler(e,i,s),i=s-1;break}if(++s>=t||(r=e[s])<32||r>126&&r<h){this._printHandler(e,i,s),i=s-1;break}}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:i,code:r,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:const o=this._csiHandlers[this._collect<<8|r];let a=o?o.length-1:-1;for(;a>=0&&(s=o[a](this._params),!0!==s);a--)if(s instanceof Promise)return this._preserveStack(3,o,a,n,i),s;a<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do{switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}}while(++i<t&&(r=e[i])>47&&r<60);i--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:const c=this._escHandlers[this._collect<<8|r];let l=c?c.length-1:-1;for(;l>=0&&(s=c[l](),!0!==s);l--)if(s instanceof Promise)return this._preserveStack(4,c,l,n,i),s;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let s=i+1;;++s)if(s>=t||24===(r=e[s])||26===r||27===r||r>127&&r<h){this._dcsParser.put(e,i,s),i=s-1;break}break;case 14:if(s=this._dcsParser.unhook(24!==r&&26!==r),s)return this._preserveStack(6,[],0,n,i),s;27===r&&(n|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let s=i+1;;s++)if(s>=t||(r=e[s])<32||r>127&&r<h){this._oscParser.put(e,i,s),i=s-1;break}break;case 6:if(s=this._oscParser.end(24!==r&&26!==r),s)return this._preserveStack(5,[],0,n,i),s;27===r&&(n|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&n}}}t.EscapeSequenceParser=c},6242:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OscHandler=t.OscParser=void 0;const s=i(5770),r=i(482),n=[];t.OscParser=class{constructor(){this._state=0,this._active=n,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);const i=this._handlers[e];return i.push(t),{dispose:()=>{const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=n}reset(){if(2===this._state)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=n,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||n,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].start();else this._handlerFb(this._id,"START")}_put(e,t,i){if(this._active.length)for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i);else this._handlerFb(this._id,"PUT",(0,r.utf32ToString)(e,t,i))}start(){this.reset(),this._state=1}put(e,t,i){if(3!==this._state){if(1===this._state)for(;t<i;){const i=e[t++];if(59===i){this._state=2,this._start();break}if(i<48||57<i)return void(this._state=3);-1===this._id&&(this._id=0),this._id=10*this._id+i-48}2===this._state&&i-t>0&&this._put(e,t,i)}}end(e,t=!0){if(0!==this._state){if(3!==this._state)if(1===this._state&&this._start(),this._active.length){let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&!1===i){for(;s>=0&&(i=this._active[s].end(e),!0!==i);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}else this._handlerFb(this._id,"END",e);this._active=n,this._id=-1,this._state=0}}},t.OscHandler=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=(0,r.utf32ToString)(e,t,i),this._data.length>s.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then((e=>(this._data="",this._hitLimit=!1,e)));return this._data="",this._hitLimit=!1,t}}},8742:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Params=void 0;const i=2147483647;class s{static fromArray(e){const t=new s;if(!e.length)return t;for(let i=Array.isArray(e[0])?1:0;i<e.length;++i){const s=e[i];if(Array.isArray(s))for(let e=0;e<s.length;++e)t.addSubParam(s[e]);else t.addParam(s)}return t}constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const e=new s(this.maxLength,this.maxSubParamsLength);return e.params.set(this.params),e.length=this.length,e._subParams.set(this._subParams),e._subParamsLength=this._subParamsLength,e._subParamsIdx.set(this._subParamsIdx),e._rejectDigits=this._rejectDigits,e._rejectSubDigits=this._rejectSubDigits,e._digitIsSub=this._digitIsSub,e}toArray(){const e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);const i=this._subParamsIdx[t]>>8,s=255&this._subParamsIdx[t];s-i>0&&e.push(Array.prototype.slice.call(this._subParams,i,s))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>i?i:e}}addSubParam(e){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(e<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=e>i?i:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(255&this._subParamsIdx[e])-(this._subParamsIdx[e]>>8)>0}getSubParams(e){const t=this._subParamsIdx[e]>>8,i=255&this._subParamsIdx[e];return i-t>0?this._subParams.subarray(t,i):null}getSubParamsAll(){const e={};for(let t=0;t<this.length;++t){const i=this._subParamsIdx[t]>>8,s=255&this._subParamsIdx[t];s-i>0&&(e[t]=this._subParams.slice(i,s))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const s=this._digitIsSub?this._subParams:this.params,r=s[t-1];s[t-1]=~r?Math.min(10*r+e,i):e}}t.Params=s},5741:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AddonManager=void 0,t.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){const i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i<this._addons.length;i++)if(this._addons[i]===e){t=i;break}if(-1===t)throw new Error("Could not dispose an addon that has not been loaded");e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}}},8771:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferApiView=void 0;const s=i(3785),r=i(511);t.BufferApiView=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){const t=this._buffer.lines.get(e);if(t)return new s.BufferLineApiView(t)}getNullCell(){return new r.CellData}}},3785:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferLineApiView=void 0;const s=i(511);t.BufferLineApiView=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new s.CellData)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}}},8285:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferNamespaceApi=void 0;const s=i(8771),r=i(8460),n=i(844);class o extends n.Disposable{constructor(e){super(),this._core=e,this._onBufferChange=this.register(new r.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new s.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new s.BufferApiView(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate((()=>this._onBufferChange.fire(this.active)))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}t.BufferNamespaceApi=o},7975:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ParserApi=void 0,t.ParserApi=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,(e=>t(e.toArray())))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,((e,i)=>t(e,i.toArray())))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}}},7090:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeApi=void 0,t.UnicodeApi=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}}},744:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.BufferService=t.MINIMUM_ROWS=t.MINIMUM_COLS=void 0;const n=i(8460),o=i(844),a=i(5295),h=i(2585);t.MINIMUM_COLS=2,t.MINIMUM_ROWS=1;let c=t.BufferService=class extends o.Disposable{get buffer(){return this.buffers.active}constructor(e){super(),this.isUserScrolling=!1,this._onResize=this.register(new n.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new n.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,t.MINIMUM_COLS),this.rows=Math.max(e.rawOptions.rows||0,t.MINIMUM_ROWS),this.buffers=this.register(new a.BufferSet(e,this))}resize(e,t){this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){const i=this.buffer;let s;s=this._cachedBlankLine,s&&s.length===this.cols&&s.getFg(0)===e.fg&&s.getBg(0)===e.bg||(s=i.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;const r=i.ybase+i.scrollTop,n=i.ybase+i.scrollBottom;if(0===i.scrollTop){const e=i.lines.isFull;n===i.lines.length-1?e?i.lines.recycle().copyFrom(s):i.lines.push(s.clone()):i.lines.splice(n+1,0,s.clone()),e?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{const e=n-r+1;i.lines.shiftElements(r+1,e-1,-1),i.lines.set(n,s.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t,i){const s=this.buffer;if(e<0){if(0===s.ydisp)return;this.isUserScrolling=!0}else e+s.ydisp>=s.ybase&&(this.isUserScrolling=!1);const r=s.ydisp;s.ydisp=Math.max(Math.min(s.ydisp+e,s.ybase),0),r!==s.ydisp&&(t||this._onScroll.fire(s.ydisp))}};t.BufferService=c=s([r(0,h.IOptionsService)],c)},7994:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CharsetService=void 0,t.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}}},1753:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreMouseService=void 0;const n=i(2585),o=i(8460),a=i(844),h={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>4!==e.button&&1===e.action&&(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>32!==e.action},DRAG:{events:23,restrict:e=>32!==e.action||3!==e.button},ANY:{events:31,restrict:e=>!0}};function c(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return 4===e.button?(i|=64,i|=e.action):(i|=3&e.button,4&e.button&&(i|=64),8&e.button&&(i|=128),32===e.action?i|=32:0!==e.action||t||(i|=3)),i}const l=String.fromCharCode,d={DEFAULT:e=>{const t=[c(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`[M${l(t[0])}${l(t[1])}${l(t[2])}`},SGR:e=>{const t=0===e.action&&4!==e.button?"m":"M";return`[<${c(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{const t=0===e.action&&4!==e.button?"m":"M";return`[<${c(e,!0)};${e.x};${e.y}${t}`}};let _=t.CoreMouseService=class extends a.Disposable{constructor(e,t){super(),this._bufferService=e,this._coreService=t,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new o.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(const e of Object.keys(h))this.addProtocol(e,h[e]);for(const e of Object.keys(d))this.addEncoding(e,d[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return 0!==this._protocols[this._activeProtocol].events}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows)return!1;if(4===e.button&&32===e.action)return!1;if(3===e.button&&32!==e.action)return!1;if(4!==e.button&&(2===e.action||3===e.action))return!1;if(e.col++,e.row++,32===e.action&&this._lastEvent&&this._equalEvents(this._lastEvent,e,"SGR_PIXELS"===this._activeEncoding))return!1;if(!this._protocols[this._activeProtocol].restrict(e))return!1;const t=this._encodings[this._activeEncoding](e);return t&&("DEFAULT"===this._activeEncoding?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(1&e),up:!!(2&e),drag:!!(4&e),move:!!(8&e),wheel:!!(16&e)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x)return!1;if(e.y!==t.y)return!1}else{if(e.col!==t.col)return!1;if(e.row!==t.row)return!1}return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};t.CoreMouseService=_=s([r(0,n.IBufferService),r(1,n.ICoreService)],_)},6975:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreService=void 0;const n=i(1439),o=i(8460),a=i(844),h=i(2585),c=Object.freeze({insertMode:!1}),l=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0});let d=t.CoreService=class extends a.Disposable{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new o.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new o.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new o.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new o.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,n.clone)(c),this.decPrivateModes=(0,n.clone)(l)}reset(){this.modes=(0,n.clone)(c),this.decPrivateModes=(0,n.clone)(l)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;const i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`,(()=>e.split("").map((e=>e.charCodeAt(0))))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`,(()=>e.split("").map((e=>e.charCodeAt(0))))),this._onBinary.fire(e))}};t.CoreService=d=s([r(0,h.IBufferService),r(1,h.ILogService),r(2,h.IOptionsService)],d)},9074:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DecorationService=void 0;const s=i(8055),r=i(8460),n=i(844),o=i(6106);let a=0,h=0;class c extends n.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new o.SortedList((e=>e?.marker.line)),this._onDecorationRegistered=this.register(new r.EventEmitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this.register(new r.EventEmitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this.register((0,n.toDisposable)((()=>this.reset())))}registerDecoration(e){if(e.marker.isDisposed)return;const t=new l(e);if(t){const e=t.marker.onDispose((()=>t.dispose()));t.onDispose((()=>{t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())})),this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(const e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let s=0,r=0;for(const n of this._decorations.getKeyIterator(t))s=n.options.x??0,r=s+(n.options.width??1),e>=s&&e<r&&(!i||(n.options.layer??"bottom")===i)&&(yield n)}forEachDecorationAtCell(e,t,i,s){this._decorations.forEachByKey(t,(t=>{a=t.options.x??0,h=a+(t.options.width??1),e>=a&&e<h&&(!i||(t.options.layer??"bottom")===i)&&s(t)}))}}t.DecorationService=c;class l extends n.Disposable{get isDisposed(){return this._isDisposed}get backgroundColorRGB(){return null===this._cachedBg&&(this.options.backgroundColor?this._cachedBg=s.css.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return null===this._cachedFg&&(this.options.foregroundColor?this._cachedFg=s.css.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}constructor(e){super(),this.options=e,this.onRenderEmitter=this.register(new r.EventEmitter),this.onRender=this.onRenderEmitter.event,this._onDispose=this.register(new r.EventEmitter),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}dispose(){this._onDispose.fire(),super.dispose()}}},4348:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InstantiationService=t.ServiceCollection=void 0;const s=i(2585),r=i(8343);class n{constructor(...e){this._entries=new Map;for(const[t,i]of e)this.set(t,i)}set(e,t){const i=this._entries.get(e);return this._entries.set(e,t),i}forEach(e){for(const[t,i]of this._entries.entries())e(t,i)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}}t.ServiceCollection=n,t.InstantiationService=class{constructor(){this._services=new n,this._services.set(s.IInstantiationService,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){const i=(0,r.getServiceDependencies)(e).sort(((e,t)=>e.index-t.index)),s=[];for(const t of i){const i=this._services.get(t.id);if(!i)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id}.`);s.push(i)}const n=i.length>0?i[0].index:t.length;if(t.length!==n)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${n+1} conflicts with ${t.length} static arguments`);return new e(...[...t,...s])}}},7866:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.traceCall=t.setTraceLogger=t.LogService=void 0;const n=i(844),o=i(2585),a={trace:o.LogLevelEnum.TRACE,debug:o.LogLevelEnum.DEBUG,info:o.LogLevelEnum.INFO,warn:o.LogLevelEnum.WARN,error:o.LogLevelEnum.ERROR,off:o.LogLevelEnum.OFF};let h,c=t.LogService=class extends n.Disposable{get logLevel(){return this._logLevel}constructor(e){super(),this._optionsService=e,this._logLevel=o.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",(()=>this._updateLogLevel()))),h=this}_updateLogLevel(){this._logLevel=a[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)"function"==typeof e[t]&&(e[t]=e[t]())}_log(e,t,i){this._evalLazyOptionalParams(i),e.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+t,...i)}trace(e,...t){this._logLevel<=o.LogLevelEnum.TRACE&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=o.LogLevelEnum.DEBUG&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=o.LogLevelEnum.INFO&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=o.LogLevelEnum.WARN&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=o.LogLevelEnum.ERROR&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};t.LogService=c=s([r(0,o.IOptionsService)],c),t.setTraceLogger=function(e){h=e},t.traceCall=function(e,t,i){if("function"!=typeof i.value)throw new Error("not supported");const s=i.value;i.value=function(...e){if(h.logLevel!==o.LogLevelEnum.TRACE)return s.apply(this,e);h.trace(`GlyphRenderer#${s.name}(${e.map((e=>JSON.stringify(e))).join(", ")})`);const t=s.apply(this,e);return h.trace(`GlyphRenderer#${s.name} return`,t),t}}},7302:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionsService=t.DEFAULT_OPTIONS=void 0;const s=i(8460),r=i(844),n=i(6114);t.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rescaleOverlappingGlyphs:!1,rightClickSelectsWord:n.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};const o=["normal","bold","100","200","300","400","500","600","700","800","900"];class a extends r.Disposable{constructor(e){super(),this._onOptionChange=this.register(new s.EventEmitter),this.onOptionChange=this._onOptionChange.event;const i={...t.DEFAULT_OPTIONS};for(const t in e)if(t in i)try{const s=e[t];i[t]=this._sanitizeAndValidateOption(t,s)}catch(e){console.error(e)}this.rawOptions=i,this.options={...i},this._setupOptions(),this.register((0,r.toDisposable)((()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null})))}onSpecificOptionChange(e,t){return this.onOptionChange((i=>{i===e&&t(this.rawOptions[e])}))}onMultipleOptionChange(e,t){return this.onOptionChange((i=>{-1!==e.indexOf(i)&&t()}))}_setupOptions(){const e=e=>{if(!(e in t.DEFAULT_OPTIONS))throw new Error(`No option with key "${e}"`);return this.rawOptions[e]},i=(e,i)=>{if(!(e in t.DEFAULT_OPTIONS))throw new Error(`No option with key "${e}"`);i=this._sanitizeAndValidateOption(e,i),this.rawOptions[e]!==i&&(this.rawOptions[e]=i,this._onOptionChange.fire(e))};for(const t in this.rawOptions){const s={get:e.bind(this,t),set:i.bind(this,t)};Object.defineProperty(this.options,t,s)}}_sanitizeAndValidateOption(e,i){switch(e){case"cursorStyle":if(i||(i=t.DEFAULT_OPTIONS[e]),!function(e){return"block"===e||"underline"===e||"bar"===e}(i))throw new Error(`"${i}" is not a valid value for ${e}`);break;case"wordSeparator":i||(i=t.DEFAULT_OPTIONS[e]);break;case"fontWeight":case"fontWeightBold":if("number"==typeof i&&1<=i&&i<=1e3)break;i=o.includes(i)?i:t.DEFAULT_OPTIONS[e];break;case"cursorWidth":i=Math.floor(i);case"lineHeight":case"tabStopWidth":if(i<1)throw new Error(`${e} cannot be less than 1, value: ${i}`);break;case"minimumContrastRatio":i=Math.max(1,Math.min(21,Math.round(10*i)/10));break;case"scrollback":if((i=Math.min(i,4294967295))<0)throw new Error(`${e} cannot be less than 0, value: ${i}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(i<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${i}`);break;case"rows":case"cols":if(!i&&0!==i)throw new Error(`${e} must be numeric, value: ${i}`);break;case"windowsPty":i=i??{}}return i}}t.OptionsService=a},2660:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OscLinkService=void 0;const n=i(2585);let o=t.OscLinkService=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){const t=this._bufferService.buffer;if(void 0===e.id){const i=t.addMarker(t.ybase+t.y),s={data:e,id:this._nextId++,lines:[i]};return i.onDispose((()=>this._removeMarkerFromLink(s,i))),this._dataByLinkId.set(s.id,s),s.id}const i=e,s=this._getEntryIdKey(i),r=this._entriesWithId.get(s);if(r)return this.addLineToLink(r.id,t.ybase+t.y),r.id;const n=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[n]};return n.onDispose((()=>this._removeMarkerFromLink(o,n))),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){const i=this._dataByLinkId.get(e);if(i&&i.lines.every((e=>e.line!==t))){const e=this._bufferService.buffer.addMarker(t);i.lines.push(e),e.onDispose((()=>this._removeMarkerFromLink(i,e)))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){const i=e.lines.indexOf(t);-1!==i&&(e.lines.splice(i,1),0===e.lines.length&&(void 0!==e.data.id&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};t.OscLinkService=o=s([r(0,n.IBufferService)],o)},8343:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createDecorator=t.getServiceDependencies=t.serviceRegistry=void 0;const i="di$target",s="di$dependencies";t.serviceRegistry=new Map,t.getServiceDependencies=function(e){return e[s]||[]},t.createDecorator=function(e){if(t.serviceRegistry.has(e))return t.serviceRegistry.get(e);const r=function(e,t,n){if(3!==arguments.length)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");!function(e,t,r){t[i]===t?t[s].push({id:e,index:r}):(t[s]=[{id:e,index:r}],t[i]=t)}(r,e,n)};return r.toString=()=>e,t.serviceRegistry.set(e,r),r}},2585:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IDecorationService=t.IUnicodeService=t.IOscLinkService=t.IOptionsService=t.ILogService=t.LogLevelEnum=t.IInstantiationService=t.ICharsetService=t.ICoreService=t.ICoreMouseService=t.IBufferService=void 0;const s=i(8343);var r;t.IBufferService=(0,s.createDecorator)("BufferService"),t.ICoreMouseService=(0,s.createDecorator)("CoreMouseService"),t.ICoreService=(0,s.createDecorator)("CoreService"),t.ICharsetService=(0,s.createDecorator)("CharsetService"),t.IInstantiationService=(0,s.createDecorator)("InstantiationService"),function(e){e[e.TRACE=0]="TRACE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.OFF=5]="OFF"}(r||(t.LogLevelEnum=r={})),t.ILogService=(0,s.createDecorator)("LogService"),t.IOptionsService=(0,s.createDecorator)("OptionsService"),t.IOscLinkService=(0,s.createDecorator)("OscLinkService"),t.IUnicodeService=(0,s.createDecorator)("UnicodeService"),t.IDecorationService=(0,s.createDecorator)("DecorationService")},1480:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeService=void 0;const s=i(8460),r=i(225);class n{static extractShouldJoin(e){return 0!=(1&e)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,i=!1){return(16777215&e)<<3|(3&t)<<1|(i?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new s.EventEmitter,this.onChange=this._onChange.event;const e=new r.UnicodeV6;this.register(e),this._active=e.version,this._activeProvider=e}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw new Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(e){let t=0,i=0;const s=e.length;for(let r=0;r<s;++r){let o=e.charCodeAt(r);if(55296<=o&&o<=56319){if(++r>=s)return t+this.wcwidth(o);const i=e.charCodeAt(r);56320<=i&&i<=57343?o=1024*(o-55296)+i-56320+65536:t+=this.wcwidth(i)}const a=this.charProperties(o,i);let h=n.extractWidth(a);n.extractShouldJoin(a)&&(h-=n.extractWidth(i)),t+=h,i=a}return t}charProperties(e,t){return this._activeProvider.charProperties(e,t)}}t.UnicodeService=n}},t={};function i(s){var r=t[s];if(void 0!==r)return r.exports;var n=t[s]={exports:{}};return e[s].call(n.exports,n,n.exports,i),n.exports}var s={};return(()=>{var e=s;Object.defineProperty(e,"__esModule",{value:!0}),e.Terminal=void 0;const t=i(9042),r=i(3236),n=i(844),o=i(5741),a=i(8285),h=i(7975),c=i(7090),l=["cols","rows"];class d extends n.Disposable{constructor(e){super(),this._core=this.register(new r.Terminal(e)),this._addonManager=this.register(new o.AddonManager),this._publicOptions={...this._core.options};const t=e=>this._core.options[e],i=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(const e in this._core.options){const s={get:t.bind(this,e),set:i.bind(this,e)};Object.defineProperty(this._publicOptions,e,s)}}_checkReadonlyOptions(e){if(l.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new h.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new c.UnicodeApi(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this.register(new a.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const e=this._core.coreService.decPrivateModes;let t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any"}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(const t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write("\r\n",t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return t}_verifyIntegers(...e){for(const t of e)if(t===1/0||isNaN(t)||t%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(const t of e)if(t&&(t===1/0||isNaN(t)||t%1!=0||t<0))throw new Error("This API only accepts positive integers")}}e.Terminal=d})(),s})()));+//# sourceMappingURL=xterm.js.map\ No newline at end of filediff --git a/src/config.rs b/src/config.rsindex 9c3c4e7..eccc534 100644--- a/src/config.rs+++ b/src/config.rs@@ -561,6 +561,25 @@ pub struct Settings {/// see fleet::sessions::actions). The others use Muxin's own.#[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]pub prompts: std::collections::BTreeMap<String, String>,+ /// Sharing sessions by link (see crate::share).+ pub share: ShareSettings,+}++#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]+#[serde(default)]+pub struct ShareSettings {+ /// The share server links go through; empty for Muxin's.+ pub server: String,+ /// The name you join others' shares with.+ pub name: String,+}++impl Settings {+ /// The share server new links use.+ pub fn share_server(&self) -> String {+ let s = self.share.server.trim();+ if s.is_empty() { crate::share::default_server() } else { s.to_string() }+ }}#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]@@ -628,6 +647,7 @@ impl Default for Settings {editor: String::new(),cloud: CloudSettings::default(),prompts: Default::default(),+ share: ShareSettings::default(),}}}diff --git a/src/main.rs b/src/main.rsindex 793452d..349cf43 100644--- a/src/main.rs+++ b/src/main.rs@@ -12,6 +12,8 @@ mod ops;mod probe;#[cfg(feature = "gui")]mod renamed;+#[cfg_attr(not(feature = "gui"), allow(dead_code))]+mod share;mod shell_command;mod update;#[cfg(feature = "gui")]@@ -1369,7 +1371,13 @@ fn main() -> ExitCode {.without_time().init();- let cli = Cli::parse();+ // A share link opened with Muxin: Linux and Windows hand it over as the+ // argument (macOS through the app, see ui::open_link).+ let mut argv: Vec<std::ffi::OsString> = std::env::args_os().collect();+ if let Some(url) = argv.get(1).and_then(|a| a.to_str()).filter(|a| a.starts_with("muxin://join")).map(String::from) {+ argv = vec![argv[0].clone(), "open".into(), "--view".into(), format!("join:{url}").into()];+ }+ let cli = Cli::parse_from(argv);let runtime = match tokio::runtime::Runtime::new().context("starting the async runtime") {Ok(rt) => rt,Err(e) => {diff --git a/src/share/guest.rs b/src/share/guest.rsnew file mode 100644index 0000000..b188cdc--- /dev/null+++ b/src/share/guest.rs@@ -0,0 +1,234 @@+//! Joining someone's share from Muxin: connect through the link's server,+//! check that the answer comes from the share's own certificate, prove the+//! link, then watch (and type, when let) the session shared.++use std::sync::Arc;+use std::sync::atomic::{AtomicBool, Ordering};+use std::time::Duration;++use serde_json::{Value, json};+use tokio::sync::mpsc;+use webrtc::data_channel::DataChannel;+use webrtc::peer_connection::{PeerConnection, RTCPeerConnectionState, RTCSessionDescription};++use super::rtc::{self, Event};+use super::signal;+use super::ticket::{Ticket, hex};++/// The channel the shared session arrives on.+const SESSION: u32 = 1;++/// What's shared, as its host describes it.+#[derive(Clone, Debug, Default)]+pub struct Info {+ pub title: String,+ pub agent: String,+ pub machine: String,+ pub by: String,+ pub can_type: bool,+ /// Unix seconds.+ pub ends_at: i64,+}++/// What happens, in order: the code to read out, what's shared, waiting,+/// let in (or not), then the session.+#[derive(Debug)]+pub enum Update {+ Code(String),+ Info(Info),+ Waiting,+ Admitted { can_type: bool },+ Denied,+ Typing(bool),+ Output(Vec<u8>),+ /// The session's size; draw at it.+ Size(u16, u16),+ /// The session ended (with its code).+ Exited(Option<i32>),+ /// The share ended or the connection dropped, and why.+ Ended(String),+}++/// A joined share: keys to send, and leaving.+pub struct Joined {+ dc: Arc<dyn DataChannel>,+ pc: Arc<dyn PeerConnection>,+ can_type: Arc<AtomicBool>,+ /// Where sending runs (keys can come from any thread, the window's included).+ runtime: tokio::runtime::Handle,+}++impl Joined {+ pub fn can_type(&self) -> bool {+ self.can_type.load(Ordering::Relaxed)+ }++ /// Keys for the session (dropped unless the host lets this guest type;+ /// the host drops them too).+ pub fn send_keys(&self, keys: &[u8]) {+ if !self.can_type() {+ return;+ }+ let dc = self.dc.clone();+ let frame = super::frame(SESSION, super::DATA, keys);+ self.runtime.spawn(async move {+ let _ = rtc::send(&dc, frame).await;+ });+ }++ pub fn leave(&self) {+ let (dc, pc) = (self.dc.clone(), self.pc.clone());+ self.runtime.spawn(async move {+ let _ = rtc::send(&dc, rtc::json_frame(&json!({ "op": "bye" }))).await;+ let _ = pc.close().await;+ });+ }+}++/// Joins the share behind `link` as `name`. Runs on the current Tokio+/// runtime; updates arrive until the share ends or `leave`.+pub async fn join(link: &str, name: &str) -> Result<(Arc<Joined>, mpsc::UnboundedReceiver<Update>), String> {+ let ticket = Ticket::parse(link)?;+ let server = signal::Server::new(&ticket.server);+ let room = ticket.room();+ let (open, ice) = server.room(&room).await.map_err(|e| e.to_string())?;+ if !open {+ return Err("That share isn't open right now. It may have ended.".into());+ }+ let (pc, mut events) = rtc::peer(&ice, None).await?;+ let dc = pc.create_data_channel(rtc::LABEL, None).await.map_err(|e| e.to_string())?;+ let offer = pc.create_offer(None).await.map_err(|e| e.to_string())?;+ pc.set_local_description(offer).await.map_err(|e| e.to_string())?;+ rtc::gathered(&pc, &mut events, &ice).await;+ let sdp = pc.local_description().await.ok_or("no offer")?.sdp;+ let my_fp = rtc::fingerprint(&sdp).ok_or("no certificate in the offer")?;+ let host_fp = hex(&ticket.fingerprint);++ let connecting = async {+ let id = server.offer(&room, &sdp).await.map_err(|e| e.to_string())?;+ // The answer, once the sharing computer picks the offer up (it+ // checks in every couple of seconds).+ let answer = loop {+ tokio::time::sleep(Duration::from_millis(700)).await;+ match server.answer_to(&room, &id).await {+ Ok((Some(answer), _)) => break answer,+ Ok((None, true)) => {}+ Ok((None, false)) | Err(signal::Error::Gone(_)) => return Err("That share has ended.".to_string()),+ Err(e) => return Err(e.to_string()),+ }+ };+ // Only the share's own certificate: the server can't stand in.+ if rtc::fingerprint(&answer).as_deref() != Some(host_fp.as_str()) {+ return Err("That share's connection couldn't be verified.".to_string());+ }+ pc.set_remote_description(RTCSessionDescription::answer(answer).map_err(|e| e.to_string())?).await.map_err(|e| e.to_string())?;+ tokio::select! {+ open = rtc::opened(&dc) => if open { Ok(()) } else { Err("Couldn't connect to the computer sharing it.".to_string()) },+ failed = async {+ loop {+ match events.recv().await {+ Some(Event::State(RTCPeerConnectionState::Failed)) | None => return,+ Some(_) => {}+ }+ }+ } => {+ let () = failed;+ Err("Couldn't connect to the computer sharing it.".to_string())+ }+ }+ };+ let result = tokio::time::timeout(Duration::from_secs(45), connecting).await.unwrap_or_else(|_| Err("Couldn't connect to the computer sharing it.".into()));+ if let Err(e) = result {+ let _ = pc.close().await;+ return Err(e);+ }++ let (tx, rx) = mpsc::unbounded_channel();+ let _ = tx.send(Update::Code(ticket.code(&my_fp)));+ let hello = json!({ "op": "hello", "v": 1, "name": name, "client": "app", "proof": ticket.proof(&host_fp, &my_fp) });+ rtc::send(&dc, rtc::json_frame(&hello)).await?;+ let joined = Arc::new(Joined { dc: dc.clone(), pc: pc.clone(), can_type: Arc::new(AtomicBool::new(false)), runtime: tokio::runtime::Handle::current() });+ let can_type = joined.can_type.clone();+ tokio::spawn(async move {+ let why = relay(&dc, &tx, &can_type, &mut events).await;+ let _ = tx.send(Update::Ended(why));+ let _ = pc.close().await;+ });+ Ok((joined, rx))+}++/// The host's messages and the session, until it ends: why.+async fn relay(dc: &Arc<dyn DataChannel>, tx: &mpsc::UnboundedSender<Update>, can_type: &AtomicBool, events: &mut mpsc::UnboundedReceiver<Event>) -> String {+ loop {+ let msg = tokio::select! {+ m = rtc::next_message(dc) => m,+ e = events.recv() => match e {+ None | Some(Event::State(RTCPeerConnectionState::Failed | RTCPeerConnectionState::Closed)) => None,+ Some(_) => continue,+ },+ };+ let Some(msg) = msg else { return "The connection dropped.".into() };+ let Some((channel, kind, body)) = super::parse_frame(&msg) else { continue };+ if channel == SESSION {+ let _ = match kind {+ super::DATA => tx.send(Update::Output(body.to_vec())),+ super::SIZE if body.len() == 4 => tx.send(Update::Size(u16::from_be_bytes([body[0], body[1]]), u16::from_be_bytes([body[2], body[3]]))),+ super::EXIT => tx.send(Update::Exited((body.len() == 4).then(|| i32::from_be_bytes([body[0], body[1], body[2], body[3]])))),+ super::CLOSE => return "The session ended.".into(),+ _ => Ok(()),+ };+ continue;+ }+ if channel != 0 || kind != super::JSON {+ continue;+ }+ let m: Value = serde_json::from_slice(body).unwrap_or(Value::Null);+ match m["event"].as_str().unwrap_or("") {+ "share" => {+ let info = Info {+ title: text(&m["title"], 120),+ agent: text(&m["agent"], 40),+ machine: text(&m["machine"], 80),+ by: text(&m["by"], 80),+ can_type: m["can_type"].as_bool().unwrap_or(false),+ ends_at: m["ends_at"].as_i64().unwrap_or(0),+ };+ let _ = tx.send(Update::Info(info));+ }+ "waiting" => {+ let _ = tx.send(Update::Waiting);+ }+ "admitted" => {+ let allowed = m["can_type"].as_bool().unwrap_or(false);+ can_type.store(allowed, Ordering::Relaxed);+ let _ = tx.send(Update::Admitted { can_type: allowed });+ let _ = rtc::send(dc, rtc::json_frame(&json!({ "op": "watch", "channel": SESSION }))).await;+ }+ "typing" => {+ let allowed = m["allowed"].as_bool().unwrap_or(false);+ can_type.store(allowed, Ordering::Relaxed);+ let _ = tx.send(Update::Typing(allowed));+ }+ "denied" => {+ let _ = tx.send(Update::Denied);+ return "They didn't let you in.".into();+ }+ "ended" => {+ return match m["why"].as_str().unwrap_or("") {+ "expired" => "The share ended.",+ "removed" => "You were removed from the share.",+ _ => "They stopped sharing.",+ }+ .into();+ }+ "error" => return text(&m["error"], 200),+ _ => {}+ }+ }+}++/// A string from the host, cut short and without control characters (it's+/// shown, so it can't carry terminal escapes or run on forever).+fn text(v: &Value, max: usize) -> String {+ v.as_str().unwrap_or("").chars().filter(|c| !c.is_control()).take(max).collect()+}diff --git a/src/share/host.rs b/src/share/host.rsnew file mode 100644index 0000000..adf5e1b--- /dev/null+++ b/src/share/host.rs@@ -0,0 +1,693 @@+//! Hosting shares: each one waits for guests at the share server, checks+//! them, asks the user to let them in, then relays the one session shared.+//!+//! The gateway is the security boundary. A guest never speaks the machine's+//! link protocol: it may say `hello`, `watch` and `bye`, and send keys on+//! the channel it watches, which reach the session only when the user let+//! that guest type. Its size is never applied (the session keeps the+//! user's), and nothing else it asks for (another session, a shell, files)+//! exists here.++use std::collections::HashMap;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{Arc, Mutex, OnceLock};+use std::time::{Duration, SystemTime, UNIX_EPOCH};++use serde::Serialize;+use serde_json::{Value, json};+use tokio::sync::{mpsc, oneshot, watch};+use webrtc::data_channel::DataChannel;+use webrtc::peer_connection::{PeerConnection, RTCCertificate, RTCPeerConnectionState, RTCSessionDescription};++use super::rtc::{self, Event};+use super::signal;+use super::ticket::{Ticket, hex};+use crate::fleet::link::Link;++/// Guests at once, per share (waiting or in).+const MAX_GUESTS: usize = 16;+/// How long a guest has to say hello once connected.+const HELLO_TIMEOUT: Duration = Duration::from_secs(20);+/// Wrong proofs before a share stops answering (someone guessing).+const MAX_BAD_PROOFS: u32 = 20;+/// How often the sharing app checks in at the share server for guests.+const CHECK_IN: Duration = Duration::from_secs(2);+/// The longest a share can last.+pub const MAX_TTL: Duration = Duration::from_secs(7 * 24 * 3600);++/// What's shared: one session.+#[derive(Clone, Debug, Serialize)]+pub struct Target {+ /// `<machine>/<session>`.+ pub session_id: String,+ pub machine_id: String,+ /// The session's name on the machine.+ pub name: String,+ pub title: String,+ /// "claude", "codex", "shell"...+ pub agent: String,+ pub machine_name: String,+ /// Who shares it, as guests see it.+ pub by: String,+}++#[derive(Clone, Copy, Debug)]+pub struct Options {+ /// Ask before letting each guest in.+ pub approve: bool,+ /// New guests may type.+ pub can_type: bool,+ pub ttl: Duration,+}++/// Where the shared session's machine is reached.+#[async_trait::async_trait]+pub trait Source: Send + Sync + 'static {+ async fn link(&self) -> Result<Arc<Link>, String>;+}++/// The machine through Muxin's engine: its agent up to date, then its link.+pub struct EngineSource {+ pub engine: Arc<crate::fleet::Engine>,+ pub machine_id: String,+}++#[async_trait::async_trait]+impl Source for EngineSource {+ async fn link(&self) -> Result<Arc<Link>, String> {+ let (spec, probe) = self.engine.machine(&self.machine_id).ok_or("That machine is gone.")?;+ crate::fleet::sessions::agent::ensure(&spec, probe.as_ref()).await?;+ crate::fleet::link::get(&spec).await.ok_or_else(|| format!("Can't reach {} right now.", spec.name))+ }+}++/// A guest, as the UI shows it.+#[derive(Clone, Debug, Serialize)]+pub struct GuestView {+ pub id: u64,+ pub name: String,+ pub code: String,+ /// "app" or "browser".+ pub client: String,+ /// "waiting" (for the user to let them in) or "in".+ pub state: String,+ pub can_type: bool,+ /// "direct" or "relay", once known.+ pub path: String,+}++/// A share, as the UI shows it.+#[derive(Clone, Debug, Serialize)]+pub struct ShareView {+ pub id: String,+ pub link: String,+ pub target: Target,+ pub approve: bool,+ pub can_type: bool,+ /// Unix seconds.+ pub ends_at: i64,+ pub guests: Vec<GuestView>,+}++struct Guest {+ view: Mutex<GuestView>,+ /// The user's answer, while the guest waits.+ decide: Mutex<Option<oneshot::Sender<bool>>>,+ control: watch::Sender<Control>,+}++#[derive(Clone, Copy, PartialEq)]+struct Control {+ can_type: bool,+ /// Why the guest is being let go.+ end: Option<&'static str>,+}++struct Share {+ ticket: Ticket,+ /// The share server, and this share's key there.+ server: signal::Server,+ key: String,+ /// Guests being connected (offers answered, not in yet).+ connecting: std::sync::atomic::AtomicUsize,+ cert: RTCCertificate,+ target: Target,+ source: Arc<dyn Source>,+ options: Mutex<Options>,+ ends_at: Mutex<SystemTime>,+ guests: Mutex<HashMap<u64, Arc<Guest>>>,+ stop: watch::Sender<Option<&'static str>>,+ bad_proofs: Mutex<u32>,+}++impl Share {+ fn view(&self) -> ShareView {+ let o = *self.options.lock().unwrap();+ let mut guests: Vec<GuestView> = self.guests.lock().unwrap().values().map(|g| g.view.lock().unwrap().clone()).collect();+ guests.sort_by_key(|g| g.id);+ ShareView {+ id: self.ticket.room(),+ link: self.ticket.link(),+ target: self.target.clone(),+ approve: o.approve,+ can_type: o.can_type,+ ends_at: unix(*self.ends_at.lock().unwrap()),+ guests,+ }+ }++ fn ends_in(&self) -> Duration {+ self.ends_at.lock().unwrap().duration_since(SystemTime::now()).unwrap_or(Duration::ZERO)+ }++ fn info(&self, can_type: bool) -> Value {+ json!({+ "event": "share",+ "title": self.target.title,+ "agent": self.target.agent,+ "machine": self.target.machine_name,+ "by": self.target.by,+ "can_type": can_type,+ "ends_at": unix(*self.ends_at.lock().unwrap()),+ })+ }+}++fn unix(t: SystemTime) -> i64 {+ t.duration_since(UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)+}++#[derive(Default)]+struct Registry {+ shares: Mutex<HashMap<String, Arc<Share>>>,+ changed: OnceLock<watch::Sender<u64>>,+ next_guest: AtomicU64,+}++fn registry() -> &'static Registry {+ static R: OnceLock<Registry> = OnceLock::new();+ R.get_or_init(Registry::default)+}++fn changed() {+ let tx = registry().changed.get_or_init(|| watch::channel(0).0);+ tx.send_modify(|n| *n += 1);+}++/// Bumps whenever a share or a guest changes.+pub fn subscribe() -> watch::Receiver<u64> {+ registry().changed.get_or_init(|| watch::channel(0).0).subscribe()+}++/// Every share running.+pub fn list() -> Vec<ShareView> {+ let mut all: Vec<ShareView> = registry().shares.lock().unwrap().values().map(|s| s.view()).collect();+ all.sort_by(|a, b| a.target.session_id.cmp(&b.target.session_id).then(a.id.cmp(&b.id)));+ all+}++fn find(id: &str) -> Option<Arc<Share>> {+ registry().shares.lock().unwrap().get(id).cloned()+}++fn guest(share: &str, guest: u64) -> Option<Arc<Guest>> {+ find(share)?.guests.lock().unwrap().get(&guest).cloned()+}++/// Starts sharing a session; the view carries the link to give out. Runs+/// on the current Tokio runtime until stopped, expired, or the app quits.+pub async fn start(server: &str, target: Target, options: Options, source: Arc<dyn Source>) -> Result<ShareView, String> {+ let (cert, fingerprint) = rtc::certificate()?;+ let ticket = Ticket::new(server, fingerprint)?;+ let server = signal::Server::new(&ticket.server);+ let key = signal::host_key();+ // The first check-in: the server answers, and keeps the room for us.+ server.check_in(&ticket.room(), &key).await.map_err(|e| e.to_string())?;+ let ttl = options.ttl.min(MAX_TTL);+ let share = Arc::new(Share {+ ticket,+ server,+ key,+ connecting: std::sync::atomic::AtomicUsize::new(0),+ cert,+ target,+ source,+ options: Mutex::new(Options { ttl, ..options }),+ ends_at: Mutex::new(SystemTime::now() + ttl),+ guests: Mutex::new(HashMap::new()),+ stop: watch::channel(None).0,+ bad_proofs: Mutex::new(0),+ });+ registry().shares.lock().unwrap().insert(share.ticket.room(), share.clone());+ changed();+ tokio::spawn(serve(share.clone()));+ Ok(share.view())+}++/// Stops a share: its guests are let go and its link stops working.+pub fn stop(id: &str) {+ if let Some(s) = find(id) {+ s.stop.send_replace(Some("stopped"));+ }+}++/// Stops every share (the app is quitting).+pub fn stop_all() {+ for s in registry().shares.lock().unwrap().values() {+ s.stop.send_replace(Some("stopped"));+ }+}++/// Lets a waiting guest in, or not.+pub fn admit(share: &str, guest_id: u64, yes: bool) {+ if let Some(g) = guest(share, guest_id) {+ if let Some(tx) = g.decide.lock().unwrap().take() {+ let _ = tx.send(yes);+ }+ }+}++/// Lets a guest go.+pub fn remove(share: &str, guest_id: u64) {+ if let Some(g) = guest(share, guest_id) {+ if let Some(tx) = g.decide.lock().unwrap().take() {+ let _ = tx.send(false);+ }+ g.control.send_modify(|c| c.end = Some("removed"));+ }+}++/// Lets a guest type, or not (right away).+pub fn set_typing(share: &str, guest_id: u64, allowed: bool) {+ if let Some(g) = guest(share, guest_id) {+ g.control.send_modify(|c| c.can_type = allowed);+ g.view.lock().unwrap().can_type = allowed;+ changed();+ }+}++/// Who can join and whether guests can type, for a share already going:+/// new guests follow it, and guests in get typing on or off with it. Only+/// guests the user lets in can type; letting anyone in lets in whoever waits.+pub fn set_options(id: &str, approve: bool, can_type: bool) {+ let Some(s) = find(id) else { return };+ let can_type = can_type && approve;+ {+ let mut o = s.options.lock().unwrap();+ o.approve = approve;+ o.can_type = can_type;+ }+ for g in s.guests.lock().unwrap().values() {+ let waiting = g.view.lock().unwrap().state == "waiting";+ if waiting {+ if !approve && let Some(tx) = g.decide.lock().unwrap().take() {+ let _ = tx.send(true);+ }+ continue;+ }+ g.control.send_modify(|c| c.can_type = can_type);+ g.view.lock().unwrap().can_type = can_type;+ }+ changed();+}++/// Ends a share this long from now (a week at most).+pub fn set_ends_in(id: &str, ttl: Duration) {+ if let Some(s) = find(id) {+ *s.ends_at.lock().unwrap() = SystemTime::now() + ttl.min(MAX_TTL);+ changed();+ }+}++/// Makes a share last longer.+pub fn extend(id: &str, by: Duration) {+ if let Some(s) = find(id) {+ let mut ends = s.ends_at.lock().unwrap();+ *ends = (*ends + by).min(SystemTime::now() + MAX_TTL);+ drop(ends);+ changed();+ }+}++/// Checks in at the share server for guests until the share ends.+async fn serve(share: Arc<Share>) {+ let mut stop = share.stop.subscribe();+ let room = share.ticket.room();+ let mut wait = CHECK_IN;+ let why = loop {+ tokio::select! {+ _ = stop.changed() => break stop.borrow().unwrap_or("stopped"),+ _ = tokio::time::sleep(wait.min(share.ends_in())) => {}+ }+ if share.ends_in() == Duration::ZERO {+ break "expired";+ }+ match share.server.check_in(&room, &share.key).await {+ Ok((ice, offers)) => {+ wait = CHECK_IN;+ for (id, sdp) in offers {+ let busy = share.guests.lock().unwrap().len() + share.connecting.load(Ordering::Relaxed);+ if busy >= MAX_GUESTS || *share.bad_proofs.lock().unwrap() >= MAX_BAD_PROOFS {+ continue;+ }+ tokio::spawn(connect_guest(share.clone(), id, sdp, ice.clone()));+ }+ }+ // Away from the server (offline, asleep): guests already in stay,+ // new ones get in once it answers again.+ Err(e) => {+ tracing::debug!("share server: {e}");+ wait = (wait * 2).min(Duration::from_secs(30));+ }+ }+ };+ share.stop.send_replace(Some(why));+ for g in share.guests.lock().unwrap().values() {+ if let Some(tx) = g.decide.lock().unwrap().take() {+ let _ = tx.send(false);+ }+ g.control.send_modify(|c| c.end = Some(why));+ }+ registry().shares.lock().unwrap().remove(&room);+ changed();+ share.server.close(&room, &share.key).await;+}++/// Answers a guest's offer, then runs its connection.+async fn connect_guest(share: Arc<Share>, id: String, offer: String, ice: Value) {+ let Some(guest_fp) = rtc::fingerprint(&offer) else { return };+ share.connecting.fetch_add(1, Ordering::Relaxed);+ let connected = async {+ let (pc, mut events) = rtc::peer(&ice, Some(share.cert.clone())).await.ok()?;+ let answered = async {+ pc.set_remote_description(RTCSessionDescription::offer(offer).map_err(|e| e.to_string())?).await.map_err(|e| e.to_string())?;+ let answer = pc.create_answer(None).await.map_err(|e| e.to_string())?;+ pc.set_local_description(answer).await.map_err(|e| e.to_string())?;+ rtc::gathered(&pc, &mut events, &ice).await;+ let sdp = pc.local_description().await.ok_or("no answer")?.sdp;+ share.server.answer(&share.ticket.room(), &share.key, &id, &sdp).await.map_err(|e| e.to_string())+ }+ .await;+ let dc = match answered {+ Ok(()) => {+ let channel = async {+ loop {+ match events.recv().await? {+ Event::State(RTCPeerConnectionState::Failed | RTCPeerConnectionState::Closed) => return None,+ Event::Channel(dc) => return Some(dc),+ _ => {}+ }+ }+ };+ tokio::time::timeout(Duration::from_secs(30), channel).await.ok().flatten()+ }+ Err(_) => None,+ };+ match dc {+ Some(dc) => Some((pc, dc, events)),+ None => {+ let _ = pc.close().await;+ None+ }+ }+ };+ let connected = connected.await;+ share.connecting.fetch_sub(1, Ordering::Relaxed);+ let Some((pc, dc, events)) = connected else { return };+ let host_fp = hex(&share.ticket.fingerprint);+ run_guest(&share, &pc, dc, &host_fp, &guest_fp, events).await;+ let _ = pc.close().await;+}++/// A guest's connection, from its hello until it leaves or is let go.+async fn run_guest(share: &Arc<Share>, pc: &Arc<dyn PeerConnection>, dc: Arc<dyn DataChannel>, host_fp: &str, guest_fp: &str, mut events: mpsc::UnboundedReceiver<Event>) {+ // What the guest sends, read in one place.+ let (msg_tx, mut from_guest) = mpsc::unbounded_channel::<Vec<u8>>();+ let reader = dc.clone();+ tokio::spawn(async move {+ while let Some(m) = rtc::next_message(&reader).await {+ if msg_tx.send(m).is_err() {+ break;+ }+ }+ });++ // Hello, with the proof that it has the link.+ let hello = match tokio::time::timeout(HELLO_TIMEOUT, from_guest.recv()).await {+ Ok(Some(m)) => m,+ _ => return,+ };+ let hello = match super::parse_frame(&hello) {+ Some((0, super::JSON, body)) => serde_json::from_slice::<Value>(body).unwrap_or(Value::Null),+ _ => Value::Null,+ };+ if hello["op"] != "hello" || !share.ticket.check_proof(host_fp, guest_fp, hello["proof"].as_str().unwrap_or("")) {+ *share.bad_proofs.lock().unwrap() += 1;+ let _ = rtc::send(&dc, rtc::error_frame("This link doesn't work anymore.")).await;+ rtc::flush(&dc).await;+ return;+ }+ let options = *share.options.lock().unwrap();+ let id = registry().next_guest.fetch_add(1, Ordering::Relaxed) + 1;+ let client = if hello["client"] == "browser" { "browser" } else { "app" };+ let view = GuestView {+ id,+ name: clean_name(hello["name"].as_str().unwrap_or("")),+ code: share.ticket.code(guest_fp),+ client: client.into(),+ state: if options.approve { "waiting" } else { "in" }.into(),+ can_type: options.can_type,+ path: String::new(),+ };+ let (decide_tx, decide_rx) = oneshot::channel();+ let guest = Arc::new(Guest {+ view: Mutex::new(view),+ decide: Mutex::new(options.approve.then_some(decide_tx)),+ control: watch::channel(Control { can_type: options.can_type, end: None }).0,+ });+ share.guests.lock().unwrap().insert(id, guest.clone());+ changed();+ let path = pc.clone();+ let g = guest.clone();+ tokio::spawn(async move {+ if let Some(p) = connection_path(&path).await {+ g.view.lock().unwrap().path = p;+ changed();+ }+ });++ let result = admitted(share, &guest, &dc, decide_rx, options, &mut from_guest, &mut events).await;+ if let Err(why) = result {+ let _ = rtc::send(&dc, rtc::json_frame(&json!({ "event": "ended", "why": why }))).await;+ rtc::flush(&dc).await;+ }+ share.guests.lock().unwrap().remove(&id);+ changed();+}++/// Lets the guest in (asking first when the share says so), then relays+/// the session until something ends it: Err(why) to tell the guest.+async fn admitted(+ share: &Arc<Share>,+ guest: &Arc<Guest>,+ dc: &Arc<dyn DataChannel>,+ decide: oneshot::Receiver<bool>,+ options: Options,+ from_guest: &mut mpsc::UnboundedReceiver<Vec<u8>>,+ events: &mut mpsc::UnboundedReceiver<Event>,+) -> Result<(), &'static str> {+ let mut control = guest.control.subscribe();+ rtc::send(dc, rtc::json_frame(&share.info(options.can_type))).await.map_err(|_| "gone")?;+ if options.approve {+ rtc::send(dc, rtc::json_frame(&json!({ "event": "waiting" }))).await.map_err(|_| "gone")?;+ let mut decide = decide;+ let yes = loop {+ tokio::select! {+ d = &mut decide => break d.unwrap_or(false),+ m = from_guest.recv() => if m.is_none() { return Ok(()) },+ _ = control.changed() => if let Some(why) = control.borrow().end { return Err(why) },+ e = events.recv() => if gone(e) { return Ok(()) },+ }+ };+ if !yes {+ let _ = rtc::send(dc, rtc::json_frame(&json!({ "event": "denied" }))).await;+ rtc::flush(dc).await;+ return Ok(());+ }+ guest.view.lock().unwrap().state = "in".into();+ changed();+ }+ let can_type = control.borrow().can_type;+ rtc::send(dc, rtc::json_frame(&json!({ "event": "admitted", "can_type": can_type }))).await.map_err(|_| "gone")?;++ // The session, once the guest asks for it.+ let mut watching: Option<Watching> = None;+ let result = loop {+ let session = async {+ match watching.as_mut() {+ Some(w) => w.frames.recv().await,+ None => std::future::pending().await,+ }+ };+ tokio::select! {+ m = from_guest.recv() => {+ let Some(m) = m else { break Ok(()) };+ match super::parse_frame(&m) {+ Some((0, super::JSON, body)) => {+ let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);+ match req["op"].as_str().unwrap_or("") {+ "watch" => {+ let channel = req["channel"].as_u64().filter(|c| (1..1 << 20).contains(c)).unwrap_or(1) as u32;+ if let Some(w) = watching.take() {+ w.close();+ }+ let can_type = control.borrow().can_type;+ match watch_session(share, channel, can_type).await {+ Ok(w) => watching = Some(w),+ Err(e) => {+ let _ = rtc::send(dc, rtc::error_frame(&e)).await;+ }+ }+ }+ "bye" => break Ok(()),+ _ => {}+ }+ }+ // Keys, only from a guest the user lets type.+ Some((channel, super::DATA, keys)) => {+ if let Some(w) = watching.as_ref().filter(|w| w.guest_channel == channel && w.can_type) {+ w.link.send(w.link_channel, crate::fleet::link::DATA, keys);+ }+ }+ _ => {}+ }+ }+ f = session => {+ let w = watching.as_ref().expect("watching");+ match f {+ Some((kind, bytes)) if [super::DATA, super::SIZE, super::EXIT].contains(&kind) => {+ if rtc::send(dc, super::frame(w.guest_channel, kind, &bytes)).await.is_err() {+ break Ok(());+ }+ }+ Some(_) => {}+ None => {+ let channel = w.guest_channel;+ watching = None;+ let _ = rtc::send(dc, super::frame(channel, super::CLOSE, &[])).await;+ }+ }+ }+ _ = control.changed() => {+ let c = *control.borrow();+ if let Some(why) = c.end {+ break Err(why);+ }+ if watching.as_ref().is_some_and(|w| w.can_type != c.can_type) {+ // Typing on or off: attach again the other way (the+ // session server enforces it too).+ let channel = watching.as_ref().map(|w| w.guest_channel).unwrap_or(1);+ if let Some(w) = watching.take() {+ w.close();+ }+ watching = watch_session(share, channel, c.can_type).await.ok();+ }+ let _ = rtc::send(dc, rtc::json_frame(&json!({ "event": "typing", "allowed": c.can_type }))).await;+ }+ e = events.recv() => if gone(e) { break Ok(()) },+ }+ };+ if let Some(w) = watching {+ w.close();+ }+ result+}++/// The peer connection failed or closed.+fn gone(e: Option<Event>) -> bool {+ matches!(e, None | Some(Event::State(RTCPeerConnectionState::Failed | RTCPeerConnectionState::Closed)))+}++/// The shared session, attached for one guest.+struct Watching {+ link: Arc<Link>,+ link_channel: u32,+ guest_channel: u32,+ can_type: bool,+ frames: mpsc::UnboundedReceiver<(u8, Vec<u8>)>,+}++impl Watching {+ fn close(self) {+ self.link.close_channel(self.link_channel);+ }+}++async fn watch_session(share: &Arc<Share>, guest_channel: u32, can_type: bool) -> Result<Watching, String> {+ let link = share.source.link().await?;+ if !supports_sharing(link.version()) {+ return Err(format!("Muxin's agent on {} needs an update to share sessions.", share.target.machine_name));+ }+ let (link_channel, frames) = link.open_channel();+ let request = json!({ "op": "attach", "name": share.target.name, "channel": link_channel, "watch_only": !can_type, "sizes": true });+ let reply = link.request(request, Duration::from_secs(15)).await?;+ if reply["ok"].as_bool() != Some(true) {+ link.close_channel(link_channel);+ return Err(reply["error"].as_str().unwrap_or("The session couldn't be shown.").to_string());+ }+ Ok(Watching { link, link_channel, guest_channel, can_type, frames })+}++/// Agents from 0.2.9 attach watchers that can't type and report sizes.+fn supports_sharing(version: &str) -> bool {+ let mut parts = version.split('.').map(|p| p.parse::<u32>().unwrap_or(0));+ (parts.next().unwrap_or(0), parts.next().unwrap_or(0), parts.next().unwrap_or(0)) >= (0, 2, 9)+}++/// A guest's name as shown: printable, short, never empty.+fn clean_name(name: &str) -> String {+ let name: String = name.chars().filter(|c| !c.is_control()).collect::<String>().split_whitespace().collect::<Vec<_>>().join(" ");+ let name: String = name.chars().take(40).collect();+ if name.is_empty() { "Someone".into() } else { name }+}++/// "direct" or "relay": whether the connection goes through the TURN server.+async fn connection_path(pc: &Arc<dyn PeerConnection>) -> Option<String> {+ use ::rtc::peer_connection::transport::RTCIceCandidateType;+ use ::rtc::statistics::report::RTCStatsReportEntry;+ use ::rtc::statistics::stats::ice_candidate_pair::RTCStatsIceCandidatePairState;+ for _ in 0..20 {+ tokio::time::sleep(Duration::from_millis(500)).await;+ let report = pc.get_stats(std::time::Instant::now(), webrtc::peer_connection::StatsSelector::None).await;+ let pair = report.iter().find_map(|e| match e {+ RTCStatsReportEntry::IceCandidatePair(p) if p.nominated && p.state == RTCStatsIceCandidatePairState::Succeeded => Some(p),+ _ => None,+ });+ let Some(pair) = pair else { continue };+ let relayed = [&pair.local_candidate_id, &pair.remote_candidate_id].iter().any(|id| {+ matches!(report.get(id), Some(RTCStatsReportEntry::LocalCandidate(c) | RTCStatsReportEntry::RemoteCandidate(c)) if c.candidate_type == RTCIceCandidateType::Relay)+ });+ return Some(if relayed { "relay" } else { "direct" }.into());+ }+ None+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn names_are_cleaned() {+ assert_eq!(clean_name(" Sam \u{7}\n Lee "), "Sam Lee");+ assert_eq!(clean_name(""), "Someone");+ assert_eq!(clean_name(&"x".repeat(100)).len(), 40);+ }++ #[test]+ fn knows_which_agents_share() {+ assert!(supports_sharing("0.2.9"));+ assert!(supports_sharing("0.3.0"));+ assert!(!supports_sharing("0.2.8"));+ assert!(!supports_sharing(""));+ }+}diff --git a/src/share/mod.rs b/src/share/mod.rsnew file mode 100644index 0000000..1897cef--- /dev/null+++ b/src/share/mod.rs@@ -0,0 +1,71 @@+//! Sharing a session by link, peer to peer from this computer.+//!+//! The person sharing gets a link; whoever opens it joins from Muxin or a+//! browser, straight to this computer over WebRTC (a data channel; an+//! encrypted relay only when no direct path works). This app hosts the+//! share: guests never reach the machine itself, only what the gateway here+//! lets through (`host.rs`). It ends when the share expires, is stopped, or+//! this app quits.+//!+//! The link: `https://muxin.dev/s#1.<ticket>` (`ticket.rs`). The server only+//! introduces the two sides (`signal.rs`); the part after `#` never reaches+//! it. The ticket holds the share's id, a secret, and the SHA-256+//! fingerprint of the share's own DTLS certificate.+//!+//! Joining:+//!+//! 1. The guest leaves an offer in the share's room (its id) at the server;+//! the host, checking in every couple of seconds, answers it.+//! 2. The guest refuses an answer whose certificate fingerprint isn't the+//! one in the link, so the server can't sit in the middle.+//! 3. Over the data channel the guest proves it has the secret:+//! `hello.proof = HMAC-SHA256(secret, "muxin-share-v1\n" + host fp + "\n"+//! + guest fp)`, bound to both certificates of this connection.+//! 4. Both sides show the same 6-digit code, made from the secret and the+//! guest's certificate; the host lets the guest in (or a share lets+//! anyone with the link watch).+//!+//! On the data channel each message is one frame, `[channel: u32 BE][kind:+//! u8][payload]`, the link's kinds (`fleet::link`): JSON on channel 0, a+//! terminal on the others (DATA, EXIT, SIZE, CLOSE).+//!+//! Guest to host: `{"op": "hello", "v": 1, "name", "client": "app" |+//! "browser", "proof"}`, then `{"op": "watch", "channel": n}`. Host to guest:+//! `{"event": "share", ...}` (what's shared), `"waiting"`, `"admitted"`,+//! `"denied"`, `"typing"` (`allowed` changed), `"ended"` (`why`), `"error"`.++pub mod guest;+pub mod host;+mod rtc;+mod signal;+#[cfg(test)]+mod tests;+pub mod ticket;++/// Frame kinds on the data channel (the link's).+pub const JSON: u8 = 10;+pub const DATA: u8 = 0;+pub const EXIT: u8 = 2;+pub const SIZE: u8 = 3;+pub const CLOSE: u8 = 11;++/// A frame for the data channel.+pub fn frame(channel: u32, kind: u8, payload: &[u8]) -> Vec<u8> {+ let mut f = Vec::with_capacity(5 + payload.len());+ f.extend(channel.to_be_bytes());+ f.push(kind);+ f.extend(payload);+ f+}++/// A frame's channel, kind and payload.+pub fn parse_frame(msg: &[u8]) -> Option<(u32, u8, &[u8])> {+ let head = msg.get(..5)?;+ Some((u32::from_be_bytes([head[0], head[1], head[2], head[3]]), head[4], &msg[5..]))+}++/// The share server used when Settings don't name another (or+/// `MUXIN_SHARE_SERVER`, for a server of your own while developing).+pub fn default_server() -> String {+ std::env::var("MUXIN_SHARE_SERVER").ok().filter(|s| !s.trim().is_empty()).unwrap_or_else(|| "https://muxin.dev".into())+}diff --git a/src/share/rtc.rs b/src/share/rtc.rsnew file mode 100644index 0000000..8afbc59--- /dev/null+++ b/src/share/rtc.rs@@ -0,0 +1,266 @@+//! WebRTC for both sides of a share: a peer connection with one data+//! channel, its events as a stream, and the certificate checks.++use std::sync::Arc;+use std::time::Duration;++use bytes::BytesMut;+use rtc::peer_connection::certificate::CertificateParams;+use serde_json::{Value, json};+use tokio::sync::mpsc;+use webrtc::data_channel::{DataChannel, DataChannelEvent};+use webrtc::peer_connection::crypto::{self, SignatureScheme};+use webrtc::peer_connection::{+ PeerConnection, PeerConnectionBuilder, PeerConnectionEventHandler, RTCCertificate, RTCConfigurationBuilder, RTCIceGatheringState, RTCIceServer, RTCPeerConnectionState,+};++/// The data channel's label.+pub const LABEL: &str = "muxin";+/// A guest that falls this far behind (bytes waiting to go out) is dropped+/// rather than held in memory.+pub const MAX_BUFFERED: usize = 16 << 20;++/// What a peer connection reports.+pub enum Event {+ /// Every local candidate is known: the description is whole.+ Gathered,+ State(RTCPeerConnectionState),+ Channel(Arc<dyn DataChannel>),+}++struct Handler(mpsc::UnboundedSender<Event>);++#[async_trait::async_trait]+impl PeerConnectionEventHandler for Handler {+ async fn on_ice_gathering_state_change(&self, state: RTCIceGatheringState) {+ if state == RTCIceGatheringState::Complete {+ let _ = self.0.send(Event::Gathered);+ }+ }++ async fn on_connection_state_change(&self, state: RTCPeerConnectionState) {+ let _ = self.0.send(Event::State(state));+ }++ async fn on_data_channel(&self, dc: Arc<dyn DataChannel>) {+ let _ = self.0.send(Event::Channel(dc));+ }+}++/// A new share's certificate and its fingerprint.+pub fn certificate() -> Result<(RTCCertificate, [u8; 32]), String> {+ let provider = crypto::default_provider().map_err(|e| e.to_string())?;+ let params = CertificateParams::new(vec!["muxin-share".to_string()]).map_err(|e| e.to_string())?;+ let cert = RTCCertificate::generate(provider.crypto(), SignatureScheme::EcdsaP256Sha256, params).map_err(|e| e.to_string())?;+ let fp = cert.get_fingerprints(provider.crypto()).map_err(|e| e.to_string())?.into_iter().next().ok_or("no fingerprint")?;+ let bytes = super::ticket::fingerprint_bytes(&fp.value).ok_or("odd fingerprint")?;+ Ok((cert, bytes))+}++/// A peer connection using the server's STUN and TURN servers (`ice`), and+/// `cert` when given (the host's, which guests check).+pub async fn peer(ice: &Value, cert: Option<RTCCertificate>) -> Result<(Arc<dyn PeerConnection>, mpsc::UnboundedReceiver<Event>), String> {+ let (tx, rx) = mpsc::unbounded_channel();+ let mut config = RTCConfigurationBuilder::new().with_ice_servers(ice_servers(ice));+ if let Some(c) = cert {+ config = config.with_certificates(vec![c]);+ }+ let pc = PeerConnectionBuilder::new()+ .with_configuration(config.build())+ .with_handler(Arc::new(Handler(tx)))+ .with_runtime(runtime())+ .with_udp_addrs(vec!["0.0.0.0:0".to_string(), "[::]:0".to_string()])+ .build()+ .await+ .map_err(|e| format!("Couldn't start a connection: {e}"))?;+ Ok((Arc::new(pc), rx))+}++fn runtime() -> Arc<dyn webrtc::runtime::Runtime> {+ static RT: std::sync::OnceLock<Arc<dyn webrtc::runtime::Runtime>> = std::sync::OnceLock::new();+ RT.get_or_init(|| webrtc::runtime::default_runtime().expect("tokio runtime")).clone()+}++/// The server's `ice` list as WebRTC takes it.+fn ice_servers(ice: &Value) -> Vec<RTCIceServer> {+ ice.as_array()+ .into_iter()+ .flatten()+ .filter_map(|s| {+ let urls: Vec<String> = match &s["urls"] {+ Value::String(u) => vec![u.clone()],+ Value::Array(a) => a.iter().filter_map(|u| u.as_str().map(String::from)).collect(),+ _ => return None,+ };+ // STUN, and TURN over UDP: what the WebRTC here speaks (browsers+ // take the rest of the list).+ let urls: Vec<String> = urls.into_iter().filter(|u| u.starts_with("stun:") || (u.starts_with("turn:") && (!u.contains("transport=") || u.contains("transport=udp")))).collect();+ (!urls.is_empty()).then(|| RTCIceServer {+ urls,+ username: s["username"].as_str().unwrap_or("").to_string(),+ credential: s["credential"].as_str().unwrap_or("").to_string(),+ })+ })+ .collect()+}++/// The one SHA-256 certificate fingerprint in an SDP, as lowercase hex; None+/// when there's none, or more than one that differ.+pub fn fingerprint(sdp: &str) -> Option<String> {+ let mut found: Option<String> = None;+ for line in sdp.lines() {+ let Some(rest) = line.trim().strip_prefix("a=fingerprint:") else { continue };+ let (algo, value) = rest.split_once(' ')?;+ if !algo.eq_ignore_ascii_case("sha-256") {+ return None;+ }+ let hex = value.trim().replace(':', "").to_lowercase();+ if hex.len() != 64 || found.as_ref().is_some_and(|f| *f != hex) {+ return None;+ }+ found = Some(hex);+ }+ found+}++/// Waits until the description has the addresses that matter: this+/// computer's own, its public one when there's a STUN server (`ice`), and+/// the relay's when there's a relay. They come within a few hundred ms;+/// the end of gathering itself can take far longer (or never come), and+/// the description goes whole, so waiting for it would only delay joining.+pub async fn gathered(pc: &Arc<dyn PeerConnection>, events: &mut mpsc::UnboundedReceiver<Event>, ice: &Value) {+ let servers = ice_servers(ice);+ let has = |scheme: &str| servers.iter().any(|s| s.urls.iter().any(|u| u.starts_with(scheme)));+ let (public, relay) = (has("stun:"), has("turn:"));+ let deadline = tokio::time::Instant::now() + Duration::from_millis(2500);+ while tokio::time::Instant::now() < deadline {+ if matches!(events.try_recv(), Ok(Event::Gathered)) {+ return;+ }+ let sdp = pc.local_description().await.map(|d| d.sdp).unwrap_or_default();+ if sdp.contains("typ host") && (!public || sdp.contains("typ srflx")) && (!relay || sdp.contains("typ relay")) {+ // A moment for the other networks' addresses.+ tokio::time::sleep(Duration::from_millis(100)).await;+ return;+ }+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+}++/// Sends a frame, waiting while too much is already on its way; an error+/// when the other side has gone or fell too far behind.+pub async fn send(dc: &Arc<dyn DataChannel>, frame: Vec<u8>) -> Result<(), String> {+ let mut waited = Duration::ZERO;+ while dc.outstanding_bytes().await.unwrap_or(0) > MAX_BUFFERED {+ if waited > Duration::from_secs(10) {+ return Err("the other side fell too far behind".into());+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ waited += Duration::from_millis(50);+ }+ dc.send(BytesMut::from(&frame[..])).await.map_err(|e| e.to_string())+}++/// Waits (briefly) until what was sent has gone out, so a last word+/// arrives before the connection closes.+pub async fn flush(dc: &Arc<dyn DataChannel>) {+ for _ in 0..40 {+ if dc.outstanding_bytes().await.unwrap_or(0) == 0 {+ break;+ }+ tokio::time::sleep(Duration::from_millis(25)).await;+ }+ tokio::time::sleep(Duration::from_millis(150)).await;+}++/// What arrives on a data channel, as frames (None: it closed).+pub async fn next_message(dc: &Arc<dyn DataChannel>) -> Option<Vec<u8>> {+ loop {+ match dc.poll().await? {+ DataChannelEvent::OnMessage(m) => return Some(m.data.to_vec()),+ DataChannelEvent::OnClose => return None,+ _ => {}+ }+ }+}++/// Waits for a data channel to open (false: it closed first, or took too long).+pub async fn opened(dc: &Arc<dyn DataChannel>) -> bool {+ let wait = async {+ loop {+ match dc.poll().await {+ Some(DataChannelEvent::OnOpen) => return true,+ Some(DataChannelEvent::OnClose) | None => return false,+ Some(_) => {}+ }+ }+ };+ tokio::time::timeout(Duration::from_secs(20), wait).await.unwrap_or(false)+}++/// A JSON message on channel 0.+pub fn json_frame(v: &Value) -> Vec<u8> {+ super::frame(0, super::JSON, v.to_string().as_bytes())+}++/// An `{"event": "error"}` to tell the other side why.+pub fn error_frame(why: &str) -> Vec<u8> {+ json_frame(&json!({ "event": "error", "error": why }))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn reads_one_fingerprint() {+ let a = "AA:".repeat(31) + "AA";+ let b = "BB:".repeat(31) + "BB";+ let one = format!("v=0\r\na=fingerprint:sha-256 {a}\r\nm=application\r\na=fingerprint:sha-256 {a}\r\n");+ assert_eq!(fingerprint(&one), Some("aa".repeat(32)));+ let two = format!("a=fingerprint:sha-256 {a}\r\na=fingerprint:sha-256 {b}\r\n");+ assert_eq!(fingerprint(&two), None);+ assert_eq!(fingerprint(&format!("a=fingerprint:sha-1 {a}\r\n")), None);+ assert_eq!(fingerprint("v=0\r\n"), None);+ }++ #[test]+ fn keeps_only_stun_and_turn() {+ let servers = ice_servers(&json!([+ { "urls": "stun:stun.example.com:3478" },+ { "urls": ["turn:t.example.com:3478?transport=udp", "turn:t.example.com:80?transport=tcp", "turns:t.example.com:443?transport=tcp", "http://nope"], "username": "u", "credential": "c" },+ { "urls": "javascript:alert(1)" }+ ]));+ assert_eq!(servers.len(), 2);+ assert_eq!(servers[1].urls, vec!["turn:t.example.com:3478?transport=udp".to_string()]);+ assert_eq!(servers[1].username, "u");+ }+}+++#[cfg(test)]+mod relay_check {+ use super::*;++ /// Whether this WebRTC gets a relay address from the share server's+ /// relay (`MUXIN_TEST_SHARE_SERVER`; makes one share's credentials).+ #[tokio::test(flavor = "multi_thread")]+ #[ignore]+ async fn gets_a_relay_address() {+ let server = super::super::signal::Server::new(&std::env::var("MUXIN_TEST_SHARE_SERVER").expect("MUXIN_TEST_SHARE_SERVER"));+ let room = "UkVMQVlDSEVDS1JFTEFZQw";+ let key = super::super::signal::host_key();+ let (ice, _) = server.check_in(room, &key).await.unwrap();+ let (pc, mut events) = peer(&ice, None).await.unwrap();+ let _dc = pc.create_data_channel(LABEL, None).await.unwrap();+ let offer = pc.create_offer(None).await.unwrap();+ let t = std::time::Instant::now();+ pc.set_local_description(offer).await.unwrap();+ gathered(&pc, &mut events, &ice).await;+ let sdp = pc.local_description().await.unwrap().sdp;+ let types: Vec<&str> = sdp.lines().filter_map(|l| l.split(" typ ").nth(1)).map(|t| t.split(' ').next().unwrap_or("")).collect();+ println!("after {:?}: candidate types {types:?}", t.elapsed());+ server.close(room, &key).await;+ assert!(types.contains(&"relay"), "no relay address");+ }+}diff --git a/src/share/signal.rs b/src/share/signal.rsnew file mode 100644index 0000000..dd424e6--- /dev/null+++ b/src/share/signal.rs@@ -0,0 +1,127 @@+//! The share server, from either side: where the two meet before they talk+//! directly (share-server/ in this repository, and muxin.dev's own). HTTP+//! and JSON under `<server>/share/v1`; a room is a share's id:+//!+//! - `POST /rooms/{room}/host`, with `X-Muxin-Host: <key>`: the sharing app+//! checks in (every couple of seconds) and takes the guests' offers+//! waiting: `{ice, offers: [{id, sdp}]}`. 409 when another computer holds+//! the room.+//! - `POST /rooms/{room}/offers/{id}/answer` (the host): `{sdp}`.+//! - `DELETE /rooms/{room}` (the host): the share ended.+//! - `GET /rooms/{room}`: `{open, ice}`, for a guest.+//! - `POST /rooms/{room}/offers`: a guest's `{sdp}`, answered `{id}`.+//! - `GET /rooms/{room}/offers/{id}`: `{answer, open}`, polled by the guest.+//!+//! Errors are `{error}` with a status. Descriptions go whole, every+//! candidate in them (no trickling), and `ice` names the STUN and TURN+//! servers to use.++use std::time::Duration;++use base64::Engine as _;+use base64::engine::general_purpose::URL_SAFE_NO_PAD;+use ring::rand::{SecureRandom, SystemRandom};+use serde_json::{Value, json};++/// How the server answered when it wasn't a yes.+#[derive(Debug)]+pub enum Error {+ /// Another computer holds this share's room.+ Taken,+ /// Not there (the share isn't open, the offer expired).+ Gone(String),+ Other(String),+}++impl std::fmt::Display for Error {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Error::Taken => f.write_str("That share is open on another computer."),+ Error::Gone(e) | Error::Other(e) => f.write_str(e),+ }+ }+}++#[derive(Clone)]+pub struct Server {+ base: String,+ http: reqwest::Client,+}++/// A host's key for its room: only it can check in there.+pub fn host_key() -> String {+ let mut key = [0u8; 32];+ let _ = SystemRandom::new().fill(&mut key);+ URL_SAFE_NO_PAD.encode(key)+}++impl Server {+ /// The server at `origin` (`https://muxin.dev`).+ pub fn new(origin: &str) -> Server {+ let http = reqwest::Client::builder().timeout(Duration::from_secs(15)).connect_timeout(Duration::from_secs(8)).build().unwrap_or_default();+ Server { base: format!("{}/share/v1", origin.trim_end_matches('/')), http }+ }++ async fn call(&self, req: reqwest::RequestBuilder) -> Result<Value, Error> {+ let res = req.header("Accept", "application/json").send().await.map_err(|e| Error::Other(format!("Couldn't reach the share server: {}", short(e))))?;+ let status = res.status();+ let body: Value = res.json().await.unwrap_or(Value::Null);+ let why = || body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("The share server said {status}."));+ match status.as_u16() {+ 200..=299 => Ok(body),+ 409 => Err(Error::Taken),+ 404 | 410 => Err(Error::Gone(why())),+ _ => Err(Error::Other(why())),+ }+ }++ /// The host checks in: the STUN/TURN servers, and the offers waiting.+ pub async fn check_in(&self, room: &str, key: &str) -> Result<(Value, Vec<(String, String)>), Error> {+ let v = self.call(self.http.post(format!("{}/rooms/{room}/host", self.base)).header("X-Muxin-Host", key).json(&json!({}))).await?;+ let offers = v["offers"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|o| Some((o["id"].as_str()?.to_string(), o["sdp"].as_str()?.to_string())))+ .collect();+ Ok((v["ice"].clone(), offers))+ }++ pub async fn answer(&self, room: &str, key: &str, id: &str, sdp: &str) -> Result<(), Error> {+ self.call(self.http.post(format!("{}/rooms/{room}/offers/{id}/answer", self.base)).header("X-Muxin-Host", key).json(&json!({ "sdp": sdp }))).await.map(|_| ())+ }++ /// The share ended: guests still knocking hear so.+ pub async fn close(&self, room: &str, key: &str) {+ let _ = self.call(self.http.delete(format!("{}/rooms/{room}", self.base)).header("X-Muxin-Host", key)).await;+ }++ /// Whether the share is open, and the STUN/TURN servers to use.+ pub async fn room(&self, room: &str) -> Result<(bool, Value), Error> {+ let v = self.call(self.http.get(format!("{}/rooms/{room}", self.base))).await?;+ Ok((v["open"].as_bool() == Some(true), v["ice"].clone()))+ }++ /// Leaves a guest's offer; its id, to wait for the answer with.+ pub async fn offer(&self, room: &str, sdp: &str) -> Result<String, Error> {+ let v = self.call(self.http.post(format!("{}/rooms/{room}/offers", self.base)).json(&json!({ "sdp": sdp }))).await?;+ v["id"].as_str().map(str::to_string).ok_or_else(|| Error::Other("The share server sent something odd.".into()))+ }++ /// The answer to an offer, once there is one, and whether the share is still open.+ pub async fn answer_to(&self, room: &str, id: &str) -> Result<(Option<String>, bool), Error> {+ let v = self.call(self.http.get(format!("{}/rooms/{room}/offers/{id}", self.base))).await?;+ Ok((v["answer"].as_str().map(str::to_string), v["open"].as_bool() != Some(false)))+ }+}++/// An error without the URL (which says nothing useful to the user).+fn short(e: reqwest::Error) -> String {+ if e.is_timeout() {+ "it didn't answer".into()+ } else if e.is_connect() {+ "no connection".into()+ } else {+ e.without_url().to_string()+ }+}diff --git a/src/share/tests.rs b/src/share/tests.rsnew file mode 100644index 0000000..10d2f9c--- /dev/null+++ b/src/share/tests.rs@@ -0,0 +1,240 @@+//! A share end to end: a share server, an agent with a session, a host and+//! guests, all on this computer. Needs the server running and an agent+//! build, and moves HOME (so it runs alone):+//!+//! ```text+//! cargo run -p muxin-share-server &+//! MUXIN_TEST_SHARE_SERVER=http://127.0.0.1:8787 MUXIN_TEST_AGENT=target/debug/muxen-agent \+//! cargo test share::tests -- --ignored --test-threads=1+//! ```++use std::sync::Arc;+use std::time::Duration;++use serde_json::json;+use tokio::sync::mpsc;++use super::guest::{self, Update};+use super::host::{self, Options, Source, Target};+use crate::config::MachineSpec;+use crate::fleet::link::{self, Link};++struct Local(MachineSpec);++#[async_trait::async_trait]+impl Source for Local {+ async fn link(&self) -> Result<Arc<Link>, String> {+ link::get(&self.0).await.ok_or_else(|| "no link".to_string())+ }+}++/// Waits for an update that `want` accepts, skipping others.+async fn next(rx: &mut mpsc::UnboundedReceiver<Update>, what: &str, want: impl Fn(&Update) -> bool) -> Update {+ let wait = async {+ loop {+ match rx.recv().await {+ Some(u) if want(&u) => return u,+ Some(_) => {}+ None => panic!("updates ended waiting for {what}"),+ }+ }+ };+ tokio::time::timeout(Duration::from_secs(20), wait).await.unwrap_or_else(|_| panic!("no {what}"))+}++/// Everything the guest's terminal got, until `needle` shows up (or not).+async fn output_until(rx: &mut mpsc::UnboundedReceiver<Update>, needle: &str, within: Duration) -> (String, bool) {+ let mut text = String::new();+ let deadline = tokio::time::Instant::now() + within;+ while let Ok(Some(u)) = tokio::time::timeout_at(deadline, rx.recv()).await {+ if let Update::Output(b) = u {+ text.push_str(&String::from_utf8_lossy(&b));+ if text.contains(needle) {+ return (text, true);+ }+ }+ }+ (text, false)+}++async fn screen(l: &Link) -> String {+ let r = l.request(json!({ "op": "read", "name": "shared", "lines": 50 }), Duration::from_secs(10)).await.unwrap();+ r["text"].as_str().unwrap_or("").to_string()+}++#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+#[ignore]+async fn a_guest_watches_then_types_when_let() {+ let (Ok(server), Ok(agent)) = (std::env::var("MUXIN_TEST_SHARE_SERVER"), std::env::var("MUXIN_TEST_AGENT")) else {+ panic!("set MUXIN_TEST_SHARE_SERVER and MUXIN_TEST_AGENT");+ };+ // A home of its own: the agent and its sessions live there.+ let home = std::env::temp_dir().join(format!("muxin-share-test-{}", std::process::id()));+ std::fs::create_dir_all(home.join(".muxen/bin")).unwrap();+ std::fs::copy(&agent, home.join(".muxen/bin/muxen-agent")).unwrap();+ unsafe { std::env::set_var("HOME", &home) };+ let spec: MachineSpec = toml::from_str("name = \"Here\"\nid = \"here\"\nhost = \"local\"").unwrap();+ let l = link::get(&spec).await.expect("link to the test agent");+ let started = l.request(json!({ "op": "start", "name": "shared", "agent": "shell", "cwd": home.display().to_string(), "cols": 100, "rows": 30 }), Duration::from_secs(15)).await.unwrap();+ assert_eq!(started["ok"], true, "{started}");++ let target = Target {+ session_id: "here/shared".into(),+ machine_id: "here".into(),+ name: "shared".into(),+ title: "Checkout fix".into(),+ agent: "shell".into(),+ machine_name: "Here".into(),+ by: "Adib".into(),+ };+ let share = host::start(&server, target, Options { approve: true, can_type: false, ttl: Duration::from_secs(120) }, Arc::new(Local(spec.clone()))).await.expect("share");+ assert!(share.link.contains("/s#1."));++ // A link with the wrong secret gets nowhere.+ let mut forged = super::ticket::Ticket::parse(&share.link).unwrap();+ forged.secret = [0; 32];+ match guest::join(&forged.link(), "Mallory").await {+ Ok((_, mut rx)) => match next(&mut rx, "the end", |u| matches!(u, Update::Ended(_))).await {+ Update::Ended(why) => assert!(why.contains("doesn't work"), "{why}"),+ _ => unreachable!(),+ },+ Err(e) => panic!("forged link: {e}"),+ }+ // Nor does one naming another certificate (the server standing in).+ let mut swapped = super::ticket::Ticket::parse(&share.link).unwrap();+ swapped.fingerprint = [7; 32];+ let refused = guest::join(&swapped.link(), "Mallory").await.err().expect("refused");+ assert!(refused.contains("verified"), "{refused}");++ // Sam joins and waits with a code the host sees too.+ let (joined, mut rx) = guest::join(&share.link, "Sam").await.expect("join");+ let code = match next(&mut rx, "the code", |u| matches!(u, Update::Code(_))).await {+ Update::Code(c) => c,+ _ => unreachable!(),+ };+ let info = match next(&mut rx, "what's shared", |u| matches!(u, Update::Info(_))).await {+ Update::Info(i) => i,+ _ => unreachable!(),+ };+ assert_eq!((info.title.as_str(), info.by.as_str(), info.can_type), ("Checkout fix", "Adib", false));+ next(&mut rx, "waiting", |u| matches!(u, Update::Waiting)).await;+ let waiting = host::list().into_iter().find(|s| s.id == share.id).unwrap();+ let sam = waiting.guests.iter().find(|g| g.name == "Sam").expect("Sam knocks");+ assert_eq!((sam.code.as_str(), sam.state.as_str(), sam.client.as_str()), (code.as_str(), "waiting", "app"));+ host::admit(&share.id, sam.id, true);+ next(&mut rx, "admitted", |u| matches!(u, Update::Admitted { can_type: false })).await;+ match next(&mut rx, "the size", |u| matches!(u, Update::Size(..))).await {+ Update::Size(c, r) => assert_eq!((c, r), (100, 30)),+ _ => unreachable!(),+ }++ // On this computer the connection is direct (no relay offered anyway).+ let mut path = String::new();+ for _ in 0..30 {+ path = host::list().into_iter().find(|s| s.id == share.id).and_then(|s| s.guests.into_iter().find(|g| g.id == sam.id)).map(|g| g.path).unwrap_or_default();+ if !path.is_empty() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(300)).await;+ }+ assert_eq!(path, "direct");++ // Watching: the owner's typing shows; Sam's keys go nowhere.+ let (owner, _owner_rx) = l.open_channel();+ let attached = l.request(json!({ "op": "attach", "name": "shared", "channel": owner }), Duration::from_secs(10)).await.unwrap();+ assert_eq!(attached["ok"], true);+ l.send(owner, link::DATA, b"echo FROM_OWNER\r");+ let (_, seen) = output_until(&mut rx, "FROM_OWNER", Duration::from_secs(10)).await;+ assert!(seen, "the guest sees the session");+ joined.send_keys(b"echo FROM_SAM_EARLY\r");+ // Bypassing the app's own check: the host drops it too.+ tokio::time::sleep(Duration::from_millis(1500)).await;+ assert!(!screen(&l).await.contains("FROM_SAM_EARLY"));++ // Let Sam type.+ host::set_typing(&share.id, sam.id, true);+ next(&mut rx, "typing allowed", |u| matches!(u, Update::Typing(true))).await;+ joined.send_keys(b"echo FROM_SAM\r");+ let (_, typed) = output_until(&mut rx, "FROM_SAM", Duration::from_secs(10)).await;+ assert!(typed, "Sam's keys reach the session once let");+ assert!(screen(&l).await.contains("FROM_SAM"));++ // Someone the user doesn't let in hears so.+ let (_, mut kim) = guest::join(&share.link, "Kim").await.expect("join");+ next(&mut kim, "waiting", |u| matches!(u, Update::Waiting)).await;+ let knock = host::list().into_iter().find(|s| s.id == share.id).unwrap().guests.into_iter().find(|g| g.name == "Kim").expect("Kim knocks");+ host::admit(&share.id, knock.id, false);+ next(&mut kim, "denied", |u| matches!(u, Update::Denied)).await;++ // Stopping the share lets Sam go.+ host::stop(&share.id);+ match next(&mut rx, "the end", |u| matches!(u, Update::Ended(_))).await {+ Update::Ended(why) => assert_eq!(why, "They stopped sharing."),+ _ => unreachable!(),+ }+ tokio::time::sleep(Duration::from_millis(500)).await;+ assert!(host::list().is_empty());+ let after = guest::join(&share.link, "Sam").await;+ assert!(after.is_err(), "a stopped share's link stops working");++ let _ = l.request(json!({ "op": "stop", "name": "shared" }), Duration::from_secs(10)).await;+ let _ = std::fs::remove_dir_all(&home);+}++/// Hosts a share for a browser to join by hand (or by a browser driver):+/// writes the link to `MUXIN_TEST_LINK_FILE`, lets guests in, lets them type+/// 15 seconds later, and keeps the session busy. Stops after 10 minutes.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+#[ignore]+async fn hosts_for_a_browser() {+ let (Ok(server), Ok(agent), Ok(link_file)) = (std::env::var("MUXIN_TEST_SHARE_SERVER"), std::env::var("MUXIN_TEST_AGENT"), std::env::var("MUXIN_TEST_LINK_FILE")) else {+ panic!("set MUXIN_TEST_SHARE_SERVER, MUXIN_TEST_AGENT and MUXIN_TEST_LINK_FILE");+ };+ let home = std::env::temp_dir().join(format!("muxin-share-browser-{}", std::process::id()));+ std::fs::create_dir_all(home.join(".muxen/bin")).unwrap();+ std::fs::copy(&agent, home.join(".muxen/bin/muxen-agent")).unwrap();+ unsafe { std::env::set_var("HOME", &home) };+ let spec: MachineSpec = toml::from_str("name = \"Here\"\nid = \"here\"\nhost = \"local\"").unwrap();+ let l = link::get(&spec).await.expect("link to the test agent");+ l.request(json!({ "op": "start", "name": "shared", "agent": "shell", "cwd": home.display().to_string(), "cols": 100, "rows": 30 }), Duration::from_secs(15)).await.unwrap();+ let target = Target {+ session_id: "here/shared".into(),+ machine_id: "here".into(),+ name: "shared".into(),+ title: "Checkout fix".into(),+ agent: "claude".into(),+ machine_name: "Forge".into(),+ by: "Adib".into(),+ };+ let share = host::start(&server, target, Options { approve: true, can_type: false, ttl: Duration::from_secs(600) }, Arc::new(Local(spec))).await.expect("share");+ std::fs::write(&link_file, &share.link).unwrap();+ let (owner, _rx) = l.open_channel();+ l.request(json!({ "op": "attach", "name": "shared", "channel": owner }), Duration::from_secs(10)).await.unwrap();+ let started = std::time::Instant::now();+ let mut admitted: std::collections::HashMap<u64, std::time::Instant> = Default::default();+ let mut tick = 0u32;+ while started.elapsed() < Duration::from_secs(600) {+ tokio::time::sleep(Duration::from_secs(1)).await;+ tick += 1;+ let Some(view) = host::list().into_iter().find(|s| s.id == share.id) else { break };+ for g in &view.guests {+ if g.state == "waiting" && !admitted.contains_key(&g.id) {+ eprintln!("guest {} ({}) code {} — letting in", g.name, g.client, g.code);+ admitted.insert(g.id, std::time::Instant::now());+ host::admit(&share.id, g.id, true);+ }+ if let Some(at) = admitted.get(&g.id) {+ if !g.can_type && at.elapsed() > Duration::from_secs(15) {+ eprintln!("letting {} type ({})", g.name, g.path);+ host::set_typing(&share.id, g.id, true);+ }+ }+ }+ if tick % 5 == 0 {+ l.send(owner, link::DATA, format!("echo owner tick {tick}\r").as_bytes());+ }+ }+ host::stop(&share.id);+ let _ = l.request(json!({ "op": "stop", "name": "shared" }), Duration::from_secs(10)).await;+ let _ = std::fs::remove_dir_all(&home);+}diff --git a/src/share/ticket.rs b/src/share/ticket.rsnew file mode 100644index 0000000..2a7b121--- /dev/null+++ b/src/share/ticket.rs@@ -0,0 +1,241 @@+//! A share's link and what it proves: `https://<server>/s#1.<ticket>`, the+//! ticket being base64url of the share's id (16 bytes), secret (32) and+//! certificate fingerprint (32). Muxin also takes `muxin://join?server=+//! <server>#1.<ticket>` (the link's page opening the app).++use base64::Engine as _;+use base64::engine::general_purpose::URL_SAFE_NO_PAD;+use ring::hmac;+use ring::rand::{SecureRandom, SystemRandom};++const VERSION: &str = "1";++#[derive(Clone, PartialEq, Eq)]+pub struct Ticket {+ /// Where the two sides meet: `https://muxin.dev` (http only for+ /// this computer's own addresses, while developing).+ pub server: String,+ pub id: [u8; 16],+ pub secret: [u8; 32],+ /// SHA-256 of the share's DTLS certificate.+ pub fingerprint: [u8; 32],+}++impl std::fmt::Debug for Ticket {+ // Never the secret, in logs or errors.+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Ticket").field("server", &self.server).field("room", &self.room()).finish_non_exhaustive()+ }+}++impl Ticket {+ /// A new share's ticket, for a certificate with this fingerprint.+ pub fn new(server: &str, fingerprint: [u8; 32]) -> Result<Ticket, String> {+ let server = origin(server)?;+ let rng = SystemRandom::new();+ let (mut id, mut secret) = ([0u8; 16], [0u8; 32]);+ rng.fill(&mut id).map_err(|_| "no randomness")?;+ rng.fill(&mut secret).map_err(|_| "no randomness")?;+ Ok(Ticket { server, id, secret, fingerprint })+ }++ /// The link to give out.+ pub fn link(&self) -> String {+ format!("{}/s#{}", self.server, self.fragment())+ }++ /// The part after `#`.+ pub fn fragment(&self) -> String {+ let mut bytes = Vec::with_capacity(80);+ bytes.extend(self.id);+ bytes.extend(self.secret);+ bytes.extend(self.fingerprint);+ format!("{VERSION}.{}", URL_SAFE_NO_PAD.encode(bytes))+ }++ /// Reads a link (or the app's own form of one).+ pub fn parse(link: &str) -> Result<Ticket, String> {+ let link = link.trim();+ let (before, fragment) = link.split_once('#').ok_or("That isn't a Muxin share link.")?;+ let server = if let Some(query) = before.strip_prefix("muxin://join") {+ let query = query.trim_start_matches('/').trim_start_matches('?');+ let value = query.split('&').find_map(|kv| kv.strip_prefix("server=")).ok_or("That link doesn't say where to connect.")?;+ percent_decode(value)+ } else {+ let after_scheme = before.split_once("://").map(|(_, rest)| rest).ok_or("That isn't a Muxin share link.")?;+ let host = after_scheme.split('/').next().unwrap_or("");+ let scheme = before.split_once("://").map(|(s, _)| s).unwrap_or("");+ format!("{scheme}://{host}")+ };+ let server = origin(&server)?;+ let (version, data) = fragment.split_once('.').ok_or("That share link is cut short.")?;+ if version != VERSION {+ return Err("That share link is from a newer Muxin. Update Muxin to open it.".into());+ }+ let bytes = URL_SAFE_NO_PAD.decode(data.trim()).map_err(|_| "That share link is damaged.")?;+ if bytes.len() != 80 {+ return Err("That share link is cut short.".into());+ }+ let mut t = Ticket { server, id: [0; 16], secret: [0; 32], fingerprint: [0; 32] };+ t.id.copy_from_slice(&bytes[..16]);+ t.secret.copy_from_slice(&bytes[16..48]);+ t.fingerprint.copy_from_slice(&bytes[48..]);+ Ok(t)+ }++ /// The room the server knows the share by.+ pub fn room(&self) -> String {+ URL_SAFE_NO_PAD.encode(self.id)+ }++ /// The guest's proof that it has the link, bound to this connection's+ /// two certificates (fingerprints as lowercase hex).+ pub fn proof(&self, host_fp: &str, guest_fp: &str) -> String {+ let key = hmac::Key::new(hmac::HMAC_SHA256, &self.secret);+ hex(hmac::sign(&key, format!("muxin-share-v1\n{host_fp}\n{guest_fp}").as_bytes()).as_ref())+ }++ /// Whether a guest's proof is right (in constant time).+ pub fn check_proof(&self, host_fp: &str, guest_fp: &str, proof: &str) -> bool {+ let Some(tag) = unhex(proof) else { return false };+ let key = hmac::Key::new(hmac::HMAC_SHA256, &self.secret);+ hmac::verify(&key, format!("muxin-share-v1\n{host_fp}\n{guest_fp}").as_bytes(), &tag).is_ok()+ }++ /// The 6-digit code both sides show for a guest's connection.+ pub fn code(&self, guest_fp: &str) -> String {+ let key = hmac::Key::new(hmac::HMAC_SHA256, &self.secret);+ let tag = hmac::sign(&key, format!("muxin-share-code-v1\n{guest_fp}").as_bytes());+ let n = u32::from_be_bytes([tag.as_ref()[0], tag.as_ref()[1], tag.as_ref()[2], tag.as_ref()[3]]) % 1_000_000;+ format!("{n:06}")+ }+}++/// `scheme://host[:port]` of a server, refusing plain http except to this+/// computer (a server run while developing).+fn origin(server: &str) -> Result<String, String> {+ let s = server.trim().trim_end_matches('/');+ let (scheme, rest) = s.split_once("://").ok_or("The share server needs to be an https:// address.")?;+ let host = rest.split('/').next().unwrap_or("");+ if host.is_empty() || host.contains(['@', ' ', '?', '#']) {+ return Err("The share server's address isn't valid.".into());+ }+ let bare = match host.strip_prefix('[') {+ Some(v6) => v6.split(']').next().unwrap_or(""),+ None => host.rsplit_once(':').map(|(h, _)| h).unwrap_or(host),+ };+ let local = ["localhost", "127.0.0.1", "::1"].contains(&bare);+ match scheme.to_ascii_lowercase().as_str() {+ "https" => Ok(format!("https://{host}")),+ "http" if local => Ok(format!("http://{host}")),+ _ => Err("The share server needs to be an https:// address.".into()),+ }+}++/// A DTLS fingerprint as SDP writes it (`AB:CD:...`) as 32 bytes.+pub fn fingerprint_bytes(sdp_value: &str) -> Option<[u8; 32]> {+ let bytes = unhex(&sdp_value.replace(':', ""))?;+ bytes.try_into().ok()+}++pub fn hex(bytes: &[u8]) -> String {+ bytes.iter().map(|b| format!("{b:02x}")).collect()+}++fn unhex(s: &str) -> Option<Vec<u8>> {+ let s = s.trim();+ if s.len() % 2 != 0 {+ return None;+ }+ (0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect()+}++fn percent_decode(s: &str) -> String {+ let bytes = s.as_bytes();+ let mut out = Vec::with_capacity(bytes.len());+ let mut i = 0;+ while i < bytes.len() {+ if bytes[i] == b'%' && let Some(b) = s.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok()) {+ out.push(b);+ i += 3;+ } else {+ out.push(bytes[i]);+ i += 1;+ }+ }+ String::from_utf8_lossy(&out).into_owned()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn sample() -> Ticket {+ Ticket { server: "https://share.example.com".into(), id: [1; 16], secret: [2; 32], fingerprint: [3; 32] }+ }++ #[test]+ fn links_round_trip() {+ let t = Ticket::new("https://share.example.com/", [9; 32]).unwrap();+ let link = t.link();+ assert!(link.starts_with("https://share.example.com/s#1."));+ assert_eq!(Ticket::parse(&link).unwrap(), t);+ let app = format!("muxin://join?server=https%3A%2F%2Fshare.example.com#{}", t.fragment());+ assert_eq!(Ticket::parse(&app).unwrap(), t);+ }++ #[test]+ fn refuses_plain_http_except_here() {+ assert!(Ticket::new("http://share.example.com", [0; 32]).is_err());+ assert!(Ticket::new("ftp://x", [0; 32]).is_err());+ let local = Ticket::new("http://127.0.0.1:8787", [0; 32]).unwrap();+ assert_eq!(local.server, "http://127.0.0.1:8787");+ assert!(Ticket::new("http://localhost:8787", [0; 32]).is_ok());+ assert!(Ticket::new("http://[::1]:8787", [0; 32]).is_ok());+ // A look-alike host isn't this computer.+ assert!(Ticket::new("http://localhost.evil.com", [0; 32]).is_err());+ let mut t = sample();+ t.server = "http://share.example.com".into();+ assert!(Ticket::parse(&format!("http://share.example.com/s#{}", t.fragment())).is_err());+ }++ #[test]+ fn rejects_damaged_links() {+ let t = sample();+ let link = t.link();+ assert!(Ticket::parse(&link[..link.len() - 4]).is_err());+ assert!(Ticket::parse(&link.replace("#1.", "#2.")).is_err());+ assert!(Ticket::parse("https://share.example.com/s").is_err());+ assert!(!format!("{t:?}").contains(&hex(&t.secret)));+ }++ #[test]+ fn proofs_bind_both_certificates() {+ let t = sample();+ let p = t.proof("aa", "bb");+ assert!(t.check_proof("aa", "bb", &p));+ assert!(!t.check_proof("aa", "cc", &p));+ assert!(!t.check_proof("ab", "bb", &p));+ assert!(!t.check_proof("aa", "bb", "zz"));+ let mut other = sample();+ other.secret = [7; 32];+ assert!(!other.check_proof("aa", "bb", &p));+ }++ #[test]+ fn codes_are_six_digits_per_guest() {+ let t = sample();+ let c = t.code("bb");+ assert_eq!(c.len(), 6);+ assert!(c.chars().all(|ch| ch.is_ascii_digit()));+ assert_eq!(c, t.code("bb"));+ assert_ne!(c, t.code("cc"));+ }++ #[test]+ fn reads_sdp_fingerprints() {+ let fp = fingerprint_bytes("CD:AC:9F:A6:01:82:0E:7F:6B:FD:50:50:57:35:CB:5D:54:8E:9F:82:AD:6E:90:1F:CC:05:89:FC:5E:B2:CD:B4").unwrap();+ assert_eq!(fp[0], 0xcd);+ assert!(fingerprint_bytes("CD:AC").is_none());+ }+}diff --git a/src/ui/assets.rs b/src/ui/assets.rsindex 7bfff7a..9d6358d 100644--- a/src/ui/assets.rs+++ b/src/ui/assets.rs@@ -21,6 +21,7 @@ icons!("rotate-ccw", "scroll-text", "search", "server", "settings", "square", "terminal", "trash-2","triangle-alert", "x", "zap", "arrow-left", "arrow-right", "gauge", "radio", "workflow","bot", "square-terminal", "power", "plug", "unplug",+ "eye", "link", "users", "user-x", "user-check","agent-claude", "agent-codex", "agent-gemini", "agent-opencode", "agent-amp", "agent-pi", "agent-github","circle-dot", "git-pull-request", "git-pull-request-draft", "git-merge", "message-square", "lock", "star","arrow-down", "arrow-up", "book-open", "star-filled", "maximize", "minimize", "panel-right", "panel-left", "columns-2", "rows-2", "pause", "circle-stop",diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rsindex f444934..e1980d6 100644--- a/src/ui/dialogs.rs+++ b/src/ui/dialogs.rs@@ -40,6 +40,8 @@ pub enum DialogEvent {StartInNewVm(crate::ops::vm::VmCreate, Option<CreateWorkspace>, StartSession),/// A virtual monitor was added: (machine, display) to show.DisplayAdded(String, String),+ /// A share joined and let in: open its session.+ JoinedShare(super::share::JoinedHandle),}pub(super) fn frame(theme: &Theme, title: impl Into<SharedString>, intro: Option<SharedString>) -> gpui::Div {diff --git a/src/ui/menu.rs b/src/ui/menu.rsindex 6770415..23c56b2 100644--- a/src/ui/menu.rs+++ b/src/ui/menu.rs@@ -29,6 +29,8 @@ pub enum MenuTarget {Display { machine: String, display: String },/// The editors to open a machine's folder in.Editors { machine: String, path: String },+ /// A shared session's guests and link (by session id).+ Share(String),}pub struct ContextMenu {@@ -95,6 +97,14 @@ enum Action {RemoveDisplay(String, String),/// A monitor's size or scale.SetDisplay(String, String, Option<(u32, u32)>, Option<f64>),+ /// A share's guest: let in (or not), let type (or not), removed.+ ShareAdmit(String, u64, bool),+ ShareTyping(String, u64, bool),+ ShareRemove(String, u64),+ ShareExtend(String),+ ShareStop(String),+ /// The Share dialog of a session (its link and options).+ ShareOptions(String),}enum Item {@@ -335,6 +345,34 @@ impl Root {items.push(Item::Action { label: "End session…".into(), glyph: Glyph::Icon("power"), action: Action::End(id.clone()), danger: true });items}+ MenuTarget::Share(sid) => {+ let Some(share) = self.share_of(sid).cloned() else { return Vec::new() };+ let mut items = vec![Item::Note(format!("Ends in {}", super::share::time_left(share.ends_at)))];+ if share.guests.is_empty() {+ items.push(Item::Note("No one has joined yet.".into()));+ }+ for g in &share.guests {+ let state = if g.state == "waiting" { "waiting" } else if g.can_type { "typing" } else { "watching" };+ let how = if g.client == "browser" { "browser" } else { "Muxin" };+ let path = if g.path.is_empty() { String::new() } else { format!(" · {}", g.path) };+ items.push(Item::Separator);+ items.push(Item::Note(format!("{} · {state} · {how}{path}", g.name)));+ if g.state == "waiting" {+ items.push(act(&format!("Let {} in (code {})", g.name, g.code), "user-check", Action::ShareAdmit(share.id.clone(), g.id, true)));+ items.push(Item::Action { label: format!("Deny {}", g.name), glyph: Glyph::Icon("user-x"), action: Action::ShareAdmit(share.id.clone(), g.id, false), danger: true });+ } else {+ let label = if g.can_type { format!("Stop {} typing", g.name) } else { format!("Let {} type", g.name) };+ items.push(act(&label, "keyboard", Action::ShareTyping(share.id.clone(), g.id, !g.can_type)));+ items.push(Item::Action { label: format!("Remove {}", g.name), glyph: Glyph::Icon("user-x"), action: Action::ShareRemove(share.id.clone(), g.id), danger: true });+ }+ }+ items.push(Item::Separator);+ items.push(act("Link and options…", "sliders-horizontal", Action::ShareOptions(sid.clone())));+ items.push(act("Copy link", "copy", Action::CopyUrl(share.link.clone())));+ items.push(act("Add an hour", "clock", Action::ShareExtend(share.id.clone())));+ items.push(Item::Action { label: "Stop sharing".into(), glyph: Glyph::Icon("power"), action: Action::ShareStop(share.id.clone()), danger: true });+ items+ }MenuTarget::Editors { machine, path } => {let mut items = vec![Item::Note("Open it in".into())];items.extend(editor_items(&self.engine.settings().editor, machine, path, false));@@ -551,6 +589,15 @@ impl Root {cx.write_to_clipboard(ClipboardItem::new_string(url));self.notify_user("Copied the link.", false, cx);}+ Action::ShareAdmit(share, guest, yes) => crate::share::host::admit(&share, guest, yes),+ Action::ShareTyping(share, guest, allowed) => crate::share::host::set_typing(&share, guest, allowed),+ Action::ShareRemove(share, guest) => crate::share::host::remove(&share, guest),+ Action::ShareExtend(share) => crate::share::host::extend(&share, std::time::Duration::from_secs(3600)),+ Action::ShareOptions(session) => self.show_share(&session, window, cx),+ Action::ShareStop(share) => {+ crate::share::host::stop(&share);+ self.notify_user("Stopped sharing. The link doesn't work anymore.", false, cx);+ }}cx.notify();}diff --git a/src/ui/mod.rs b/src/ui/mod.rsindex 3246068..d3c597a 100644--- a/src/ui/mod.rs+++ b/src/ui/mod.rs@@ -23,6 +23,7 @@ mod desktop;mod sessions;mod compose;mod services;+mod share;mod settings;mod shortcuts;mod terminal;@@ -49,7 +50,10 @@ pub fn run(engine: Arc<Engine>, initial_view: Option<String>) {if !engine.is_demo() {std::thread::spawn(crate::renamed::retire_old_app);}- Application::new().with_assets(assets::Assets).run(move |cx: &mut App| {+ let app = Application::new().with_assets(assets::Assets);+ // Share links (muxin://join?server=...#...) opened with Muxin.+ app.on_open_urls(|urls| urls.into_iter().filter(|u| u.starts_with("muxin://join")).for_each(open_link));+ app.run(move |cx: &mut App| {assets::load_fonts(cx);assets::set_dock_icon();// The look lives in config.toml ([ui]); demo mode keeps it in memory.@@ -62,6 +66,12 @@ pub fn run(engine: Arc<Engine>, initial_view: Option<String>) {desktop::bind_keys(cx);root::bind_keys(cx);cx.on_action(|_: &Quit, cx| cx.quit());+ // Quitting ends this app's shares: guests hear so if there's time.+ cx.on_app_quit(|cx| {+ crate::share::host::stop_all();+ cx.background_executor().timer(std::time::Duration::from_millis(90))+ })+ .detach();root::bind_app_actions(cx);cx.set_menus(root::menus());updates::start(engine.clone(), cx);@@ -135,6 +145,24 @@ pub fn run(engine: Arc<Engine>, initial_view: Option<String>) {});}+fn opened_links() -> &'static (futures::channel::mpsc::UnboundedSender<String>, std::sync::Mutex<Option<futures::channel::mpsc::UnboundedReceiver<String>>>) {+ static LINKS: std::sync::OnceLock<(futures::channel::mpsc::UnboundedSender<String>, std::sync::Mutex<Option<futures::channel::mpsc::UnboundedReceiver<String>>>)> = std::sync::OnceLock::new();+ LINKS.get_or_init(|| {+ let (tx, rx) = futures::channel::mpsc::unbounded();+ (tx, std::sync::Mutex::new(Some(rx)))+ })+}++/// A share link opened with Muxin: the window offers to join it.+pub fn open_link(url: String) {+ let _ = opened_links().0.unbounded_send(url);+}++/// The links opened with Muxin, for the window (once).+fn take_opened_links() -> Option<futures::channel::mpsc::UnboundedReceiver<String>> {+ opened_links().1.lock().unwrap().take()+}+/// This computer's clipboard right now: a number that changes with every/// copy, and whether what's there is private (a password manager marks its/// copies: per nspasteboard.org on a Mac, with Windows' clipboard-historydiff --git a/src/ui/palette.rs b/src/ui/palette.rsindex f3b0cd6..b527fb6 100644--- a/src/ui/palette.rs+++ b/src/ui/palette.rs@@ -66,6 +66,9 @@ enum Command {ChooseTheme,/// The machine or session on screen.Rename,+ JoinShare,+ /// The session on screen.+ Share,}#[derive(Clone)]@@ -290,6 +293,12 @@ impl Root {Command::NewVm => self.show_vm_dialog(None, window, cx),Command::NewSchedule => self.show_schedule_dialog(None, window, cx),Command::NewSession => self.show_new_session(None, window, cx),+ Command::JoinShare => self.show_join(None, window, cx),+ Command::Share => {+ if let Route::Session(id) = self.route.clone() {+ self.show_share(&id, window, cx);+ }+ }Command::NewWorkspace => self.show_new_workspace(None, window, cx),Command::CopyFiles => self.show_copy_files(None, None, window, cx),Command::CheckMachines => self.engine.trigger_check(None),@@ -467,6 +476,10 @@ impl Root {};// The machine or session on screen comes first.let rename = self.rename_target().map(|(_, name)| item(&format!("Rename {name}…"), "pencil", None, Run::Do(Command::Rename)));+ let share = match &self.route {+ Route::Session(id) if !self.engine.is_demo() => self.snapshot.sessions.iter().find(|x| &x.id == id && x.persistent).map(|x| item(&format!("Share {}…", x.title), "link", None, Run::Do(Command::Share))),+ _ => None,+ };let all = [item("Add machine…", "plus", Some("add-machine"), Run::Do(Command::AddMachine)),item("New cloud machine…", "cloud", None, Run::Do(Command::NewCloudMachine)),@@ -475,6 +488,7 @@ impl Root {item("Go to Schedules", "clock", Some("schedules"), Run::Go(Route::Schedules)),item("New session…", "square-terminal", Some("new-session"), Run::Do(Command::NewSession)),item("New workspace…", "layers", None, Run::Do(Command::NewWorkspace)),+ item("Join a shared session…", "link", None, Run::Do(Command::JoinShare)),item("Copy files between machines…", "folder", None, Run::Do(Command::CopyFiles)),item("Go to Overview", "gauge", Some("overview"), Run::Go(Route::Overview)),item("Go to Jobs", "workflow", Some("jobs"), Run::Go(Route::Jobs)),@@ -502,7 +516,7 @@ impl Root {item("Theme: Match the system", "palette", None, Run::Do(Command::Theme(Mode::System))),item("About Muxin", "info", None, Run::Go(Route::About)),];- rename.into_iter().chain(all).collect()+ share.into_iter().chain(rename).chain(all).collect()}pub(super) fn render_palette(&self, theme: &Theme, cx: &mut Context<Self>) -> Option<AnyElement> {diff --git a/src/ui/root.rs b/src/ui/root.rsindex 541a224..7b26340 100644--- a/src/ui/root.rs+++ b/src/ui/root.rs@@ -236,6 +236,8 @@ pub enum Route {Logs(String),/// A machine's services and containers.Services(String),+ /// A session someone shared with you, joined here.+ Shared(String),Settings,About,}@@ -272,6 +274,8 @@ pub enum Modal {Rename(Entity<RenameDialog>),AddDisplay(Entity<AddDisplayDialog>),MonitorPassword(Entity<MonitorPasswordDialog>),+ Share(Entity<super::share::ShareDialog>),+ Join(Entity<super::share::JoinDialog>),}pub struct Notice {@@ -403,6 +407,14 @@ pub struct Root {pub(super) ws_ui: WorkspaceUi,/// This computer's clipboard as last seen (see watch_clipboard).clipboard_seen: ClipboardSeen,+ /// Sessions this app shares, and the guests already announced.+ pub(super) shares: Vec<crate::share::host::ShareView>,+ pub(super) knocks_seen: HashSet<(String, u64)>,+ /// Sessions others shared with you, joined here.+ pub(super) joined: Vec<super::share::JoinedSession>,+ pub(super) joined_count: u32,+ /// A share link opened with Muxin, for the Join dialog on the next render.+ pending_join: Option<String>,_tasks: Vec<Task<()>>,pub(super) _subscriptions: Vec<Subscription>,}@@ -572,6 +584,11 @@ impl Root {window_active: false,ws_ui: WorkspaceUi::default(),clipboard_seen: ClipboardSeen { count: super::pasteboard_state().map(|s| s.0).unwrap_or(0), ..Default::default() },+ shares: Vec::new(),+ knocks_seen: HashSet::new(),+ joined: Vec::new(),+ joined_count: 0,+ pending_join: None,_tasks: vec![updates, ticker, clipboard_out, clipboard_in],_subscriptions: subscriptions,};@@ -588,6 +605,29 @@ impl Root {}});ws._tasks.push(watch);+ // Shares: guests knocking, coming and going.+ let mut shares = crate::share::host::subscribe();+ let sharing = cx.spawn(async move |this, cx| {+ while shares.changed().await.is_ok() {+ if this.update(cx, |this, cx| this.shares_changed(cx)).is_err() {+ break;+ }+ }+ });+ ws._tasks.push(sharing);+ // Share links opened with Muxin (muxin://join...).+ if let Some(mut links) = super::take_opened_links() {+ let opened = cx.spawn(async move |this, cx| {+ use futures::StreamExt;+ while let Some(link) = links.next().await {+ let _ = this.update(cx, |this, cx| {+ this.pending_join = Some(link);+ cx.notify()+ });+ }+ });+ ws._tasks.push(opened);+ }ws}@@ -972,6 +1012,10 @@ impl Root {}"activity" => self.show(Route::Activity, cx),"about" => self.navigate(Route::About, window, cx),+ // A share link, in the Join dialog.+ "join" => self.show_join((!arg.is_empty()).then(|| arg.to_string()), window, cx),+ // The Share dialog for a session.+ "share" => self.show_share(arg, window, cx),// "desktop:<machine>", or "desktop:<machine>@<display>" for one of its displays."desktop" => match arg.split_once('@') {Some((machine, display)) => self.show_display(machine.into(), Some(display.into()), window, cx),@@ -1738,6 +1782,8 @@ impl Root {Modal::Rename(d) => d.read(cx).first_focus(cx),Modal::AddDisplay(d) => d.read(cx).first_focus(cx),Modal::MonitorPassword(d) => d.read(cx).first_focus(cx),+ Modal::Share(d) => d.read(cx).first_focus(cx),+ Modal::Join(d) => d.read(cx).first_focus(cx),Modal::Licenses(d) => d.focus_handle(cx),};window.focus(&focus);@@ -1763,6 +1809,7 @@ impl Root {DialogEvent::StartInWorkspace(req, session) => self.start_in_workspace(req.clone(), session.clone(), window, cx),DialogEvent::StartInNewVm(vm, workspace, session) => self.start_in_new_vm(vm.clone(), workspace.clone(), session.clone(), window, cx),DialogEvent::DisplayAdded(machine, display) => self.show_display(machine.clone(), Some(display.clone()), window, cx),+ DialogEvent::JoinedShare(handle) => self.open_joined(handle, window, cx),DialogEvent::StartSession(req) => {self.start_session(req.clone(), window, cx);cx.notify();@@ -2098,6 +2145,10 @@ impl Root {}self.sidebar_indent.set(0.);}+ if !self.joined.is_empty() {+ rows.push(self.section_header("Shared with you", self.joined.len(), false, cx).into_any_element());+ rows.extend(self.joined_rows(&theme, cx));+ }if !unassigned.is_empty() {rows.push(self.section_header("On GitHub only", unassigned.len(), false, cx).into_any_element());for r in unassigned {@@ -3192,6 +3243,7 @@ impl Root {}},Route::About => self.render_about(cx),+ Route::Shared(id) => self.render_joined(&id, window, cx),Route::Github | Route::GithubRepo(_) | Route::GithubItem(..) => self.render_github(window, cx),Route::Settings => match &self.settings {Some(page) => page.clone().into_any_element(),@@ -3206,6 +3258,9 @@ impl Root {impl Render for Root {fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ if let Some(link) = self.pending_join.take() {+ self.show_join(Some(link), window, cx);+ }let theme = cx.theme();// A drag released outside the window never reaches `on_drop`.if self.sidebar_resizing && !cx.has_active_drag() {@@ -3246,6 +3301,8 @@ impl Render for Root {Modal::Rename(d) => d.clone().into_any_element(),Modal::AddDisplay(d) => d.clone().into_any_element(),Modal::MonitorPassword(d) => d.clone().into_any_element(),+ Modal::Share(d) => d.clone().into_any_element(),+ Modal::Join(d) => d.clone().into_any_element(),Modal::Licenses(d) => d.clone().into_any_element(),});let notice = self.render_notice(&theme);@@ -3394,6 +3451,7 @@ fn route_title(s: &Snapshot, route: &Route) -> (Option<&'static str>, String) {Route::Workspace(id) => (Some("Workspaces"), s.workspaces.iter().find(|w| &w.id == id).map(|w| w.name.clone()).unwrap_or_else(|| id.clone())),Route::Settings => (None, "Settings".into()),Route::About => (None, "About".into()),+ Route::Shared(_) => (Some("Shared with you"), "Session".into()),Route::Github => (None, "GitHub".into()),Route::GithubRepo(name) => (Some("GitHub"), name.clone()),Route::GithubItem(repo, n) => (Some("GitHub"), format!("{repo} #{n}")),diff --git a/src/ui/sessions.rs b/src/ui/sessions.rsindex 0f34215..293cd16 100644--- a/src/ui/sessions.rs+++ b/src/ui/sessions.rs@@ -604,6 +604,8 @@ impl Root {.on_click(cx.listener(move |this, _, window, cx| this.toggle_split(&sid, window, cx))),)})+ // Others watching (or typing) by link, peer to peer.+ .when(info.persistent && !exited && offline.is_none() && !self.engine.is_demo(), |d| d.child(self.share_button(&info, cx))).child(Button::new("session-end", "End").icon("power").style(ButtonStyle::Ghost).disabled(offline.is_some()).on_click(cx.listener(move |this, _, window, cx| {if let Some(s) = this.snapshot.sessions.iter().find(|x| x.id == sid2).cloned() {this.confirm_end_session(&s, window, cx);@@ -685,6 +687,15 @@ impl Root {}None => body.into_any_element(),};+ // Over the terminal, not above it: the session keeps its size.+ let knocks = self.knock_cards(&info.id, cx);+ let body = div()+ .relative()+ .flex_1()+ .min_h(px(0.))+ .flex()+ .child(body)+ .when(!knocks.is_empty(), |d| d.child(div().absolute().top_0().left_0().right_0().flex().flex_col().children(knocks)));div().size_full().flex().flex_col().child(header).child(body).into_any_element()}@@ -869,7 +880,10 @@ impl Root {let exited = s.status == "exited";let offline = self.snapshot.machines.iter().any(|m| m.id == s.machine_id && m.is_down());// Explicit width: GPUI 0.2 only ellipsizes text whose width it knows up front.- let trailing = if exited { 40. } else if s.busy || s.attention.is_some() { 20. } else { 0. };+ let shared = self.share_of(&s.id);+ let knocking = shared.is_some_and(|sh| sh.guests.iter().any(|g| g.state == "waiting"));+ let watched = shared.is_some_and(|sh| sh.guests.iter().any(|g| g.state == "in"));+ let trailing = if exited { 40. } else if s.busy || s.attention.is_some() { 20. } else { 0. } + if knocking || watched { 18. } else { 0. };let trailing = trailing + if exited && s.attention.is_some() { 14. } else { 0. };let text_w = (self.row_width() - 20. - 22. - 8. - 16. - 8. - trailing).max(40.);div()@@ -895,6 +909,9 @@ impl Root {.child(s.title.clone()),).child(div().flex_1())+ // Shared: someone's asking to join, or watching.+ .when(watched && !knocking, |d| d.child(kit::icon("eye", 12., theme.text_accent)))+ .when(knocking, |d| d.child(div().size(px(8.)).rounded_full().bg(theme.accent))).when(s.busy && !exited, |d| d.child(spinner(SharedString::from(format!("side-s-spin-{}", s.id)), 11., theme.accent)))// Unread: it finished, rang the bell, or exited. Cleared by opening it..when(!s.busy && !selected, |d| d.children(s.attention.as_deref().map(|kind| attention_dot(theme, kind, s.exit_code))))diff --git a/src/ui/share.rs b/src/ui/share.rsnew file mode 100644index 0000000..3e66c66--- /dev/null+++ b/src/ui/share.rs@@ -0,0 +1,836 @@+//! Sharing in the window: the Share dialog and the session header's button,+//! letting guests in, and sessions others shared with you (joined from a+//! link). The sharing itself is crate::share.++use std::sync::{Arc, Mutex};+use std::time::Duration;++use gpui::{AnyElement, App, ClipboardItem, Context, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, SharedString, Subscription, Window, div, prelude::*, px};+use tokio::sync::mpsc;++use super::dialogs::{DialogEvent, error_line, field, footer, frame};+use super::input::{InputEvent, TextInput};+use super::kit::{self, Button, ButtonStyle, card, icon};+use super::root::{Modal, Route, Root};+use super::terminal::{RemoteIo, RemoteOutput, TerminalView};+use super::theme::{ActiveTheme, Theme, mono_font};+use crate::fleet::Engine;+use crate::fleet::sessions::SessionInfo;+use crate::share::{guest, host};++/// How long a share lasts: what the dialog offers.+const DURATIONS: &[(&str, u64)] = &[("15 min", 15 * 60), ("1 hour", 3600), ("8 hours", 8 * 3600), ("1 day", 24 * 3600)];++/// "42 min", "3 hours".+pub(super) fn time_left(ends_at: i64) -> String {+ let left = ends_at - chrono::Utc::now().timestamp();+ if left <= 0 {+ "Ending".into()+ } else if left < 3600 {+ format!("{} min", (left / 60).max(1))+ } else {+ let h = (left + 1800) / 3600;+ format!("{h} hour{}", if h == 1 { "" } else { "s" })+ }+}++fn fact(theme: &Theme, glyph: &'static str, text: impl Into<SharedString>) -> impl IntoElement {+ div().flex().items_center().gap(px(10.)).text_size(px(13.)).text_color(theme.text).child(icon(glyph, 15., theme.text_muted)).child(text.into())+}++// ---------------------------------------------------------------------------+// Sharing a session++/// Sharing a session: one click makes the link and copies it (you let each+/// person in, they watch, for an hour); what they can do and for how long+/// change here afterwards, while it runs.+pub struct ShareDialog {+ engine: Arc<Engine>,+ target: host::Target,+ /// The share, once made.+ share: Option<String>,+ creating: bool,+ copied: bool,+ error: Option<String>,+ focus: FocusHandle,+}++impl EventEmitter<DialogEvent> for ShareDialog {}++impl ShareDialog {+ /// The share this session has, or a new one made right away.+ pub fn new(engine: Arc<Engine>, target: host::Target, existing: Option<String>, cx: &mut Context<Self>) -> Self {+ let mut dialog = ShareDialog { engine, target, share: existing, creating: false, copied: false, error: None, focus: cx.focus_handle() };+ if dialog.share.is_none() {+ dialog.create(cx);+ }+ dialog+ }++ pub fn first_focus(&self, _: &App) -> FocusHandle {+ self.focus.clone()+ }++ fn create(&mut self, cx: &mut Context<Self>) {+ if self.creating {+ return;+ }+ self.creating = true;+ self.error = None;+ cx.notify();+ let options = host::Options { approve: true, can_type: false, ttl: Duration::from_secs(3600) };+ let source = Arc::new(host::EngineSource { engine: self.engine.clone(), machine_id: self.target.machine_id.clone() });+ let (target, server) = (self.target.clone(), self.engine.settings().share_server());+ let job = self.engine.runtime().spawn(async move { host::start(&server, target, options, source).await });+ cx.spawn(async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));+ let _ = this.update(cx, |this, cx| {+ this.creating = false;+ match result {+ Ok(view) => {+ cx.write_to_clipboard(ClipboardItem::new_string(view.link.clone()));+ this.copied = true;+ this.share = Some(view.id);+ }+ Err(e) => this.error = Some(e),+ }+ cx.notify();+ });+ })+ .detach();+ }++ fn render_making(&mut self, theme: &Theme, cx: &mut Context<Self>) -> AnyElement {+ let title = format!("Share {}", self.target.title);+ match self.error.clone() {+ None => frame(theme, title, None)+ .child(div().flex().items_center().gap(px(10.)).text_size(px(13.)).text_color(theme.text_muted).child(kit::spinner("share-making", 14., theme.accent)).child("Making a link…"))+ .into_any_element(),+ Some(e) => frame(theme, title, None)+ .children(error_line(theme, &Some(e)))+ .child(footer(vec![+ Button::new("share-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element(),+ Button::new("share-retry", "Try again").style(ButtonStyle::Primary).on_click(cx.listener(|this, _, _, cx| this.create(cx))).into_any_element(),+ ]))+ .into_any_element(),+ }+ }++ fn render_share(&mut self, theme: &Theme, view: host::ShareView, cx: &mut Context<Self>) -> AnyElement {+ let link = view.link.clone();+ let (id, id2, id3) = (view.id.clone(), view.id.clone(), view.id.clone());+ let (approve, can_type) = (view.approve, view.can_type);+ let left = view.ends_at - chrono::Utc::now().timestamp();+ let typing_row = if approve {+ kit::checkbox(theme, "share-type", can_type, "They can type", move |on, _, _| host::set_options(&id2, true, *on)).into_any_element()+ } else {+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .text_size(px(12.5))+ .text_color(theme.text_placeholder)+ .child(div().size(px(15.)).rounded(px(4.)).border_1().border_color(theme.border_variant))+ .child("They can type")+ .into_any_element()+ };+ frame(theme, format!("Share {}", self.target.title), Some(if self.copied { "Link copied. Send it to anyone: it opens in their browser or in Muxin." } else { "Send the link to anyone: it opens in their browser or in Muxin." }.into()))+ .w(px(540.))+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .p(px(6.))+ .pl(px(12.))+ .rounded(px(9.))+ .border_1()+ .border_color(theme.border)+ .bg(theme.surface)+ .child(div().w(px(380.)).truncate().font_family(mono_font()).text_size(px(12.5)).child(link.clone()))+ .child(div().flex_1())+ .child(Button::new("share-copy", if self.copied { "Copied" } else { "Copy" }).icon(if self.copied { "check" } else { "copy" }).style(ButtonStyle::Primary).on_click(cx.listener(+ move |this, _, _, cx| {+ cx.write_to_clipboard(ClipboardItem::new_string(link.clone()));+ this.copied = true;+ cx.notify()+ },+ ))),+ )+ .child(+ card(theme)+ .p(px(14.))+ .gap(px(12.))+ .child(+ div()+ .flex()+ .flex_col()+ .gap(px(3.))+ .child(kit::checkbox(theme, "share-approve", approve, "Ask me before letting someone in", move |on, _, _| host::set_options(&id, *on, *on && can_type)))+ .child(div().pl(px(23.)).text_size(px(11.5)).text_color(theme.text_placeholder).child(if approve { "You see who's asking, and their code." } else { "Anyone with the link can watch." })),+ )+ .child(+ div()+ .flex()+ .flex_col()+ .gap(px(3.))+ .child(typing_row)+ .child(div().pl(px(23.)).text_size(px(11.5)).text_color(if approve && can_type { theme.warning } else { theme.text_placeholder }).child(if approve {+ "Their keys go to this session, as you."+ } else {+ "Only for people you let in."+ })),+ )+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .child(icon("clock", 14., theme.text_muted))+ .child(div().flex_1().text_size(px(12.5)).child(format!("Ends in {}", time_left(view.ends_at))))+ .children(DURATIONS.iter().enumerate().map(|(i, (label, secs))| {+ let (secs, id) = (*secs, id3.clone());+ // The choice closest to what's left shows as picked.+ let picked = DURATIONS.iter().min_by_key(|(_, d)| (*d as i64 - left).abs()).is_some_and(|(l, _)| l == label);+ div()+ .id(("share-ttl", i))+ .px(px(10.))+ .h(px(26.))+ .flex()+ .items_center()+ .rounded(px(6.))+ .border_1()+ .cursor_pointer()+ .text_size(px(12.))+ .border_color(if picked { theme.accent } else { theme.border_variant })+ .bg(if picked { theme.accent.opacity(0.12) } else { theme.element })+ .child(*label)+ .on_click(move |_, _, _| host::set_ends_in(&id, Duration::from_secs(secs)))+ })),+ ),+ )+ .child(footer(vec![+ Button::new("share-stop", "Stop sharing")+ .style(ButtonStyle::Danger)+ .on_click(cx.listener(move |_, _, _, cx| {+ host::stop(&view.id);+ cx.emit(DialogEvent::Dismissed)+ }))+ .into_any_element(),+ div().flex_1().into_any_element(),+ Button::new("share-done", "Done").style(ButtonStyle::Outlined).key_hint("esc").on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::Dismissed))).into_any_element(),+ ]))+ .into_any_element()+ }+}++impl Focusable for ShareDialog {+ fn focus_handle(&self, _: &App) -> FocusHandle {+ self.focus.clone()+ }+}++impl Render for ShareDialog {+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let view = self.share.as_ref().and_then(|id| host::list().into_iter().find(|s| &s.id == id));+ let body = match view {+ Some(view) => self.render_share(&theme, view, cx),+ // Stopped from elsewhere (the menu, its time ran out).+ None if self.share.is_some() => {+ cx.emit(DialogEvent::Dismissed);+ div().into_any_element()+ }+ None => self.render_making(&theme, cx),+ };+ div()+ .track_focus(&self.focus)+ .on_key_down(cx.listener(|_, e: &gpui::KeyDownEvent, _, cx| {+ if e.keystroke.key == "escape" || e.keystroke.key == "enter" {+ cx.emit(DialogEvent::Dismissed)+ }+ }))+ .child(body)+ }+}++// ---------------------------------------------------------------------------+// Joining one++/// A share joined and let in, on its way from the Join dialog to its page.+#[derive(Clone)]+pub struct JoinedHandle {+ joined: Arc<guest::Joined>,+ updates: Arc<Mutex<Option<mpsc::UnboundedReceiver<guest::Update>>>>,+ info: guest::Info,+ can_type: bool,+}++enum Stage {+ Form,+ Connecting,+ /// Connected: the code to read out, what's shared, whether it waits.+ Joined { code: String, info: Option<guest::Info>, waiting: bool },+}++pub struct JoinDialog {+ engine: Arc<Engine>,+ link: Entity<TextInput>,+ name: Entity<TextInput>,+ stage: Stage,+ joined: Option<Arc<guest::Joined>>,+ error: Option<String>,+ _subscriptions: Vec<Subscription>,+}++impl EventEmitter<DialogEvent> for JoinDialog {}++impl JoinDialog {+ pub fn new(engine: Arc<Engine>, link: Option<String>, name: String, window: &mut Window, cx: &mut Context<Self>) -> Self {+ let link = cx.new(|cx| TextInput::new(cx, "https://muxin.dev/s#1.…").with_text(link.unwrap_or_default()));+ let name = cx.new(|cx| TextInput::new(cx, "Your name").with_text(name).selected());+ let mut subs = Vec::new();+ for input in [&link, &name] {+ subs.push(cx.subscribe_in(input, window, |this: &mut Self, _, e: &InputEvent, _, cx| match e {+ InputEvent::Submit => this.join(cx),+ InputEvent::Cancel => this.cancel(cx),+ InputEvent::Changed => {+ this.error = None;+ cx.notify()+ }+ }));+ }+ JoinDialog { engine, link, name, stage: Stage::Form, joined: None, error: None, _subscriptions: subs }+ }++ pub fn first_focus(&self, cx: &App) -> FocusHandle {+ if self.link.read(cx).text().trim().is_empty() { self.link.focus_handle(cx) } else { self.name.focus_handle(cx) }+ }++ fn cancel(&mut self, cx: &mut Context<Self>) {+ if let Some(j) = self.joined.take() {+ j.leave();+ }+ cx.emit(DialogEvent::Dismissed);+ }++ fn join(&mut self, cx: &mut Context<Self>) {+ if !matches!(self.stage, Stage::Form) {+ return;+ }+ let link = self.link.read(cx).text().trim().to_string();+ let name = self.name.read(cx).text().trim().to_string();+ if let Err(e) = crate::share::ticket::Ticket::parse(&link) {+ self.error = Some(e);+ cx.notify();+ return;+ }+ if name.is_empty() {+ self.error = Some("Enter your name first.".into());+ cx.notify();+ return;+ }+ let mut settings = self.engine.settings();+ if settings.share.name != name {+ settings.share.name = name.clone();+ let _ = self.engine.update_settings(settings);+ }+ self.stage = Stage::Connecting;+ self.error = None;+ cx.notify();+ let job = self.engine.runtime().spawn(async move { guest::join(&link, &name).await });+ cx.spawn(async move |this, cx| {+ let (joined, mut rx) = match job.await.unwrap_or_else(|e| Err(e.to_string())) {+ Ok(j) => j,+ Err(e) => {+ let _ = this.update(cx, |this, cx| {+ this.stage = Stage::Form;+ this.error = Some(e);+ cx.notify()+ });+ return;+ }+ };+ let _ = this.update(cx, |this, _| this.joined = Some(joined.clone()));+ while let Some(u) = rx.recv().await {+ let mut done = None;+ let alive = this.update(cx, |this, cx| {+ match u {+ guest::Update::Code(code) => this.stage = Stage::Joined { code, info: None, waiting: false },+ guest::Update::Info(i) => {+ if let Stage::Joined { info, .. } = &mut this.stage {+ *info = Some(i);+ }+ }+ guest::Update::Waiting => {+ if let Stage::Joined { waiting, .. } = &mut this.stage {+ *waiting = true;+ }+ }+ guest::Update::Admitted { can_type } => {+ let info = match &this.stage {+ Stage::Joined { info, .. } => info.clone().unwrap_or_default(),+ _ => Default::default(),+ };+ done = Some((info, can_type));+ }+ guest::Update::Denied => {+ this.stage = Stage::Form;+ this.joined = None;+ this.error = Some("They didn't let you in.".into());+ }+ guest::Update::Ended(why) => {+ this.stage = Stage::Form;+ this.joined = None;+ this.error = Some(why);+ }+ _ => {}+ }+ cx.notify();+ });+ if alive.is_err() {+ joined.leave();+ return;+ }+ if let Some((info, can_type)) = done {+ let handle = JoinedHandle { joined: joined.clone(), updates: Arc::new(Mutex::new(Some(rx))), info, can_type };+ let _ = this.update(cx, |this, cx| {+ this.joined = None;+ cx.emit(DialogEvent::JoinedShare(handle))+ });+ return;+ }+ }+ })+ .detach();+ }+}++impl Render for JoinDialog {+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ match &self.stage {+ Stage::Form | Stage::Connecting => {+ let connecting = matches!(self.stage, Stage::Connecting);+ frame(&theme, "Join a shared session", Some("Paste the link someone sent you.".into()))+ .child(field(&theme, "Link", self.link.clone(), None))+ .child(field(&theme, "Your name", self.name.clone(), Some("They see it when you ask to join.")))+ .children(error_line(&theme, &self.error))+ .child(footer(vec![+ Button::new("join-cancel", "Cancel").style(ButtonStyle::Ghost).on_click(cx.listener(|this, _, _, cx| this.cancel(cx))).into_any_element(),+ Button::new("join-go", if connecting { "Connecting…" } else { "Join" })+ .style(ButtonStyle::Primary)+ .loading(connecting)+ .key_hint("↵")+ .on_click(cx.listener(|this, _, _, cx| this.join(cx)))+ .into_any_element(),+ ]))+ .into_any_element()+ }+ Stage::Joined { code, info, waiting } => {+ let by = info.as_ref().map(|i| i.by.clone()).unwrap_or_else(|| "them".into());+ let title = info.as_ref().map(|i| if i.title.is_empty() { "a session".to_string() } else { i.title.clone() }).unwrap_or_else(|| "a session".into());+ let sub = info.as_ref().map(|i| format!("{} on {} · shared by {}", agent_name(&i.agent), i.machine, i.by));+ let (a, b) = code.split_at(3.min(code.len()));+ frame(&theme, format!("Join {title}"), sub.map(SharedString::from))+ .children(info.as_ref().map(|i| {+ div()+ .flex()+ .flex_col()+ .gap(px(8.))+ .child(fact(&theme, if i.can_type { "keyboard" } else { "eye" }, if i.can_type { "You can watch and type" } else { "You can watch" }))+ .child(fact(&theme, "clock", format!("Ends in {}", time_left(i.ends_at))))+ }))+ .child(+ div()+ .flex()+ .flex_col()+ .items_center()+ .gap(px(4.))+ .p(px(16.))+ .rounded(px(10.))+ .bg(theme.surface)+ .border_1()+ .border_color(theme.border)+ .child(div().text_size(px(12.)).text_color(theme.text_muted).child("Your code"))+ .child(div().font_family(mono_font()).text_size(px(30.)).font_weight(FontWeight::MEDIUM).child(format!("{a} {b}")))+ .child(div().text_size(px(12.)).text_color(theme.text_muted).child(format!("Read it to {by} so they know it's you."))),+ )+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .child(kit::spinner("join-wait", 12., theme.accent))+ .child(div().flex_1().text_size(px(12.5)).text_color(theme.text_accent).child(if *waiting { format!("Waiting for {by} to let you in…") } else { "Asking to join…".into() }))+ .child(Button::new("join-cancel-wait", "Cancel").style(ButtonStyle::Outlined).on_click(cx.listener(|this, _, _, cx| this.cancel(cx)))),+ )+ .into_any_element()+ }+ }+ }+}++fn agent_name(agent: &str) -> &'static str {+ crate::fleet::sessions::agent(agent).map(|a| a.name).unwrap_or("A session")+}++/// Keys for a joined session (dropped unless its host lets us type).+struct GuestIo(Arc<guest::Joined>);++impl RemoteIo for GuestIo {+ fn write(&self, bytes: &[u8]) {+ self.0.send_keys(bytes);+ }++ fn resize(&self, _: u16, _: u16) {}++ fn close(&self) {}+}++/// A session someone shared with you, open here.+pub struct JoinedSession {+ pub id: String,+ pub info: guest::Info,+ joined: Arc<guest::Joined>,+ pub terminal: Entity<TerminalView>,+ pub can_type: bool,+ /// Why it ended, once it has.+ pub ended: Option<String>,+}++impl Root {+ /// The Share dialog for a session: its link when it's shared already.+ pub(super) fn show_share(&mut self, session_id: &str, window: &mut Window, cx: &mut Context<Self>) {+ let Some(info) = self.snapshot.sessions.iter().find(|x| x.id == session_id).cloned() else { return };+ let machine_name = self.snapshot.machines.iter().find(|m| m.id == info.machine_id).map(|m| m.name.clone()).unwrap_or_else(|| info.machine_id.clone());+ let by = self.snapshot.github.login.clone().filter(|l| !l.is_empty()).or_else(|| std::env::var("USER").ok()).unwrap_or_else(|| "Someone".into());+ let target = host::Target {+ session_id: info.id.clone(),+ machine_id: info.machine_id.clone(),+ name: info.id.split_once('/').map(|(_, n)| n.to_string()).unwrap_or_default(),+ title: info.title.clone(),+ agent: info.agent.clone(),+ machine_name,+ by,+ };+ let existing = self.share_of(session_id).map(|s| s.id.clone());+ let engine = self.engine.clone();+ let dialog = cx.new(|cx| ShareDialog::new(engine, target, existing, cx));+ self.show_modal(Modal::Share(dialog.clone()), window, cx);+ self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));+ }++ pub(super) fn share_of(&self, session_id: &str) -> Option<&host::ShareView> {+ self.shares.iter().find(|s| s.target.session_id == session_id)+ }++ /// Shares changed (a guest knocked, came in, left): show it, and say+ /// who's asking to join when they first do.+ pub(super) fn shares_changed(&mut self, cx: &mut Context<Self>) {+ self.shares = host::list();+ let mut knocks = Vec::new();+ for s in &self.shares {+ for g in s.guests.iter().filter(|g| g.state == "waiting") {+ if self.knocks_seen.insert((s.id.clone(), g.id)) {+ knocks.push(format!("{} wants to join {}", g.name, s.target.title));+ }+ }+ }+ if let Some(k) = knocks.pop() {+ self.notify_user(k, false, cx);+ }+ cx.notify();+ }++ /// The session header's Share button, or what's going on with its share.+ pub(super) fn share_button(&self, info: &SessionInfo, cx: &mut Context<Self>) -> AnyElement {+ let sid = info.id.clone();+ let Some(share) = self.share_of(&info.id) else {+ return Button::new("session-share", "Share")+ .icon("link")+ .tooltip("Share this session by link")+ .on_click(cx.listener(move |this, _, window, cx| this.show_share(&sid, window, cx)))+ .into_any_element();+ };+ let waiting = share.guests.iter().filter(|g| g.state == "waiting").count();+ let inside: Vec<&host::GuestView> = share.guests.iter().filter(|g| g.state == "in").collect();+ let typing = inside.iter().any(|g| g.can_type);+ let what = match (inside.len(), waiting) {+ (_, w) if w > 0 => format!("{w} waiting"),+ (0, _) => "no one yet".to_string(),+ (1, _) => format!("{} {}", inside[0].name, if typing { "typing" } else { "watching" }),+ (n, _) => format!("{n} watching"),+ };+ Button::new("session-shared", format!("Shared · {what}"))+ .icon(if typing { "keyboard" } else { "eye" })+ .style(ButtonStyle::Outlined)+ .tooltip("Who's here, the link, and stopping")+ .on_click(cx.listener(move |this, e: &gpui::ClickEvent, _, cx| this.open_menu(super::menu::MenuTarget::Share(sid.clone()), e.position(), cx)))+ .into_any_element()+ }++ /// Above a shared session's terminal: each guest waiting to be let in.+ pub(super) fn knock_cards(&self, session_id: &str, cx: &mut Context<Self>) -> Vec<AnyElement> {+ let theme = cx.theme();+ let Some(share) = self.share_of(session_id) else { return Vec::new() };+ share+ .guests+ .iter()+ .filter(|g| g.state == "waiting")+ .map(|g| {+ let (share_id, guest_id) = (share.id.clone(), g.id);+ let share_id2 = share_id.clone();+ let (a, b) = g.code.split_at(3.min(g.code.len()));+ let how = if g.client == "browser" { "In a browser" } else { "In Muxin" };+ let wants = if share.can_type { "wants to join" } else { "wants to watch" };+ div()+ .mx(px(20.))+ .mt(px(12.))+ .flex()+ .items_center()+ .gap(px(14.))+ .p(px(14.))+ .rounded(px(10.))+ .border_1()+ .border_color(theme.accent)+ .bg(theme.elevated)+ .shadow_lg()+ .child(+ div()+ .size(px(36.))+ .flex_none()+ .rounded_full()+ .bg(theme.accent.opacity(0.25))+ .flex()+ .items_center()+ .justify_center()+ .text_size(px(15.))+ .font_weight(FontWeight::SEMIBOLD)+ .child(g.name.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_default()),+ )+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .gap(px(2.))+ .child(div().text_size(px(13.5)).font_weight(FontWeight::SEMIBOLD).child(format!("{} {wants}", g.name)))+ .child(div().text_size(px(12.)).text_color(theme.text_muted).child(format!("{how} · ask {} to read their code", g.name))),+ )+ .child(+ div()+ .flex()+ .flex_col()+ .items_end()+ .px(px(8.))+ .child(div().text_size(px(11.5)).text_color(theme.text_muted).child("Their code"))+ .child(div().font_family(mono_font()).text_size(px(22.)).font_weight(FontWeight::MEDIUM).child(format!("{a} {b}"))),+ )+ .child(Button::new(SharedString::from(format!("knock-deny-{guest_id}")), "Deny").style(ButtonStyle::Outlined).on_click(cx.listener(move |_, _, _, _| host::admit(&share_id, guest_id, false))))+ .child(Button::new(SharedString::from(format!("knock-in-{guest_id}")), "Let in").style(ButtonStyle::Primary).on_click(cx.listener(move |_, _, _, _| host::admit(&share_id2, guest_id, true))))+ .into_any_element()+ })+ .collect()+ }++ /// The Join dialog (from a link opened, or the command palette).+ pub(super) fn show_join(&mut self, link: Option<String>, window: &mut Window, cx: &mut Context<Self>) {+ let engine = self.engine.clone();+ let name = Some(self.engine.settings().share.name).filter(|n| !n.is_empty()).or_else(|| self.snapshot.github.login.clone()).unwrap_or_default();+ let dialog = cx.new(|cx| JoinDialog::new(engine, link, name, window, cx));+ self.show_modal(Modal::Join(dialog.clone()), window, cx);+ self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));+ }++ /// A share joined and let in: its terminal, fed from now on, and its page.+ pub(super) fn open_joined(&mut self, handle: &JoinedHandle, window: &mut Window, cx: &mut Context<Self>) {+ let Some(mut updates) = handle.updates.lock().unwrap().take() else { return };+ self.joined_count += 1;+ let id = format!("shared-{}", self.joined_count);+ let (tx, output) = futures::channel::mpsc::unbounded();+ let io: Arc<dyn RemoteIo> = Arc::new(GuestIo(handle.joined.clone()));+ let terminal = cx.new(|cx| TerminalView::guest(io, output, (100, 30), window, cx));+ self.joined.push(JoinedSession { id: id.clone(), info: handle.info.clone(), joined: handle.joined.clone(), terminal, can_type: handle.can_type, ended: None });+ let sid = id.clone();+ let task = cx.spawn(async move |this, cx| {+ while let Some(u) = updates.recv().await {+ let mut fed = true;+ match u {+ guest::Update::Output(b) => fed = tx.unbounded_send(RemoteOutput::Bytes(b)).is_ok(),+ guest::Update::Size(c, r) => {+ let _ = tx.unbounded_send(RemoteOutput::Resize(c, r));+ let _ = this.update(cx, |_, cx| cx.notify());+ }+ guest::Update::Typing(allowed) => {+ let _ = this.update(cx, |this, cx| {+ if let Some(j) = this.joined.iter_mut().find(|j| j.id == sid) {+ j.can_type = allowed;+ }+ this.notify_user(if allowed { "You can type now." } else { "Typing is off. You're watching." }, false, cx);+ });+ }+ guest::Update::Exited(code) => fed = tx.unbounded_send(RemoteOutput::Ended(code)).is_ok(),+ guest::Update::Ended(why) => {+ let _ = tx.unbounded_send(RemoteOutput::Ended(None));+ let _ = this.update(cx, |this, cx| {+ if let Some(j) = this.joined.iter_mut().find(|j| j.id == sid) {+ j.ended = Some(why);+ }+ cx.notify();+ });+ return;+ }+ _ => {}+ }+ if !fed {+ break;+ }+ }+ });+ self.track(task);+ self.navigate(Route::Shared(id), window, cx);+ }++ /// Lets go of a session shared with you.+ pub(super) fn leave_joined(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) {+ if let Some(i) = self.joined.iter().position(|j| j.id == id) {+ let j = self.joined.remove(i);+ j.joined.leave();+ }+ if self.route == Route::Shared(id.to_string()) {+ self.navigate(Route::Overview, window, cx);+ }+ cx.notify();+ }++ /// A session someone shared with you.+ pub(super) fn render_joined(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme();+ let Some(j) = self.joined.iter().find(|j| j.id == id) else {+ return div().size_full().flex().items_center().justify_center().text_color(theme.text_muted).child("That share is closed.").into_any_element();+ };+ let (icon_name, (from, to)) = kit::agent_look(&j.info.agent);+ let title = if j.info.title.is_empty() { agent_name(&j.info.agent).to_string() } else { j.info.title.clone() };+ let leave = j.id.clone();+ let header = div()+ .flex()+ .flex_none()+ .items_center()+ .gap(px(12.))+ .px(px(20.))+ .py(px(12.))+ .border_b_1()+ .border_color(theme.border_variant)+ .child(kit::tile(icon_name, from, to, 32.))+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .gap(px(2.))+ .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).child(title))+ .child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(format!("{} · {} · shared by {}", agent_name(&j.info.agent), j.info.machine, j.info.by))),+ )+ .when(j.ended.is_none(), |d| {+ d.child(kit::pill(if j.can_type { "Typing" } else { "Watching" }, theme.accent))+ .child(div().text_size(px(12.)).text_color(theme.text_muted).child(format!("{} left", time_left(j.info.ends_at))))+ })+ .child(Button::new("joined-leave", if j.ended.is_some() { "Close" } else { "Leave" }).icon("x").style(ButtonStyle::Outlined).on_click(cx.listener(move |this, _, window, cx| this.leave_joined(&leave, window, cx))));+ let body = match &j.ended {+ Some(why) => div()+ .flex_1()+ .flex()+ .items_center()+ .justify_center()+ .child(+ card(&theme)+ .items_center()+ .gap(px(10.))+ .p(px(22.))+ .max_w(px(420.))+ .child(kit::color_tile("eye", 36.))+ .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).child(why.clone())),+ )+ .into_any_element(),+ None => {+ let (cols, rows) = j.terminal.read(cx).fixed_size().unwrap_or((100, 30));+ let (w, h) = TerminalView::pixel_size(cols, rows, window, cx);+ let note = if j.can_type { "You can type. Keys go to their session.".to_string() } else { format!("You're watching. Only {} can type.", j.info.by) };+ div()+ .flex_1()+ .min_h(px(0.))+ .flex()+ .flex_col()+ .gap(px(10.))+ .p(px(16.))+ .child(+ div()+ .flex_1()+ .min_h(px(0.))+ .overflow_hidden()+ .child(div().w(px(w)).h(px(h)).rounded(px(8.)).overflow_hidden().border_1().border_color(theme.border_variant).child(j.terminal.clone())),+ )+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .px(px(12.))+ .py(px(8.))+ .rounded(px(8.))+ .bg(theme.surface)+ .text_size(px(12.))+ .text_color(theme.text_muted)+ .child(icon(if j.can_type { "keyboard" } else { "lock" }, 13., theme.text_muted))+ .child(div().flex_1().child(note))+ .child(format!("Shown at {}'s size", j.info.by)),+ )+ .into_any_element()+ }+ };+ div().size_full().flex().flex_col().child(header).child(body).into_any_element()+ }++ /// The sidebar's "Shared with you" rows.+ pub(super) fn joined_rows(&self, theme: &Theme, cx: &mut Context<Self>) -> Vec<AnyElement> {+ self.joined+ .iter()+ .map(|j| {+ let id = j.id.clone();+ let selected = self.route == Route::Shared(j.id.clone());+ let (icon_name, (from, to)) = kit::agent_look(&j.info.agent);+ let title = if j.info.title.is_empty() { agent_name(&j.info.agent).to_string() } else { j.info.title.clone() };+ let text_w = (self.sidebar_width - 20. - 22. - 8. - 16. - 8. - 24.).max(40.);+ div()+ .id(SharedString::from(format!("side-j-{}", j.id)))+ .flex()+ .items_center()+ .gap(px(8.))+ .h(px(30.))+ .mx(px(10.))+ .pl(px(10.))+ .pr(px(8.))+ .rounded(px(7.))+ .cursor_pointer()+ .when(selected, |d| d.bg(theme.element_selected))+ .when(!selected, |d| d.hover(|st| st.bg(theme.ghost_hover)))+ .child(kit::tile(icon_name, from, to, 16.))+ .child(+ div()+ .w(px(text_w))+ .flex()+ .flex_col()+ .child(div().w(px(text_w)).truncate().text_size(px(12.5)).text_color(if selected { theme.text } else { theme.text_muted }).child(title))+ .child(div().w(px(text_w)).truncate().text_size(px(11.)).text_color(theme.text_placeholder).child(format!("from {}", j.info.by))),+ )+ .child(div().flex_1())+ .child(icon(if j.ended.is_some() { "x" } else { "eye" }, 12., theme.text_accent))+ .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Shared(id.clone()), window, cx)))+ .into_any_element()+ })+ .collect()+ }+}diff --git a/src/ui/terminal/mod.rs b/src/ui/terminal/mod.rsindex d5ec8c6..706e98f 100644--- a/src/ui/terminal/mod.rs+++ b/src/ui/terminal/mod.rs@@ -133,6 +133,8 @@ pub trait RemoteIo: Send + Sync {/// What arrives for a remote terminal.pub enum RemoteOutput {Bytes(Vec<u8>),+ /// Draw at this size (cols, rows): someone else's session, shown as they size it.+ Resize(u16, u16),/// The session ended (with its code), or the connection did (None).Ended(Option<i32>),}@@ -151,6 +153,8 @@ struct Shared {term: Arc<FairMutex<Term<Listener>>>,backend: Backend,geometry: Mutex<Geometry>,+ /// A size set from elsewhere (a shared session's), instead of the space it has.+ fixed: Mutex<Option<(usize, usize)>>,}impl Shared {@@ -164,6 +168,15 @@ impl Shared {}}+ /// Draws at a size set from elsewhere from now on.+ fn fix_size(&self, cols: usize, rows: usize) {+ *self.fixed.lock().unwrap() = Some((cols, rows));+ let mut term = self.term.lock();+ if term.columns() != cols || term.screen_lines() != rows {+ term.resize(TermDims { cols, rows });+ }+ }+/// Resizes the grid and tells the PTY, when the visible area changed.fn resize(&self, cols: usize, rows: usize, cell_w: f32, line_h: f32) {let mut term = self.term.lock();@@ -204,6 +217,9 @@ pub struct TerminalView {shared: Arc<Shared>,focus: FocusHandle,exited: bool,+ /// Someone else's session, joined through a share: what this terminal+ /// would answer (queries) or take (a program's copy) stays here.+ guest: bool,/// Dragging a local text selection.selecting: bool,/// The button held in mouse-reporting mode, and the last cell reported.@@ -270,15 +286,24 @@ impl TerminalView {batch.push(more);}let mut ended = None;+ let mut size = None;{let mut t = term.lock();for item in batch {match item {RemoteOutput::Bytes(b) => parser.advance(&mut *t, &b),RemoteOutput::Ended(code) => ended = Some(code),+ RemoteOutput::Resize(cols, rows) => {+ let dims = TermDims { cols: (cols as usize).clamp(2, 1000), rows: (rows as usize).clamp(1, 500) };+ t.resize(dims);+ size = Some((dims.cols, dims.rows));+ }}}}+ if let Some((cols, rows)) = size {+ let _ = this.update(cx, |this, _| this.shared.fix_size(cols, rows));+ }let alive = this.update(cx, |this, cx| match ended {Some(code) => this.finish(code, cx),None => cx.notify(),@@ -293,6 +318,27 @@ impl TerminalView {view}+ /// Someone else's session, joined through a share: drawn at their size+ /// (`Resize` updates), keys to `io` (which drops them unless the host+ /// lets this guest type).+ pub fn guest(io: Arc<dyn RemoteIo>, output: futures::channel::mpsc::UnboundedReceiver<RemoteOutput>, (cols, rows): (u16, u16), window: &mut Window, cx: &mut Context<Self>) -> Self {+ let mut view = Self::remote(io, output, (cols, rows), window, cx);+ view.guest = true;+ view.shared.fix_size(cols as usize, rows as usize);+ view+ }++ /// The size it's drawn at when set from elsewhere.+ pub fn fixed_size(&self) -> Option<(usize, usize)> {+ *self.shared.fixed.lock().unwrap()+ }++ /// Pixels a grid of `cols`×`rows` takes, padding included.+ pub fn pixel_size(cols: usize, rows: usize, window: &Window, cx: &App) -> (f32, f32) {+ let (w, h) = render::cell_size(window, Metrics::current(cx));+ (cols as f32 * w + 2. * PAD_X, rows as f32 * h + 2. * PAD_Y)+ }+/// A terminal showing fixed output (the demo), with no program behind it.pub fn replay(bytes: &[u8], window: &mut Window, cx: &mut Context<Self>) -> Self {let (term, _listener, rx) = new_term(110, 34);@@ -351,9 +397,10 @@ impl TerminalView {}});TerminalView {- shared: Arc::new(Shared { term, backend, geometry: Mutex::new(Geometry::default()) }),+ shared: Arc::new(Shared { term, backend, geometry: Mutex::new(Geometry::default()), fixed: Mutex::new(None) }),focus,exited: false,+ guest: false,selecting: false,pressed: None,scroll_rest: 0.,@@ -382,6 +429,9 @@ impl TerminalView {fn on_term_event(&mut self, event: TermEvent, window: &Window, cx: &mut Context<Self>) {match event {TermEvent::Wakeup | TermEvent::MouseCursorDirty | TermEvent::CursorBlinkingChange => cx.notify(),+ // A guest's terminal answers nothing (the host's does) and takes+ // nothing a program there puts on the clipboard.+ TermEvent::PtyWrite(_) | TermEvent::ColorRequest(..) | TermEvent::TextAreaSizeRequest(_) | TermEvent::ClipboardStore(..) if self.guest => {}TermEvent::PtyWrite(text) => self.shared.write(text.into_bytes()),// A program's copy (OSC 52) only while you're in its terminal, not// from a session in the background; and it stays on this computer:diff --git a/src/ui/terminal/render.rs b/src/ui/terminal/render.rsindex aac5c2d..35c75b4 100644--- a/src/ui/terminal/render.rs+++ b/src/ui/terminal/render.rs@@ -192,9 +192,16 @@ pub(super) fn family(window: &Window) -> SharedString {#[allow(clippy::too_many_arguments)]fn prepaint(shared: &Shared, palette: &Palette, focused: bool, show_cursor: bool, m: Metrics, bounds: Bounds<Pixels>, window: &mut Window) -> Frame {let (cell_w, line_h) = cell_size(window, m);- let cols = ((f32::from(bounds.size.width) - 2. * PAD_X) / cell_w).floor().max(2.) as usize;- let rows = ((f32::from(bounds.size.height) - 2. * PAD_Y) / line_h).floor().max(1.) as usize;- shared.resize(cols, rows, cell_w, line_h);+ let fixed = *shared.fixed.lock().unwrap();+ let (cols, rows) = match fixed {+ Some(size) => size,+ None => {+ let cols = ((f32::from(bounds.size.width) - 2. * PAD_X) / cell_w).floor().max(2.) as usize;+ let rows = ((f32::from(bounds.size.height) - 2. * PAD_Y) / line_h).floor().max(1.) as usize;+ shared.resize(cols, rows, cell_w, line_h);+ (cols, rows)+ }+ };let origin = bounds.origin + point(px(PAD_X), px(PAD_Y));*shared.geometry.lock().unwrap() = Geometry { origin, cell_w, line_h, cols, rows };