commit 4b729c5d322fb8fe84e938c86ac366a33cdd44a9 Author: Torbjörn Molin Date: Mon Oct 19 09:31:57 2026 +0200 Initial impl diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1b3486c --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/target +/fuzz/target +/fuzz/corpus +/fuzz/artifacts +**/*.snap.new +http-client.private.env.json diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..391ee32 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,5367 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "accesskit" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932" +dependencies = [ + "enumn", + "serde", + "uuid", +] + +[[package]] +name = "accesskit_consumer" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a45e2bb300bea6d5f33a82c3e051c3ddc6f41c209750f68a0acbe991a284344" +dependencies = [ + "accesskit", + "hashbrown 0.17.1", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "serde", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android-activity" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd" +dependencies = [ + "android-properties", + "bitflags 2.13.2", + "cc", + "jni", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum", + "thiserror 2.0.21", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arboard" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" +dependencies = [ + "clipboard-win", + "image", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "windows-sys 0.61.2", + "wl-clipboard-rs", + "x11rb", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom 7.1.3", + "num-traits", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + +[[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 = "assert-json-diff" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec 0.8.0", +] + +[[package]] +name = "bit-set" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" +dependencies = [ + "bit-vec 0.9.1", +] + +[[package]] +name = "bit-vec" +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 = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.3", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2 0.6.5", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.13.2", + "log", + "polling", + "rustix 0.38.44", + "slab", + "thiserror 1.0.69", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop", + "rustix 0.38.44", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "cgl" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff" +dependencies = [ + "libc", +] + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "clipboard-win" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +dependencies = [ + "error-code", +] + +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + +[[package]] +name = "color" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ec7c5eb7a16992b1904d76c517d170ab353b0e0b3d5a0c81a8a0cd1037893cf" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "colored" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c" +dependencies = [ + "lazy_static", + "windows-sys 0.52.0", +] + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "console" +version = "0.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" +dependencies = [ + "encode_unicode", + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "curl" +version = "0.4.51" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef3ce06df3ac230a4f5c91bfd3e3961cd66f177bd9964c87deb3cce59a54fb7b" +dependencies = [ + "curl-sys", + "libc", + "openssl-probe", + "openssl-sys", + "schannel", + "socket2", + "windows-sys 0.61.2", +] + +[[package]] +name = "curl-sys" +version = "0.4.91+curl-8.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd39579123e45bf762716bb893d43886ed1cabe6289455be29a4f1d4e37afb06" +dependencies = [ + "cc", + "libc", + "libnghttp2-sys", + "libz-sys", + "openssl-sys", + "pkg-config", + "vcpkg", + "windows-sys 0.61.2", +] + +[[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 = "deadpool" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0be2b1d1d6ec8d846f05e137292d0b89133caf95ef33695424c09568bdd39b1b" +dependencies = [ + "deadpool-runtime", + "lazy_static", + "num_cpus", + "tokio", +] + +[[package]] +name = "deadpool-runtime" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b" + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom 7.1.3", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "dify" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90ce0fb972943b4e88cd03b8f92953df0c71bb05e0bde8e5b684895d808013cc" +dependencies = [ + "anyhow", + "colored", + "getopts", + "image", + "rayon", +] + +[[package]] +name = "directories" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16f5094c54661b38d03bd7e50df373292118db60b585c08a411c6d840017fe7d" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "libc", + "objc2 0.6.5", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "dlib" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" +dependencies = [ + "libloading", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" + +[[package]] +name = "ecolor" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31bcbef0d4263a63eb32c4834e5d711613035ce1333468e107d928923e21e6e2" +dependencies = [ + "bytemuck", + "emath", + "serde", +] + +[[package]] +name = "eframe" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c5642501a65ca657d05f00c643a5c14ff2346cb3818032bfe23d58e1f8e5f84" +dependencies = [ + "ahash", + "bytemuck", + "document-features", + "egui", + "egui-wgpu", + "egui-winit", + "egui_glow", + "glow", + "glutin", + "glutin-winit", + "image", + "js-sys", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "pollster 1.0.1", + "profiling", + "raw-window-handle", + "ron", + "send_wrapper", + "serde", + "static_assertions", + "wasm-bindgen", + "web-sys", + "web-time", + "wgpu", + "windows-sys 0.61.2", + "winit", +] + +[[package]] +name = "egui" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bec9144f49b7a28b5f395d3147e325b4fe3e77ba686eac11d1bdf0a7da3f375f" +dependencies = [ + "accesskit", + "ahash", + "bitflags 2.13.2", + "emath", + "epaint", + "itertools", + "log", + "nohash-hasher", + "profiling", + "ron", + "serde", + "smallvec", + "unicode-segmentation", + "web-sys", +] + +[[package]] +name = "egui-wgpu" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0309cbe1febed48af5b974e4bcc424b35e9664863a4d402697147b57a488c864" +dependencies = [ + "ahash", + "bytemuck", + "document-features", + "egui", + "epaint", + "log", + "profiling", + "thiserror 2.0.21", + "type-map", + "web-time", + "wgpu", + "winit", +] + +[[package]] +name = "egui-winit" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e449f4c4a2a60c7ccb4ba7fa4078417bfe1f9ddc03b5e05ce75748e33a70de" +dependencies = [ + "arboard", + "block2 0.6.2", + "bytemuck", + "egui", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "objc2-ui-kit 0.3.2", + "profiling", + "raw-window-handle", + "serde", + "web-time", + "windows-sys 0.61.2", + "winit", +] + +[[package]] +name = "egui_extras" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "def286cf47194f3fe45b8e37c503ada7a20a64b59a903b4bc704baec943b1827" +dependencies = [ + "ahash", + "egui", + "enum-map", + "image", + "itertools", + "log", + "mime_guess2", + "profiling", + "syntect", +] + +[[package]] +name = "egui_glow" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9275ca5cc35a6b7c94e0e8cedf22542f66cb0cf45ed8ab2657c78ff49fec7268" +dependencies = [ + "bytemuck", + "egui", + "glow", + "log", + "profiling", + "winit", +] + +[[package]] +name = "egui_kittest" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0979c2e37860fcf13a2bea77508607f067a9a6a84ba9bd47b5e298582fb59b86" +dependencies = [ + "dify", + "eframe", + "egui", + "egui-wgpu", + "image", + "kittest", + "log", + "open", + "pollster 1.0.1", + "serde", + "tempfile", + "toml", + "wgpu", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "emath" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e73ce90f54750be8672c02be0743fe47530e6f251e066f0ee2869b59eb297af5" +dependencies = [ + "bytemuck", + "serde", +] + +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + +[[package]] +name = "enum-map" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06" +dependencies = [ + "enum-map-derive", +] + +[[package]] +name = "enum-map-derive" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "enumn" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "epaint" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97bac86ae3dde93fc3951e790951caea739ff39a6c89d909cdaf1d9278dbb1bd" +dependencies = [ + "ahash", + "bytemuck", + "ecolor", + "emath", + "epaint_default_fonts", + "font-types", + "harfrust", + "log", + "nohash-hasher", + "parking_lot", + "profiling", + "self_cell", + "serde", + "skrifa", + "smallvec", + "unicode-general-category", + "unicode-properties", + "unicode-segmentation", + "vello_cpu", +] + +[[package]] +name = "epaint_default_fonts" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfc1cc505827f4c23eedc297975a0fd038268d41293f389dd8ff3b574aefab19" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "fancy-regex" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "998b056554fbe42e03ae0e152895cd1a7e1002aec800fdc6635d20270260c46f" +dependencies = [ + "bit-set 0.8.0", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "fearless_simd" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "font-types" +version = "0.12.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" +dependencies = [ + "bytemuck", + "serde", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fsevent-sys" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2" +dependencies = [ + "libc", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix 1.1.5", + "windows-link", +] + +[[package]] +name = "getopts" +version = "0.2.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "gl_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" +dependencies = [ + "khronos_api", + "log", + "xml-rs", +] + +[[package]] +name = "glifo" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282a26c1e23de04bdab3e34a21b6f877a479b96737792516b9b8b8f69b6661be" +dependencies = [ + "bytemuck", + "foldhash 0.2.0", + "hashbrown 0.17.1", + "log", + "peniko", + "skrifa", + "smallvec", + "vello_common", +] + +[[package]] +name = "glow" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "glutin" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12124de845cacfebedff80e877bb37b5b75c34c5a4c89e47e1cdd67fb6041325" +dependencies = [ + "bitflags 2.13.2", + "cfg_aliases", + "cgl", + "dispatch2", + "glutin_egl_sys", + "glutin_glx_sys", + "glutin_wgl_sys", + "libloading", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "once_cell", + "raw-window-handle", + "wayland-sys", + "windows-sys 0.52.0", + "x11-dl", +] + +[[package]] +name = "glutin-winit" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85edca7075f8fc728f28cb8fbb111a96c3b89e930574369e3e9c27eb75d3788f" +dependencies = [ + "cfg_aliases", + "glutin", + "raw-window-handle", + "winit", +] + +[[package]] +name = "glutin_egl_sys" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c4680ba6195f424febdc3ba46e7a42a0e58743f2edb115297b86d7f8ecc02d2" +dependencies = [ + "gl_generator", + "windows-sys 0.52.0", +] + +[[package]] +name = "glutin_glx_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7bb2938045a88b612499fbcba375a77198e01306f52272e692f8c1f3751185" +dependencies = [ + "gl_generator", + "x11-dl", +] + +[[package]] +name = "glutin_wgl_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" +dependencies = [ + "gl_generator", +] + +[[package]] +name = "gpu-allocator" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" +dependencies = [ + "ash", + "hashbrown 0.16.1", + "log", + "presser", + "thiserror 2.0.21", + "windows", +] + +[[package]] +name = "guillotiere" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b17e70c989c36bad147b27a58d148c0741c51448aa5653436547323e524d0ab" +dependencies = [ + "euclid", +] + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy", +] + +[[package]] +name = "harfrust" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "read-fonts", + "smallvec", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash 0.2.0", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +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 = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "inotify" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592" +dependencies = [ + "bitflags 2.13.2", + "inotify-sys", + "libc", +] + +[[package]] +name = "inotify-sys" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d" +dependencies = [ + "libc", +] + +[[package]] +name = "insta" +version = "1.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67d3d2e287e4b86c10b3f3b641033d1f89b74bdb39d05f34952e2b9a6fe21cd" +dependencies = [ + "console", + "once_cell", + "serde", + "similar", + "tempfile", +] + +[[package]] +name = "is-docker" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" +dependencies = [ + "once_cell", +] + +[[package]] +name = "is-wsl" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" +dependencies = [ + "is-docker", + "once_cell", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "khronos-egl" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" +dependencies = [ + "libc", + "libloading", + "pkg-config", +] + +[[package]] +name = "khronos_api" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" + +[[package]] +name = "kittest" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb81a721ba76aa095b7f45deb180504f786904e56ca4b8e141f66eb89a78b75" +dependencies = [ + "accesskit", + "accesskit_consumer", +] + +[[package]] +name = "kqueue" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea" +dependencies = [ + "kqueue-sys", + "libc", +] + +[[package]] +name = "kqueue-sys" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087" +dependencies = [ + "bitflags 2.13.2", + "libc", +] + +[[package]] +name = "kurbo" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" +dependencies = [ + "arrayvec", + "euclid", + "polycool", + "smallvec", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libnghttp2-sys" +version = "0.1.13+1.68.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "492e00167f1418c15648144f42bbfc63099806ecee9bf8d09a6353d6b4856b3c" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "bitflags 2.13.2", + "libc", + "plain", + "redox_syscall 0.9.5", +] + +[[package]] +name = "libz-sys" +version = "1.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f710a23e6dbf193214fd46ca56a9d6864e550abe86202184532ae7275e46de19" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linebender_resource_handle" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" + +[[package]] +name = "linked-hash-map" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +dependencies = [ + "libc", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess2" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1706dc14a2e140dec0a7a07109d9a3d5890b81e85bd6c60b906b249a77adf0ca" +dependencies = [ + "mime", + "phf", + "phf_shared", + "unicase", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "naga" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130" +dependencies = [ + "arrayvec", + "bit-set 0.10.0", + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.17.1", + "indexmap", + "libm", + "log", + "naga-types", + "num-traits", + "once_cell", + "rustc-hash 1.1.0", + "spirv", + "thiserror 2.0.21", + "unicode-ident", +] + +[[package]] +name = "naga-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49" +dependencies = [ + "hashbrown 0.17.1", + "indexmap", + "rustc-hash 1.1.0", + "thiserror 2.0.21", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "notify" +version = "8.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3" +dependencies = [ + "bitflags 2.13.2", + "fsevent-sys", + "inotify", + "kqueue", + "libc", + "log", + "mio", + "notify-types", + "walkdir", + "windows-sys 0.60.2", +] + +[[package]] +name = "notify-types" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "libc", + "objc2 0.5.3", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation 0.2.2", + "objc2-quartz-core 0.2.2", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-contacts" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-contacts", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "dispatch", + "libc", + "objc2 0.5.3", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-link-presentation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-symbols" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +dependencies = [ + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-image", + "objc2-core-location", + "objc2-foundation 0.2.2", + "objc2-link-presentation", + "objc2-quartz-core 0.2.2", + "objc2-symbols", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "open" +version = "5.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa576c76302b7b808eecc68061e67336c47833ef9d22caa74dda10fa9675eebc" +dependencies = [ + "is-wsl", + "libc", +] + +[[package]] +name = "openssl-probe" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "orbclient" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747" +dependencies = [ + "libc", + "libredox", +] + +[[package]] +name = "ordered-float" +version = "5.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0" +dependencies = [ + "num-traits", +] + +[[package]] +name = "os_pipe" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[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 = "peniko" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6" +dependencies = [ + "bytemuck", + "color", + "kurbo", + "linebender_resource_handle", + "smallvec", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap", +] + +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared", + "rand", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", + "unicase", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", + "unicase", +] + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "plist" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2896bade328c13f7042a297ea5ac5b0951f6cf989dea5f32c2fd98da398195cb" +dependencies = [ + "base64 0.23.1", + "indexmap", + "quick-xml 0.42.0", + "serde", + "time", +] + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "pollster" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" + +[[package]] +name = "pollster" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336" + +[[package]] +name = "polycool" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "presser" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "range-alloc" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "pem", + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + +[[package]] +name = "read-fonts" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "renderdoc-sys" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" + +[[package]] +name = "reqlite-app" +version = "0.1.0" +dependencies = [ + "anyhow", + "base64 0.23.1", + "directories", + "eframe", + "egui", + "egui_extras", + "egui_kittest", + "image", + "notify", + "reqlite-core", + "reqlite-http-curl", + "rfd", + "serde", + "serde_json", + "tempfile", + "tokio", + "toml", + "tracing", + "tracing-appender", + "tracing-subscriber", + "uuid", + "winresource", +] + +[[package]] +name = "reqlite-cli" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "reqlite-core", + "reqlite-http-curl", + "serde_json", + "tempfile", + "tokio", + "wiremock", +] + +[[package]] +name = "reqlite-core" +version = "0.1.0" +dependencies = [ + "async-trait", + "base64 0.23.1", + "insta", + "serde", + "serde_json", + "shell-words", + "tempfile", + "thiserror 2.0.21", + "uuid", +] + +[[package]] +name = "reqlite-http-curl" +version = "0.1.0" +dependencies = [ + "curl", + "rcgen", + "reqlite-core", + "rustls", + "tempfile", + "tokio", + "tokio-rustls", + "tracing", + "wiremock", +] + +[[package]] +name = "rfd" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220" +dependencies = [ + "block2 0.6.2", + "dispatch2", + "js-sys", + "libc", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "percent-encoding", + "pollster 0.4.0", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "web-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "ron" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81116b9531d61eabc41aeb228e4b6b2435bcca3233b98cf3b3077d4e6e9debb3" +dependencies = [ + "bitflags 2.13.2", + "once_cell", + "serde", + "serde_derive", + "typeid", + "unicode-ident", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "self_cell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "send_wrapper" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash 0.2.0", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shell-words" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "skrifa" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +dependencies = [ + "bytemuck", + "read-fonts", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +dependencies = [ + "serde", +] + +[[package]] +name = "smithay-client-toolkit" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" +dependencies = [ + "bitflags 2.13.2", + "calloop", + "calloop-wayland-source", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 0.38.44", + "thiserror 1.0.69", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spirv" +version = "0.4.0+sdk-1.4.341.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "symlink" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "syntect" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "656b45c05d95a5704399aeef6bd0ddec7b2b3531b7c9e900abbf7c4d2190c925" +dependencies = [ + "bincode", + "fancy-regex", + "flate2", + "fnv", + "once_cell", + "plist", + "regex-syntax", + "serde", + "serde_derive", + "serde_json", + "thiserror 2.0.21", + "walkdir", + "yaml-rust", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +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 = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.53.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.17+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-appender" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" +dependencies = [ + "crossbeam-channel", + "symlink", + "thiserror 2.0.21", + "time", + "tracing-subscriber", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "tree_magic_mini" +version = "3.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" +dependencies = [ + "memchr", + "nom 8.0.0", + "petgraph", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "type-map" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb30dbbd9036155e74adad6812e9898d03ec374946234fbcebd5dfc7b9187b90" +dependencies = [ + "rustc-hash 2.1.3", +] + +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uuid" +version = "1.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "vello_common" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbb2141a2bca6e6d598e471fd4d1d7eed8e020aad6a28187edda07f091a325dd" +dependencies = [ + "bytemuck", + "fearless_simd", + "guillotiere", + "log", + "peniko", + "smallvec", + "thiserror 2.0.21", +] + +[[package]] +name = "vello_cpu" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ace506ca414548966fcf3c283be94eb1cad8254de488791ee698bf438b0890a9" +dependencies = [ + "bytemuck", + "glifo", + "hashbrown 0.17.1", + "vello_common", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs", + "rustix 1.1.5", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.2", + "rustix 1.1.5", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-csd-frame" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" +dependencies = [ + "bitflags 2.13.2", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" +dependencies = [ + "rustix 1.1.5", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml 0.41.0", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "wgpu" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e" +dependencies = [ + "arrayvec", + "bitflags 2.13.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "js-sys", + "log", + "naga", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "wgpu-core", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14" +dependencies = [ + "arrayvec", + "bit-set 0.10.0", + "bit-vec 0.9.1", + "bitflags 2.13.2", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "indexmap", + "log", + "naga", + "naga-types", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash 1.1.0", + "smallvec", + "thiserror 2.0.21", + "wgpu-core-deps-apple", + "wgpu-core-deps-emscripten", + "wgpu-core-deps-wasm", + "wgpu-core-deps-windows-linux-android", + "wgpu-hal", + "wgpu-naga-bridge", + "wgpu-types", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "061f3d319a40d39d00b1ecc2c33b89fe21d4e6fe01859df3500a3a8ecccd6b68" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-emscripten" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98b86cf4abf524a902dd35f18ca6a3f08fc2ae9847c8f10b48e30491b1f0b86" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-wasm" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d260ca2ca8adc654f513a869bf3cac0b47f5b8d3f87803d6942015f8de597aae" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7586165fd5f6d881cb9ce4bb71f40d6caab2c0f1837e3fc1d9788a197fb6004f" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-hal" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set 0.10.0", + "bitflags 2.13.2", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "glow", + "glutin_wgl_sys", + "gpu-allocator", + "hashbrown 0.17.1", + "js-sys", + "khronos-egl", + "libc", + "libloading", + "log", + "naga", + "naga-types", + "ndk-sys", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "once_cell", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "range-alloc", + "raw-window-handle", + "raw-window-metal", + "renderdoc-sys", + "smallvec", + "static_assertions", + "thiserror 2.0.21", + "wasm-bindgen", + "wayland-sys", + "web-sys", + "wgpu-naga-bridge", + "wgpu-types", + "windows", + "windows-core", + "windows-result", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081" +dependencies = [ + "naga", + "wgpu-types", +] + +[[package]] +name = "wgpu-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "js-sys", + "log", + "naga-types", + "raw-window-handle", + "static_assertions", + "web-sys", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "winit" +version = "0.30.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" +dependencies = [ + "ahash", + "android-activity", + "atomic-waker", + "bitflags 2.13.2", + "block2 0.5.1", + "bytemuck", + "calloop", + "cfg_aliases", + "concurrent-queue", + "core-foundation", + "core-graphics", + "cursor-icon", + "dpi", + "js-sys", + "libc", + "memmap2", + "ndk", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", + "objc2-ui-kit 0.2.2", + "orbclient", + "percent-encoding", + "pin-project", + "raw-window-handle", + "redox_syscall 0.4.1", + "rustix 0.38.44", + "smithay-client-toolkit", + "smol_str", + "tracing", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "web-sys", + "web-time", + "windows-sys 0.52.0", + "x11-dl", + "x11rb", + "xkbcommon-dl", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "winresource" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b" +dependencies = [ + "toml", + "version_check", +] + +[[package]] +name = "wiremock" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08db1edfb05d9b3c1542e521aea074442088292f00b5f28e435c714a98f85031" +dependencies = [ + "assert-json-diff", + "base64 0.22.1", + "deadpool", + "futures", + "http", + "http-body-util", + "hyper", + "hyper-util", + "log", + "once_cell", + "regex", + "serde", + "serde_json", + "tokio", + "url", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wl-clipboard-rs" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d7888ccd4896447b2d14d3a9350a85df2aeb6f181e2e7a31349d104ac46cac1" +dependencies = [ + "libc", + "log", + "os_pipe", + "rustix 1.1.5", + "thiserror 2.0.21", + "tree_magic_mini", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "libloading", + "once_cell", + "rustix 1.1.5", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom 7.1.3", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + +[[package]] +name = "xcursor" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" + +[[package]] +name = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags 2.13.2", + "dlib", + "log", + "once_cell", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "xml-rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" + +[[package]] +name = "yaml-rust" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" +dependencies = [ + "linked-hash-map", +] + +[[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 = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure 0.14.0", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure 0.14.0", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..d19906e --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,55 @@ +[workspace] +resolver = "2" +members = ["crates/core", "crates/http-curl", "crates/app", "crates/cli"] + +[workspace.package] +version = "0.1.0" +edition = "2021" +license = "MIT OR Apache-2.0" +rust-version = "1.98" +publish = false + +[workspace.dependencies] +reqlite-core = { path = "crates/core" } +reqlite-http-curl = { path = "crates/http-curl" } + +anyhow = "1.0.104" +async-trait = "0.1.92" +base64 = "0.23.1" +bytes = "1.12.1" +clap = { version = "4.6.7", features = ["derive"] } +curl = { version = "0.4.51", default-features = false, features = ["static-curl", "http2", "ssl"] } +directories = "6.0.0" +eframe = { version = "0.37.0", default-features = false, features = ["default_fonts", "wgpu", "persistence", "wayland", "x11"] } +egui = { version = "0.37.0", features = ["monochrome_emoji_fonts"] } +egui_extras = { version = "0.37.0", features = ["syntect", "image"] } +egui_kittest = { version = "0.37.0", features = ["wgpu", "snapshot"] } +image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "gif", "webp"] } +insta = { version = "1.49.0", features = ["yaml"] } +notify = "8.2.0" +rand = "0.10.3" +rcgen = "0.14.10" +rfd = "0.17.2" +rustls = { version = "0.23.46", default-features = false, features = ["ring", "std"] } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = { version = "1.0.154", features = ["preserve_order"] } +shell-words = "1.1.1" +tempfile = "3.27.0" +thiserror = "2.0.21" +tokio = { version = "1.53.3", features = ["rt-multi-thread", "macros", "sync", "time", "fs", "io-util"] } +tokio-rustls = { version = "0.26.6", default-features = false, features = ["ring"] } +toml = "1.1.8" +tracing = "0.1.44" +tracing-appender = "0.2.5" +tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } +uuid = { version = "1.28.0", features = ["v4"] } +wiremock = "0.6.5" +winresource = "0.1.34" + +[profile.release] +lto = "thin" +codegen-units = 1 +strip = true + +[profile.dev.package."*"] +opt-level = 2 diff --git a/README.md b/README.md new file mode 100644 index 0000000..66af05b --- /dev/null +++ b/README.md @@ -0,0 +1,184 @@ +# reqlite + +A small, fast API client. Requests live in plain `.http` files (the JetBrains +HTTP Client / VS Code REST Client format), so collections are git-friendly and +open in your IDE too. Built in Rust with egui, libcurl and Tokio, following +[implementation-plan.md](implementation-plan.md). + +- `reqlite-gui [folder]` is the desktop app. +- `reqlite` is the command line (`reqlite run api/users.http --env dev`). + +## Building + +Needs Rust (pinned in `rust-toolchain.toml`) and a C compiler; libcurl is built +from source and linked statically. On Windows the MSVC Build Tools are enough +(TLS uses Schannel). On Linux, TLS uses the system OpenSSL (`libssl-dev`). + +```sh +cargo install --locked just cargo-deny # once +just check # fmt + clippy -D warnings + all tests + cargo deny +just release # target/release/reqlite-gui and target/release/reqlite +just run # start the GUI (debug build) +``` + +`just release-glow` builds the GUI with the OpenGL renderer instead of wgpu, +for old GPUs, VMs and remote desktops. `just install-hook` adds a git +pre-push hook that runs `just check`. + +## Using it + +Open a folder (**File → Open collection folder**). Every `.http` file in it +shows up in the sidebar as *folder → file → requests*. Click a request to open +it in a tab, edit it, and press **Ctrl+Enter** to send and **Ctrl+S** to save. +Saving only rewrites that request's bytes in the file; everything else, including +comments and response-handler scripts, stays as it was. + +```http +### Create user +# @name create-user +POST {{base_url}}/users +Content-Type: application/json +Authorization: Bearer {{token}} + +{ "name": "Ada" } +``` + +Environments come from `http-client.env.json` (committed) and +`http-client.private.env.json` (secrets, git-ignored) next to the `.http` files. +Pick one in the top bar; **Edit…** opens the environment editor. Variables are +green when defined and red when not; hover one to see its value (private values +show as `••••`). Lookup order: private env, public env, file variables +(`@name = value`), then built-ins (`{{$uuid}}`, `{{$timestamp}}`, +`{{$isoTimestamp}}`, `{{$randomInt}}`, `{{$randomInt 1 10}}`). The special +`$shared` environment applies to all environments. + +Other things worth knowing: + +- **Paste a curl command into the URL bar** to import it (Chrome/Firefox + "Copy as cURL" in bash, cmd or PowerShell form all work). **…** → *Copy as + curl* goes the other way. +- **File → Import Postman collection…** converts a v2.1 collection into a folder + of `.http` files plus `http-client.env.json`. Scripts are skipped and listed. + The CLI does the same: `reqlite import postman coll.json out/ --env env.json`. +- The **Source** tab shows the request as `.http` text; edits there and in the + form stay in sync. +- The **Auth** tab is a helper that writes the `Authorization` header. Basic + auth is written as `Basic user password` and encoded when sent, like JetBrains. +- Cookies are kept in memory per collection (**View → Cookies**); + `# @no-cookie-jar` skips them for one request. +- **View → History** lists sent requests; *Open* restores one into a new tab. + `# @no-log` keeps a request out of history. +- Large responses are spilled to a temp file above 5 MB and shown in a + virtualized viewer; **Ctrl+F** searches the body. +- Files changed outside the app (editor, `git pull`) are reloaded; if the open + tab has unsaved edits you are asked which version to keep. + +| Shortcut | Action | +|---|---| +| Ctrl+Enter | Send | +| Ctrl+S | Save | +| Ctrl+T | New tab | +| Ctrl+W | Close tab | +| Ctrl+L | Focus the URL bar | +| Ctrl+P | Quick-open a request | +| Ctrl+F | Find in the response | + +Settings (timeout, proxy, TLS verification, extra CA file, theme, font size) +are stored in the config directory (`~/.config/reqlite/settings.toml` on Linux, +`%APPDATA%\reqlite\config\settings.toml` on Windows). History and logs are in the +data directory. Set `REQLITE_LOG=debug` for verbose logs. + +## The `.http` dialect + +reqlite supports the subset that JetBrains and VS Code REST Client largely agree +on: + +- `###` separators with an optional title; a request needs no separator if it + is the first in the file. +- `METHOD URL [HTTP/version]`, or a bare URL (GET). Query parameters may + continue on indented lines starting with `?`, `&` or `/`. +- Headers, a blank line, then the body. `# Name: value` is a disabled header. +- `{{var}}` placeholders, `\{{` for a literal `{{`. +- File variables: `@name = value`. +- Bodies from files: `< ./file` (sent as-is) and `<@ ./file` (variables + replaced). +- `multipart/form-data` bodies with a boundary, parts may be `< ./file`. +- Directives: `# @name`, `# @no-redirect`, `# @no-cookie-jar`, `# @no-log`, + `# @timeout 30` / `500 ms`, `# @connection-timeout`. `# @insecure` is a + reqlite extension written by curl import for `-k`. +- `#` and `//` comments. + +Anything else (unknown directives, response handlers `> {% … %}` and +`> ./script.js`, `<> ./previous-response`) is kept verbatim and never run. +Request chaining (`{{create-user.response.body.$.id}}`) is not supported yet. + +## Command line + +```text +reqlite run [--name NAME] [--env ENV] [-k] [--timeout SECS] + [--body-only] [--pretty] [--fail] +reqlite curl [--name NAME] [--env ENV] # print as curl commands +reqlite import curl ['curl …'] # print as .http (stdin if omitted) +reqlite import postman [--env env.json]… +``` + +Without `--name`, `run` sends every request in the file in order, sharing one +cookie jar. Env files are taken from the nearest folder at or above the +`.http` file. + +## Code layout + +``` +crates/core model, lossless .http parser/writer, templating, env files, + collections, cookies, curl/Postman import, curl export. + No UI, no network, no async runtime. +crates/http-curl libcurl HttpClient: spawn_blocking around Easy2, cancel via + the progress callback, temp-file spill, timings. +crates/app egui app: AppState, Action → update() → Effect, Tokio effects. +crates/cli the reqlite command. +tests/fixtures .http files, curl commands, Postman exports. +fuzz/ cargo-fuzz target for the parser (nightly). +``` + +The app follows the plan's data flow: UI panels only read `AppState` and push +`Action`s; `action::update` is a pure function that changes state and returns +`Effect`s; `effects::Runner` runs effects as Tokio tasks and sends results back +as actions over a channel, waking egui with `request_repaint`. Most behaviour is +tested by calling `update` directly (`crates/app/src/action/tests.rs`). + +## Tests + +`just check` runs everything below: + +- **Parser:** snapshots of the syntax tree for every fixture, byte-identical + round trips, edit-only-touches-one-request checks, and a randomized test over + thousands of generated files (`REQLITE_FUZZ_CASES=300000` for a longer run). +- **Templating, env, cookies, import/export:** table-driven tests and snapshots + over real-world curl commands and Postman exports. +- **HTTP:** wiremock tests for every method and body type, redirects, timeout, + cancel mid-transfer (task ends within 200 ms), 20 concurrent requests, temp + file spill, and a TLS test with a fresh CA (fails by default, works with `-k` + or the CA file). +- **App:** `update()` tests (URL/params sync, send/receive/cancel, save writes + nothing when unchanged, external-change conflicts, collection operations …), + egui_kittest UI smoke tests with a fake client, a file-watcher test, and a + check that every symbol used in the UI exists in the bundled fonts. +- **CLI:** end-to-end against wiremock with env files and cookies. + +`cargo test -p reqlite-app --test render -- --ignored` with +`REQLITE_RENDER_DIR=dir` renders screenshots of the real UI (needs a GPU or a +software Vulkan driver). + +## Packaging + +- **Linux:** `just package-linux` makes a tarball with both binaries, the icon + and a `.desktop` file. `cargo bundle --release -p reqlite-app` can make a + `.deb`. +- **Windows:** `just package-windows` makes a portable zip. The exe embeds the + icon and version info (`winresource`). For an MSI: `cargo install cargo-wix`, + then `cargo wix init -p reqlite-app` once and `cargo wix -p reqlite-app`. + Without code signing, SmartScreen shows a warning. +- **macOS:** `cargo bundle --release -p reqlite-app` makes a `.app`. + +Releases are made by hand: run `just check` and the package recipe on each OS, +tag the commit, and upload the files. diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml new file mode 100644 index 0000000..e9ca3d2 --- /dev/null +++ b/crates/app/Cargo.toml @@ -0,0 +1,58 @@ +[package] +name = "reqlite-app" +description = "reqlite desktop app (egui)." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +publish.workspace = true + +build = "build.rs" + +[[bin]] +name = "reqlite-gui" +path = "src/main.rs" + +[lib] +path = "src/lib.rs" + +[features] +default = [] +# Use the OpenGL renderer instead of wgpu (old GPUs, VMs, remote desktops). +glow = ["eframe/glow"] + +[dependencies] +reqlite-core.workspace = true +reqlite-http-curl.workspace = true +anyhow.workspace = true +base64.workspace = true +directories.workspace = true +eframe.workspace = true +egui.workspace = true +egui_extras.workspace = true +image.workspace = true +notify.workspace = true +rfd.workspace = true +serde.workspace = true +serde_json.workspace = true +tokio.workspace = true +toml.workspace = true +tracing.workspace = true +tracing-appender.workspace = true +tracing-subscriber.workspace = true +uuid.workspace = true + +[dev-dependencies] +egui_kittest.workspace = true +tempfile.workspace = true + +[target.'cfg(windows)'.build-dependencies] +winresource.workspace = true + +# `cargo bundle --release -p reqlite-app` builds a macOS .app (and .deb). +[package.metadata.bundle] +name = "reqlite" +identifier = "se.torbjornmolin.reqlite" +icon = ["assets/icon.png"] +category = "public.app-category.developer-tools" +short_description = "A small API client for .http files" diff --git a/crates/app/assets/icon.ico b/crates/app/assets/icon.ico new file mode 100644 index 0000000..1467bb1 Binary files /dev/null and b/crates/app/assets/icon.ico differ diff --git a/crates/app/assets/icon.png b/crates/app/assets/icon.png new file mode 100644 index 0000000..789ba7e Binary files /dev/null and b/crates/app/assets/icon.png differ diff --git a/crates/app/assets/reqlite.desktop b/crates/app/assets/reqlite.desktop new file mode 100644 index 0000000..53f16b8 --- /dev/null +++ b/crates/app/assets/reqlite.desktop @@ -0,0 +1,9 @@ +[Desktop Entry] +Type=Application +Name=reqlite +Comment=A small API client for .http files +Exec=reqlite-gui %f +Icon=reqlite +Terminal=false +Categories=Development;Network; +StartupWMClass=reqlite diff --git a/crates/app/build.rs b/crates/app/build.rs new file mode 100644 index 0000000..611060a --- /dev/null +++ b/crates/app/build.rs @@ -0,0 +1,13 @@ +//! Embeds the icon and version info in the Windows executable. + +fn main() { + println!("cargo:rerun-if-changed=assets/icon.ico"); + #[cfg(windows)] + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { + let mut res = winresource::WindowsResource::new(); + res.set_icon("assets/icon.ico"); + res.set("ProductName", "reqlite"); + res.set("FileDescription", "reqlite API client"); + res.compile().expect("embedding Windows resources"); + } +} diff --git a/crates/app/src/action.rs b/crates/app/src/action.rs new file mode 100644 index 0000000..ff4a7bf --- /dev/null +++ b/crates/app/src/action.rs @@ -0,0 +1,1330 @@ +//! `Action`s (what happened) and the pure `update` function that applies them +//! to [`AppState`] and returns [`Effect`]s (what to do outside: I/O, dialogs). + +use std::path::{Path, PathBuf}; +use std::time::{Instant, SystemTime, UNIX_EPOCH}; + +use reqlite_core::collection::{self, Collection}; +use reqlite_core::env::{self, Environments}; +use reqlite_core::export::curl::to_curl; +use reqlite_core::http::{HttpError, Response}; +use reqlite_core::httpfile::{render_request, HttpFile}; +use reqlite_core::import::curl::{from_curl, looks_like_curl}; +use reqlite_core::params::{parse_params, with_params, Param}; +use reqlite_core::resolve::resolve_request; +use reqlite_core::{Body, CancelToken, Header, Method, Request}; + +use crate::effects::{Effect, FileOp}; +use crate::history::HistoryEntry; +use crate::settings::Settings; +use crate::state::*; + +#[derive(Debug)] +pub enum Action { + // Tabs. + NewTab, + CloseTab(TabId), + /// Close even with unsaved changes. + DiscardAndCloseTab(TabId), + SelectTab(TabId), + OpenRequest { + file: PathBuf, + index: usize, + }, + NewTabFromHttp(String), + + // Editing a tab. + SetMethod(TabId, Method), + UrlEdited(TabId, String), + ParamsEdited(TabId, Vec), + HeadersEdited(TabId, Vec
), + BodyEdited(TabId, Body), + /// Sets (`Some`) or removes (`None`) the Authorization header. + AuthEdited(TabId, Option), + SourceEdited(TabId, String), + SetRequestTab(TabId, RequestTab), + SetResponseTab(TabId, ResponseTab), + SetBodyView(TabId, BodyView), + SetNoRedirect(TabId, bool), + PickBodyFile(TabId), + BodyFilePicked(TabId, PathBuf), + + // Sending. + Send(TabId), + Cancel(TabId), + ResponseReceived { + tab: TabId, + seq: u64, + result: Result, + }, + BodyPrepared { + tab: TabId, + seq: u64, + body: PreparedBody, + }, + SaveResponseBody(TabId), + + // Response search. + SearchOpen(TabId, bool), + SearchQuery(TabId, String), + SearchStep(TabId, i32), + ScrolledTo(TabId), + + // Collections. + PickCollection, + OpenCollection(PathBuf), + CollectionLoaded(Result), + /// The environments, and whether the private file exists without being git-ignored. + EnvironmentsLoaded(Result<(Environments, bool), String>), + FileChangedOnDisk { + path: PathBuf, + text: Option, + }, + Rescan, + Save(TabId), + /// `existing` is the current content of `path`, if it exists. + SaveAs { + tab: TabId, + path: PathBuf, + existing: Option, + }, + ResolveConflict { + tab: TabId, + keep_mine: bool, + }, + NewFile { + dir: PathBuf, + name: String, + }, + NewRequestIn { + file: PathBuf, + }, + RenameRequest { + file: PathBuf, + index: usize, + title: String, + }, + DuplicateRequest { + file: PathBuf, + index: usize, + }, + DeleteRequest { + file: PathBuf, + index: usize, + }, + MoveRequest { + from: PathBuf, + index: usize, + to: PathBuf, + }, + RenameFile { + path: PathBuf, + new_name: String, + }, + DeleteFile(PathBuf), + DuplicateFile(PathBuf), + + // Environments. + SelectEnv(Option), + OpenEnvEditor, + EnvEditorChanged(EnvEditor), + EnvEditorSave, + EnvEditorClose, + AddPrivateFileToGitignore, + DismissGitignoreOffer, + + // Import / export. + CopyAsCurl(TabId), + CopyAsHttp(TabId), + ImportPostman, + PostmanImported { + root: PathBuf, + files: usize, + warnings: Vec, + }, + + // History, cookies, settings. + HistoryLoaded(Vec), + RestoreHistory(usize), + ClearHistory, + ClearCookies, + DeleteCookie(usize), + SettingsLoaded(Settings), + SettingsChanged(Settings), + PickCaFile, + CaFilePicked(PathBuf), + + // Shell. + ShowDialog(Option), + SetWindows(Windows), + QuickOpen(Option), + FocusUrl, + UrlFocused, + CloseRequested, + ConfirmQuit, + Error(String), + Info(String), + DismissStatus, +} + +/// Applies an action. The only place that changes [`AppState`]. +pub fn update(state: &mut AppState, action: Action) -> Vec { + let mut fx = Vec::new(); + match action { + // ---------------------------------------------------------- tabs + Action::NewTab => { + new_tab(state, Request::default(), None, String::new()); + state.focus_url = true; + } + Action::CloseTab(id) => { + if state.tab(id).is_some_and(Tab::is_dirty) { + state.dialog = Some(Dialog::ConfirmCloseTab(id)); + } else { + close_tab(state, id); + } + } + Action::DiscardAndCloseTab(id) => { + state.dialog = None; + close_tab(state, id); + } + Action::SelectTab(id) => { + if state.tab(id).is_some() { + state.active = Some(id); + } + } + Action::OpenRequest { file, index } => open_request(state, &file, index), + Action::NewTabFromHttp(text) => { + let f = HttpFile::parse(text.clone()); + match f.request(0) { + Some(r) => { + let mut r = r.clone(); + r.source = Default::default(); + let src = f.request_source(0).unwrap_or("").to_string(); + new_tab(state, r, None, src); + } + None => state.set_error("No request in that text"), + } + } + + // ---------------------------------------------------- editing + Action::SetMethod(id, m) => edit(state, id, |r| r.method = m), + Action::UrlEdited(id, url) => { + if looks_like_curl(&url) { + match from_curl(&url) { + Ok(mut req) => { + if let Some(t) = state.tab(id) { + req.title = t.request.title.clone(); + req.name = t.request.name.clone(); + } + edit(state, id, |r| *r = req); + state.set_info("Imported the curl command"); + } + Err(e) => { + state.set_error(format!("Could not import curl command: {e}")); + edit(state, id, |r| r.url = url); + } + } + } else { + edit(state, id, |r| r.url = url); + } + } + Action::ParamsEdited(id, params) => { + if let Some(t) = state.tab_mut(id) { + let url = with_params(&t.request.url, ¶ms); + t.request.url = url; + // Keep the rows as the user has them (including a half-typed + // empty row) rather than re-deriving from the URL. + t.params = params; + after_form_edit(t); + } + } + Action::HeadersEdited(id, headers) => edit(state, id, |r| r.headers = headers), + Action::BodyEdited(id, body) => edit(state, id, |r| r.body = body), + Action::AuthEdited(id, value) => edit(state, id, |r| match value { + Some(v) => r.set_header("Authorization", v), + None => r.remove_header("Authorization"), + }), + Action::SetNoRedirect(id, on) => edit(state, id, |r| r.directives.no_redirect = on), + Action::PickBodyFile(id) => fx.push(Effect::PickBodyFile(id)), + Action::BodyFilePicked(id, path) => { + let Some(t) = state.tab(id) else { return fx }; + // Store it relative to the .http file when possible, like `< ./x`. + let base = state.base_dir_for(t); + let path = match path.strip_prefix(&base) { + Ok(rel) => Path::new(".").join(rel), + Err(_) => path, + }; + let substitute = matches!(t.request.body, Body::FileRef { substitute: true, .. }); + edit(state, id, |r| r.body = Body::FileRef { path, substitute }); + } + Action::SourceEdited(id, text) => { + if let Some(t) = state.tab_mut(id) { + let f = HttpFile::parse(text.clone()); + t.source = text; + t.source_authoritative = true; + match f.request_count() { + 1 => { + let mut r = f.request(0).unwrap().clone(); + r.source = t.request.source; + t.params = parse_params(&r.url); + t.request = r; + t.source_error = None; + } + 0 => t.source_error = Some("No request line found".into()), + n => t.source_error = Some(format!("The source must contain exactly one request (found {n})")), + } + } + } + Action::SetRequestTab(id, rt) => { + if let Some(t) = state.tab_mut(id) { + t.request_tab = rt; + } + } + Action::SetResponseTab(id, rt) => { + if let Some(t) = state.tab_mut(id) { + t.response_tab = rt; + } + } + Action::SetBodyView(id, v) => { + if let Some(t) = state.tab_mut(id) { + t.body_view = v; + recompute_search(t); + } + } + + // ---------------------------------------------------- sending + Action::Send(id) => send(state, id, &mut fx), + Action::Cancel(id) => { + if let Some(t) = state.tab_mut(id) { + if let Some(f) = t.in_flight.take() { + f.cancel.cancel(); + t.error = Some("Cancelled".into()); + } + } + } + Action::ResponseReceived { tab, seq, result } => receive(state, tab, seq, result, &mut fx), + Action::BodyPrepared { tab, seq, body } => { + if let Some(t) = state.tab_mut(tab) { + if t.seq == seq { + if let Some(r) = &mut t.response { + r.prepared = Some(body); + } + recompute_search(t); + } + } + } + Action::SaveResponseBody(id) => { + if let Some(r) = state.tab(id).and_then(|t| t.response.as_ref()) { + fx.push(Effect::SaveResponseBody { + body: r.response.body.clone(), + suggested_name: suggested_file_name(&r.response), + }); + } + } + + // ---------------------------------------------------- search + Action::SearchOpen(id, open) => { + if let Some(t) = state.tab_mut(id) { + t.search.open = open; + if open { + t.response_tab = ResponseTab::Body; + } + } + } + Action::SearchQuery(id, q) => { + if let Some(t) = state.tab_mut(id) { + t.search.query = q; + t.search.current = 0; + recompute_search(t); + t.search.scroll_to = t.search.matches.first().map(|m| m.0); + } + } + Action::SearchStep(id, delta) => { + if let Some(t) = state.tab_mut(id) { + let n = t.search.matches.len(); + if n > 0 { + t.search.current = (t.search.current as i64 + delta as i64).rem_euclid(n as i64) as usize; + t.search.scroll_to = Some(t.search.matches[t.search.current].0); + } + } + } + Action::ScrolledTo(id) => { + if let Some(t) = state.tab_mut(id) { + t.search.scroll_to = None; + } + } + + // ---------------------------------------------------- collections + Action::PickCollection => fx.push(Effect::PickCollectionFolder), + Action::OpenCollection(root) => { + state.settings.add_recent(root.clone()); + fx.push(Effect::SaveSettings(state.settings.clone())); + fx.push(Effect::LoadCollection(root)); + } + Action::CollectionLoaded(Err(e)) => state.set_error(format!("Could not open the collection: {e}")), + Action::CollectionLoaded(Ok(c)) => collection_loaded(state, c, &mut fx), + Action::EnvironmentsLoaded(res) => { + if let Some(c) = &mut state.collection { + match res { + Ok((envs, private_not_ignored)) => { + c.envs = envs; + c.env_error = None; + c.private_not_ignored = private_not_ignored; + if let Some(sel) = &state.selected_env { + if !c.envs.names().contains(sel) { + state.selected_env = None; + } + } + } + Err(e) => c.env_error = Some(e), + } + } + } + Action::FileChangedOnDisk { path, text } => file_changed(state, path, text, &mut fx), + Action::Rescan => { + if let Some(c) = &state.collection { + fx.push(Effect::LoadCollection(c.root.clone())); + } + } + Action::Save(id) => save(state, id, &mut fx), + Action::SaveAs { tab, path, existing } => save_as(state, tab, path, existing, &mut fx), + Action::ResolveConflict { tab, keep_mine } => { + state.dialog = None; + if !keep_mine { + if let Some(t) = state.tab(tab) { + if let Some(o) = t.origin.clone() { + reload_tab_from_file(state, tab, &o.file); + } + } + } + } + Action::NewFile { dir, name } => { + state.dialog = None; + let name = name.trim(); + if name.is_empty() { + return fx; + } + let name = if collection::is_http_file(Path::new(name)) { + name.to_string() + } else { + format!("{name}.http") + }; + let path = dir.join(name); + if state.collection.as_ref().is_some_and(|c| c.files.contains_key(&path)) { + state.set_error(format!("{} already exists", path.display())); + return fx; + } + let req = Request { + title: Some("New request".into()), + ..Request::default() + }; + let text = render_request(&req, "\n"); + fx.push(file_ops(state, vec![FileOp::Write(path.clone(), text.clone())], true)); + insert_file(state, &path, text); + open_request(state, &path, 0); + } + Action::NewRequestIn { file } => { + let Some(f) = file_of(state, &file) else { return fx }; + let n = f.request_count(); + let req = Request { + title: Some(unique_title(f, "New request")), + ..Request::default() + }; + let text = f.insert_request(None, &req); + fx.push(file_ops(state, vec![FileOp::Write(file.clone(), text.clone())], false)); + insert_file(state, &file, text); + open_request(state, &file, n); + state.focus_url = true; + } + Action::RenameRequest { file, index, title } => { + state.dialog = None; + let Some(f) = file_of(state, &file) else { return fx }; + let Some(old) = f.request(index).cloned() else { + return fx; + }; + let mut req = old.clone(); + let title = title.trim().to_string(); + req.title = (!title.is_empty()).then_some(title); + // A rename should rename: drop an @name that would shadow the title. + if req.name.is_some() { + req.name = req.title.as_deref().map(slug_name); + } + let Some(text) = f.replace_request(index, &req) else { + return fx; + }; + fx.push(file_ops(state, vec![FileOp::Write(file.clone(), text.clone())], false)); + insert_file(state, &file, text); + // Keep open tabs pointing at the renamed request. + let new_key = file_of(state, &file).and_then(|f| f.key_of(index)); + for t in state.tabs.iter_mut() { + if let Some(o) = &mut t.origin { + if o.file == file && o.key.index == index { + if let Some(k) = &new_key { + o.key = k.clone(); + } + t.request.title = req.title.clone(); + t.request.name = req.name.clone(); + t.saved.title = req.title.clone(); + t.saved.name = req.name.clone(); + refresh_source(t); + } + } + } + } + Action::DuplicateRequest { file, index } => { + let Some(f) = file_of(state, &file) else { return fx }; + let Some(src) = f.request_source(index) else { return fx }; + let orig = f.request(index).cloned().unwrap_or_default(); + // Re-title the copy so its key is unique. + let base = orig.display_name().unwrap_or("Request").to_string(); + let mut copy = HttpFile::parse(src.to_string()); + let mut r = copy.request(0).cloned().unwrap_or_default(); + r.title = Some(unique_title(f, &format!("{base} copy"))); + r.name = r.name.as_ref().map(|_| slug_name(r.title.as_deref().unwrap())); + if let Some(t) = copy.replace_request(0, &r) { + copy = HttpFile::parse(t); + } + let block = if copy.text().starts_with("###") { + copy.text().to_string() + } else { + format!("###\n{}", copy.text()) + }; + let text = f.insert_request_text(Some(index), &block); + fx.push(file_ops(state, vec![FileOp::Write(file.clone(), text.clone())], false)); + shift_origins(state, &file, index + 1, 1); + insert_file(state, &file, text); + open_request(state, &file, index + 1); + } + Action::DeleteRequest { file, index } => { + state.dialog = None; + let Some(f) = file_of(state, &file) else { return fx }; + let Some(text) = f.remove_request(index) else { return fx }; + fx.push(file_ops(state, vec![FileOp::Write(file.clone(), text.clone())], false)); + orphan_tabs(state, &file, Some(index)); + shift_origins(state, &file, index + 1, -1); + insert_file(state, &file, text); + } + Action::MoveRequest { from, index, to } => { + if from == to { + return fx; + } + let (Some(src_file), Some(dst_file)) = (file_of(state, &from), file_of(state, &to)) else { + return fx; + }; + let Some(block) = src_file.request_source(index) else { + return fx; + }; + let mut block = block.to_string(); + if !block.starts_with("###") { + block = format!("###\n{block}"); + } + let new_index = dst_file.request_count(); + let Some(src_text) = src_file.remove_request(index) else { + return fx; + }; + let dst_text = dst_file.insert_request_text(None, &block); + fx.push(file_ops( + state, + vec![ + FileOp::Write(to.clone(), dst_text.clone()), + FileOp::Write(from.clone(), src_text.clone()), + ], + false, + )); + // Tabs follow the request to its new file. + for t in state.tabs.iter_mut() { + if let Some(o) = &mut t.origin { + if o.file == from && o.key.index == index { + o.file = to.clone(); + o.key.index = new_index; + } + } + } + shift_origins(state, &from, index + 1, -1); + insert_file(state, &to, dst_text); + insert_file(state, &from, src_text); + } + Action::RenameFile { path, new_name } => { + state.dialog = None; + let new_name = new_name.trim(); + if new_name.is_empty() { + return fx; + } + let new_name = if collection::is_http_file(Path::new(new_name)) { + new_name.to_string() + } else { + format!("{new_name}.http") + }; + let Some(dir) = path.parent() else { return fx }; + let to = dir.join(new_name); + if to == path { + return fx; + } + fx.push(file_ops(state, vec![FileOp::Rename(path.clone(), to.clone())], true)); + for t in state.tabs.iter_mut() { + if let Some(o) = &mut t.origin { + if o.file == path { + o.file = to.clone(); + } + } + } + if let Some(c) = &mut state.collection { + if let Some(f) = c.files.remove(&path) { + c.files.insert(to, f); + } + } + } + Action::DuplicateFile(path) => { + let Some(f) = file_of(state, &path) else { return fx }; + let text = f.text().to_string(); + let stem = path + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + let ext = path + .extension() + .map(|e| e.to_string_lossy().into_owned()) + .unwrap_or("http".into()); + let dir = path.parent().map(Path::to_path_buf).unwrap_or_default(); + let taken = |p: &PathBuf| state.collection.as_ref().is_some_and(|c| c.files.contains_key(p)); + let copy = std::iter::once(dir.join(format!("{stem} copy.{ext}"))) + .chain((2..).map(|n| dir.join(format!("{stem} copy {n}.{ext}")))) + .find(|p| !taken(p)) + .unwrap(); + fx.push(file_ops(state, vec![FileOp::Write(copy.clone(), text.clone())], true)); + insert_file(state, ©, text); + } + Action::DeleteFile(path) => { + state.dialog = None; + fx.push(file_ops(state, vec![FileOp::Delete(path.clone())], true)); + orphan_tabs(state, &path, None); + if let Some(c) = &mut state.collection { + c.files.remove(&path); + } + } + + // ---------------------------------------------------- environments + Action::SelectEnv(e) => state.selected_env = e, + Action::OpenEnvEditor => { + if let Some(c) = &state.collection { + let selected = state + .selected_env + .clone() + .or_else(|| c.envs.names().first().cloned()) + .unwrap_or_else(|| "dev".into()); + state.env_editor = Some(EnvEditor { + envs: c.envs.clone(), + selected, + revealed: Vec::new(), + dirty: false, + }); + } else { + state.set_error("Open a collection folder first; environments live next to the .http files"); + } + } + Action::EnvEditorChanged(e) => state.env_editor = Some(e), + Action::EnvEditorClose => state.env_editor = None, + Action::EnvEditorSave => { + let (Some(ed), Some(c)) = (&mut state.env_editor, &mut state.collection) else { + return fx; + }; + let mut ops = Vec::new(); + if ed.envs.public != c.envs.public { + ops.push(FileOp::Write(c.root.join(env::PUBLIC_FILE), ed.envs.public.to_json())); + } + if ed.envs.private != c.envs.private { + ops.push(FileOp::Write(c.root.join(env::PRIVATE_FILE), ed.envs.private.to_json())); + } + c.envs = ed.envs.clone(); + ed.dirty = false; + if !ops.is_empty() { + fx.push(Effect::FileOps { ops, rescan: None }); + // Re-check whether the private file is git-ignored. + fx.push(Effect::LoadEnvironments(c.root.clone())); + } + } + Action::AddPrivateFileToGitignore => { + if let Some(c) = &mut state.collection { + fx.push(Effect::AppendGitignore(c.root.clone())); + c.private_not_ignored = false; + } + } + Action::DismissGitignoreOffer => { + if let Some(c) = &mut state.collection { + c.gitignore_offer_dismissed = true; + } + } + + // ---------------------------------------------------- import/export + Action::CopyAsCurl(id) => { + let Some(t) = state.tab(id) else { return fx }; + let resolver = state.resolver_for(t); + match resolve_request( + &t.request, + &resolver, + &state.base_dir_for(t), + &state.settings.request_options(), + ) { + Ok(r) => { + fx.push(Effect::CopyToClipboard(to_curl(&r))); + state.set_info("Copied as curl"); + } + Err(e) => state.set_error(format!("Cannot build the curl command: {e}")), + } + } + Action::CopyAsHttp(id) => { + let Some(t) = state.tab(id) else { return fx }; + let text = if t.source.trim().is_empty() { + render_request(&t.request, "\n") + } else { + t.source.clone() + }; + fx.push(Effect::CopyToClipboard(text)); + state.set_info("Copied as .http"); + } + Action::ImportPostman => fx.push(Effect::PickPostmanImport), + Action::PostmanImported { root, files, warnings } => { + state.dialog = Some(Dialog::ImportSummary { + root: root.clone(), + files, + warnings, + }); + return update(state, Action::OpenCollection(root)); + } + + // ---------------------------------------------------- history etc. + Action::HistoryLoaded(h) => state.history = h, + Action::RestoreHistory(i) => { + if let Some(e) = state.history.get(i) { + let text = e.http.clone(); + if e.env.is_some() + && state + .collection + .as_ref() + .is_some_and(|c| c.envs.names().contains(e.env.as_ref().unwrap())) + { + state.selected_env = e.env.clone(); + } + return update(state, Action::NewTabFromHttp(text)); + } + } + Action::ClearHistory => { + state.history.clear(); + fx.push(Effect::RewriteHistory(Vec::new())); + } + Action::ClearCookies => { + let key = state.collection.as_ref().map(|c| c.root.clone()); + state.cookie_jars.entry(key).or_default().clear(); + } + Action::DeleteCookie(i) => { + let key = state.collection.as_ref().map(|c| c.root.clone()); + state.cookie_jars.entry(key).or_default().remove(i); + } + Action::SettingsLoaded(s) => { + fx.push(Effect::SetConcurrency(s.max_concurrent_requests)); + state.settings = s; + } + Action::SettingsChanged(s) => { + if s.max_concurrent_requests != state.settings.max_concurrent_requests { + fx.push(Effect::SetConcurrency(s.max_concurrent_requests)); + } + state.settings = s; + fx.push(Effect::SaveSettings(state.settings.clone())); + } + Action::PickCaFile => fx.push(Effect::PickCaFile), + Action::CaFilePicked(p) => { + state.settings.ca_file = Some(p); + fx.push(Effect::SaveSettings(state.settings.clone())); + } + + // ---------------------------------------------------- shell + Action::ShowDialog(d) => state.dialog = d, + Action::SetWindows(w) => state.windows = w, + Action::QuickOpen(q) => state.quick_open = q, + Action::FocusUrl => state.focus_url = true, + Action::UrlFocused => state.focus_url = false, + Action::CloseRequested => { + if state.any_dirty() && !state.quit_confirmed { + state.dialog = Some(Dialog::ConfirmQuit); + } else { + state.quit_confirmed = true; + fx.push(Effect::Quit); + } + } + Action::ConfirmQuit => { + state.dialog = None; + state.quit_confirmed = true; + fx.push(Effect::Quit); + } + Action::Error(e) => state.set_error(e), + Action::Info(i) => state.set_info(i), + Action::DismissStatus => state.status = None, + } + fx +} + +// ------------------------------------------------------------------ helpers + +fn new_tab(state: &mut AppState, req: Request, origin: Option, source: String) -> TabId { + let id = state.alloc_tab_id(); + let source = if source.is_empty() && !req.url.is_empty() { + render_request(&req, "\n") + } else { + source + }; + state.tabs.push(Tab::new(id, req, origin, source)); + state.active = Some(id); + id +} + +fn close_tab(state: &mut AppState, id: TabId) { + let Some(pos) = state.tabs.iter().position(|t| t.id == id) else { + return; + }; + let tab = state.tabs.remove(pos); + if let Some(f) = tab.in_flight { + f.cancel.cancel(); + } + if state.active == Some(id) { + state.active = state + .tabs + .get(pos) + .or_else(|| state.tabs.get(pos.wrapping_sub(1))) + .map(|t| t.id); + } +} + +fn file_of<'a>(state: &'a AppState, path: &Path) -> Option<&'a HttpFile> { + state.collection.as_ref()?.files.get(path) +} + +fn insert_file(state: &mut AppState, path: &Path, text: String) { + if let Some(c) = &mut state.collection { + c.files.insert(path.to_path_buf(), HttpFile::parse(text)); + } +} + +fn file_ops(state: &AppState, ops: Vec, rescan: bool) -> Effect { + Effect::FileOps { + ops, + rescan: if rescan { + state.collection.as_ref().map(|c| c.root.clone()) + } else { + None + }, + } +} + +fn open_request(state: &mut AppState, file: &Path, index: usize) { + // Focus an existing tab for the same request. + if let Some(t) = state.tabs.iter().find(|t| { + t.origin + .as_ref() + .is_some_and(|o| o.file == file && o.key.index == index) + }) { + state.active = Some(t.id); + return; + } + let Some(f) = file_of(state, file) else { return }; + let (Some(req), Some(key), Some(src)) = (f.request(index), f.key_of(index), f.request_source(index)) else { + return; + }; + let (req, src) = (req.clone(), src.to_string()); + new_tab( + state, + req, + Some(Origin { + file: file.to_path_buf(), + key, + }), + src, + ); +} + +/// Applies a form edit to a tab's request. +fn edit(state: &mut AppState, id: TabId, f: impl FnOnce(&mut Request)) { + if let Some(t) = state.tab_mut(id) { + f(&mut t.request); + t.params = parse_params(&t.request.url); + after_form_edit(t); + } +} + +fn after_form_edit(t: &mut Tab) { + t.source_authoritative = false; + t.source_error = None; + refresh_source(t); +} + +/// Regenerates the Source text from the form, keeping comments and other +/// unmodelled parts of the saved text. +fn refresh_source(t: &mut Tab) { + let base = HttpFile::parse(t.saved_source.clone()); + t.source = if base.request_count() == 1 { + base.replace_request(0, &t.request) + .unwrap_or_else(|| render_request(&t.request, "\n")) + } else { + render_request(&t.request, "\n") + }; +} + +fn send(state: &mut AppState, id: TabId, fx: &mut Vec) { + let Some(t) = state.tab(id) else { return }; + if t.in_flight.is_some() { + return; + } + if let Some(e) = &t.source_error { + let e = e.clone(); + if let Some(t) = state.tab_mut(id) { + t.error = Some(format!("Fix the source first: {e}")); + } + return; + } + let resolver = state.resolver_for(t); + let base_dir = state.base_dir_for(t); + let resolved = resolve_request(&t.request, &resolver, &base_dir, &state.settings.request_options()); + let mut resolved = match resolved { + Ok(r) => r, + Err(e) => { + if let Some(t) = state.tab_mut(id) { + t.error = Some(e.to_string()); + t.response = None; + } + return; + } + }; + + let jar_key = (!t.request.directives.no_cookie_jar).then(|| state.collection.as_ref().map(|c| c.root.clone())); + if let Some(key) = &jar_key { + let has_cookie = resolved.headers.iter().any(|(n, _)| n.eq_ignore_ascii_case("cookie")); + if let Some(c) = state + .cookie_jars + .get(key) + .and_then(|j| j.header_for(&resolved.url, SystemTime::now())) + { + if !has_cookie { + resolved.headers.push(("Cookie".into(), c)); + } + } + } + + let history = HistoryEntry { + at: SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0), + method: resolved.method.clone(), + url: resolved.url.clone(), + status: None, + duration_ms: 0, + env: state.selected_env.clone(), + http: if t.source.trim().is_empty() { + render_request(&t.request, "\n") + } else { + t.source.clone() + }, + error: None, + }; + let no_log = t.request.directives.no_log; + let cancel = CancelToken::new(); + let t = state.tab_mut(id).unwrap(); + t.seq += 1; + t.error = None; + t.search.matches.clear(); + t.in_flight = Some(InFlight { + cancel: cancel.clone(), + started: Instant::now(), + seq: t.seq, + history: HistoryEntry { + // `@no-log` keeps the request out of history. + http: if no_log { String::new() } else { history.http }, + ..history + }, + cookie_jar: jar_key, + url: resolved.url.clone(), + }); + fx.push(Effect::SendRequest { + tab: id, + seq: t.seq, + request: resolved, + cancel, + }); +} + +fn receive(state: &mut AppState, id: TabId, seq: u64, result: Result, fx: &mut Vec) { + let Some(t) = state.tab_mut(id) else { return }; + if t.seq != seq { + return; // a newer request replaced this one + } + let Some(flight) = t.in_flight.take() else { + return; // cancelled + }; + let mut entry = flight.history; + entry.duration_ms = flight.started.elapsed().as_millis() as u64; + match result { + Ok(resp) => { + entry.status = Some(resp.status); + entry.duration_ms = resp.timings.total.as_millis() as u64; + fx.push(Effect::PrepareBody { + tab: id, + seq, + body: resp.body.clone(), + content_type: resp.content_type().to_string(), + }); + let set_cookies: Vec = resp.headers_named("set-cookie").map(str::to_string).collect(); + t.response = Some(ResponseView { + response: resp, + received_at: SystemTime::now(), + prepared: None, + }); + t.error = None; + if let Some(key) = flight.cookie_jar { + state.cookie_jars.entry(key).or_default().store( + &flight.url, + set_cookies.iter().map(String::as_str), + SystemTime::now(), + ); + } + } + Err(HttpError::Cancelled) => return, + Err(e) => { + entry.error = Some(e.to_string()); + t.error = Some(e.to_string()); + t.response = None; + } + } + if !entry.http.is_empty() { + state.history.push(entry.clone()); + let limit = state.settings.history_limit.max(1); + if state.history.len() > limit { + let excess = state.history.len() - limit; + state.history.drain(..excess); + } + fx.push(Effect::AppendHistory(entry)); + } +} + +fn suggested_file_name(r: &Response) -> String { + let last = r + .effective_url + .split(['?', '#']) + .next() + .unwrap_or("") + .rsplit('/') + .next() + .unwrap_or("") + .to_string(); + let ext = match r.content_type().split(';').next().unwrap_or("").trim() { + "application/json" => "json", + "text/html" => "html", + "text/plain" => "txt", + "application/xml" | "text/xml" => "xml", + "image/png" => "png", + "image/jpeg" => "jpg", + "application/pdf" => "pdf", + _ => "bin", + }; + if !last.is_empty() && last.contains('.') { + last + } else if !last.is_empty() { + format!("{last}.{ext}") + } else { + format!("response.{ext}") + } +} + +/// Recomputes search matches over the visible body text. +fn recompute_search(t: &mut Tab) { + t.search.matches.clear(); + let q = t.search.query.to_lowercase(); + if q.is_empty() { + return; + } + let Some(prepared) = t.response.as_ref().and_then(|r| r.prepared.as_ref()) else { + return; + }; + let lines = prepared.text(t.body_view); + const MAX: usize = 10_000; + for i in 0..lines.line_count() { + let line = lines.line(i); + let lower = line.to_lowercase(); + // Byte offsets only line up when lowercasing kept the length. + if lower.len() != line.len() { + continue; + } + let mut from = 0; + while let Some(pos) = lower[from..].find(&q) { + let start = from + pos; + t.search.matches.push((i, start..start + q.len())); + from = start + q.len().max(1); + if t.search.matches.len() >= MAX { + return; + } + } + } + if t.search.current >= t.search.matches.len() { + t.search.current = 0; + } +} + +fn collection_loaded(state: &mut AppState, c: Collection, fx: &mut Vec) { + let same_root = state.collection.as_ref().is_some_and(|old| old.root == c.root); + let (envs, env_error, dismissed) = match state.collection.take() { + Some(old) if same_root => (old.envs, old.env_error, old.gitignore_offer_dismissed), + _ => (Environments::default(), None, false), + }; + let root = c.root.clone(); + state.collection = Some(CollectionState { + root: c.root, + tree: c.tree, + files: c.files, + envs, + env_error, + private_not_ignored: false, + gitignore_offer_dismissed: dismissed, + }); + if !same_root { + // Tabs from another collection keep their content but lose their file. + for t in state.tabs.iter_mut() { + if t.origin.as_ref().is_some_and(|o| !o.file.starts_with(&root)) { + t.origin = None; + t.orphaned = true; + } + } + state.selected_env = None; + fx.push(Effect::Watch(Some(root.clone()))); + } else { + // Re-sync open tabs with what's on disk now. + let ids: Vec<(TabId, PathBuf)> = state + .tabs + .iter() + .filter_map(|t| t.origin.as_ref().map(|o| (t.id, o.file.clone()))) + .collect(); + for (id, file) in ids { + if file_of(state, &file).is_none() { + if let Some(t) = state.tab_mut(id) { + t.orphaned = true; + } + } + } + } + fx.push(Effect::LoadEnvironments(root)); +} + +fn file_changed(state: &mut AppState, path: PathBuf, text: Option, fx: &mut Vec) { + let Some(c) = &mut state.collection else { return }; + let name = path.file_name().and_then(|n| n.to_str()).unwrap_or(""); + if name == env::PUBLIC_FILE || name == env::PRIVATE_FILE { + fx.push(Effect::LoadEnvironments(c.root.clone())); + return; + } + if !collection::is_http_file(&path) { + return; + } + match text { + None => { + if c.files.remove(&path).is_some() { + orphan_tabs(state, &path, None); + fx.push(Effect::LoadCollection(state.collection.as_ref().unwrap().root.clone())); + } + } + Some(text) => { + if c.files.get(&path).is_some_and(|f| f.text() == text) { + return; // our own write, or no real change + } + let is_new = !c.files.contains_key(&path); + c.files.insert(path.clone(), HttpFile::parse(text)); + if is_new { + fx.push(Effect::LoadCollection(c.root.clone())); + } + let ids: Vec = state + .tabs + .iter() + .filter(|t| t.origin.as_ref().is_some_and(|o| o.file == path)) + .map(|t| t.id) + .collect(); + for id in ids { + let dirty = state.tab(id).is_some_and(Tab::is_dirty); + if dirty { + state.dialog = Some(Dialog::Conflict { + tab: id, + path: path.clone(), + }); + } else { + reload_tab_from_file(state, id, &path); + } + } + } + } +} + +/// Replaces a tab's request with the version in its file. +fn reload_tab_from_file(state: &mut AppState, id: TabId, path: &Path) { + let Some(key) = state.tab(id).and_then(|t| t.origin.as_ref()).map(|o| o.key.clone()) else { + return; + }; + let found = file_of(state, path).and_then(|f| { + let i = f.find(&key)?; + Some((f.request(i)?.clone(), f.request_source(i)?.to_string(), f.key_of(i)?)) + }); + let Some(t) = state.tab_mut(id) else { return }; + match found { + Some((req, src, key)) => { + t.params = parse_params(&req.url); + t.request = req.clone(); + t.saved = req; + t.source = src.clone(); + t.saved_source = src; + t.source_authoritative = false; + t.source_error = None; + t.orphaned = false; + if let Some(o) = &mut t.origin { + o.key = key; + } + } + None => t.orphaned = true, + } +} + +/// Marks tabs whose request no longer exists in its file. +fn orphan_tabs(state: &mut AppState, file: &Path, index: Option) { + for t in state.tabs.iter_mut() { + if let Some(o) = &t.origin { + if o.file == file && index.is_none_or(|i| o.key.index == i) { + t.origin = None; + t.orphaned = true; + } + } + } +} + +/// Shifts the index of tabs pointing at requests `from..` in `file`. +fn shift_origins(state: &mut AppState, file: &Path, from: usize, delta: i64) { + for t in state.tabs.iter_mut() { + if let Some(o) = &mut t.origin { + if o.file == file && o.key.index >= from { + o.key.index = (o.key.index as i64 + delta).max(0) as usize; + } + } + } +} + +fn unique_title(f: &HttpFile, base: &str) -> String { + let taken = |t: &str| f.requests().any(|r| r.display_name() == Some(t)); + if !taken(base) { + return base.to_string(); + } + (2..).map(|n| format!("{base} {n}")).find(|t| !taken(t)).unwrap() +} + +fn slug_name(title: &str) -> String { + reqlite_core::import::postman::slug(title) +} + +fn save(state: &mut AppState, id: TabId, fx: &mut Vec) { + let Some(t) = state.tab(id) else { return }; + if let Some(e) = &t.source_error { + let e = e.clone(); + state.set_error(format!("Cannot save: {e}")); + return; + } + let Some(origin) = t.origin.clone() else { + fx.push(Effect::PickSaveTarget(id)); + return; + }; + let Some(f) = file_of(state, &origin.file) else { + state.set_error(format!("{} is not loaded", origin.file.display())); + return; + }; + let Some(index) = f.find(&origin.key) else { + state.set_error("The request is no longer in its file; use Save As"); + return; + }; + let new_text = if t.source_authoritative { + f.replace_request_text(index, &t.source) + } else { + f.replace_request(index, &t.request) + }; + let Some(new_text) = new_text else { return }; + let changed = new_text != f.text(); + if changed { + fx.push(Effect::FileOps { + ops: vec![FileOp::Write(origin.file.clone(), new_text.clone())], + rescan: None, + }); + insert_file(state, &origin.file, new_text); + } + // The file may now say slightly different things (e.g. a new title). + let fresh = file_of(state, &origin.file).and_then(|f| { + Some(( + f.request(index)?.clone(), + f.request_source(index)?.to_string(), + f.key_of(index)?, + )) + }); + let t = state.tab_mut(id).unwrap(); + if let Some((req, src, key)) = fresh { + t.saved = req.clone(); + t.request = req; + t.saved_source = src.clone(); + t.source = src; + t.source_authoritative = false; + t.params = parse_params(&t.request.url); + if let Some(o) = &mut t.origin { + o.key = key; + } + } + t.orphaned = false; +} + +fn save_as(state: &mut AppState, id: TabId, path: PathBuf, existing: Option, fx: &mut Vec) { + let Some(t) = state.tab(id) else { return }; + let block = if t.source_authoritative && !t.source.trim().is_empty() { + t.source.clone() + } else { + render_request(&t.request, "\n") + }; + let existing = file_of(state, &path).map(|f| f.text().to_string()).or(existing); + let file = HttpFile::parse(existing.unwrap_or_default()); + let index = file.request_count(); + let block = if index > 0 && !block.starts_with("###") { + format!("###\n{block}") + } else { + block + }; + let text = file.insert_request_text(None, &block); + fx.push(Effect::FileOps { + ops: vec![FileOp::Write(path.clone(), text.clone())], + rescan: state + .collection + .as_ref() + .filter(|c| path.starts_with(&c.root)) + .map(|c| c.root.clone()), + }); + let parsed = HttpFile::parse(text); + let fresh = (|| { + Some(( + parsed.request(index)?.clone(), + parsed.request_source(index)?.to_string(), + parsed.key_of(index)?, + )) + })(); + if let Some(c) = &mut state.collection { + if path.starts_with(&c.root) { + c.files.insert(path.clone(), parsed); + } + } + let t = state.tab_mut(id).unwrap(); + if let Some((req, src, key)) = fresh { + t.request = req.clone(); + t.saved = req; + t.source = src.clone(); + t.saved_source = src; + t.source_authoritative = false; + t.origin = Some(Origin { file: path, key }); + t.orphaned = false; + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/app/src/action/tests.rs b/crates/app/src/action/tests.rs new file mode 100644 index 0000000..e3e9f56 --- /dev/null +++ b/crates/app/src/action/tests.rs @@ -0,0 +1,761 @@ +//! `update()` tests: app behaviour without a window. + +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use reqlite_core::collection::{Collection, Node}; +use reqlite_core::env::EnvFile; +use reqlite_core::http::{BodyStore, Timings}; + +use super::*; + +fn state() -> AppState { + AppState::default() +} + +fn active(s: &AppState) -> TabId { + s.active.expect("an active tab") +} + +fn response(status: u16, body: &str, headers: &[(&str, &str)]) -> Response { + Response { + status, + reason: "OK".into(), + http_version: "HTTP/1.1".into(), + headers: headers.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect(), + body: BodyStore::InMemory(Arc::new(body.as_bytes().to_vec())), + timings: Timings { + total: Duration::from_millis(12), + ..Default::default() + }, + size: body.len() as u64, + effective_url: "http://x/".into(), + } +} + +/// A loaded collection at `/c` with the given files. +fn with_collection(s: &mut AppState, files: &[(&str, &str)]) -> PathBuf { + let root = PathBuf::from("/c"); + let c = Collection { + root: root.clone(), + tree: Node::Folder { + name: "c".into(), + path: root.clone(), + children: files + .iter() + .map(|(n, _)| Node::File { + name: n.to_string(), + path: root.join(n), + }) + .collect(), + }, + files: files + .iter() + .map(|(n, t)| (root.join(n), HttpFile::parse(t.to_string()))) + .collect(), + }; + let fx = update(s, Action::CollectionLoaded(Ok(c))); + assert!(fx.iter().any(|e| matches!(e, Effect::Watch(Some(_))))); + assert!(fx.iter().any(|e| matches!(e, Effect::LoadEnvironments(_)))); + root +} + +fn writes(fx: &[Effect]) -> Vec<(PathBuf, String)> { + fx.iter() + .filter_map(|e| match e { + Effect::FileOps { ops, .. } => Some(ops), + _ => None, + }) + .flatten() + .filter_map(|op| match op { + FileOp::Write(p, t) => Some((p.clone(), t.clone())), + _ => None, + }) + .collect() +} + +// ------------------------------------------------------------- URL & params + +#[test] +fn url_and_params_stay_in_sync() { + let mut s = state(); + update(&mut s, Action::NewTab); + let id = active(&s); + update(&mut s, Action::UrlEdited(id, "{{base}}/users?limit=20&q=a".into())); + let t = s.tab(id).unwrap(); + assert_eq!(t.params, vec![Param::new("limit", "20"), Param::new("q", "a")]); + + let mut p = t.params.clone(); + p[0].value = Some("50".into()); + p.remove(1); + p.push(Param::new("sort", "{{order}}")); + update(&mut s, Action::ParamsEdited(id, p)); + assert_eq!(s.tab(id).unwrap().request.url, "{{base}}/users?limit=50&sort={{order}}"); + + update(&mut s, Action::ParamsEdited(id, vec![])); + assert_eq!(s.tab(id).unwrap().request.url, "{{base}}/users"); +} + +#[test] +fn pasting_curl_into_the_url_bar_imports_it() { + let mut s = state(); + update(&mut s, Action::NewTab); + let id = active(&s); + update( + &mut s, + Action::UrlEdited( + id, + "curl -X POST 'https://api.x/y?z=1' -H 'A: b' --data-raw '{\"k\":1}'".into(), + ), + ); + let t = s.tab(id).unwrap(); + assert_eq!(t.request.method, Method::Post); + assert_eq!(t.request.url, "https://api.x/y?z=1"); + assert_eq!(t.request.header("A"), Some("b")); + assert_eq!(t.request.body, Body::Text("{\"k\":1}".into())); + assert_eq!(t.params, vec![Param::new("z", "1")]); +} + +#[test] +fn form_edits_update_the_source_and_source_edits_update_the_form() { + let mut s = state(); + update(&mut s, Action::NewTab); + let id = active(&s); + update(&mut s, Action::UrlEdited(id, "http://x/a".into())); + assert_eq!(s.tab(id).unwrap().source, "GET http://x/a\n"); + + update(&mut s, Action::SourceEdited(id, "POST http://x/b\nA: 1\n\nbody".into())); + let t = s.tab(id).unwrap(); + assert_eq!(t.request.method, Method::Post); + assert_eq!(t.request.url, "http://x/b"); + assert_eq!(t.request.body, Body::Text("body".into())); + assert!(t.source_error.is_none()); + + update(&mut s, Action::SourceEdited(id, "GET /a\n\n###\nGET /b\n".into())); + assert!(s.tab(id).unwrap().source_error.is_some()); + // Sending is refused while the source is broken. + assert!(update(&mut s, Action::Send(id)).is_empty()); +} + +// ---------------------------------------------------------- send & receive + +#[test] +fn send_then_receive() { + let mut s = state(); + update(&mut s, Action::NewTab); + let id = active(&s); + update(&mut s, Action::UrlEdited(id, "http://localhost/x".into())); + let fx = update(&mut s, Action::Send(id)); + let (seq, cancel) = match &fx[..] { + [Effect::SendRequest { + tab, + seq, + request, + cancel, + }] => { + assert_eq!(*tab, id); + assert_eq!(request.url, "http://localhost/x"); + (*seq, cancel.clone()) + } + other => panic!("{other:?}"), + }; + assert!(s.tab(id).unwrap().in_flight.is_some()); + // A second send while in flight is ignored. + assert!(update(&mut s, Action::Send(id)).is_empty()); + + let fx = update( + &mut s, + Action::ResponseReceived { + tab: id, + seq, + result: Ok(response(200, "{\"a\":1}", &[("content-type", "application/json")])), + }, + ); + assert!(!cancel.is_cancelled()); + let t = s.tab(id).unwrap(); + assert!(t.in_flight.is_none()); + assert_eq!(t.response.as_ref().unwrap().response.status, 200); + assert!(fx.iter().any(|e| matches!(e, Effect::PrepareBody { .. }))); + assert!(fx + .iter() + .any(|e| matches!(e, Effect::AppendHistory(h) if h.status == Some(200)))); + assert_eq!(s.history.len(), 1); +} + +#[test] +fn cancel_stops_the_request_and_ignores_a_late_response() { + let mut s = state(); + update(&mut s, Action::NewTab); + let id = active(&s); + update(&mut s, Action::UrlEdited(id, "http://localhost/slow".into())); + let fx = update(&mut s, Action::Send(id)); + let Effect::SendRequest { seq, cancel, .. } = &fx[0] else { + panic!() + }; + let (seq, cancel) = (*seq, cancel.clone()); + + update(&mut s, Action::Cancel(id)); + assert!(cancel.is_cancelled()); + let t = s.tab(id).unwrap(); + assert!(t.in_flight.is_none()); + assert_eq!(t.error.as_deref(), Some("Cancelled")); + + let fx = update( + &mut s, + Action::ResponseReceived { + tab: id, + seq, + result: Ok(response(200, "late", &[])), + }, + ); + assert!(fx.is_empty()); + assert!(s.tab(id).unwrap().response.is_none()); + assert!(s.history.is_empty()); +} + +#[test] +fn unresolved_variables_are_reported_not_sent() { + let mut s = state(); + update(&mut s, Action::NewTab); + let id = active(&s); + update(&mut s, Action::UrlEdited(id, "{{base}}/x".into())); + assert!(update(&mut s, Action::Send(id)).is_empty()); + assert_eq!(s.tab(id).unwrap().error.as_deref(), Some("unknown variable `base`")); +} + +#[test] +fn environments_resolve_and_switch() { + let mut s = state(); + let root = with_collection( + &mut s, + &[("a.http", "### A\nGET {{base}}/x\nAuthorization: Bearer {{token}}\n")], + ); + let envs = Environments { + public: EnvFile::parse( + r#"{"dev": {"base": "http://dev"}, "prod": {"base": "https://prod"}}"#, + &root, + ) + .unwrap(), + private: EnvFile::parse(r#"{"dev": {"token": "t-dev"}, "prod": {"token": "t-prod"}}"#, &root).unwrap(), + }; + update(&mut s, Action::EnvironmentsLoaded(Ok((envs, false)))); + update( + &mut s, + Action::OpenRequest { + file: root.join("a.http"), + index: 0, + }, + ); + let id = active(&s); + + for (env, url, auth) in [ + ("dev", "http://dev/x", "Bearer t-dev"), + ("prod", "https://prod/x", "Bearer t-prod"), + ] { + update(&mut s, Action::SelectEnv(Some(env.into()))); + let fx = update(&mut s, Action::Send(id)); + let Effect::SendRequest { request, seq, .. } = &fx[0] else { + panic!() + }; + assert_eq!(request.url, url); + assert_eq!(request.headers[0].1, auth); + assert!(s.is_private_var("token")); + let seq = *seq; + update( + &mut s, + Action::ResponseReceived { + tab: id, + seq, + result: Err(HttpError::Timeout), + }, + ); + } +} + +#[test] +fn cookies_are_stored_and_sent_unless_disabled() { + let mut s = state(); + update(&mut s, Action::NewTab); + let id = active(&s); + update(&mut s, Action::UrlEdited(id, "http://h/login".into())); + let fx = update(&mut s, Action::Send(id)); + let Effect::SendRequest { seq, .. } = &fx[0] else { + panic!() + }; + let seq = *seq; + update( + &mut s, + Action::ResponseReceived { + tab: id, + seq, + result: Ok(response(200, "", &[("set-cookie", "sid=1; Path=/")])), + }, + ); + let fx = update(&mut s, Action::Send(id)); + let Effect::SendRequest { request, seq, .. } = &fx[0] else { + panic!() + }; + assert!(request.headers.contains(&("Cookie".into(), "sid=1".into()))); + let seq = *seq; + update( + &mut s, + Action::ResponseReceived { + tab: id, + seq, + result: Err(HttpError::Timeout), + }, + ); + + update( + &mut s, + Action::SourceEdited(id, "# @no-cookie-jar\nGET http://h/login\n".into()), + ); + let fx = update(&mut s, Action::Send(id)); + let Effect::SendRequest { request, .. } = &fx[0] else { + panic!() + }; + assert!(request.headers.iter().all(|(n, _)| n != "Cookie")); +} + +#[test] +fn no_log_keeps_requests_out_of_history() { + let mut s = state(); + update(&mut s, Action::NewTab); + let id = active(&s); + update( + &mut s, + Action::SourceEdited(id, "# @no-log\nGET http://h/secret\n".into()), + ); + let fx = update(&mut s, Action::Send(id)); + let Effect::SendRequest { seq, .. } = &fx[0] else { + panic!() + }; + let seq = *seq; + let fx = update( + &mut s, + Action::ResponseReceived { + tab: id, + seq, + result: Ok(response(200, "", &[])), + }, + ); + assert!(s.history.is_empty()); + assert!(!fx.iter().any(|e| matches!(e, Effect::AppendHistory(_)))); +} + +#[test] +fn search_finds_matches_in_the_prepared_body() { + let mut s = state(); + update(&mut s, Action::NewTab); + let id = active(&s); + update(&mut s, Action::UrlEdited(id, "http://h/".into())); + let fx = update(&mut s, Action::Send(id)); + let Effect::SendRequest { seq, .. } = &fx[0] else { + panic!() + }; + let seq = *seq; + let body = "{\"name\":\"Ada\",\"friend\":{\"name\":\"Grace\"}}"; + update( + &mut s, + Action::ResponseReceived { + tab: id, + seq, + result: Ok(response(200, body, &[("content-type", "application/json")])), + }, + ); + let prepared = prepare_body( + &BodyStore::InMemory(Arc::new(body.as_bytes().to_vec())), + "application/json", + 1 << 20, + ); + assert_eq!(prepared.kind, BodyKind::Json); + update( + &mut s, + Action::BodyPrepared { + tab: id, + seq, + body: prepared, + }, + ); + update(&mut s, Action::SearchQuery(id, "NAME".into())); + let t = s.tab(id).unwrap(); + assert_eq!(t.search.matches.len(), 2); + assert_eq!(t.search.scroll_to, Some(t.search.matches[0].0)); + update(&mut s, Action::SearchStep(id, 1)); + update(&mut s, Action::SearchStep(id, 1)); + assert_eq!(s.tab(id).unwrap().search.current, 0, "wraps around"); +} + +// ----------------------------------------------------------- collections + +const USERS: &str = "### List users\nGET {{base}}/users\n\n### Create user\n# @name create-user\nPOST {{base}}/users\nContent-Type: application/json\n\n{\"name\": \"Ada\"}\n\n> {% client.global.set(\"id\", response.body.id) %}\n"; + +#[test] +fn saving_an_unchanged_request_writes_nothing() { + let mut s = state(); + let root = with_collection(&mut s, &[("users.http", USERS)]); + update( + &mut s, + Action::OpenRequest { + file: root.join("users.http"), + index: 1, + }, + ); + let id = active(&s); + assert!(!s.tab(id).unwrap().is_dirty()); + let fx = update(&mut s, Action::Save(id)); + assert!(writes(&fx).is_empty(), "{fx:?}"); +} + +#[test] +fn saving_an_edit_rewrites_only_that_request() { + let mut s = state(); + let root = with_collection(&mut s, &[("users.http", USERS)]); + let file = root.join("users.http"); + update( + &mut s, + Action::OpenRequest { + file: file.clone(), + index: 1, + }, + ); + let id = active(&s); + update(&mut s, Action::UrlEdited(id, "{{base}}/v2/users".into())); + assert!(s.tab(id).unwrap().is_dirty()); + let fx = update(&mut s, Action::Save(id)); + let w = writes(&fx); + assert_eq!(w.len(), 1); + assert_eq!(w[0].0, file); + assert_eq!(w[0].1, USERS.replace("POST {{base}}/users", "POST {{base}}/v2/users")); + assert!(!s.tab(id).unwrap().is_dirty()); + // A second save is a no-op. + assert!(writes(&update(&mut s, Action::Save(id))).is_empty()); +} + +#[test] +fn saving_from_the_source_tab_keeps_comments() { + let mut s = state(); + let root = with_collection(&mut s, &[("users.http", USERS)]); + let file = root.join("users.http"); + update( + &mut s, + Action::OpenRequest { + file: file.clone(), + index: 0, + }, + ); + let id = active(&s); + let src = s.tab(id).unwrap().source.clone(); + assert_eq!(src, "### List users\nGET {{base}}/users\n"); + update(&mut s, Action::SourceEdited(id, format!("{src}# a new comment\n"))); + assert!(s.tab(id).unwrap().is_dirty(), "a comment-only edit is still a change"); + let w = writes(&update(&mut s, Action::Save(id))); + assert_eq!( + w[0].1, + USERS.replace("GET {{base}}/users\n", "GET {{base}}/users\n# a new comment\n") + ); +} + +#[test] +fn untitled_tabs_save_as_into_a_file() { + let mut s = state(); + let root = with_collection(&mut s, &[("users.http", USERS)]); + update(&mut s, Action::NewTab); + let id = active(&s); + update(&mut s, Action::UrlEdited(id, "http://new".into())); + assert!(matches!(update(&mut s, Action::Save(id))[..], [Effect::PickSaveTarget(t)] if t == id)); + let file = root.join("users.http"); + let fx = update( + &mut s, + Action::SaveAs { + tab: id, + path: file.clone(), + existing: None, + }, + ); + let w = writes(&fx); + assert_eq!(w[0].1, format!("{USERS}\n###\nGET http://new\n")); + let t = s.tab(id).unwrap(); + assert_eq!(t.origin.as_ref().unwrap().file, file); + assert_eq!(t.origin.as_ref().unwrap().key.index, 2); + assert!(!t.is_dirty()); +} + +#[test] +fn external_change_reloads_clean_tabs_and_prompts_for_dirty_ones() { + let mut s = state(); + let root = with_collection(&mut s, &[("users.http", USERS)]); + let file = root.join("users.http"); + update( + &mut s, + Action::OpenRequest { + file: file.clone(), + index: 0, + }, + ); + let clean = active(&s); + update( + &mut s, + Action::OpenRequest { + file: file.clone(), + index: 1, + }, + ); + let dirty = active(&s); + update(&mut s, Action::UrlEdited(dirty, "{{base}}/mine".into())); + + // Our own write echoing back changes nothing. + update( + &mut s, + Action::FileChangedOnDisk { + path: file.clone(), + text: Some(USERS.into()), + }, + ); + assert!(s.dialog.is_none()); + + let changed = USERS.replace("GET {{base}}/users", "GET {{base}}/people"); + update( + &mut s, + Action::FileChangedOnDisk { + path: file.clone(), + text: Some(changed), + }, + ); + assert_eq!(s.tab(clean).unwrap().request.url, "{{base}}/people"); + assert_eq!( + s.dialog, + Some(Dialog::Conflict { + tab: dirty, + path: file.clone() + }) + ); + + update( + &mut s, + Action::ResolveConflict { + tab: dirty, + keep_mine: false, + }, + ); + assert_eq!(s.tab(dirty).unwrap().request.url, "{{base}}/users"); + assert!(!s.tab(dirty).unwrap().is_dirty()); +} + +#[test] +fn create_rename_duplicate_move_delete() { + let mut s = state(); + let root = with_collection(&mut s, &[("users.http", USERS), ("other.http", "### X\nGET /x\n")]); + let users = root.join("users.http"); + let other = root.join("other.http"); + + // New request in a file. + let w = writes(&update(&mut s, Action::NewRequestIn { file: other.clone() })); + assert_eq!(w[0].1, "### X\nGET /x\n\n### New request\nGET \n"); + + // Rename (the @name follows the title). + let w = writes(&update( + &mut s, + Action::RenameRequest { + file: users.clone(), + index: 1, + title: "Add user".into(), + }, + )); + assert!(w[0].1.contains("### Add user\n# @name add-user\nPOST")); + + // Duplicate. + let w = writes(&update( + &mut s, + Action::DuplicateRequest { + file: users.clone(), + index: 0, + }, + )); + let f = HttpFile::parse(w[0].1.clone()); + let names: Vec<_> = f.requests().map(|r| r.display_name().unwrap().to_string()).collect(); + assert_eq!(names, ["List users", "List users copy", "add-user"]); + // The open tab is now the copy. + let copy_tab = active(&s); + assert_eq!(s.tab(copy_tab).unwrap().origin.as_ref().unwrap().key.index, 1); + + // Move the copy to the other file; its tab follows. + let fx = update( + &mut s, + Action::MoveRequest { + from: users.clone(), + index: 1, + to: other.clone(), + }, + ); + let w = writes(&fx); + let o = w.iter().find(|(p, _)| p == &other).unwrap(); + assert!(o.1.ends_with("### List users copy\nGET {{base}}/users\n")); + let u = w.iter().find(|(p, _)| p == &users).unwrap(); + assert_eq!(HttpFile::parse(u.1.clone()).request_count(), 2); + let origin = s.tab(copy_tab).unwrap().origin.clone().unwrap(); + assert_eq!(origin.file, other); + assert_eq!(origin.key.index, 2); + + // Delete orphans the tab. + update( + &mut s, + Action::DeleteRequest { + file: other.clone(), + index: 2, + }, + ); + assert!(s.tab(copy_tab).unwrap().orphaned); + assert_eq!(s.collection.as_ref().unwrap().files[&other].request_count(), 2); +} + +#[test] +fn new_file_and_rename_file() { + let mut s = state(); + let root = with_collection(&mut s, &[("users.http", USERS)]); + let fx = update( + &mut s, + Action::NewFile { + dir: root.clone(), + name: "orders".into(), + }, + ); + let w = writes(&fx); + assert_eq!(w[0], (root.join("orders.http"), "### New request\nGET \n".to_string())); + assert!(matches!(&fx[0], Effect::FileOps { rescan: Some(_), .. })); + let id = active(&s); + + let fx = update( + &mut s, + Action::RenameFile { + path: root.join("orders.http"), + new_name: "shop".into(), + }, + ); + assert!( + matches!(&fx[0], Effect::FileOps { ops, .. } if ops == &[FileOp::Rename(root.join("orders.http"), root.join("shop.http"))]) + ); + assert_eq!(s.tab(id).unwrap().origin.as_ref().unwrap().file, root.join("shop.http")); +} + +#[test] +fn closing_a_dirty_tab_asks_first() { + let mut s = state(); + update(&mut s, Action::NewTab); + let id = active(&s); + update(&mut s, Action::CloseTab(id)); + assert!(s.tabs.is_empty(), "a clean tab closes right away"); + + update(&mut s, Action::NewTab); + let id = active(&s); + update(&mut s, Action::UrlEdited(id, "http://x".into())); + update(&mut s, Action::CloseTab(id)); + assert_eq!(s.dialog, Some(Dialog::ConfirmCloseTab(id))); + update(&mut s, Action::DiscardAndCloseTab(id)); + assert!(s.tabs.is_empty()); + assert!(s.dialog.is_none()); +} + +#[test] +fn quitting_with_unsaved_changes_asks_first() { + let mut s = state(); + update(&mut s, Action::NewTab); + let id = active(&s); + update(&mut s, Action::UrlEdited(id, "http://x".into())); + assert!(update(&mut s, Action::CloseRequested).is_empty()); + assert_eq!(s.dialog, Some(Dialog::ConfirmQuit)); + assert!(matches!(update(&mut s, Action::ConfirmQuit)[..], [Effect::Quit])); + assert!(s.quit_confirmed); +} + +#[test] +fn restore_history_opens_a_new_tab() { + let mut s = state(); + update( + &mut s, + Action::HistoryLoaded(vec![HistoryEntry { + at: 0, + method: "POST".into(), + url: "http://x/y".into(), + status: Some(201), + duration_ms: 3, + env: None, + http: "### Make\nPOST http://x/y\n\nhello\n".into(), + error: None, + }]), + ); + update(&mut s, Action::RestoreHistory(0)); + let t = s.active_tab().unwrap(); + assert_eq!(t.request.method, Method::Post); + assert_eq!(t.request.body, Body::Text("hello".into())); + assert!(t.origin.is_none()); +} + +#[test] +fn env_editor_writes_both_files() { + let mut s = state(); + let root = with_collection(&mut s, &[]); + update(&mut s, Action::OpenEnvEditor); + let mut ed = s.env_editor.clone().unwrap(); + ed.envs.public.env_mut("dev").set("base", "http://localhost"); + ed.envs.private.env_mut("dev").set("token", "secret"); + update(&mut s, Action::EnvEditorChanged(ed)); + let fx = update(&mut s, Action::EnvEditorSave); + let w = writes(&fx); + assert_eq!(w.len(), 2); + assert!(w + .iter() + .any(|(p, t)| p == &root.join(env::PUBLIC_FILE) && t.contains("\"base\": \"http://localhost\""))); + assert!(w + .iter() + .any(|(p, t)| p == &root.join(env::PRIVATE_FILE) && t.contains("\"token\": \"secret\""))); + assert_eq!(s.collection.as_ref().unwrap().envs.names(), vec!["dev"]); +} + +#[test] +fn body_file_paths_are_stored_relative_to_the_http_file() { + let mut s = state(); + let root = with_collection(&mut s, &[("users.http", USERS)]); + update( + &mut s, + Action::OpenRequest { + file: root.join("users.http"), + index: 1, + }, + ); + let id = active(&s); + update(&mut s, Action::BodyFilePicked(id, root.join("payloads/a.json"))); + assert_eq!( + s.tab(id).unwrap().request.body, + Body::FileRef { + path: "./payloads/a.json".into(), + substitute: false + } + ); +} + +#[test] +fn duplicate_file_copies_it_under_a_free_name() { + let mut s = state(); + let root = with_collection(&mut s, &[("users.http", USERS), ("users copy.http", "GET /x\n")]); + let fx = update(&mut s, Action::DuplicateFile(root.join("users.http"))); + assert_eq!(writes(&fx), vec![(root.join("users copy 2.http"), USERS.to_string())]); +} + +#[test] +fn concurrency_setting_reaches_the_runner() { + let mut s = state(); + let fx = update( + &mut s, + Action::SettingsLoaded(Settings { + max_concurrent_requests: 3, + ..Settings::default() + }), + ); + assert!(matches!(fx[..], [Effect::SetConcurrency(3)])); + let mut changed = s.settings.clone(); + changed.max_concurrent_requests = 5; + let fx = update(&mut s, Action::SettingsChanged(changed)); + assert!(fx.iter().any(|e| matches!(e, Effect::SetConcurrency(5)))); +} diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs new file mode 100644 index 0000000..1f7d16c --- /dev/null +++ b/crates/app/src/app.rs @@ -0,0 +1,89 @@ +//! The eframe app: owns the state, the effects runner and the action inbox. + +use std::sync::Arc; + +use reqlite_core::http::DynHttpClient; +use tokio::runtime::Handle; +use tokio::sync::mpsc; + +use crate::action::{update, Action}; +use crate::effects::{Paths, Runner}; +use crate::settings::ThemeChoice; +use crate::state::AppState; + +pub struct ReqliteApp { + pub state: AppState, + runner: Runner, + inbox: mpsc::UnboundedReceiver, + applied: Option<(f32, ThemeChoice)>, +} + +impl ReqliteApp { + /// `paths` is `None` in tests: nothing is read from or written to the + /// user's config and data directories. + pub fn new( + ctx: Option, + handle: Handle, + client: Arc, + paths: Option, + ) -> Self { + let (runner, inbox) = Runner::new(handle, ctx, client, paths, 8); + runner.load_startup(); + Self { + state: AppState::default(), + runner, + inbox, + applied: None, + } + } + + pub fn dispatch(&mut self, action: Action) { + tracing::trace!(?action, "action"); + for effect in update(&mut self.state, action) { + self.runner.run(effect); + } + } + + /// Applies actions that effects have sent back. + pub fn pump(&mut self) { + while let Ok(a) = self.inbox.try_recv() { + self.dispatch(a); + } + } + + /// One UI frame: drain the inbox, draw, apply what the user did. + pub fn frame(&mut self, ui: &mut egui::Ui) { + self.pump(); + let ctx = ui.ctx().clone(); + let wanted = (self.state.settings.zoom, self.state.settings.theme); + if self.applied != Some(wanted) { + ctx.set_zoom_factor(wanted.0.clamp(0.5, 3.0)); + ctx.set_theme(match wanted.1 { + ThemeChoice::System => egui::ThemePreference::System, + ThemeChoice::Light => egui::ThemePreference::Light, + ThemeChoice::Dark => egui::ThemePreference::Dark, + }); + self.applied = Some(wanted); + } + if ctx.input(|i| i.viewport().close_requested()) && self.state.any_dirty() && !self.state.quit_confirmed { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + self.dispatch(Action::CloseRequested); + } + + let mut actions = Vec::new(); + crate::ui::draw(ui, &self.state, &mut actions); + for a in actions { + self.dispatch(a); + } + } +} + +impl eframe::App for ReqliteApp { + fn logic(&mut self, _ctx: &egui::Context, _frame: &mut eframe::Frame) { + self.pump(); + } + + fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + self.frame(ui); + } +} diff --git a/crates/app/src/effects.rs b/crates/app/src/effects.rs new file mode 100644 index 0000000..727d392 --- /dev/null +++ b/crates/app/src/effects.rs @@ -0,0 +1,567 @@ +//! Effects: work that happens outside `update` (HTTP, disk, dialogs, file +//! watching). Each effect runs as a Tokio task and reports back by sending an +//! [`Action`] over a channel and waking the UI. + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use notify::{RecursiveMode, Watcher}; +use reqlite_core::collection; +use reqlite_core::env::{self, Environments}; +use reqlite_core::http::{BodyStore, DynHttpClient, ResolvedRequest}; +use reqlite_core::CancelToken; +use tokio::runtime::Handle; +use tokio::sync::{mpsc, Semaphore}; + +use crate::action::Action; +use crate::history::{self, HistoryEntry}; +use crate::settings::Settings; +use crate::state::{prepare_body, TabId}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FileOp { + Write(PathBuf, String), + Delete(PathBuf), + Rename(PathBuf, PathBuf), +} + +#[derive(Debug)] +pub enum Effect { + SendRequest { + tab: TabId, + seq: u64, + request: ResolvedRequest, + cancel: CancelToken, + }, + PrepareBody { + tab: TabId, + seq: u64, + body: BodyStore, + content_type: String, + }, + LoadCollection(PathBuf), + LoadEnvironments(PathBuf), + /// Watch a collection folder (or stop watching). + Watch(Option), + /// Run file operations in order, then rescan the collection if given. + FileOps { + ops: Vec, + rescan: Option, + }, + AppendGitignore(PathBuf), + PickCollectionFolder, + PickSaveTarget(TabId), + PickBodyFile(TabId), + PickCaFile, + PickPostmanImport, + SaveResponseBody { + body: BodyStore, + suggested_name: String, + }, + CopyToClipboard(String), + AppendHistory(HistoryEntry), + RewriteHistory(Vec), + SaveSettings(Settings), + /// Change how many requests may run at once (in-flight ones keep going). + SetConcurrency(usize), + Quit, +} + +/// Where settings, history and logs live. +#[derive(Debug, Clone)] +pub struct Paths { + pub config_dir: PathBuf, + pub data_dir: PathBuf, +} + +impl Paths { + pub fn from_system() -> Option { + let d = directories::ProjectDirs::from("", "", "reqlite")?; + Some(Self { + config_dir: d.config_dir().to_path_buf(), + data_dir: d.data_dir().to_path_buf(), + }) + } + + pub fn settings_file(&self) -> PathBuf { + self.config_dir.join("settings.toml") + } + + pub fn history_file(&self) -> PathBuf { + self.data_dir.join("history.jsonl") + } + + pub fn log_dir(&self) -> PathBuf { + self.data_dir.join("logs") + } +} + +/// Sends actions back to the UI and wakes it up. +#[derive(Clone)] +pub struct Outbox { + tx: mpsc::UnboundedSender, + ctx: Option, +} + +impl Outbox { + pub fn send(&self, a: Action) { + let _ = self.tx.send(a); + if let Some(ctx) = &self.ctx { + ctx.request_repaint(); + } + } +} + +pub struct Runner { + handle: Handle, + outbox: Outbox, + client: Arc, + semaphore: Mutex>, + watcher: Arc>>, + paths: Option, + /// Serializes history writes. + history_lock: Arc>, +} + +/// Bodies bigger than this are only partly shown (the rest can be saved). +const MAX_DISPLAY: u64 = 64 * 1024 * 1024; + +impl Runner { + pub fn new( + handle: Handle, + ctx: Option, + client: Arc, + paths: Option, + max_concurrent: usize, + ) -> (Self, mpsc::UnboundedReceiver) { + let (tx, rx) = mpsc::unbounded_channel(); + ( + Self { + handle, + outbox: Outbox { tx, ctx }, + client, + semaphore: Mutex::new(Arc::new(Semaphore::new(max_concurrent.max(1)))), + watcher: Arc::new(Mutex::new(None)), + paths, + history_lock: Arc::new(tokio::sync::Mutex::new(())), + }, + rx, + ) + } + + pub fn outbox(&self) -> Outbox { + self.outbox.clone() + } + + /// Loads settings and history at startup. + pub fn load_startup(&self) { + let Some(paths) = self.paths.clone() else { return }; + let out = self.outbox(); + self.handle.spawn(async move { + let settings = match tokio::fs::read_to_string(paths.settings_file()).await { + Ok(text) => Settings::from_toml(&text).unwrap_or_else(|e| { + out.send(Action::Error(format!("settings.toml: {e}"))); + Settings::default() + }), + Err(_) => Settings::default(), + }; + let limit = settings.history_limit; + if let Some(last) = settings.recent_collections.first().cloned() { + if last.is_dir() { + out.send(Action::OpenCollection(last)); + } + } + out.send(Action::SettingsLoaded(settings)); + if let Ok(text) = tokio::fs::read_to_string(paths.history_file()).await { + let entries = history::parse(&text, limit); + // Compact the file once it holds twice the limit. + if text.lines().count() > limit * 2 { + let _ = tokio::fs::write(paths.history_file(), history::to_text(&entries)).await; + } + out.send(Action::HistoryLoaded(entries)); + } + }); + } + + pub fn run(&self, effect: Effect) { + let out = self.outbox(); + match effect { + Effect::SendRequest { + tab, + seq, + request, + cancel, + } => { + let client = self.client.clone(); + let sem = self.semaphore.lock().unwrap().clone(); + self.handle.spawn(async move { + let result = tokio::select! { + permit = sem.acquire_owned() => { + let _permit = permit; + client.send_dyn(request, cancel).await + } + _ = cancel.cancelled() => Err(reqlite_core::http::HttpError::Cancelled), + }; + out.send(Action::ResponseReceived { tab, seq, result }); + }); + } + Effect::PrepareBody { + tab, + seq, + body, + content_type, + } => { + self.handle.spawn(async move { + let prepared = + tokio::task::spawn_blocking(move || prepare_body(&body, &content_type, MAX_DISPLAY)).await; + if let Ok(body) = prepared { + out.send(Action::BodyPrepared { tab, seq, body }); + } + }); + } + Effect::LoadCollection(root) => { + self.handle.spawn(async move { + let r = tokio::task::spawn_blocking(move || collection::scan(&root).map_err(|e| e.to_string())) + .await + .unwrap_or_else(|e| Err(e.to_string())); + out.send(Action::CollectionLoaded(r)); + }); + } + Effect::LoadEnvironments(root) => { + self.handle.spawn(async move { + let r = tokio::task::spawn_blocking(move || { + let envs = Environments::load(&root).map_err(|e| e.to_string())?; + let not_ignored = root.join(env::PRIVATE_FILE).exists() && !env::private_file_ignored(&root); + Ok((envs, not_ignored)) + }) + .await + .unwrap_or_else(|e| Err(e.to_string())); + out.send(Action::EnvironmentsLoaded(r)); + }); + } + Effect::Watch(root) => self.watch(root), + Effect::FileOps { ops, rescan } => { + self.handle.spawn(async move { + for op in ops { + if let Err(e) = run_file_op(&op).await { + out.send(Action::Error(e)); + } + } + if let Some(root) = rescan { + let r = tokio::task::spawn_blocking(move || collection::scan(&root).map_err(|e| e.to_string())) + .await + .unwrap_or_else(|e| Err(e.to_string())); + out.send(Action::CollectionLoaded(r)); + } + }); + } + Effect::AppendGitignore(root) => { + self.handle.spawn(async move { + let path = root.join(".gitignore"); + let existing = tokio::fs::read_to_string(&path).await.unwrap_or_default(); + let text = format!("{existing}{}", env::gitignore_addition(&existing)); + match tokio::fs::write(&path, text).await { + Ok(()) => out.send(Action::Info(format!("Added {} to .gitignore", env::PRIVATE_FILE))), + Err(e) => out.send(Action::Error(format!("{}: {e}", path.display()))), + } + }); + } + Effect::PickCollectionFolder => { + self.handle.spawn(async move { + if let Some(dir) = rfd::AsyncFileDialog::new() + .set_title("Open collection folder") + .pick_folder() + .await + { + out.send(Action::OpenCollection(dir.path().to_path_buf())); + } + }); + } + Effect::PickSaveTarget(tab) => { + self.handle.spawn(async move { + if let Some(f) = rfd::AsyncFileDialog::new() + .set_title("Save request to .http file") + .add_filter("HTTP request files", &["http", "rest"]) + .set_file_name("requests.http") + .save_file() + .await + { + let path = f.path().to_path_buf(); + let existing = tokio::fs::read_to_string(&path).await.ok(); + out.send(Action::SaveAs { tab, path, existing }); + } + }); + } + Effect::PickBodyFile(tab) => { + self.handle.spawn(async move { + if let Some(f) = rfd::AsyncFileDialog::new() + .set_title("Request body file") + .pick_file() + .await + { + out.send(Action::BodyFilePicked(tab, f.path().to_path_buf())); + } + }); + } + Effect::PickCaFile => { + self.handle.spawn(async move { + if let Some(f) = rfd::AsyncFileDialog::new() + .set_title("CA certificate bundle (PEM)") + .add_filter("PEM", &["pem", "crt", "cer"]) + .pick_file() + .await + { + out.send(Action::CaFilePicked(f.path().to_path_buf())); + } + }); + } + Effect::PickPostmanImport => { + self.handle.spawn(async move { + let Some(coll) = rfd::AsyncFileDialog::new() + .set_title("Postman collection (v2.1) to import") + .add_filter("Postman collection", &["json"]) + .pick_file() + .await + else { + return; + }; + let Some(out_dir) = rfd::AsyncFileDialog::new() + .set_title("Folder to write the .http files to") + .pick_folder() + .await + else { + return; + }; + let coll = coll.path().to_path_buf(); + let out_dir = out_dir.path().to_path_buf(); + match import_postman(&coll, &out_dir).await { + Ok((files, warnings)) => out.send(Action::PostmanImported { + root: out_dir, + files, + warnings, + }), + Err(e) => out.send(Action::Error(format!("Postman import failed: {e}"))), + } + }); + } + Effect::SaveResponseBody { body, suggested_name } => { + self.handle.spawn(async move { + let Some(f) = rfd::AsyncFileDialog::new() + .set_title("Save response body") + .set_file_name(&suggested_name) + .save_file() + .await + else { + return; + }; + let path = f.path().to_path_buf(); + let r = match &body { + BodyStore::InMemory(b) => tokio::fs::write(&path, b.as_ref()).await, + BodyStore::TempFile(p) => tokio::fs::copy(&**p, &path).await.map(|_| ()), + }; + match r { + Ok(()) => out.send(Action::Info(format!("Saved {}", path.display()))), + Err(e) => out.send(Action::Error(format!("{}: {e}", path.display()))), + } + }); + } + Effect::CopyToClipboard(text) => { + if let Some(ctx) = &self.outbox.ctx { + ctx.copy_text(text); + } + } + Effect::AppendHistory(entry) => { + let Some(paths) = self.paths.clone() else { return }; + let lock = self.history_lock.clone(); + self.handle.spawn(async move { + let _g = lock.lock().await; + if let Err(e) = append(&paths.history_file(), &history::to_line(&entry)).await { + tracing::warn!("history: {e}"); + } + }); + } + Effect::RewriteHistory(entries) => { + let Some(paths) = self.paths.clone() else { return }; + let lock = self.history_lock.clone(); + self.handle.spawn(async move { + let _g = lock.lock().await; + let _ = tokio::fs::create_dir_all(&paths.data_dir).await; + let _ = tokio::fs::write(paths.history_file(), history::to_text(&entries)).await; + }); + } + Effect::SetConcurrency(n) => { + *self.semaphore.lock().unwrap() = Arc::new(Semaphore::new(n.max(1))); + } + Effect::SaveSettings(s) => { + let Some(paths) = self.paths.clone() else { return }; + self.handle.spawn(async move { + let _ = tokio::fs::create_dir_all(&paths.config_dir).await; + if let Err(e) = tokio::fs::write(paths.settings_file(), s.to_toml()).await { + out.send(Action::Error(format!("Could not save settings: {e}"))); + } + }); + } + Effect::Quit => { + if let Some(ctx) = &self.outbox.ctx { + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + } + } + } + + /// Watches a collection with `notify`; changes are debounced and turned + /// into `FileChangedOnDisk` actions (and a rescan when files come or go). + fn watch(&self, root: Option) { + let mut slot = self.watcher.lock().unwrap(); + *slot = None; // drops (stops) the old watcher + let Some(root) = root else { return }; + let (tx, mut rx) = mpsc::unbounded_channel::(); + let watcher = notify::recommended_watcher(move |res: notify::Result| { + if let Ok(ev) = res { + let _ = tx.send(ev); + } + }); + let mut watcher = match watcher { + Ok(w) => w, + Err(e) => { + self.outbox + .send(Action::Error(format!("Cannot watch {}: {e}", root.display()))); + return; + } + }; + if let Err(e) = watcher.watch(&root, RecursiveMode::Recursive) { + self.outbox + .send(Action::Error(format!("Cannot watch {}: {e}", root.display()))); + return; + } + *slot = Some(watcher); + let out = self.outbox(); + self.handle.spawn(async move { + while let Some(first) = rx.recv().await { + // Debounce: collect everything that arrives within 150 ms. + let mut events = vec![first]; + let deadline = tokio::time::sleep(Duration::from_millis(150)); + tokio::pin!(deadline); + loop { + tokio::select! { + ev = rx.recv() => match ev { + Some(ev) => events.push(ev), + None => break, + }, + _ = &mut deadline => break, + } + } + // Folders appearing or disappearing (e.g. after `git pull`) + // can hide file events from us, so rescan the whole tree. + let rescan = events.iter().any(|e| { + use notify::event::{CreateKind, EventKind, RemoveKind}; + matches!( + e.kind, + EventKind::Create(CreateKind::Folder) | EventKind::Remove(RemoveKind::Folder) + ) || ((e.kind.is_create() || e.kind.is_remove()) && e.paths.iter().any(|p| p.is_dir())) + }); + let mut paths: Vec = events + .into_iter() + .filter(|e| !e.kind.is_access()) + .flat_map(|e| e.paths) + .filter(|p| is_relevant(p)) + .collect(); + paths.sort(); + paths.dedup(); + for p in paths { + let text = tokio::fs::read_to_string(&p).await.ok(); + out.send(Action::FileChangedOnDisk { path: p, text }); + } + if rescan { + out.send(Action::Rescan); + } + } + }); + } +} + +fn is_relevant(p: &Path) -> bool { + if p.components().any(|c| { + let s = c.as_os_str().to_string_lossy(); + s == ".git" || s == "node_modules" || s == "target" + }) { + return false; + } + collection::is_http_file(p) + || p.file_name() + .is_some_and(|n| n == env::PUBLIC_FILE || n == env::PRIVATE_FILE) +} + +async fn append(path: &Path, line: &str) -> std::io::Result<()> { + use tokio::io::AsyncWriteExt; + if let Some(dir) = path.parent() { + tokio::fs::create_dir_all(dir).await?; + } + let mut f = tokio::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + .await?; + f.write_all(line.as_bytes()).await +} + +async fn run_file_op(op: &FileOp) -> Result<(), String> { + let r = match op { + FileOp::Write(p, text) => { + if let Some(dir) = p.parent() { + let _ = tokio::fs::create_dir_all(dir).await; + } + // Write to a temp file and rename, so a crash never leaves half a file. + let tmp = p.with_extension("http.reqlite-tmp"); + match tokio::fs::write(&tmp, text).await { + Ok(()) => tokio::fs::rename(&tmp, p).await, + Err(e) => Err(e), + } + .map_err(|e| format!("{}: {e}", p.display())) + } + FileOp::Delete(p) => tokio::fs::remove_file(p) + .await + .map_err(|e| format!("{}: {e}", p.display())), + FileOp::Rename(a, b) => { + if tokio::fs::try_exists(b).await.unwrap_or(false) { + return Err(format!("{} already exists", b.display())); + } + tokio::fs::rename(a, b) + .await + .map_err(|e| format!("{}: {e}", a.display())) + } + }; + tracing::debug!(?op, ok = r.is_ok(), "file op"); + r +} + +async fn import_postman(coll: &Path, out_dir: &Path) -> Result<(usize, Vec), String> { + let json = tokio::fs::read_to_string(coll).await.map_err(|e| e.to_string())?; + let imp = reqlite_core::import::postman::import(&json, &[]).map_err(|e| e.to_string())?; + for (rel, _) in &imp.files { + let p = out_dir.join(rel); + if tokio::fs::try_exists(&p).await.unwrap_or(false) { + return Err(format!("{} already exists; pick an empty folder", p.display())); + } + } + for (rel, text) in &imp.files { + run_file_op(&FileOp::Write(out_dir.join(rel), text.clone())).await?; + } + let mut warnings = imp.warnings.clone(); + if let Some(e) = &imp.public_env { + let p = out_dir.join(env::PUBLIC_FILE); + if tokio::fs::try_exists(&p).await.unwrap_or(false) { + warnings.push(format!( + "{} exists; collection variables were not written", + env::PUBLIC_FILE + )); + } else { + run_file_op(&FileOp::Write(p, e.clone())).await?; + } + } + if let Some(e) = &imp.private_env { + run_file_op(&FileOp::Write(out_dir.join(env::PRIVATE_FILE), e.clone())).await?; + } + Ok((imp.files.len(), warnings)) +} diff --git a/crates/app/src/history.rs b/crates/app/src/history.rs new file mode 100644 index 0000000..81921c1 --- /dev/null +++ b/crates/app/src/history.rs @@ -0,0 +1,60 @@ +//! Request history: an append-only JSON Lines file, capped. + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct HistoryEntry { + /// Unix seconds. + pub at: u64, + pub method: String, + /// The resolved URL that was sent. + pub url: String, + pub status: Option, + pub duration_ms: u64, + pub env: Option, + /// The request as `.http` text (unresolved), for restoring. + pub http: String, + #[serde(default)] + pub error: Option, +} + +pub fn to_line(e: &HistoryEntry) -> String { + let mut s = serde_json::to_string(e).unwrap_or_default(); + s.push('\n'); + s +} + +/// Parses a history file, skipping corrupt lines, keeping the newest `limit`. +pub fn parse(text: &str, limit: usize) -> Vec { + let mut v: Vec = text.lines().filter_map(|l| serde_json::from_str(l).ok()).collect(); + if v.len() > limit { + v.drain(..v.len() - limit); + } + v +} + +pub fn to_text(entries: &[HistoryEntry]) -> String { + entries.iter().map(to_line).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_skips_bad_lines_and_caps() { + let e = |n: u64| HistoryEntry { + at: n, + method: "GET".into(), + url: format!("http://x/{n}"), + status: Some(200), + duration_ms: 1, + env: None, + http: "GET http://x\n".into(), + error: None, + }; + let text = format!("{}not json\n{}{}", to_line(&e(1)), to_line(&e(2)), to_line(&e(3))); + let parsed = parse(&text, 2); + assert_eq!(parsed, vec![e(2), e(3)]); + } +} diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs new file mode 100644 index 0000000..665350d --- /dev/null +++ b/crates/app/src/lib.rs @@ -0,0 +1,16 @@ +//! The reqlite desktop app. +//! +//! Data flow (implementation plan §2.2): UI panels read [`state::AppState`] +//! and emit [`action::Action`]s; [`action::update`] applies them and returns +//! [`effects::Effect`]s; the [`effects::Runner`] runs those as Tokio tasks, +//! which send their results back as actions. + +pub mod action; +pub mod app; +pub mod effects; +pub mod history; +pub mod settings; +pub mod state; +pub mod ui; + +pub use app::ReqliteApp; diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs new file mode 100644 index 0000000..a62f584 --- /dev/null +++ b/crates/app/src/main.rs @@ -0,0 +1,77 @@ +//! `reqlite-gui [collection-folder]` + +#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] + +use std::sync::Arc; + +use reqlite_app::effects::Paths; +use reqlite_app::{action::Action, ReqliteApp}; +use reqlite_core::http::DynHttpClient; +use reqlite_http_curl::CurlClient; + +fn init_logging(paths: Option<&Paths>) -> Option { + use tracing_subscriber::EnvFilter; + let filter = EnvFilter::try_from_env("REQLITE_LOG") + .unwrap_or_else(|_| EnvFilter::new("info,wgpu=warn,wgpu_core=warn,wgpu_hal=warn,naga=warn,eframe=warn")); + let dir = paths?.log_dir(); + std::fs::create_dir_all(&dir).ok()?; + let appender = tracing_appender::rolling::Builder::new() + .rotation(tracing_appender::rolling::Rotation::DAILY) + .filename_prefix("reqlite") + .filename_suffix("log") + .max_log_files(7) + .build(&dir) + .ok()?; + let (writer, guard) = tracing_appender::non_blocking(appender); + tracing_subscriber::fmt() + .with_env_filter(filter) + .with_writer(writer) + .with_ansi(false) + .init(); + Some(guard) +} + +fn main() -> eframe::Result { + let paths = Paths::from_system(); + let _log_guard = init_logging(paths.as_ref()); + tracing::info!(version = env!("CARGO_PKG_VERSION"), curl = %CurlClient::version(), "starting"); + + // Tokio runs on its own threads; eframe keeps the main thread (winit + // needs it on macOS), so no #[tokio::main] here. + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .thread_name("reqlite-io") + .build() + .expect("failed to start the async runtime"); + let handle = runtime.handle().clone(); + let client: Arc = Arc::new(CurlClient::new()); + let open_dir = std::env::args_os().nth(1).map(std::path::PathBuf::from); + + let options = eframe::NativeOptions { + viewport: egui::ViewportBuilder::default() + .with_title("reqlite") + .with_app_id("reqlite") + .with_inner_size([1280.0, 820.0]) + .with_min_inner_size([640.0, 420.0]) + .with_icon( + eframe::icon_data::from_png_bytes(include_bytes!("../assets/icon.png")) + .expect("the bundled icon is a PNG"), + ), + persist_window: true, + ..Default::default() + }; + let result = eframe::run_native( + "reqlite", + options, + Box::new(move |cc| { + egui_extras::install_image_loaders(&cc.egui_ctx); + let mut app = ReqliteApp::new(Some(cc.egui_ctx.clone()), handle, client, paths); + if let Some(dir) = open_dir.and_then(|d| std::fs::canonicalize(d).ok()) { + app.dispatch(Action::OpenCollection(dir)); + } + Ok(Box::new(app)) + }), + ); + runtime.shutdown_timeout(std::time::Duration::from_secs(1)); + result +} diff --git a/crates/app/src/settings.rs b/crates/app/src/settings.rs new file mode 100644 index 0000000..b457781 --- /dev/null +++ b/crates/app/src/settings.rs @@ -0,0 +1,110 @@ +//! User settings, stored as TOML in the config directory. + +use std::path::PathBuf; +use std::time::Duration; + +use reqlite_core::http::{Proxy, RequestOptions}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ThemeChoice { + #[default] + System, + Light, + Dark, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ProxyMode { + #[default] + System, + None, + Manual, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Settings { + /// Seconds; 0 means no timeout. + pub default_timeout_secs: u64, + pub proxy_mode: ProxyMode, + pub proxy_url: String, + pub verify_tls: bool, + /// Extra CA bundle (PEM), used in addition to the system store. + pub ca_file: Option, + pub zoom: f32, + pub theme: ThemeChoice, + pub max_concurrent_requests: usize, + pub history_limit: usize, + pub recent_collections: Vec, +} + +impl Default for Settings { + fn default() -> Self { + Self { + default_timeout_secs: 0, + proxy_mode: ProxyMode::System, + proxy_url: String::new(), + verify_tls: true, + ca_file: None, + zoom: 1.0, + theme: ThemeChoice::System, + max_concurrent_requests: 8, + history_limit: 500, + recent_collections: Vec::new(), + } + } +} + +impl Settings { + pub fn request_options(&self) -> RequestOptions { + RequestOptions { + timeout: (self.default_timeout_secs > 0).then(|| Duration::from_secs(self.default_timeout_secs)), + verify_tls: self.verify_tls, + ca_file: self.ca_file.clone(), + proxy: match self.proxy_mode { + ProxyMode::System => Proxy::System, + ProxyMode::None => Proxy::None, + ProxyMode::Manual if self.proxy_url.trim().is_empty() => Proxy::System, + ProxyMode::Manual => Proxy::Manual(self.proxy_url.trim().to_string()), + }, + ..RequestOptions::default() + } + } + + pub fn add_recent(&mut self, p: PathBuf) { + self.recent_collections.retain(|r| r != &p); + self.recent_collections.insert(0, p); + self.recent_collections.truncate(10); + } + + pub fn from_toml(s: &str) -> Result { + toml::from_str(s) + } + + pub fn to_toml(&self) -> String { + toml::to_string_pretty(self).unwrap_or_default() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trips_and_tolerates_missing_fields() { + let mut s = Settings { + proxy_mode: ProxyMode::Manual, + proxy_url: "http://proxy:3128".into(), + ..Default::default() + }; + s.add_recent("/a".into()); + assert_eq!(Settings::from_toml(&s.to_toml()).unwrap(), s); + let partial = Settings::from_toml("zoom = 1.5\n").unwrap(); + assert_eq!(partial.zoom, 1.5); + assert_eq!(partial.max_concurrent_requests, 8); + assert_eq!(s.request_options().proxy, Proxy::Manual("http://proxy:3128".into())); + } +} diff --git a/crates/app/src/state.rs b/crates/app/src/state.rs new file mode 100644 index 0000000..d6ff443 --- /dev/null +++ b/crates/app/src/state.rs @@ -0,0 +1,509 @@ +//! `AppState`: everything the UI shows, as plain data. Only +//! [`crate::action::update`] changes it. + +use std::collections::{BTreeMap, HashMap}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Instant, SystemTime}; + +use reqlite_core::collection::Node; +use reqlite_core::cookies::CookieJar; +use reqlite_core::env::Environments; +use reqlite_core::http::{BodyStore, Response}; +use reqlite_core::httpfile::{HttpFile, RequestKey}; +use reqlite_core::params::Param; +use reqlite_core::template::Resolver; +use reqlite_core::{CancelToken, Request}; + +use crate::history::HistoryEntry; +use crate::settings::Settings; + +pub type TabId = u64; + +#[derive(Default)] +pub struct AppState { + pub tabs: Vec, + pub active: Option, + pub next_tab_id: TabId, + pub collection: Option, + pub selected_env: Option, + pub settings: Settings, + /// Oldest first. + pub history: Vec, + /// Keyed by collection root; `None` for requests outside a collection. + pub cookie_jars: HashMap, CookieJar>, + pub status: Option, + pub dialog: Option, + pub windows: Windows, + pub quick_open: Option, + pub env_editor: Option, + /// Asks the UI to focus the URL field on the next frame. + pub focus_url: bool, + /// Set when the user confirmed quitting with unsaved changes. + pub quit_confirmed: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Status { + pub text: String, + pub is_error: bool, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Windows { + pub history: bool, + pub cookies: bool, + pub settings: bool, + pub about: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Dialog { + /// Closing a tab with unsaved changes. + ConfirmCloseTab(TabId), + /// Quitting with unsaved changes. + ConfirmQuit, + /// The file of a tab with unsaved changes changed on disk. + Conflict { tab: TabId, path: PathBuf }, + /// A text prompt (new file, rename …). + Prompt(Prompt), + /// Confirm a destructive collection operation. + ConfirmDelete(DeleteTarget), + /// Result of a Postman import. + ImportSummary { + root: PathBuf, + files: usize, + warnings: Vec, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DeleteTarget { + Request { file: PathBuf, index: usize, label: String }, + File(PathBuf), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Prompt { + pub kind: PromptKind, + pub title: String, + pub value: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PromptKind { + NewFile { dir: PathBuf }, + RenameFile { path: PathBuf }, + RenameRequest { file: PathBuf, index: usize }, + NewEnvironment, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct QuickOpen { + pub query: String, + pub selected: usize, +} + +/// The environment editor works on a copy that is written on Save. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EnvEditor { + pub envs: Environments, + pub selected: String, + /// Private values whose text is shown instead of `••••`. + pub revealed: Vec<(String, String)>, + pub dirty: bool, +} + +pub struct CollectionState { + pub root: PathBuf, + pub tree: Node, + pub files: BTreeMap, + pub envs: Environments, + pub env_error: Option, + /// The private env file exists but is not git-ignored. + pub private_not_ignored: bool, + pub gitignore_offer_dismissed: bool, +} + +impl CollectionState { + /// Every request in the collection as `(file, index, request)`. + pub fn all_requests(&self) -> impl Iterator { + self.files + .iter() + .flat_map(|(p, f)| f.requests().enumerate().map(move |(i, r)| (p, i, r))) + } + + pub fn relative<'a>(&self, p: &'a Path) -> &'a Path { + p.strip_prefix(&self.root).unwrap_or(p) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum RequestTab { + #[default] + Params, + Headers, + Body, + Auth, + Source, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum ResponseTab { + #[default] + Body, + Headers, + Timings, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum BodyView { + #[default] + Pretty, + Raw, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Origin { + pub file: PathBuf, + pub key: RequestKey, +} + +pub struct InFlight { + pub cancel: CancelToken, + pub started: Instant, + pub seq: u64, + /// What goes into history once the response arrives. + pub history: HistoryEntry, + pub cookie_jar: Option>, + pub url: String, +} + +pub struct Tab { + pub id: TabId, + pub origin: Option, + /// The request being edited. + pub request: Request, + /// The last loaded or saved version (for the dirty marker). + pub saved: Request, + /// The Source tab text. + pub source: String, + pub saved_source: String, + /// The last edit was made in the Source tab, so its text (with comments + /// and anything else the form doesn't model) is what gets saved. + pub source_authoritative: bool, + pub source_error: Option, + /// Derived from the URL; edits go back to the URL. + pub params: Vec, + pub request_tab: RequestTab, + pub response_tab: ResponseTab, + pub body_view: BodyView, + pub in_flight: Option, + pub seq: u64, + pub response: Option, + pub error: Option, + pub search: Search, + /// The request was deleted from (or never belonged to) its file. + pub orphaned: bool, +} + +impl Tab { + pub fn new(id: TabId, request: Request, origin: Option, source: String) -> Self { + Self { + id, + origin, + params: reqlite_core::params::parse_params(&request.url), + saved: request.clone(), + request, + saved_source: source.clone(), + source, + source_authoritative: false, + source_error: None, + request_tab: RequestTab::default(), + response_tab: ResponseTab::default(), + body_view: BodyView::default(), + in_flight: None, + seq: 0, + response: None, + error: None, + search: Search::default(), + orphaned: false, + } + } + + pub fn is_dirty(&self) -> bool { + !self.request.same_content(&self.saved) || (self.source_authoritative && self.source != self.saved_source) + } + + pub fn title(&self) -> String { + if let Some(n) = self.request.display_name() { + return n.to_string(); + } + let url = self.request.url.trim(); + if url.is_empty() { + "New request".into() + } else { + let short: String = url.chars().take(40).collect(); + if url.chars().count() > 40 { + format!("{short}…") + } else { + short + } + } + } +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Search { + pub open: bool, + pub query: String, + /// `(line, byte range in line)`. + pub matches: Vec<(usize, std::ops::Range)>, + pub current: usize, + /// Asks the UI to scroll to this line. + pub scroll_to: Option, +} + +pub struct ResponseView { + pub response: Response, + pub received_at: SystemTime, + pub prepared: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BodyKind { + Json, + Text, + Image, + Binary, + Empty, +} + +/// A response body made ready for display (off the UI thread). +#[derive(Debug, Clone)] +pub struct PreparedBody { + pub kind: BodyKind, + pub raw: TextLines, + pub pretty: Option, + pub image: Option>, + /// Only the first part of the body is shown. + pub truncated: bool, +} + +impl PreparedBody { + pub fn text(&self, view: BodyView) -> &TextLines { + match (view, &self.pretty) { + (BodyView::Pretty, Some(p)) => p, + _ => &self.raw, + } + } +} + +/// Text plus the byte offset where each line starts. +#[derive(Debug, Clone, Default)] +pub struct TextLines { + pub text: Arc, + pub starts: Arc>, +} + +impl TextLines { + pub fn new(text: String) -> Self { + let mut starts = vec![0]; + starts.extend(text.match_indices('\n').map(|(i, _)| i + 1)); + if starts.len() > 1 && *starts.last().unwrap() == text.len() { + starts.pop(); + } + Self { + text: Arc::new(text), + starts: Arc::new(starts), + } + } + + pub fn line_count(&self) -> usize { + if self.text.is_empty() { + 0 + } else { + self.starts.len() + } + } + + pub fn line(&self, i: usize) -> &str { + let start = self.starts[i]; + let end = self.starts.get(i + 1).copied().unwrap_or(self.text.len()); + self.text[start..end].trim_end_matches(['\n', '\r']) + } +} + +impl AppState { + pub fn tab(&self, id: TabId) -> Option<&Tab> { + self.tabs.iter().find(|t| t.id == id) + } + + pub fn tab_mut(&mut self, id: TabId) -> Option<&mut Tab> { + self.tabs.iter_mut().find(|t| t.id == id) + } + + pub fn active_tab(&self) -> Option<&Tab> { + self.active.and_then(|id| self.tab(id)) + } + + pub fn alloc_tab_id(&mut self) -> TabId { + self.next_tab_id += 1; + self.next_tab_id + } + + pub fn any_dirty(&self) -> bool { + self.tabs.iter().any(Tab::is_dirty) + } + + /// File variables of the tab's file plus the selected environment. + pub fn resolver_for(&self, tab: &Tab) -> Resolver { + let file_vars = tab + .origin + .as_ref() + .and_then(|o| self.collection.as_ref()?.files.get(&o.file)) + .map(|f| f.variables()) + .unwrap_or_default(); + match &self.collection { + Some(c) => c.envs.resolver(self.selected_env.as_deref(), &file_vars), + None => Environments::default().resolver(None, &file_vars), + } + } + + /// Whether `name` comes from the private env file (shown masked). + pub fn is_private_var(&self, name: &str) -> bool { + match (&self.collection, &self.selected_env) { + (Some(c), Some(env)) => c.envs.is_private(env, name), + (Some(c), None) => c.envs.is_private(reqlite_core::env::SHARED_ENV, name), + _ => false, + } + } + + /// Directory that relative file references in the tab resolve against. + pub fn base_dir_for(&self, tab: &Tab) -> PathBuf { + if let Some(o) = &tab.origin { + if let Some(p) = o.file.parent() { + return p.to_path_buf(); + } + } + if let Some(c) = &self.collection { + return c.root.clone(); + } + std::env::current_dir().unwrap_or_default() + } + + pub fn set_error(&mut self, text: impl Into) { + self.status = Some(Status { + text: text.into(), + is_error: true, + }); + } + + pub fn set_info(&mut self, text: impl Into) { + self.status = Some(Status { + text: text.into(), + is_error: false, + }); + } +} + +/// Builds a `PreparedBody` (runs on a blocking thread for big bodies). +pub fn prepare_body(body: &BodyStore, content_type: &str, max_display: u64) -> PreparedBody { + let ct = content_type.to_ascii_lowercase(); + let mut bytes = match body { + BodyStore::InMemory(b) => b.as_ref().clone(), + BodyStore::TempFile(p) => { + use std::io::Read; + let mut buf = Vec::new(); + if let Ok(f) = std::fs::File::open(&**p) { + let _ = f.take(max_display).read_to_end(&mut buf); + } + buf + } + }; + let total = match body { + BodyStore::InMemory(b) => b.len() as u64, + BodyStore::TempFile(p) => std::fs::metadata(&**p).map(|m| m.len()).unwrap_or(0), + }; + let truncated = total > max_display; + bytes.truncate(max_display as usize); + + if bytes.is_empty() { + return PreparedBody { + kind: BodyKind::Empty, + raw: TextLines::default(), + pretty: None, + image: None, + truncated: false, + }; + } + if ct.starts_with("image/") && !ct.contains("svg") && !truncated { + return PreparedBody { + kind: BodyKind::Image, + raw: TextLines::default(), + pretty: None, + image: Some(Arc::from(bytes.into_boxed_slice())), + truncated, + }; + } + let looks_binary = std::str::from_utf8(&bytes[..bytes.len().min(4096)]).is_err() + && !ct.starts_with("text/") + && !ct.contains("json") + && !ct.contains("xml"); + if looks_binary { + return PreparedBody { + kind: BodyKind::Binary, + raw: TextLines::new(hex_dump(&bytes[..bytes.len().min(64 * 1024)])), + pretty: None, + image: None, + truncated: truncated || bytes.len() > 64 * 1024, + }; + } + let text = String::from_utf8_lossy(&bytes).into_owned(); + let is_json = ct.contains("json") || { + let t = text.trim_start(); + (t.starts_with('{') || t.starts_with('[')) && !ct.contains("html") + }; + if is_json && !truncated { + if let Ok(v) = serde_json::from_str::(&text) { + let pretty = serde_json::to_string_pretty(&v).unwrap_or_default(); + return PreparedBody { + kind: BodyKind::Json, + raw: TextLines::new(text), + pretty: Some(TextLines::new(pretty)), + image: None, + truncated, + }; + } + } + PreparedBody { + kind: BodyKind::Text, + raw: TextLines::new(text), + pretty: None, + image: None, + truncated, + } +} + +fn hex_dump(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len() * 4); + for (i, chunk) in bytes.chunks(16).enumerate() { + out.push_str(&format!("{:08x} ", i * 16)); + for j in 0..16 { + match chunk.get(j) { + Some(b) => out.push_str(&format!("{b:02x} ")), + None => out.push_str(" "), + } + } + out.push(' '); + for &b in chunk { + out.push(if b.is_ascii_graphic() || b == b' ' { + b as char + } else { + '.' + }); + } + out.push('\n'); + } + out +} diff --git a/crates/app/src/ui/mod.rs b/crates/app/src/ui/mod.rs new file mode 100644 index 0000000..f7a981b --- /dev/null +++ b/crates/app/src/ui/mod.rs @@ -0,0 +1,292 @@ +//! UI panels. They only read [`AppState`] and push [`Action`]s. + +pub mod request; +pub mod response; +pub mod sidebar; +pub mod widgets; +pub mod windows; + +use egui::{Context, Key, KeyboardShortcut, Modifiers, RichText, Ui}; + +use crate::action::Action; +use crate::state::{AppState, QuickOpen}; +use widgets::VarCtx; + +pub fn draw(ui: &mut Ui, state: &AppState, acts: &mut Vec) { + shortcuts(ui.ctx(), state, acts); + + egui::Panel::top("menu").show(ui, |ui| menu_bar(ui, state, acts)); + egui::Panel::bottom("status").show(ui, |ui| status_bar(ui, state, acts)); + egui::Panel::left("sidebar") + .resizable(true) + .default_size(250.0) + .show(ui, |ui| sidebar::show(ui, state, acts)); + egui::CentralPanel::default().show(ui, |ui| { + tab_bar(ui, state, acts); + match state.active_tab() { + Some(tab) => { + let resolver = state.resolver_for(tab); + let is_private = |n: &str| state.is_private_var(n); + let vars = VarCtx { + resolver: &resolver, + is_private: &is_private, + }; + if tab.orphaned { + ui.label( + RichText::new("This request is no longer in its file. Save writes it to a file you pick.") + .color(ui.visuals().warn_fg_color), + ); + } + request::url_bar(ui, state, tab, &vars, acts); + ui.add_space(4.0); + egui::Panel::top(("request-editor", tab.id)) + .resizable(true) + .default_size(250.0) + .size_range(80.0..=f32::INFINITY) + .show(ui, |ui| request::editor(ui, state, tab, &vars, acts)); + egui::CentralPanel::no_frame().show(ui, |ui| { + ui.add_space(4.0); + response::show(ui, tab, acts); + }); + } + None => welcome(ui, acts), + } + }); + + windows::show(ui.ctx(), state, acts); +} + +fn shortcuts(ctx: &Context, state: &AppState, acts: &mut Vec) { + if state.dialog.is_some() { + return; + } + let cmd = |k| KeyboardShortcut::new(Modifiers::COMMAND, k); + let active = state.active; + ctx.input_mut(|i| { + if i.consume_shortcut(&cmd(Key::Enter)) { + if let Some(id) = active { + acts.push(Action::Send(id)); + } + } + if i.consume_shortcut(&cmd(Key::S)) { + if let Some(id) = active { + acts.push(Action::Save(id)); + } + } + if i.consume_shortcut(&cmd(Key::T)) { + acts.push(Action::NewTab); + } + if i.consume_shortcut(&cmd(Key::W)) { + if let Some(id) = active { + acts.push(Action::CloseTab(id)); + } + } + if i.consume_shortcut(&cmd(Key::L)) { + acts.push(Action::FocusUrl); + } + if i.consume_shortcut(&cmd(Key::P)) { + acts.push(Action::QuickOpen(Some(QuickOpen::default()))); + } + if i.consume_shortcut(&cmd(Key::F)) { + if let Some(id) = active { + acts.push(Action::SearchOpen(id, true)); + } + } + }); +} + +fn menu_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec) { + egui::MenuBar::new().ui(ui, |ui| { + ui.menu_button("File", |ui| { + if ui.button("New tab Ctrl+T").clicked() { + acts.push(Action::NewTab); + ui.close(); + } + if ui.button("Open collection folder…").clicked() { + acts.push(Action::PickCollection); + ui.close(); + } + ui.menu_button("Recent collections", |ui| { + for p in &state.settings.recent_collections { + if ui.button(p.display().to_string()).clicked() { + acts.push(Action::OpenCollection(p.clone())); + ui.close(); + } + } + if state.settings.recent_collections.is_empty() { + ui.label(RichText::new("None yet").weak()); + } + }); + ui.separator(); + let has_tab = state.active.is_some(); + if ui + .add_enabled(has_tab, egui::Button::new("Save Ctrl+S")) + .clicked() + { + acts.push(Action::Save(state.active.unwrap())); + ui.close(); + } + ui.separator(); + if ui.button("Import Postman collection…").clicked() { + acts.push(Action::ImportPostman); + ui.close(); + } + ui.label( + RichText::new("Tip: paste a curl command into the URL bar to import it.") + .small() + .weak(), + ); + ui.separator(); + if ui.button("Settings…").clicked() { + acts.push(Action::SetWindows(crate::state::Windows { + settings: true, + ..state.windows + })); + ui.close(); + } + if ui.button("Quit").clicked() { + acts.push(Action::CloseRequested); + ui.close(); + } + }); + ui.menu_button("View", |ui| { + let mut w = state.windows; + ui.checkbox(&mut w.history, "History"); + ui.checkbox(&mut w.cookies, "Cookies"); + if w != state.windows { + acts.push(Action::SetWindows(w)); + } + if ui.button("Quick open… Ctrl+P").clicked() { + acts.push(Action::QuickOpen(Some(QuickOpen::default()))); + ui.close(); + } + }); + ui.menu_button("Help", |ui| { + if ui.button("About and shortcuts").clicked() { + acts.push(Action::SetWindows(crate::state::Windows { + about: true, + ..state.windows + })); + ui.close(); + } + }); + + // Environment picker on the right. + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if let Some(c) = &state.collection { + if ui.button("Edit…").on_hover_text("Edit environments").clicked() { + acts.push(Action::OpenEnvEditor); + } + let names = c.envs.names(); + let label = state.selected_env.clone().unwrap_or_else(|| "No environment".into()); + egui::ComboBox::from_id_salt("env-picker") + .selected_text(label) + .width(150.0) + .show_ui(ui, |ui| { + if ui + .selectable_label(state.selected_env.is_none(), "No environment") + .clicked() + { + acts.push(Action::SelectEnv(None)); + } + for n in names { + if ui + .selectable_label(state.selected_env.as_ref() == Some(&n), &n) + .clicked() + { + acts.push(Action::SelectEnv(Some(n.clone()))); + } + } + }); + ui.label("Environment:"); + } + }); + }); +} + +fn tab_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec) { + egui::ScrollArea::horizontal().id_salt("tabs").show(ui, |ui| { + ui.horizontal(|ui| { + for t in &state.tabs { + let selected = state.active == Some(t.id); + let mut title = t.title(); + if t.is_dirty() { + title.push_str(" •"); + } + if t.in_flight.is_some() { + title.push_str(" ⏳"); + } + let resp = ui.selectable_label(selected, title); + let resp = match &t.origin { + Some(o) => resp.on_hover_text(o.file.display().to_string()), + None => resp, + }; + if resp.clicked() { + acts.push(Action::SelectTab(t.id)); + } + if resp.middle_clicked() { + acts.push(Action::CloseTab(t.id)); + } + resp.context_menu(|ui| { + if ui.button("Close").clicked() { + acts.push(Action::CloseTab(t.id)); + ui.close(); + } + }); + if ui.small_button("×").on_hover_text("Close (Ctrl+W)").clicked() { + acts.push(Action::CloseTab(t.id)); + } + ui.separator(); + } + if ui.button("+").on_hover_text("New tab (Ctrl+T)").clicked() { + acts.push(Action::NewTab); + } + }); + }); + ui.separator(); +} + +fn status_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec) { + ui.horizontal(|ui| { + match &state.status { + Some(s) => { + let color = if s.is_error { + ui.visuals().error_fg_color + } else { + ui.visuals().text_color() + }; + ui.colored_label(color, &s.text); + if ui.small_button("×").clicked() { + acts.push(Action::DismissStatus); + } + } + None => { + ui.label(RichText::new("Ready").weak()); + } + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let n = state.tabs.iter().filter(|t| t.in_flight.is_some()).count(); + if n > 0 { + ui.spinner(); + ui.label(format!("{n} in flight")); + } + }); + }); +} + +fn welcome(ui: &mut Ui, acts: &mut Vec) { + ui.vertical_centered(|ui| { + ui.add_space(60.0); + ui.heading("reqlite"); + ui.label("Send HTTP requests and keep them as .http files."); + ui.add_space(12.0); + if ui.button("New request (Ctrl+T)").clicked() { + acts.push(Action::NewTab); + } + if ui.button("Open a collection folder…").clicked() { + acts.push(Action::PickCollection); + } + ui.add_space(12.0); + ui.label(RichText::new("Tip: paste a curl command into the URL bar to import it.").weak()); + }); +} diff --git a/crates/app/src/ui/request.rs b/crates/app/src/ui/request.rs new file mode 100644 index 0000000..1359733 --- /dev/null +++ b/crates/app/src/ui/request.rs @@ -0,0 +1,647 @@ +//! The URL bar and the request editor tabs. + +use base64::Engine; +use egui::{Key, RichText, Ui}; +use reqlite_core::params::Param; +use reqlite_core::{Body, Header, Method, Part, PartBody}; + +use super::widgets::{code_edit, method_color, var_text_edit, VarCtx}; +use crate::action::Action; +use crate::state::{AppState, RequestTab, Tab}; + +pub const MULTIPART_BOUNDARY: &str = "WebAppBoundary"; + +pub fn url_bar(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec) { + let id = tab.id; + ui.horizontal(|ui| { + // Method. + let dark = ui.visuals().dark_mode; + let current = tab.request.method.clone(); + egui::ComboBox::from_id_salt(("method", id)) + .width(90.0) + .selected_text( + RichText::new(current.as_str()) + .strong() + .color(method_color(current.as_str(), dark)), + ) + .show_ui(ui, |ui| { + for m in Method::COMMON { + let label = RichText::new(m.as_str()).color(method_color(m.as_str(), dark)); + if ui.selectable_label(m == current, label).clicked() && m != current { + acts.push(Action::SetMethod(id, m.clone())); + } + } + }); + + // Buttons on the right, URL takes the rest. + let buttons_w = 190.0; + let mut url = tab.request.url.clone(); + let w = (ui.available_width() - buttons_w).max(120.0); + let resp = var_text_edit( + ui, + &mut url, + Some(vars), + "Enter a URL, or paste a curl command", + w, + ("url", id), + ); + if state.focus_url { + resp.request_focus(); + acts.push(Action::UrlFocused); + } + if resp.changed() { + acts.push(Action::UrlEdited(id, url)); + } + if resp.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) { + acts.push(Action::Send(id)); + } + + if tab.in_flight.is_some() { + if ui.button("Cancel").on_hover_text("Stop the request").clicked() { + acts.push(Action::Cancel(id)); + } + } else if ui + .add(egui::Button::new(RichText::new("Send").strong())) + .on_hover_text("Send (Ctrl+Enter)") + .clicked() + { + acts.push(Action::Send(id)); + } + let save_label = if tab.is_dirty() { "Save •" } else { "Save" }; + if ui + .button(save_label) + .on_hover_text("Save to the .http file (Ctrl+S)") + .clicked() + { + acts.push(Action::Save(id)); + } + ui.menu_button("…", |ui| { + if ui.button("Copy as curl").clicked() { + acts.push(Action::CopyAsCurl(id)); + ui.close(); + } + if ui.button("Copy as .http").clicked() { + acts.push(Action::CopyAsHttp(id)); + ui.close(); + } + ui.separator(); + let mut follow = !tab.request.directives.no_redirect; + if ui.checkbox(&mut follow, "Follow redirects").changed() { + acts.push(Action::SetNoRedirect(id, !follow)); + } + }); + }); +} + +pub fn editor(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec) { + let id = tab.id; + ui.horizontal(|ui| { + let enabled_headers = tab.request.headers.iter().filter(|h| !h.disabled).count(); + let tabs = [ + (RequestTab::Params, format!("Params ({})", tab.params.len())), + (RequestTab::Headers, format!("Headers ({enabled_headers})")), + ( + RequestTab::Body, + if tab.request.body.is_none() { + "Body".into() + } else { + "Body •".into() + }, + ), + (RequestTab::Auth, "Auth".into()), + ( + RequestTab::Source, + if tab.source_error.is_some() { + "Source ⚠".into() + } else { + "Source".into() + }, + ), + ]; + for (t, label) in tabs { + if ui.selectable_label(tab.request_tab == t, label).clicked() { + acts.push(Action::SetRequestTab(id, t)); + } + } + }); + ui.separator(); + egui::ScrollArea::vertical() + .id_salt(("req-scroll", id)) + .auto_shrink(false) + .show(ui, |ui| match tab.request_tab { + RequestTab::Params => params(ui, tab, vars, acts), + RequestTab::Headers => headers(ui, tab, vars, acts), + RequestTab::Body => body(ui, state, tab, vars, acts), + RequestTab::Auth => auth(ui, tab, vars, acts), + RequestTab::Source => source(ui, tab, vars, acts), + }); +} + +fn params(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec) { + let id = tab.id; + let mut rows: Vec = tab.params.clone(); + let mut changed = false; + let mut remove = None; + let n = rows.len(); + rows.push(Param::default()); // the "add" row + // Measure before the grid: inside it, the width is a single cell's. + let w = ((ui.available_width() - 60.0) / 2.0).max(100.0); + egui::Grid::new(("params", id)) + .num_columns(3) + .striped(true) + .show(ui, |ui| { + ui.label(RichText::new("Key").weak()); + ui.label(RichText::new("Value").weak()); + ui.label(""); + ui.end_row(); + for (i, p) in rows.iter_mut().enumerate() { + changed |= var_text_edit( + ui, + &mut p.key, + Some(vars), + if i == n { "Add parameter" } else { "" }, + w, + ("pk", id, i), + ) + .changed(); + let mut v = p.value.clone().unwrap_or_default(); + if var_text_edit(ui, &mut v, Some(vars), "", w, ("pv", id, i)).changed() { + p.value = Some(v); + changed = true; + } + if i < n && ui.small_button("×").on_hover_text("Remove").clicked() { + remove = Some(i); + } + ui.end_row(); + } + }); + if let Some(i) = remove { + rows.remove(i); + changed = true; + } + if changed { + if rows + .last() + .is_some_and(|p| p.key.is_empty() && p.value.as_deref().unwrap_or("").is_empty()) + { + rows.pop(); + } + acts.push(Action::ParamsEdited(id, rows)); + } + ui.add_space(4.0); + ui.label( + RichText::new("Parameters are kept in the URL, exactly as typed.") + .small() + .weak(), + ); +} + +fn headers(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec) { + let id = tab.id; + let mut rows = tab.request.headers.clone(); + let n = rows.len(); + rows.push(Header::new("", "")); + let mut changed = false; + let mut remove = None; + let w = (ui.available_width() - 90.0).max(240.0); + egui::Grid::new(("headers", id)) + .num_columns(4) + .striped(true) + .show(ui, |ui| { + ui.label(""); + ui.label(RichText::new("Name").weak()); + ui.label(RichText::new("Value").weak()); + ui.label(""); + ui.end_row(); + for (i, h) in rows.iter_mut().enumerate() { + if i < n { + let mut on = !h.disabled; + if ui + .checkbox(&mut on, "") + .on_hover_text("Disabled headers are kept as `# Name: value` comments") + .changed() + { + h.disabled = !on; + changed = true; + } + } else { + ui.label(""); + } + changed |= var_text_edit( + ui, + &mut h.name, + Some(vars), + if i == n { "Add header" } else { "" }, + (w * 0.35).max(100.0), + ("hn", id, i), + ) + .changed(); + changed |= + var_text_edit(ui, &mut h.value, Some(vars), "", (w * 0.65).max(120.0), ("hv", id, i)).changed(); + if i < n && ui.small_button("×").on_hover_text("Remove").clicked() { + remove = Some(i); + } + ui.end_row(); + } + }); + if let Some(i) = remove { + rows.remove(i); + changed = true; + } + if changed { + if rows.last().is_some_and(|h| h.name.is_empty() && h.value.is_empty()) { + rows.pop(); + } + acts.push(Action::HeadersEdited(id, rows)); + } +} + +#[derive(PartialEq, Clone, Copy)] +enum BodyKind { + None, + Text, + File, + Form, +} + +const MAX_EDITABLE_BODY: usize = 1024 * 1024; + +fn body(ui: &mut Ui, _state: &AppState, tab: &Tab, vars: &VarCtx, acts: &mut Vec) { + let id = tab.id; + let req = &tab.request; + let kind = match &req.body { + Body::None => BodyKind::None, + Body::Text(_) => BodyKind::Text, + Body::FileRef { .. } => BodyKind::File, + Body::Multipart { .. } => BodyKind::Form, + }; + ui.horizontal(|ui| { + for (k, label) in [ + (BodyKind::None, "None"), + (BodyKind::Text, "Text"), + (BodyKind::File, "File"), + (BodyKind::Form, "Multipart form"), + ] { + if ui.radio(kind == k, label).clicked() && kind != k { + match k { + BodyKind::None => acts.push(Action::BodyEdited(id, Body::None)), + BodyKind::Text => acts.push(Action::BodyEdited(id, Body::Text(String::new()))), + BodyKind::File => acts.push(Action::BodyEdited( + id, + Body::FileRef { + path: "./body.json".into(), + substitute: false, + }, + )), + BodyKind::Form => { + let mut headers = req.headers.clone(); + headers.retain(|h| !h.name.eq_ignore_ascii_case("content-type")); + headers.push(Header::new( + "Content-Type", + format!("multipart/form-data; boundary={MULTIPART_BOUNDARY}"), + )); + acts.push(Action::HeadersEdited(id, headers)); + acts.push(Action::BodyEdited( + id, + Body::Multipart { + boundary: MULTIPART_BOUNDARY.into(), + parts: vec![Part { + name: "field".into(), + filename: None, + headers: Vec::new(), + body: PartBody::Text(String::new()), + }], + }, + )); + } + } + } + } + }); + ui.add_space(4.0); + match &req.body { + Body::None => { + ui.label(RichText::new("This request has no body.").weak()); + } + Body::Text(text) => { + let ct = req.header("content-type").unwrap_or("").to_ascii_lowercase(); + let is_json = ct.contains("json"); + ui.horizontal(|ui| { + ui.label("Content-Type:"); + for (label, value) in [ + ("JSON", "application/json"), + ("XML", "application/xml"), + ("Text", "text/plain"), + ("Form", "application/x-www-form-urlencoded"), + ] { + if ui.selectable_label(ct.starts_with(value), label).clicked() { + let mut headers = req.headers.clone(); + headers.retain(|h| !h.name.eq_ignore_ascii_case("content-type")); + headers.push(Header::new("Content-Type", value)); + acts.push(Action::HeadersEdited(id, headers)); + } + } + if is_json && ui.button("Format").on_hover_text("Pretty-print the JSON").clicked() { + match serde_json::from_str::(text) { + Ok(v) => acts.push(Action::BodyEdited( + id, + Body::Text(serde_json::to_string_pretty(&v).unwrap_or_else(|_| text.clone())), + )), + Err(e) => acts.push(Action::Error(format!("Not valid JSON: {e}"))), + } + } + }); + if text.len() > MAX_EDITABLE_BODY { + ui.label( + RichText::new(format!( + "The body is {} KB, too large to edit here. Edit it in the .http file, or move it to a file (`< ./body.json`).", + text.len() / 1024 + )) + .weak(), + ); + } else { + let mut t = text.clone(); + if code_edit(ui, &mut t, is_json, Some(vars.resolver), 12, ("body", id)).changed() { + acts.push(Action::BodyEdited(id, Body::Text(t))); + } + } + } + Body::FileRef { path, substitute } => { + ui.horizontal(|ui| { + ui.label("File:"); + let mut p = path.display().to_string(); + if ui + .add(egui::TextEdit::singleline(&mut p).desired_width(320.0)) + .changed() + { + acts.push(Action::BodyEdited( + id, + Body::FileRef { + path: p.into(), + substitute: *substitute, + }, + )); + } + if ui.button("Browse…").clicked() { + acts.push(Action::PickBodyFile(id)); + } + }); + let mut sub = *substitute; + if ui + .checkbox(&mut sub, "Replace {{variables}} in the file (`<@`)") + .changed() + { + acts.push(Action::BodyEdited( + id, + Body::FileRef { + path: path.clone(), + substitute: sub, + }, + )); + } + ui.label( + RichText::new("Relative paths are relative to the .http file.") + .small() + .weak(), + ); + } + Body::Multipart { boundary, parts } => { + let mut parts = parts.clone(); + let mut changed = false; + let mut remove = None; + egui::Grid::new(("parts", id)) + .num_columns(5) + .striped(true) + .show(ui, |ui| { + for h in ["Name", "Kind", "Value / file", "Content-Type", ""] { + ui.label(RichText::new(h).weak()); + } + ui.end_row(); + for (i, p) in parts.iter_mut().enumerate() { + changed |= ui + .add_sized( + [110.0, ui.spacing().interact_size.y], + egui::TextEdit::singleline(&mut p.name), + ) + .changed(); + let is_file = matches!(p.body, PartBody::File(_)); + egui::ComboBox::from_id_salt(("pk", id, i)) + .width(60.0) + .selected_text(if is_file { "File" } else { "Text" }) + .show_ui(ui, |ui| { + if ui.selectable_label(!is_file, "Text").clicked() && is_file { + p.body = PartBody::Text(String::new()); + p.filename = None; + changed = true; + } + if ui.selectable_label(is_file, "File").clicked() && !is_file { + p.body = PartBody::File("./file.bin".into()); + p.filename = Some("file.bin".into()); + changed = true; + } + }); + match &mut p.body { + PartBody::Text(t) => { + changed |= var_text_edit(ui, t, Some(vars), "", 220.0, ("pv", id, i)).changed(); + } + PartBody::File(f) => { + let mut s = f.display().to_string(); + if ui + .add_sized( + [220.0, ui.spacing().interact_size.y], + egui::TextEdit::singleline(&mut s), + ) + .changed() + { + p.filename = std::path::Path::new(&s) + .file_name() + .map(|n| n.to_string_lossy().into_owned()); + *f = s.into(); + changed = true; + } + } + } + let mut ct = p.content_type().unwrap_or("").to_string(); + if ui + .add_sized( + [120.0, ui.spacing().interact_size.y], + egui::TextEdit::singleline(&mut ct), + ) + .changed() + { + p.headers.retain(|h| !h.name.eq_ignore_ascii_case("content-type")); + if !ct.is_empty() { + p.headers.push(Header::new("Content-Type", ct)); + } + changed = true; + } + if ui.small_button("×").clicked() { + remove = Some(i); + } + ui.end_row(); + } + }); + if let Some(i) = remove { + parts.remove(i); + changed = true; + } + if ui.button("Add field").clicked() { + parts.push(Part { + name: format!("field{}", parts.len() + 1), + filename: None, + headers: Vec::new(), + body: PartBody::Text(String::new()), + }); + changed = true; + } + if changed { + acts.push(Action::BodyEdited( + id, + Body::Multipart { + boundary: boundary.clone(), + parts, + }, + )); + } + } + } +} + +#[derive(PartialEq, Clone, Copy)] +enum AuthKind { + None, + Basic, + Bearer, + Other, +} + +/// Splits an Authorization header into what the Auth tab shows. +fn auth_parts(value: Option<&str>) -> (AuthKind, String, String) { + let Some(v) = value else { + return (AuthKind::None, String::new(), String::new()); + }; + if let Some(rest) = v.strip_prefix("Bearer ") { + return (AuthKind::Bearer, rest.trim().to_string(), String::new()); + } + if let Some(rest) = v.strip_prefix("Basic ") { + let rest = rest.trim(); + if let Some((u, p)) = rest.split_once(' ') { + return (AuthKind::Basic, u.to_string(), p.trim().to_string()); + } + // Already encoded: show the decoded user and password. + if let Some((u, p)) = base64::engine::general_purpose::STANDARD + .decode(rest) + .ok() + .and_then(|b| String::from_utf8(b).ok()) + .and_then(|s| s.split_once(':').map(|(a, b)| (a.to_string(), b.to_string()))) + { + return (AuthKind::Basic, u, p); + } + return (AuthKind::Basic, rest.to_string(), String::new()); + } + (AuthKind::Other, v.to_string(), String::new()) +} + +fn auth(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec) { + let id = tab.id; + let header = tab.request.header("authorization"); + let (kind, a, b) = auth_parts(header); + ui.horizontal(|ui| { + ui.label("Type:"); + for (k, label) in [ + (AuthKind::None, "None"), + (AuthKind::Basic, "Basic"), + (AuthKind::Bearer, "Bearer token"), + ] { + if ui.radio(kind == k, label).clicked() && kind != k { + acts.push(Action::AuthEdited( + id, + match k { + AuthKind::None => None, + AuthKind::Basic => Some("Basic {{username}} {{password}}".into()), + AuthKind::Bearer => Some("Bearer {{token}}".into()), + AuthKind::Other => unreachable!(), + }, + )); + } + } + }); + ui.add_space(6.0); + match kind { + AuthKind::None => { + ui.label(RichText::new("No Authorization header.").weak()); + } + AuthKind::Basic => { + let (mut u, mut p) = (a, b); + let mut changed = false; + egui::Grid::new(("basic", id)).num_columns(2).show(ui, |ui| { + ui.label("Username"); + changed |= var_text_edit(ui, &mut u, Some(vars), "", 260.0, ("bu", id)).changed(); + ui.end_row(); + ui.label("Password"); + changed |= var_text_edit(ui, &mut p, Some(vars), "", 260.0, ("bp", id)).changed(); + ui.end_row(); + }); + if changed { + acts.push(Action::AuthEdited(id, Some(format!("Basic {u} {p}")))); + } + ui.label( + RichText::new("Written as `Authorization: Basic user password`; it is base64-encoded when sent, like JetBrains does.") + .small() + .weak(), + ); + } + AuthKind::Bearer => { + let mut t = a; + ui.horizontal(|ui| { + ui.label("Token"); + if var_text_edit(ui, &mut t, Some(vars), "{{token}}", 420.0, ("bt", id)).changed() { + acts.push(Action::AuthEdited(id, Some(format!("Bearer {t}")))); + } + }); + } + AuthKind::Other => { + ui.label(format!("Custom Authorization header: {a}")); + ui.label(RichText::new("Edit it in the Headers tab.").weak()); + } + } + ui.add_space(6.0); + ui.label( + RichText::new("Auth is just the Authorization header; put secrets in the private env file.") + .small() + .weak(), + ); +} + +fn source(ui: &mut Ui, tab: &Tab, vars: &VarCtx, acts: &mut Vec) { + let id = tab.id; + if let Some(e) = &tab.source_error { + ui.colored_label(ui.visuals().error_fg_color, e); + } + let mut text = tab.source.clone(); + if code_edit(ui, &mut text, false, Some(vars.resolver), 14, ("source", id)).changed() { + acts.push(Action::SourceEdited(id, text)); + } + ui.label( + RichText::new("The request as it is stored in the .http file. Comments and response handlers are kept; scripts are never run.") + .small() + .weak(), + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn auth_parts_reads_the_header_forms() { + assert!(auth_parts(None).0 == AuthKind::None); + let (k, u, p) = auth_parts(Some("Basic {{user}} {{pass}}")); + assert!(k == AuthKind::Basic && u == "{{user}}" && p == "{{pass}}"); + let (k, u, p) = auth_parts(Some("Basic YWRhOnMzY3JldA==")); + assert!(k == AuthKind::Basic && u == "ada" && p == "s3cret"); + let (k, t, _) = auth_parts(Some("Bearer abc")); + assert!(k == AuthKind::Bearer && t == "abc"); + assert!(auth_parts(Some("Digest x")).0 == AuthKind::Other); + } +} diff --git a/crates/app/src/ui/response.rs b/crates/app/src/ui/response.rs new file mode 100644 index 0000000..af91052 --- /dev/null +++ b/crates/app/src/ui/response.rs @@ -0,0 +1,304 @@ +//! The response panel: status line, body viewer, headers and timings. + +use egui::{Align, FontId, Layout, RichText, Ui}; + +use super::widgets::{build_job, human_size, json_spans, status_color, Palette}; +use crate::action::Action; +use crate::state::{BodyKind, BodyView, ResponseTab, Tab, TextLines}; + +/// Lines longer than this are cut in the viewer (the full body can be saved +/// or copied). +const MAX_LINE: usize = 5_000; + +pub fn show(ui: &mut Ui, tab: &Tab, acts: &mut Vec) { + let id = tab.id; + if let Some(f) = &tab.in_flight { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(format!("Sending… {:.1} s", f.started.elapsed().as_secs_f32())); + if ui.button("Cancel").clicked() { + acts.push(Action::Cancel(id)); + } + }); + ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)); + return; + } + if let Some(e) = &tab.error { + ui.colored_label(ui.visuals().error_fg_color, e); + return; + } + let Some(view) = &tab.response else { + ui.centered_and_justified(|ui| { + ui.label(RichText::new("Send the request to see the response here.").weak()); + }); + return; + }; + let r = &view.response; + let dark = ui.visuals().dark_mode; + + ui.horizontal(|ui| { + ui.label( + RichText::new(format!("{} {}", r.status, r.reason)) + .strong() + .color(status_color(r.status, dark)), + ); + ui.separator(); + ui.label(format!("{} ms", r.timings.total.as_millis())); + ui.separator(); + ui.label(human_size(r.size)); + ui.separator(); + ui.label(RichText::new(&r.http_version).weak()); + if r.body.is_spilled() { + ui.label(RichText::new("(stored in a temp file)").weak()); + } + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if ui.button("Save to file…").clicked() { + acts.push(Action::SaveResponseBody(id)); + } + if let Some(p) = &view.prepared { + if p.kind != BodyKind::Image && ui.button("Copy body").clicked() { + ui.ctx().copy_text(p.text(tab.body_view).text.to_string()); + } + } + }); + }); + + ui.horizontal(|ui| { + for (t, label) in [ + (ResponseTab::Body, "Body".to_string()), + (ResponseTab::Headers, format!("Headers ({})", r.headers.len())), + (ResponseTab::Timings, "Timings".to_string()), + ] { + if ui.selectable_label(tab.response_tab == t, label).clicked() { + acts.push(Action::SetResponseTab(id, t)); + } + } + }); + ui.separator(); + + match tab.response_tab { + ResponseTab::Body => body(ui, tab, acts), + ResponseTab::Headers => { + egui::ScrollArea::both() + .id_salt(("resp-headers", id)) + .auto_shrink(false) + .show(ui, |ui| { + egui::Grid::new(("resp-h", id)) + .num_columns(2) + .striped(true) + .show(ui, |ui| { + for (n, v) in &r.headers { + ui.add(egui::Label::new(RichText::new(n).strong().monospace()).selectable(true)); + ui.add(egui::Label::new(RichText::new(v).monospace()).selectable(true)); + ui.end_row(); + } + }); + if r.effective_url != tab.request.url { + ui.add_space(8.0); + ui.label(RichText::new(format!("Final URL: {}", r.effective_url)).weak()); + } + }); + } + ResponseTab::Timings => timings(ui, tab), + } +} + +fn body(ui: &mut Ui, tab: &Tab, acts: &mut Vec) { + let id = tab.id; + let view = tab.response.as_ref().unwrap(); + let Some(p) = &view.prepared else { + ui.horizontal(|ui| { + ui.spinner(); + ui.label("Preparing the body…"); + }); + return; + }; + match p.kind { + BodyKind::Empty => { + ui.label(RichText::new("No body.").weak()); + return; + } + BodyKind::Image => { + if let Some(bytes) = &p.image { + egui::ScrollArea::both() + .id_salt(("img", id)) + .auto_shrink(false) + .show(ui, |ui| { + ui.add( + egui::Image::from_bytes(format!("bytes://response-{id}-{}", tab.seq), bytes.clone()) + .max_size(ui.available_size()) + .fit_to_original_size(1.0), + ); + }); + } + return; + } + _ => {} + } + + ui.horizontal(|ui| { + if p.pretty.is_some() { + if ui + .selectable_label(tab.body_view == BodyView::Pretty, "Pretty") + .clicked() + { + acts.push(Action::SetBodyView(id, BodyView::Pretty)); + } + if ui.selectable_label(tab.body_view == BodyView::Raw, "Raw").clicked() { + acts.push(Action::SetBodyView(id, BodyView::Raw)); + } + ui.separator(); + } + if p.kind == BodyKind::Binary { + ui.label(RichText::new("Binary body, shown as hex. Use “Save to file” to keep it.").weak()); + } + if p.truncated { + ui.label(RichText::new("Only the start of this large body is shown.").weak()); + } + if tab.search.open { + search_bar(ui, tab, acts); + } else if ui + .small_button("🔍 Find") + .on_hover_text("Search the body (Ctrl+F)") + .clicked() + { + acts.push(Action::SearchOpen(id, true)); + } + }); + + let lines = p.text(tab.body_view); + let json = p.kind == BodyKind::Json && (tab.body_view == BodyView::Pretty || lines.line_count() < 5_000); + text_view(ui, tab, lines, json, acts); +} + +fn search_bar(ui: &mut Ui, tab: &Tab, acts: &mut Vec) { + let id = tab.id; + let mut q = tab.search.query.clone(); + let resp = ui.add( + egui::TextEdit::singleline(&mut q) + .hint_text("Find") + .desired_width(180.0) + .id_salt(("find", id)), + ); + if !resp.has_focus() && tab.search.query.is_empty() && !resp.lost_focus() { + resp.request_focus(); + } + if resp.changed() { + acts.push(Action::SearchQuery(id, q)); + } + let n = tab.search.matches.len(); + if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + let back = ui.input(|i| i.modifiers.shift); + acts.push(Action::SearchStep(id, if back { -1 } else { 1 })); + resp.request_focus(); + } + if n > 0 { + ui.label(format!("{}/{}", tab.search.current + 1, n)); + } else if !tab.search.query.is_empty() { + ui.label(RichText::new("no matches").weak()); + } + if ui.small_button("Prev").clicked() { + acts.push(Action::SearchStep(id, -1)); + } + if ui.small_button("Next").clicked() { + acts.push(Action::SearchStep(id, 1)); + } + if ui.small_button("×").clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) { + acts.push(Action::SearchOpen(id, false)); + } +} + +/// Virtualized, line-based text viewer: only visible lines are laid out. +fn text_view(ui: &mut Ui, tab: &Tab, lines: &TextLines, json: bool, acts: &mut Vec) { + let id = tab.id; + let pal = Palette::for_ui(ui); + let font: FontId = egui::TextStyle::Monospace.resolve(ui.style()); + let row_h = ui.fonts_mut(|f| f.row_height(&font)); + let spacing = ui.spacing().item_spacing.y; + let total = lines.line_count(); + let gutter = total.max(1).to_string().len(); + let default = ui.visuals().text_color(); + + let mut area = egui::ScrollArea::both() + .id_salt(("body-view", id, tab.body_view as u8)) + .auto_shrink(false); + if let Some(line) = tab.search.scroll_to { + let y = (line as f32 * (row_h + spacing) - ui.available_height() / 3.0).max(0.0); + area = area.vertical_scroll_offset(y); + acts.push(Action::ScrolledTo(id)); + } + let matches = &tab.search.matches; + let current = matches.get(tab.search.current).cloned(); + area.show_rows(ui, row_h, total, |ui, range| { + let first = matches.partition_point(|m| m.0 < range.start); + let mut mi = first; + for i in range { + let full = lines.line(i); + let mut cut = full.len().min(MAX_LINE); + while !full.is_char_boundary(cut) { + cut -= 1; + } + let line = &full[..cut]; + let prefix = format!("{:>gutter$} ", i + 1); + let off = prefix.len(); + let mut text = prefix; + text.push_str(line); + if cut < full.len() { + text.push_str(" …"); + } + let mut colors = vec![vec![(0..off, pal.muted)]]; + if json { + colors.push( + json_spans(line, &pal) + .into_iter() + .map(|(r, c)| (r.start + off..r.end + off, c)) + .collect(), + ); + } + let mut bgs = Vec::new(); + while mi < matches.len() && matches[mi].0 == i { + let r = &matches[mi].1; + let bg = if current.as_ref() == Some(&matches[mi]) { + pal.current_bg + } else { + pal.match_bg + }; + if r.end <= cut { + bgs.push((r.start + off..r.end + off, bg)); + } + mi += 1; + } + let job = build_job(&text, font.clone(), default, &colors, &bgs, f32::INFINITY); + ui.add(egui::Label::new(job).selectable(true).extend()); + } + }); +} + +fn timings(ui: &mut Ui, tab: &Tab) { + let Some(view) = &tab.response else { return }; + let t = view.response.timings; + let total = t.total.as_secs_f32().max(0.000_1); + let bar_w = (ui.available_width() - 260.0).max(100.0); + let color = ui.visuals().selection.bg_fill; + egui::Grid::new(("timings", tab.id)).num_columns(3).show(ui, |ui| { + let mut start = 0.0f32; + for (label, d) in t.phases() { + let secs = d.as_secs_f32(); + ui.label(label); + ui.label(RichText::new(format!("{:.1} ms", secs * 1000.0)).monospace()); + let (rect, _) = ui.allocate_exact_size(egui::vec2(bar_w, 12.0), egui::Sense::hover()); + let x0 = rect.left() + bar_w * (start / total); + let x1 = (x0 + (bar_w * secs / total).max(1.0)).min(rect.right()); + ui.painter().rect_filled( + egui::Rect::from_min_max(egui::pos2(x0, rect.top()), egui::pos2(x1, rect.bottom())), + 2.0, + color, + ); + start += secs; + ui.end_row(); + } + ui.label(RichText::new("Total").strong()); + ui.label(RichText::new(format!("{:.1} ms", total * 1000.0)).monospace().strong()); + ui.end_row(); + }); +} diff --git a/crates/app/src/ui/sidebar.rs b/crates/app/src/ui/sidebar.rs new file mode 100644 index 0000000..6988b1d --- /dev/null +++ b/crates/app/src/ui/sidebar.rs @@ -0,0 +1,265 @@ +//! The collection tree: folders → files → requests. + +use std::path::Path; + +use egui::{RichText, Ui}; +use reqlite_core::collection::Node; + +use super::widgets::method_color; +use crate::action::Action; +use crate::state::{AppState, CollectionState, DeleteTarget, Dialog, Prompt, PromptKind}; + +pub fn show(ui: &mut Ui, state: &AppState, acts: &mut Vec) { + let Some(c) = &state.collection else { + ui.add_space(8.0); + ui.label("No collection open."); + ui.label(RichText::new("A collection is a folder of .http files.").weak()); + ui.add_space(4.0); + if ui.button("Open folder…").clicked() { + acts.push(Action::PickCollection); + } + if !state.settings.recent_collections.is_empty() { + ui.add_space(8.0); + ui.label(RichText::new("Recent").strong()); + for p in &state.settings.recent_collections { + let name = p + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + if ui.link(name).on_hover_text(p.display().to_string()).clicked() { + acts.push(Action::OpenCollection(p.clone())); + } + } + } + return; + }; + + ui.horizontal(|ui| { + ui.label(RichText::new(c.tree.name()).strong()) + .on_hover_text(c.root.display().to_string()); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.small_button("⟳").on_hover_text("Reload from disk").clicked() { + acts.push(Action::Rescan); + } + if ui.small_button("+").on_hover_text("New .http file").clicked() { + acts.push(new_file_prompt(&c.root)); + } + }); + }); + + if c.private_not_ignored && !c.gitignore_offer_dismissed { + egui::Frame::group(ui.style()).show(ui, |ui| { + ui.label( + RichText::new("http-client.private.env.json is not in .gitignore, so secrets could be committed.") + .color(ui.visuals().warn_fg_color), + ); + ui.horizontal(|ui| { + if ui.button("Add to .gitignore").clicked() { + acts.push(Action::AddPrivateFileToGitignore); + } + if ui.button("Dismiss").clicked() { + acts.push(Action::DismissGitignoreOffer); + } + }); + }); + } + if let Some(e) = &c.env_error { + ui.colored_label(ui.visuals().error_fg_color, format!("Environments: {e}")); + } + ui.separator(); + + egui::ScrollArea::vertical() + .id_salt("tree") + .auto_shrink(false) + .show(ui, |ui| { + if let Node::Folder { children, .. } = &c.tree { + if children.is_empty() { + ui.label(RichText::new("No .http files yet.").weak()); + if ui.button("Create one").clicked() { + acts.push(new_file_prompt(&c.root)); + } + } + for child in children { + node(ui, state, c, child, acts); + } + } + // Right-clicking the empty space below the tree. + let size = egui::vec2(ui.available_width(), ui.available_height().max(40.0)); + ui.allocate_response(size, egui::Sense::click()).context_menu(|ui| { + if ui.button("New .http file…").clicked() { + acts.push(new_file_prompt(&c.root)); + ui.close(); + } + }); + }); +} + +fn new_file_prompt(dir: &Path) -> Action { + Action::ShowDialog(Some(Dialog::Prompt(Prompt { + kind: PromptKind::NewFile { dir: dir.to_path_buf() }, + title: "New .http file".into(), + value: "requests.http".into(), + }))) +} + +fn node(ui: &mut Ui, state: &AppState, c: &CollectionState, n: &Node, acts: &mut Vec) { + match n { + Node::Folder { name, path, children } => { + let resp = egui::CollapsingHeader::new(format!("📁 {name}")) + .id_salt(path) + .default_open(true) + .show(ui, |ui| { + for ch in children { + node(ui, state, c, ch, acts); + } + }); + resp.header_response.context_menu(|ui| { + if ui.button("New .http file…").clicked() { + acts.push(new_file_prompt(path)); + ui.close(); + } + }); + } + Node::File { name, path } => { + let Some(file) = c.files.get(path) else { return }; + let resp = egui::CollapsingHeader::new(format!("📄 {name}")) + .id_salt(path) + .default_open(true) + .show(ui, |ui| { + let active = state.active_tab().and_then(|t| t.origin.as_ref()); + for (i, r) in file.requests().enumerate() { + let dark = ui.visuals().dark_mode; + let selected = active.is_some_and(|o| &o.file == path && o.key.index == i); + let label = r + .display_name() + .map(str::to_string) + .unwrap_or_else(|| short_url(&r.url)); + let mut job = egui::text::LayoutJob::default(); + job.append( + &format!("{:<6} ", short_method(r.method.as_str())), + 0.0, + egui::TextFormat { + font_id: egui::FontId::monospace(11.0), + color: method_color(r.method.as_str(), dark), + ..Default::default() + }, + ); + job.append( + &label, + 0.0, + egui::TextFormat { + font_id: egui::TextStyle::Body.resolve(ui.style()), + color: ui.visuals().text_color(), + ..Default::default() + }, + ); + let item = ui + .selectable_label(selected, job) + .on_hover_text(format!("{} {}", r.method, r.url)); + if item.clicked() { + acts.push(Action::OpenRequest { + file: path.clone(), + index: i, + }); + } + item.context_menu(|ui| { + if ui.button("Open").clicked() { + acts.push(Action::OpenRequest { + file: path.clone(), + index: i, + }); + ui.close(); + } + if ui.button("Rename…").clicked() { + acts.push(Action::ShowDialog(Some(Dialog::Prompt(Prompt { + kind: PromptKind::RenameRequest { + file: path.clone(), + index: i, + }, + title: "Rename request".into(), + value: r.display_name().unwrap_or("").to_string(), + })))); + ui.close(); + } + if ui.button("Duplicate").clicked() { + acts.push(Action::DuplicateRequest { + file: path.clone(), + index: i, + }); + ui.close(); + } + ui.menu_button("Move to", |ui| { + for other in c.files.keys().filter(|p| *p != path) { + if ui.button(c.relative(other).display().to_string()).clicked() { + acts.push(Action::MoveRequest { + from: path.clone(), + index: i, + to: other.clone(), + }); + ui.close(); + } + } + }); + ui.separator(); + if ui.button("Delete…").clicked() { + acts.push(Action::ShowDialog(Some(Dialog::ConfirmDelete(DeleteTarget::Request { + file: path.clone(), + index: i, + label: label.clone(), + })))); + ui.close(); + } + }); + } + if file.request_count() == 0 { + ui.label(RichText::new("(no requests)").weak()); + } + }); + resp.header_response.context_menu(|ui| { + if ui.button("New request").clicked() { + acts.push(Action::NewRequestIn { file: path.clone() }); + ui.close(); + } + if ui.button("Rename file…").clicked() { + acts.push(Action::ShowDialog(Some(Dialog::Prompt(Prompt { + kind: PromptKind::RenameFile { path: path.clone() }, + title: "Rename file".into(), + value: name.clone(), + })))); + ui.close(); + } + if ui.button("Duplicate file").clicked() { + acts.push(Action::DuplicateFile(path.clone())); + ui.close(); + } + ui.separator(); + if ui.button("Delete file…").clicked() { + acts.push(Action::ShowDialog(Some(Dialog::ConfirmDelete(DeleteTarget::File( + path.clone(), + ))))); + ui.close(); + } + }); + } + } +} + +fn short_method(m: &str) -> &str { + match m { + "DELETE" => "DEL", + "OPTIONS" => "OPT", + "PATCH" => "PATCH", + m if m.len() > 6 => &m[..6], + m => m, + } +} + +fn short_url(url: &str) -> String { + let u = url.split("://").nth(1).unwrap_or(url); + let s: String = u.chars().take(40).collect(); + if s.is_empty() { + "(no URL)".into() + } else { + s + } +} diff --git a/crates/app/src/ui/widgets.rs b/crates/app/src/ui/widgets.rs new file mode 100644 index 0000000..11bff4e --- /dev/null +++ b/crates/app/src/ui/widgets.rs @@ -0,0 +1,394 @@ +//! Shared widgets: syntax-coloured text and `{{var}}`-aware text fields. + +use std::ops::Range; +use std::sync::Arc; + +use egui::text::{LayoutJob, TextFormat}; +use egui::{Color32, FontId, TextBuffer, Ui}; +use reqlite_core::template::{find_vars, Resolver, VarSource}; + +pub struct Palette { + pub text: Color32, + pub key: Color32, + pub string: Color32, + pub number: Color32, + pub keyword: Color32, + pub punct: Color32, + pub var_ok: Color32, + pub var_bad: Color32, + pub match_bg: Color32, + pub current_bg: Color32, + pub muted: Color32, +} + +impl Palette { + pub fn for_ui(ui: &Ui) -> Self { + let text = ui.visuals().text_color(); + if ui.visuals().dark_mode { + Self { + text, + key: Color32::from_rgb(0x9c, 0xdc, 0xfe), + string: Color32::from_rgb(0xce, 0x91, 0x78), + number: Color32::from_rgb(0xb5, 0xce, 0xa8), + keyword: Color32::from_rgb(0x56, 0x9c, 0xd6), + punct: Color32::from_gray(0xa0), + var_ok: Color32::from_rgb(0x4e, 0xc9, 0xb0), + var_bad: Color32::from_rgb(0xf4, 0x47, 0x47), + match_bg: Color32::from_rgba_unmultiplied(0xff, 0xd7, 0x00, 0x50), + current_bg: Color32::from_rgba_unmultiplied(0xff, 0x8c, 0x00, 0xa0), + muted: Color32::from_gray(0x80), + } + } else { + Self { + text, + key: Color32::from_rgb(0x00, 0x45, 0x8a), + string: Color32::from_rgb(0xa3, 0x15, 0x15), + number: Color32::from_rgb(0x09, 0x86, 0x58), + keyword: Color32::from_rgb(0x00, 0x00, 0xff), + punct: Color32::from_gray(0x60), + var_ok: Color32::from_rgb(0x00, 0x80, 0x70), + var_bad: Color32::from_rgb(0xd0, 0x00, 0x00), + match_bg: Color32::from_rgba_unmultiplied(0xff, 0xd7, 0x00, 0x80), + current_bg: Color32::from_rgba_unmultiplied(0xff, 0x8c, 0x00, 0xc0), + muted: Color32::from_gray(0x70), + } + } + } +} + +/// Colour spans for JSON (works line by line, so huge bodies stay cheap). +pub fn json_spans(text: &str, p: &Palette) -> Vec<(Range, Color32)> { + let b = text.as_bytes(); + let mut out = Vec::new(); + let mut i = 0; + while i < b.len() { + let c = b[i]; + let start = i; + match c { + b'"' => { + i += 1; + while i < b.len() && b[i] != b'"' && b[i] != b'\n' { + if b[i] == b'\\' { + i += 1; + } + i += 1; + } + i = (i + 1).min(b.len()); + let mut j = i; + while j < b.len() && (b[j] == b' ' || b[j] == b'\t') { + j += 1; + } + let color = if j < b.len() && b[j] == b':' { p.key } else { p.string }; + out.push((start..i, color)); + } + b'-' | b'0'..=b'9' => { + i += 1; + while i < b.len() && (b[i].is_ascii_digit() || b".eE+-".contains(&b[i])) { + i += 1; + } + out.push((start..i, p.number)); + } + b't' | b'f' | b'n' => { + let rest = &text[i..]; + let kw = ["true", "false", "null"].into_iter().find(|k| rest.starts_with(k)); + match kw { + Some(k) => { + i += k.len(); + out.push((start..i, p.keyword)); + } + None => i += 1, + } + } + b'{' | b'}' | b'[' | b']' | b',' | b':' => { + i += 1; + out.push((start..i, p.punct)); + } + _ => i += 1, + } + } + out +} + +/// Colour spans for `{{var}}` placeholders. +pub fn var_spans(text: &str, resolver: Option<&Resolver>, p: &Palette) -> Vec<(Range, Color32)> { + find_vars(text) + .into_iter() + .map(|(r, name)| { + let ok = resolver.is_none_or(|res| res.is_defined(&name)); + (r, if ok { p.var_ok } else { p.var_bad }) + }) + .collect() +} + +/// Builds a layout job from base colour spans plus background highlights. +/// Later colour spans win over earlier ones. +pub fn build_job( + text: &str, + font: FontId, + default: Color32, + colors: &[Vec<(Range, Color32)>], + backgrounds: &[(Range, Color32)], + wrap_width: f32, +) -> LayoutJob { + let mut cuts: Vec = vec![0, text.len()]; + for layer in colors { + for (r, _) in layer { + cuts.push(r.start.min(text.len())); + cuts.push(r.end.min(text.len())); + } + } + for (r, _) in backgrounds { + cuts.push(r.start.min(text.len())); + cuts.push(r.end.min(text.len())); + } + cuts.retain(|&c| text.is_char_boundary(c)); + cuts.sort_unstable(); + cuts.dedup(); + + let mut job = LayoutJob::default(); + job.wrap.max_width = wrap_width; + for w in cuts.windows(2) { + let (a, b) = (w[0], w[1]); + if a == b { + continue; + } + let mut color = default; + for layer in colors { + if let Some((_, c)) = layer.iter().find(|(r, _)| r.start <= a && b <= r.end) { + color = *c; + } + } + let background = backgrounds + .iter() + .rev() + .find(|(r, _)| r.start <= a && b <= r.end) + .map(|(_, c)| *c) + .unwrap_or(Color32::TRANSPARENT); + job.append( + &text[a..b], + 0.0, + TextFormat { + font_id: font.clone(), + color, + background, + ..Default::default() + }, + ); + } + if text.is_empty() { + job.append( + "", + 0.0, + TextFormat { + font_id: font, + color: default, + ..Default::default() + }, + ); + } + job +} + +/// What the variable fields need to colour and explain `{{vars}}`. +pub struct VarCtx<'a> { + pub resolver: &'a Resolver, + pub is_private: &'a dyn Fn(&str) -> bool, +} + +impl VarCtx<'_> { + /// Text for the hover tooltip of a variable. + pub fn describe(&self, name: &str) -> String { + match self.resolver.lookup(name) { + None => format!("{{{{{name}}}}} is not defined in the selected environment"), + Some((_, VarSource::Builtin)) => format!("{{{{{name}}}}}: built-in dynamic value"), + Some((v, src)) => { + let from = match src { + VarSource::PrivateEnv => "private env", + VarSource::PublicEnv => "env", + VarSource::File => "file variable", + VarSource::Builtin => "built-in", + }; + let shown = if (self.is_private)(name) { + "••••".to_string() + } else { + match self.resolver.resolve(&v) { + Ok(r) if r != v => format!("{v} -> {r}"), + _ => v, + } + }; + format!("{name} = {shown} ({from})") + } + } + } +} + +/// A text field that colours `{{vars}}` (green when defined, red when not) +/// and shows a variable's value when hovering it. +pub fn var_text_edit( + ui: &mut Ui, + text: &mut String, + vars: Option<&VarCtx>, + hint: &str, + width: f32, + id_salt: impl egui::AsIdSalt, +) -> egui::Response { + let pal = Palette::for_ui(ui); + let font = egui::TextStyle::Monospace.resolve(ui.style()); + let default = ui.visuals().text_color(); + let resolver = vars.map(|v| v.resolver); + // Single-line text never wraps; it scrolls inside the field. + let mut layouter = |ui: &Ui, buf: &dyn TextBuffer, _wrap: f32| -> Arc { + let s = buf.as_str(); + let job = build_job( + s, + font.clone(), + default, + &[var_spans(s, resolver, &pal)], + &[], + f32::INFINITY, + ); + ui.ctx().fonts_mut(|f| f.layout_job(job)) + }; + // TextEdit never grows past the available width, and inside a Grid that + // is last frame's column width, so give it an explicitly sized area. + let height = ui.spacing().interact_size.y; + let out = ui + .allocate_ui(egui::vec2(width, height), |ui| { + ui.set_min_width(width); + egui::TextEdit::singleline(text) + .id_salt(id_salt) + .hint_text(hint) + .desired_width(width) + .font(egui::TextStyle::Monospace) + .layouter(&mut layouter) + .show(ui) + }) + .inner; + let response = out.response.response.clone(); + if let (Some(vars), Some(pos)) = (vars, response.hover_pos()) { + let cursor = out.galley.cursor_from_pos(pos - out.galley_pos); + let char_idx = cursor.index.0; + let byte_idx = text.char_indices().nth(char_idx).map(|(b, _)| b).unwrap_or(text.len()); + if let Some((_, name)) = find_vars(text) + .into_iter() + .find(|(r, _)| r.start <= byte_idx && byte_idx < r.end) + { + let tip = vars.describe(&name); + return response.on_hover_text(tip); + } + } + response +} + +/// A multi-line code editor with JSON and `{{var}}` colouring. +pub fn code_edit( + ui: &mut Ui, + text: &mut String, + json: bool, + resolver: Option<&Resolver>, + rows: usize, + id_salt: impl egui::AsIdSalt, +) -> egui::Response { + let pal = Palette::for_ui(ui); + let font = egui::TextStyle::Monospace.resolve(ui.style()); + let default = ui.visuals().text_color(); + let mut layouter = |ui: &Ui, buf: &dyn TextBuffer, wrap: f32| -> Arc { + let s = buf.as_str(); + let mut layers = Vec::new(); + if json { + layers.push(json_spans(s, &pal)); + } + layers.push(var_spans(s, resolver, &pal)); + let job = build_job(s, font.clone(), default, &layers, &[], wrap); + ui.ctx().fonts_mut(|f| f.layout_job(job)) + }; + egui::TextEdit::multiline(text) + .id_salt(id_salt) + .code_editor() + .desired_rows(rows) + .desired_width(f32::INFINITY) + .layouter(&mut layouter) + .show(ui) + .response + .response +} + +pub fn method_color(method: &str, dark: bool) -> Color32 { + let (r, g, b): (u8, u8, u8) = match method { + "GET" => (0x2e, 0xa0, 0x43), + "POST" => (0xd9, 0x8e, 0x04), + "PUT" => (0x1f, 0x6f, 0xeb), + "PATCH" => (0x8b, 0x5c, 0xf6), + "DELETE" => (0xdc, 0x26, 0x26), + _ => (0x6b, 0x72, 0x80), + }; + if dark { + Color32::from_rgb(r.saturating_add(0x20), g.saturating_add(0x20), b.saturating_add(0x20)) + } else { + Color32::from_rgb(r, g, b) + } +} + +pub fn status_color(status: u16, dark: bool) -> Color32 { + match (status / 100, dark) { + (2, true) => Color32::from_rgb(0x4a, 0xde, 0x80), + (2, false) => Color32::from_rgb(0x15, 0x80, 0x3d), + (3, true) => Color32::from_rgb(0x60, 0xa5, 0xfa), + (3, false) => Color32::from_rgb(0x1d, 0x4e, 0xd8), + (4, true) => Color32::from_rgb(0xfb, 0xbf, 0x24), + (4, false) => Color32::from_rgb(0xb4, 0x53, 0x09), + (_, true) => Color32::from_rgb(0xf8, 0x71, 0x71), + (_, false) => Color32::from_rgb(0xb9, 0x1c, 0x1c), + } +} + +pub fn human_size(n: u64) -> String { + match n { + n if n < 1024 => format!("{n} B"), + n if n < 1024 * 1024 => format!("{:.1} KB", n as f64 / 1024.0), + n => format!("{:.1} MB", n as f64 / (1024.0 * 1024.0)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn json_spans_classify_tokens() { + let p = Palette { + text: Color32::WHITE, + key: Color32::from_rgb(1, 0, 0), + string: Color32::from_rgb(2, 0, 0), + number: Color32::from_rgb(3, 0, 0), + keyword: Color32::from_rgb(4, 0, 0), + punct: Color32::from_rgb(5, 0, 0), + var_ok: Color32::WHITE, + var_bad: Color32::WHITE, + match_bg: Color32::WHITE, + current_bg: Color32::WHITE, + muted: Color32::WHITE, + }; + let s = r#"{"a": "b\"c", "n": -1.5e3, "t": true, "z": null}"#; + let kinds: Vec<(&str, u8)> = json_spans(s, &p).into_iter().map(|(r, c)| (&s[r], c.r())).collect(); + assert!(kinds.contains(&("\"a\"", 1))); + assert!(kinds.contains(&("\"b\\\"c\"", 2))); + assert!(kinds.contains(&("-1.5e3", 3))); + assert!(kinds.contains(&("true", 4))); + assert!(kinds.contains(&("null", 4))); + } + + #[test] + fn build_job_covers_the_whole_text() { + let text = "héllo {{x}} wörld"; + let job = build_job( + text, + FontId::monospace(12.0), + Color32::WHITE, + &[vec![(6..11, Color32::RED)]], + &[(0..2, Color32::YELLOW)], + 100.0, + ); + assert_eq!(job.text, text); + } +} diff --git a/crates/app/src/ui/windows.rs b/crates/app/src/ui/windows.rs new file mode 100644 index 0000000..b327c64 --- /dev/null +++ b/crates/app/src/ui/windows.rs @@ -0,0 +1,753 @@ +//! Modal dialogs and floating windows. + +use egui::{Context, Id, Key, RichText}; +use reqlite_core::env::{EnvFile, EnvVar, SHARED_ENV}; + +use super::widgets::{method_color, status_color}; +use crate::action::Action; +use crate::settings::{ProxyMode, Settings, ThemeChoice}; +use crate::state::{AppState, DeleteTarget, Dialog, EnvEditor, Prompt, PromptKind, QuickOpen}; + +pub fn show(ctx: &Context, state: &AppState, acts: &mut Vec) { + if let Some(d) = &state.dialog { + dialog(ctx, state, d, acts); + } + let mut w = state.windows; + let before = w; + if w.settings { + settings(ctx, &state.settings, &mut w.settings, acts); + } + if w.history { + history(ctx, state, &mut w.history, acts); + } + if w.cookies { + cookies(ctx, state, &mut w.cookies, acts); + } + if w.about { + about(ctx, &mut w.about); + } + if w != before { + acts.push(Action::SetWindows(w)); + } + if let Some(ed) = &state.env_editor { + env_editor(ctx, ed, acts); + } + if let Some(q) = &state.quick_open { + quick_open(ctx, state, q, acts); + } +} + +fn dialog(ctx: &Context, state: &AppState, d: &Dialog, acts: &mut Vec) { + let close = || Action::ShowDialog(None); + let modal = egui::Modal::new(Id::unique("reqlite-dialog")).show(ctx, |ui| { + ui.set_max_width(460.0); + match d { + Dialog::ConfirmCloseTab(id) => { + let title = state.tab(*id).map(|t| t.title()).unwrap_or_default(); + let has_file = state.tab(*id).is_some_and(|t| t.origin.is_some()); + ui.heading("Unsaved changes"); + ui.label(format!("“{title}” has changes that are not saved.")); + ui.add_space(8.0); + ui.horizontal(|ui| { + if has_file && ui.button("Save and close").clicked() { + acts.push(close()); + acts.push(Action::Save(*id)); + acts.push(Action::CloseTab(*id)); + } + if ui.button("Discard").clicked() { + acts.push(Action::DiscardAndCloseTab(*id)); + } + if ui.button("Cancel").clicked() { + acts.push(close()); + } + }); + } + Dialog::ConfirmQuit => { + let n = state.tabs.iter().filter(|t| t.is_dirty()).count(); + ui.heading("Quit reqlite?"); + ui.label(format!("{n} tab(s) have unsaved changes; they will be lost.")); + ui.add_space(8.0); + ui.horizontal(|ui| { + if ui.button("Quit without saving").clicked() { + acts.push(Action::ConfirmQuit); + } + if ui.button("Cancel").clicked() { + acts.push(close()); + } + }); + } + Dialog::Conflict { tab, path } => { + ui.heading("File changed on disk"); + ui.label(format!( + "{} was changed outside reqlite, and this tab has unsaved edits.", + path.display() + )); + ui.add_space(8.0); + ui.horizontal(|ui| { + if ui + .button("Reload from disk") + .on_hover_text("Discard my edits") + .clicked() + { + acts.push(Action::ResolveConflict { + tab: *tab, + keep_mine: false, + }); + } + if ui + .button("Keep my version") + .on_hover_text("Saving will overwrite this request in the new file") + .clicked() + { + acts.push(Action::ResolveConflict { + tab: *tab, + keep_mine: true, + }); + } + }); + } + Dialog::Prompt(p) => prompt(ui, state, p, acts), + Dialog::ConfirmDelete(target) => { + let what = match target { + DeleteTarget::Request { label, .. } => format!("the request “{label}”"), + DeleteTarget::File(p) => format!("the file {}", p.display()), + }; + ui.heading("Delete?"); + ui.label(format!("This deletes {what} from disk.")); + ui.add_space(8.0); + ui.horizontal(|ui| { + if ui + .button(RichText::new("Delete").color(ui.visuals().error_fg_color)) + .clicked() + { + acts.push(match target { + DeleteTarget::Request { file, index, .. } => Action::DeleteRequest { + file: file.clone(), + index: *index, + }, + DeleteTarget::File(p) => Action::DeleteFile(p.clone()), + }); + } + if ui.button("Cancel").clicked() { + acts.push(close()); + } + }); + } + Dialog::ImportSummary { root, files, warnings } => { + ui.heading("Import finished"); + ui.label(format!("Wrote {files} .http file(s) to {}.", root.display())); + if !warnings.is_empty() { + ui.add_space(6.0); + ui.label(RichText::new(format!("{} warning(s):", warnings.len())).strong()); + egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| { + for w in warnings { + ui.label(format!("• {w}")); + } + }); + } + ui.add_space(8.0); + if ui.button("OK").clicked() { + acts.push(close()); + } + } + } + }); + if modal.should_close() && !matches!(d, Dialog::Conflict { .. }) { + acts.push(close()); + } +} + +fn prompt(ui: &mut egui::Ui, state: &AppState, p: &Prompt, acts: &mut Vec) { + ui.heading(&p.title); + let mut value = p.value.clone(); + let resp = ui.add( + egui::TextEdit::singleline(&mut value) + .desired_width(380.0) + .id_salt("prompt"), + ); + if !resp.has_focus() && !resp.lost_focus() { + resp.request_focus(); + } + if resp.changed() { + acts.push(Action::ShowDialog(Some(Dialog::Prompt(Prompt { + value: value.clone(), + ..p.clone() + })))); + } + let enter = resp.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)); + ui.add_space(8.0); + ui.horizontal(|ui| { + if ui.button("OK").clicked() || enter { + let action = match &p.kind { + PromptKind::NewFile { dir } => Action::NewFile { + dir: dir.clone(), + name: value.clone(), + }, + PromptKind::RenameFile { path } => Action::RenameFile { + path: path.clone(), + new_name: value.clone(), + }, + PromptKind::RenameRequest { file, index } => Action::RenameRequest { + file: file.clone(), + index: *index, + title: value.clone(), + }, + PromptKind::NewEnvironment => { + if let Some(ed) = &state.env_editor { + let mut ed = ed.clone(); + let name = value.trim().to_string(); + if !name.is_empty() { + ed.envs.public.env_mut(&name); + ed.selected = name; + ed.dirty = true; + } + acts.push(Action::EnvEditorChanged(ed)); + } + Action::ShowDialog(None) + } + }; + acts.push(action); + } + if ui.button("Cancel").clicked() { + acts.push(Action::ShowDialog(None)); + } + }); +} + +fn settings(ctx: &Context, s: &Settings, open: &mut bool, acts: &mut Vec) { + let mut n = s.clone(); + egui::Window::new("Settings") + .open(open) + .resizable(false) + .show(ctx, |ui| { + egui::Grid::new("settings") + .num_columns(2) + .spacing([12.0, 8.0]) + .show(ui, |ui| { + ui.label("Default timeout"); + ui.horizontal(|ui| { + ui.add( + egui::DragValue::new(&mut n.default_timeout_secs) + .range(0..=3600) + .suffix(" s"), + ); + ui.label(RichText::new("0 = none; `# @timeout` wins").weak()); + }); + ui.end_row(); + + ui.label("Proxy"); + ui.vertical(|ui| { + ui.horizontal(|ui| { + ui.radio_value(&mut n.proxy_mode, ProxyMode::System, "System"); + ui.radio_value(&mut n.proxy_mode, ProxyMode::None, "None"); + ui.radio_value(&mut n.proxy_mode, ProxyMode::Manual, "Manual"); + }); + if n.proxy_mode == ProxyMode::Manual { + ui.add_sized( + [260.0, ui.spacing().interact_size.y], + egui::TextEdit::singleline(&mut n.proxy_url).hint_text("http://user:pass@proxy:3128"), + ); + } + }); + ui.end_row(); + + ui.label("TLS"); + ui.vertical(|ui| { + ui.checkbox(&mut n.verify_tls, "Verify certificates"); + ui.horizontal(|ui| { + let ca = n + .ca_file + .as_ref() + .map(|p| p.display().to_string()) + .unwrap_or_else(|| "System store only".into()); + ui.label(RichText::new(ca).weak()); + if ui.button("Add CA file…").clicked() { + acts.push(Action::PickCaFile); + } + if n.ca_file.is_some() && ui.button("Clear").clicked() { + n.ca_file = None; + } + }); + }); + ui.end_row(); + + ui.label("Theme"); + ui.horizontal(|ui| { + ui.radio_value(&mut n.theme, ThemeChoice::System, "System"); + ui.radio_value(&mut n.theme, ThemeChoice::Light, "Light"); + ui.radio_value(&mut n.theme, ThemeChoice::Dark, "Dark"); + }); + ui.end_row(); + + ui.label("Font size"); + ui.add( + egui::Slider::new(&mut n.zoom, 0.75..=2.0) + .step_by(0.05) + .custom_formatter(|v, _| format!("{:.0}%", v * 100.0)), + ); + ui.end_row(); + + ui.label("Parallel requests"); + ui.horizontal(|ui| { + ui.add(egui::DragValue::new(&mut n.max_concurrent_requests).range(1..=64)); + ui.label(RichText::new("at once").weak()); + }); + ui.end_row(); + + ui.label("History size"); + ui.add(egui::DragValue::new(&mut n.history_limit).range(10..=10_000)); + ui.end_row(); + }); + }); + if n != *s { + acts.push(Action::SettingsChanged(n)); + } +} + +fn history(ctx: &Context, state: &AppState, open: &mut bool, acts: &mut Vec) { + egui::Window::new("History") + .open(open) + .default_size([620.0, 420.0]) + .show(ctx, |ui| { + ui.horizontal(|ui| { + ui.label(format!("{} request(s)", state.history.len())); + if ui.button("Clear").clicked() { + acts.push(Action::ClearHistory); + } + }); + ui.separator(); + let dark = ui.visuals().dark_mode; + egui::ScrollArea::vertical().auto_shrink(false).show(ui, |ui| { + egui::Grid::new("history").num_columns(5).striped(true).show(ui, |ui| { + for (i, e) in state.history.iter().enumerate().rev() { + ui.label(RichText::new(format_time(e.at)).weak().monospace()); + match (e.status, &e.error) { + (Some(s), _) => ui.label(RichText::new(s.to_string()).color(status_color(s, dark))), + (None, Some(err)) => ui + .label(RichText::new("ERR").color(ui.visuals().error_fg_color)) + .on_hover_text(err), + _ => ui.label("—"), + }; + ui.label( + RichText::new(&e.method) + .color(method_color(&e.method, dark)) + .monospace(), + ); + let url: String = e.url.chars().take(70).collect(); + ui.label(url).on_hover_text(format!( + "{}\n{} ms{}", + e.url, + e.duration_ms, + e.env.as_ref().map(|v| format!(", env {v}")).unwrap_or_default() + )); + if ui + .small_button("Open") + .on_hover_text("Restore into a new tab") + .clicked() + { + acts.push(Action::RestoreHistory(i)); + } + ui.end_row(); + } + }); + }); + }); +} + +/// `YYYY-MM-DD HH:MM` (UTC) from unix seconds. +fn format_time(secs: u64) -> String { + let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs); + let iso = reqlite_core::template::iso8601(t); + format!("{} {}", &iso[..10], &iso[11..16]) +} + +fn cookies(ctx: &Context, state: &AppState, open: &mut bool, acts: &mut Vec) { + let key = state.collection.as_ref().map(|c| c.root.clone()); + let jar = state.cookie_jars.get(&key); + egui::Window::new("Cookies") + .open(open) + .default_size([560.0, 300.0]) + .show(ctx, |ui| { + ui.label(RichText::new("Cookies are kept in memory per collection; `# @no-cookie-jar` skips them.").weak()); + let cookies = jar.map(|j| j.cookies()).unwrap_or(&[]); + if cookies.is_empty() { + ui.label("No cookies yet."); + return; + } + if ui.button("Clear all").clicked() { + acts.push(Action::ClearCookies); + } + egui::ScrollArea::vertical().show(ui, |ui| { + egui::Grid::new("cookies").num_columns(5).striped(true).show(ui, |ui| { + for h in ["Domain", "Path", "Name", "Value", ""] { + ui.label(RichText::new(h).weak()); + } + ui.end_row(); + for (i, c) in cookies.iter().enumerate() { + ui.label(&c.domain); + ui.label(&c.path); + ui.label(RichText::new(&c.name).strong()); + let v: String = c.value.chars().take(40).collect(); + ui.label(v).on_hover_text(&c.value); + if ui.small_button("×").clicked() { + acts.push(Action::DeleteCookie(i)); + } + ui.end_row(); + } + }); + }); + }); +} + +fn about(ctx: &Context, open: &mut bool) { + egui::Window::new("About reqlite") + .open(open) + .resizable(false) + .show(ctx, |ui| { + ui.heading(format!("reqlite {}", env!("CARGO_PKG_VERSION"))); + ui.label("A small API client for .http files."); + ui.label(reqlite_http_curl::CurlClient::version()); + ui.add_space(6.0); + ui.label(RichText::new("Shortcuts").strong()); + egui::Grid::new("keys").show(ui, |ui| { + for (k, v) in [ + ("Ctrl+Enter", "Send"), + ("Ctrl+S", "Save"), + ("Ctrl+T", "New tab"), + ("Ctrl+W", "Close tab"), + ("Ctrl+L", "Focus the URL bar"), + ("Ctrl+P", "Quick-open a request"), + ("Ctrl+F", "Find in the response"), + ] { + ui.label(RichText::new(k).monospace()); + ui.label(v); + ui.end_row(); + } + }); + }); +} + +fn env_editor(ctx: &Context, ed: &EnvEditor, acts: &mut Vec) { + let mut e = ed.clone(); + let mut open = true; + let mut save = false; + egui::Window::new(if ed.dirty { "Environments •" } else { "Environments" }) + .open(&mut open) + .default_size([640.0, 380.0]) + .show(ctx, |ui| { + ui.horizontal(|ui| { + ui.label("Environment:"); + let mut names = e.envs.names(); + names.insert(0, SHARED_ENV.to_string()); + egui::ComboBox::from_id_salt("env-edit-sel") + .selected_text(&e.selected) + .show_ui(ui, |ui| { + for n in names { + let label = if n == SHARED_ENV { + "$shared (all environments)".to_string() + } else { + n.clone() + }; + ui.selectable_value(&mut e.selected, n, label); + } + }); + if ui.button("New…").clicked() { + acts.push(Action::ShowDialog(Some(Dialog::Prompt(Prompt { + kind: PromptKind::NewEnvironment, + title: "New environment".into(), + value: String::new(), + })))); + } + }); + ui.separator(); + + // Rows: (name, value, private). + let env = e.selected.clone(); + let mut rows: Vec<(String, String, bool, bool)> = Vec::new(); // name, value, private, structured + for (file, private) in [(&e.envs.public, false), (&e.envs.private, true)] { + if let Some(en) = file.env(&env) { + for v in &en.vars { + rows.push((v.name.clone(), v.value.clone(), private, v.is_structured())); + } + } + } + let mut new_rows = rows.clone(); + let mut changed = false; + let mut remove = None; + egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| { + egui::Grid::new("env-vars").num_columns(5).striped(true).show(ui, |ui| { + for h in ["Name", "Value", "Private", "", ""] { + ui.label(RichText::new(h).weak()); + } + ui.end_row(); + for (i, (name, value, private, structured)) in new_rows.iter_mut().enumerate() { + if *structured { + ui.label(name.as_str()); + ui.label(RichText::new("(object; edit the JSON file)").weak()); + ui.label(""); + ui.label(""); + ui.label(""); + ui.end_row(); + continue; + } + changed |= ui + .add_sized([160.0, ui.spacing().interact_size.y], egui::TextEdit::singleline(name)) + .changed(); + let revealed = e.revealed.contains(&(env.clone(), name.clone())); + if *private && !revealed { + ui.label(RichText::new("••••••••").monospace()); + } else { + changed |= ui + .add_sized( + [260.0, ui.spacing().interact_size.y], + egui::TextEdit::singleline(value).font(egui::TextStyle::Monospace), + ) + .changed(); + } + changed |= ui + .checkbox(private, "") + .on_hover_text("Stored in http-client.private.env.json (keep it out of git)") + .changed(); + if *private { + if ui + .small_button(if revealed { "🙈" } else { "👁" }) + .on_hover_text("Show / hide") + .clicked() + { + let k = (env.clone(), name.clone()); + if revealed { + e.revealed.retain(|r| r != &k); + } else { + e.revealed.push(k); + } + acts.push(Action::EnvEditorChanged(e.clone())); + } + } else { + ui.label(""); + } + if ui.small_button("×").clicked() { + remove = Some(i); + } + ui.end_row(); + } + }); + }); + if ui.button("Add variable").clicked() { + let n = (1..) + .map(|i| format!("var{i}")) + .find(|n| !new_rows.iter().any(|r| &r.0 == n)) + .unwrap(); + new_rows.push((n, String::new(), false, false)); + changed = true; + } + if let Some(i) = remove { + new_rows.remove(i); + changed = true; + } + if changed { + apply_rows(&mut e.envs.public, &env, &new_rows, false); + apply_rows(&mut e.envs.private, &env, &new_rows, true); + e.dirty = true; + acts.push(Action::EnvEditorChanged(e.clone())); + } + ui.separator(); + ui.horizontal(|ui| { + if ui.add_enabled(e.dirty, egui::Button::new("Save")).clicked() { + save = true; + } + ui.label(RichText::new("Writes http-client.env.json and http-client.private.env.json.").weak()); + }); + }); + if e.selected != ed.selected { + acts.push(Action::EnvEditorChanged(e.clone())); + } + if save { + acts.push(Action::EnvEditorSave); + } + if !open { + acts.push(Action::EnvEditorClose); + } +} + +/// Writes the editor rows for `env` back into one env file. +fn apply_rows(file: &mut EnvFile, env: &str, rows: &[(String, String, bool, bool)], private: bool) { + let has_rows = rows.iter().any(|r| r.2 == private); + if file.env(env).is_none() && !has_rows { + return; + } + let en = file.env_mut(env); + let old = std::mem::take(&mut en.vars); + for (name, value, p, structured) in rows { + if *p != private || name.trim().is_empty() { + continue; + } + if *structured { + if let Some(v) = old.iter().find(|v| &v.name == name) { + en.vars.push(v.clone()); + } + continue; + } + // Keep the original JSON value (and type) when only the name matches. + let mut v = old + .iter() + .find(|v| &v.name == name) + .cloned() + .unwrap_or_else(|| EnvVar::new(name.clone(), value.clone())); + v.value = value.clone(); + en.vars.push(v); + } +} + +fn quick_open(ctx: &Context, state: &AppState, q: &QuickOpen, acts: &mut Vec) { + let Some(c) = &state.collection else { + acts.push(Action::QuickOpen(None)); + acts.push(Action::Error("Open a collection to quick-open its requests".into())); + return; + }; + let query = q.query.to_lowercase(); + let mut items: Vec<(i32, std::path::PathBuf, usize, String, String)> = c + .all_requests() + .filter_map(|(path, i, r)| { + let name = r.display_name().unwrap_or(&r.url).to_string(); + let hay = format!("{} {} {} {}", c.relative(path).display(), name, r.method, r.url); + let score = fuzzy_score(&hay.to_lowercase(), &query)?; + Some(( + score, + path.clone(), + i, + name, + format!("{} {}", r.method, c.relative(path).display()), + )) + }) + .collect(); + items.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.3.cmp(&b.3))); + items.truncate(50); + let selected = q.selected.min(items.len().saturating_sub(1)); + + let mut next = q.clone(); + let (up, down, enter, esc) = ctx.input_mut(|i| { + ( + i.consume_key(egui::Modifiers::NONE, Key::ArrowUp), + i.consume_key(egui::Modifiers::NONE, Key::ArrowDown), + i.consume_key(egui::Modifiers::NONE, Key::Enter), + i.consume_key(egui::Modifiers::NONE, Key::Escape), + ) + }); + if esc { + acts.push(Action::QuickOpen(None)); + return; + } + if enter { + if let Some(it) = items.get(selected) { + acts.push(Action::OpenRequest { + file: it.1.clone(), + index: it.2, + }); + } + acts.push(Action::QuickOpen(None)); + return; + } + if up { + next.selected = selected.saturating_sub(1); + } + if down { + next.selected = (selected + 1).min(items.len().saturating_sub(1)); + } + + egui::Window::new("Open request") + .title_bar(false) + .anchor(egui::Align2::CENTER_TOP, [0.0, 60.0]) + .fixed_size([520.0, 360.0]) + .show(ctx, |ui| { + let mut text = q.query.clone(); + let r = ui.add( + egui::TextEdit::singleline(&mut text) + .hint_text("Type to find a request…") + .desired_width(f32::INFINITY) + .id_salt("quick-open"), + ); + r.request_focus(); + if r.changed() { + next.query = text; + next.selected = 0; + } + ui.separator(); + egui::ScrollArea::vertical().show(ui, |ui| { + for (i, it) in items.iter().enumerate() { + let resp = ui.selectable_label(i == selected, format!("{} {}", it.3, it.4)); + if i == selected && (up || down) { + resp.scroll_to_me(None); + } + if resp.clicked() { + acts.push(Action::OpenRequest { + file: it.1.clone(), + index: it.2, + }); + acts.push(Action::QuickOpen(None)); + } + } + if items.is_empty() { + ui.label(RichText::new("No matching requests").weak()); + } + }); + }); + if next != *q { + acts.push(Action::QuickOpen(Some(next))); + } +} + +/// Subsequence match; higher is better (consecutive and early matches score +/// more). `None` when not all query characters appear in order. +pub fn fuzzy_score(hay: &str, query: &str) -> Option { + if query.is_empty() { + return Some(0); + } + let mut score = 0; + let mut last: Option = None; + let mut hi = hay.char_indices(); + for qc in query.chars().filter(|c| !c.is_whitespace()) { + loop { + let (i, hc) = hi.next()?; + if hc == qc { + score += match last { + Some(l) if l + hc.len_utf8() == i || l + 1 == i => 5, + _ => 1, + }; + if i < 20 { + score += 1; + } + last = Some(i); + break; + } + } + } + Some(score) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fuzzy() { + assert!(fuzzy_score("users.http create user post", "cru").is_some()); + assert!(fuzzy_score("users.http", "xyz").is_none()); + assert!(fuzzy_score("create user", "create").unwrap() > fuzzy_score("c-r-e-a-t-e", "create").unwrap()); + } + + #[test] + fn env_rows_move_between_files() { + let mut public = EnvFile::parse(r#"{"dev": {"a": "1", "port": 80}}"#, std::path::Path::new("p")).unwrap(); + let mut private = EnvFile::default(); + let rows = vec![ + ("a".to_string(), "1".to_string(), true, false), + ("port".to_string(), "80".to_string(), false, false), + ]; + apply_rows(&mut public, "dev", &rows, false); + apply_rows(&mut private, "dev", &rows, true); + assert_eq!(public.env("dev").unwrap().get("a"), None); + assert_eq!(private.env("dev").unwrap().get("a"), Some("1")); + // The number keeps its JSON type. + assert!(public.to_json().contains("\"port\": 80")); + } +} diff --git a/crates/app/tests/glyphs.rs b/crates/app/tests/glyphs.rs new file mode 100644 index 0000000..7c677b8 --- /dev/null +++ b/crates/app/tests/glyphs.rs @@ -0,0 +1,36 @@ +//! Every non-ASCII character in the UI code must be drawable with the +//! bundled fonts (a missing glyph panics in debug builds). + +#[test] +fn ui_symbols_exist_in_the_bundled_fonts() { + let mut harness = egui_kittest::Harness::new_ui(|_ui| {}); + harness.step(); + let ctx = harness.ctx.clone(); + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/ui"); + let mut missing = Vec::new(); + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + let src = std::fs::read_to_string(&path).unwrap(); + for (n, line) in src.lines().enumerate() { + // Only string literals in code matter, not comments. + if line.trim_start().starts_with("//") { + continue; + } + for c in line.chars().filter(|c| !c.is_ascii()) { + for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { + let ok = ctx.fonts_mut(|f| f.has_glyph(&egui::FontId::new(14.0, family.clone()), c)); + if !ok { + missing.push(format!( + "{c:?} (U+{:04X}) {family:?} at {}:{}", + c as u32, + path.display(), + n + 1 + )); + } + } + } + } + } + missing.dedup(); + assert!(missing.is_empty(), "missing glyphs:\n{}", missing.join("\n")); +} diff --git a/crates/app/tests/render.rs b/crates/app/tests/render.rs new file mode 100644 index 0000000..071c95f --- /dev/null +++ b/crates/app/tests/render.rs @@ -0,0 +1,148 @@ +//! Renders the real UI to PNG files for a visual check. Needs a GPU (or a +//! software Vulkan driver), so it is ignored by default: +//! +//! REQLITE_RENDER_DIR=/tmp/shots cargo test -p reqlite-app --test render -- --ignored + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use egui_kittest::Harness; +use reqlite_app::action::Action; +use reqlite_app::state::{RequestTab, ResponseTab}; +use reqlite_app::ReqliteApp; +use reqlite_core::http::{BodyStore, HttpClient, HttpError, ResolvedRequest, Response, Timings}; +use reqlite_core::CancelToken; + +struct Canned; + +impl HttpClient for Canned { + async fn send(&self, req: ResolvedRequest, _c: CancelToken) -> Result { + let body = r#"{"id":42,"name":"Ada Lovelace","email":"ada@example.com","roles":["admin","author"],"active":true,"manager":null,"stats":{"posts":128,"score":9.75}}"#; + Ok(Response { + status: 200, + reason: "OK".into(), + http_version: "HTTP/2".into(), + headers: vec![ + ("content-type".into(), "application/json; charset=utf-8".into()), + ("cache-control".into(), "no-store".into()), + ("x-request-id".into(), "7f3a9c2e".into()), + ], + size: body.len() as u64, + body: BodyStore::InMemory(Arc::new(body.as_bytes().to_vec())), + timings: Timings { + dns: Duration::from_millis(4), + connect: Duration::from_millis(19), + tls: Duration::from_millis(48), + ttfb: Duration::from_millis(112), + total: Duration::from_millis(118), + }, + effective_url: req.url, + }) + } +} + +fn shoot(h: &mut Harness<'_, ReqliteApp>, name: &str) { + let Ok(dir) = std::env::var("REQLITE_RENDER_DIR") else { + return; + }; + std::fs::create_dir_all(&dir).unwrap(); + for _ in 0..3 { + h.step(); + } + let img = h.render().expect("render"); + img.save(format!("{dir}/{name}.png")).unwrap(); +} + +fn wait(h: &mut Harness<'_, ReqliteApp>, done: impl Fn(&ReqliteApp) -> bool) { + let start = Instant::now(); + while !done(h.state()) { + assert!(start.elapsed() < Duration::from_secs(5)); + h.step(); + std::thread::sleep(Duration::from_millis(10)); + } +} + +#[test] +#[ignore = "needs a GPU; run with --ignored"] +fn screenshots() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().canonicalize().unwrap(); + std::fs::create_dir(root.join("orders")).unwrap(); + std::fs::write( + root.join("users.http"), + "### List users\nGET {{base_url}}/users?limit=20&sort=name\nAccept: application/json\n\n### Create user\n# @name create-user\nPOST {{base_url}}/users\nContent-Type: application/json\nAuthorization: Bearer {{token}}\n\n{\n \"name\": \"Ada\",\n \"team\": \"{{team}}\"\n}\n\n### Delete user\nDELETE {{base_url}}/users/{{id}}\n", + ) + .unwrap(); + std::fs::write( + root.join("orders/orders.http"), + "### Get order\nGET {{base_url}}/orders/1\n", + ) + .unwrap(); + std::fs::write( + root.join("http-client.env.json"), + r#"{"dev": {"base_url": "http://localhost:8080", "team": "core"}, "prod": {"base_url": "https://api.example.com"}}"#, + ) + .unwrap(); + std::fs::write( + root.join("http-client.private.env.json"), + r#"{"dev": {"token": "dev-secret"}}"#, + ) + .unwrap(); + + let app = ReqliteApp::new(None, rt.handle().clone(), Arc::new(Canned), None); + let mut h = Harness::builder() + .with_size(egui::vec2(1280.0, 800.0)) + .wgpu() + .build_ui_state( + |ui, app: &mut ReqliteApp| { + egui_extras::install_image_loaders(ui.ctx()); + app.frame(ui) + }, + app, + ); + shoot(&mut h, "01-welcome"); + + h.state_mut().dispatch(Action::OpenCollection(root.clone())); + wait(&mut h, |a| { + a.state.collection.as_ref().is_some_and(|c| !c.envs.names().is_empty()) + }); + h.state_mut().dispatch(Action::SelectEnv(Some("dev".into()))); + h.state_mut().dispatch(Action::OpenRequest { + file: root.join("users.http"), + index: 1, + }); + let id = h.state().state.active.unwrap(); + h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Body)); + shoot(&mut h, "02-collection-body-tab"); + + h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Headers)); + h.state_mut().dispatch(Action::Send(id)); + wait(&mut h, |a| { + a.state + .active_tab() + .and_then(|t| t.response.as_ref()) + .is_some_and(|r| r.prepared.is_some()) + }); + shoot(&mut h, "03-json-response"); + + h.state_mut().dispatch(Action::SearchOpen(id, true)); + h.state_mut().dispatch(Action::SearchQuery(id, "a".into())); + h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Source)); + shoot(&mut h, "04-source-and-search"); + + h.state_mut().dispatch(Action::SetResponseTab(id, ResponseTab::Timings)); + h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Auth)); + shoot(&mut h, "05-auth-and-timings"); + + h.state_mut().dispatch(Action::OpenEnvEditor); + shoot(&mut h, "06-env-editor"); + h.state_mut().dispatch(Action::EnvEditorClose); + + let mut s = h.state().state.settings.clone(); + s.theme = reqlite_app::settings::ThemeChoice::Light; + h.state_mut().dispatch(Action::SettingsChanged(s)); + h.state_mut().dispatch(Action::SetResponseTab(id, ResponseTab::Body)); + h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Params)); + shoot(&mut h, "07-light-theme"); +} diff --git a/crates/app/tests/ui_smoke.rs b/crates/app/tests/ui_smoke.rs new file mode 100644 index 0000000..584b5e8 --- /dev/null +++ b/crates/app/tests/ui_smoke.rs @@ -0,0 +1,163 @@ +//! UI smoke tests with egui_kittest and a fake async HttpClient. + +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use egui_kittest::kittest::Queryable; +use egui_kittest::Harness; +use reqlite_app::action::Action; +use reqlite_app::ReqliteApp; +use reqlite_core::http::{BodyStore, HttpClient, HttpError, ResolvedRequest, Response, Timings}; +use reqlite_core::CancelToken; + +/// Answers every request with a small JSON body after a short delay. +#[derive(Default)] +struct FakeClient { + seen: Mutex>, +} + +impl HttpClient for FakeClient { + fn send( + &self, + req: ResolvedRequest, + cancel: CancelToken, + ) -> impl std::future::Future> + Send { + self.seen.lock().unwrap().push(req.clone()); + async move { + tokio::select! { + _ = tokio::time::sleep(Duration::from_millis(30)) => {} + _ = cancel.cancelled() => return Err(HttpError::Cancelled), + } + let body = format!("{{\"echo\": \"{}\", \"items\": [1, 2, 3]}}", req.url); + Ok(Response { + status: 200, + reason: "OK".into(), + http_version: "HTTP/1.1".into(), + headers: vec![("content-type".into(), "application/json".into())], + size: body.len() as u64, + body: BodyStore::InMemory(Arc::new(body.into_bytes())), + timings: Timings { + total: Duration::from_millis(30), + ..Default::default() + }, + effective_url: req.url, + }) + } + } +} + +fn harness(rt: &tokio::runtime::Runtime, client: Arc) -> Harness<'static, ReqliteApp> { + let app = ReqliteApp::new(None, rt.handle().clone(), client, None); + Harness::builder() + .with_size(egui::vec2(1100.0, 760.0)) + .build_ui_state(|ui, app: &mut ReqliteApp| app.frame(ui), app) +} + +/// Steps the UI until `done` holds (effects finish on other threads). +fn step_until(h: &mut Harness<'_, ReqliteApp>, what: &str, done: impl Fn(&Harness<'_, ReqliteApp>) -> bool) { + let start = Instant::now(); + while !done(h) { + assert!(start.elapsed() < Duration::from_secs(5), "timed out waiting for {what}"); + h.step(); + std::thread::sleep(Duration::from_millis(10)); + } +} + +#[test] +fn send_a_request_and_see_the_response() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let client = Arc::new(FakeClient::default()); + let mut h = harness(&rt, client.clone()); + h.step(); + // The welcome screen offers a new request. + h.get_by_label("New request (Ctrl+T)").click(); + h.step(); + let id = h.state().state.active.expect("a tab"); + h.state_mut() + .dispatch(Action::UrlEdited(id, "http://example.test/items?limit=3".into())); + h.step(); + + // The URL query shows up in the Params tab. + assert!(h.query_by_label("Params (1)").is_some()); + + h.get_by_label("Send").click(); + step_until(&mut h, "the response", |h| { + h.query_by_label_contains("200 OK").is_some() + }); + step_until(&mut h, "the prepared body", |h| { + h.state() + .state + .active_tab() + .unwrap() + .response + .as_ref() + .unwrap() + .prepared + .is_some() + }); + h.step(); + assert!(h.query_by_label_contains("\"items\"").is_some(), "pretty JSON is shown"); + assert_eq!(client.seen.lock().unwrap()[0].url, "http://example.test/items?limit=3"); + + // Headers and Timings tabs render. + h.get_by_label("Headers (1)").click(); + h.step(); + h.step(); + assert!(h.query_by_label("content-type").is_some()); + h.get_by_label("Timings").click(); + h.step(); + h.step(); + assert!(h.query_by_label("Total").is_some()); +} + +#[test] +fn keyboard_shortcuts_open_and_close_tabs() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let mut h = harness(&rt, Arc::new(FakeClient::default())); + h.step(); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::T); + h.step(); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::T); + h.step(); + assert_eq!(h.state().state.tabs.len(), 2); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::W); + h.step(); + assert_eq!(h.state().state.tabs.len(), 1); +} + +#[test] +fn opens_a_collection_and_shows_its_requests() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join("users.http"), + "### List users\nGET {{base}}/users\n\n### Create user\nPOST {{base}}/users\n", + ) + .unwrap(); + std::fs::write( + dir.path().join("http-client.env.json"), + r#"{"dev": {"base": "http://dev"}}"#, + ) + .unwrap(); + let client = Arc::new(FakeClient::default()); + let mut h = harness(&rt, client.clone()); + h.state_mut().dispatch(Action::OpenCollection(dir.path().to_path_buf())); + step_until(&mut h, "the collection", |h| { + h.state() + .state + .collection + .as_ref() + .is_some_and(|c| !c.envs.names().is_empty()) + }); + h.step(); + h.get_by_label_contains("Create user").click(); + h.step(); + assert_eq!(h.state().state.active_tab().unwrap().title(), "Create user"); + + h.state_mut().dispatch(Action::SelectEnv(Some("dev".into()))); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Enter); + step_until(&mut h, "the response", |h| { + h.query_by_label_contains("200 OK").is_some() + }); + assert_eq!(client.seen.lock().unwrap()[0].url, "http://dev/users"); +} diff --git a/crates/app/tests/watcher.rs b/crates/app/tests/watcher.rs new file mode 100644 index 0000000..1b8978f --- /dev/null +++ b/crates/app/tests/watcher.rs @@ -0,0 +1,78 @@ +//! The file watcher reports external edits to .http files. + +use std::sync::Arc; +use std::time::Duration; + +use reqlite_app::action::Action; +use reqlite_app::effects::{Effect, Runner}; +use reqlite_core::http::{HttpClient, HttpError, ResolvedRequest, Response}; +use reqlite_core::CancelToken; + +struct NoClient; + +impl HttpClient for NoClient { + async fn send(&self, _r: ResolvedRequest, _c: CancelToken) -> Result { + Err(HttpError::Other("unused".into())) + } +} + +#[test] +fn reports_changes_to_http_and_env_files() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().canonicalize().unwrap(); + std::fs::write(root.join("a.http"), "GET /a\n").unwrap(); + let (runner, mut rx) = Runner::new(rt.handle().clone(), None, Arc::new(NoClient), None, 4); + runner.run(Effect::Watch(Some(root.clone()))); + std::thread::sleep(Duration::from_millis(200)); + + std::fs::write(root.join("a.http"), "GET /changed\n").unwrap(); + std::fs::write(root.join("ignored.txt"), "x").unwrap(); + std::fs::create_dir(root.join("sub")).unwrap(); + std::fs::write(root.join("sub/new.http"), "GET /new\n").unwrap(); + std::fs::write(root.join("http-client.env.json"), "{}").unwrap(); + + let mut seen = std::collections::HashMap::new(); + let mut rescan = false; + rt.block_on(async { + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + while seen.len() < 2 || !rescan { + match tokio::time::timeout_at(deadline, rx.recv()).await { + Ok(Some(Action::FileChangedOnDisk { path, text })) => { + seen.insert(path, text); + } + Ok(Some(Action::Rescan)) => rescan = true, + Ok(Some(_)) => {} + _ => break, + } + } + }); + assert_eq!( + seen.get(&root.join("a.http")), + Some(&Some("GET /changed\n".to_string())) + ); + // A new folder triggers a rescan (its files may race the new watch). + assert!(rescan); + assert!(seen.contains_key(&root.join("http-client.env.json"))); + assert!(!seen.contains_key(&root.join("ignored.txt"))); + + std::fs::remove_file(root.join("a.http")).unwrap(); + let deleted = rt.block_on(async { + loop { + match tokio::time::timeout(Duration::from_secs(5), rx.recv()).await { + Ok(Some(Action::FileChangedOnDisk { path, text })) if path == root.join("a.http") => break text, + Ok(Some(_)) => {} + _ => panic!("no delete event"), + } + } + }); + assert_eq!(deleted, None); + + // Stopping the watch stops the events. + runner.run(Effect::Watch(None)); + std::thread::sleep(Duration::from_millis(100)); + while rx.try_recv().is_ok() {} + std::fs::write(root.join("b.http"), "GET /b\n").unwrap(); + std::thread::sleep(Duration::from_millis(400)); + assert!(rx.try_recv().is_err()); +} diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml new file mode 100644 index 0000000..a1e27d4 --- /dev/null +++ b/crates/cli/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "reqlite-cli" +description = "Run .http files from the command line." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +publish.workspace = true + +[[bin]] +name = "reqlite" +path = "src/main.rs" + +[dependencies] +reqlite-core.workspace = true +reqlite-http-curl.workspace = true +anyhow.workspace = true +clap.workspace = true +serde_json.workspace = true +tokio.workspace = true + +[dev-dependencies] +tempfile.workspace = true +wiremock.workspace = true diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs new file mode 100644 index 0000000..a40233d --- /dev/null +++ b/crates/cli/src/main.rs @@ -0,0 +1,280 @@ +//! `reqlite` command line: run requests from `.http` files and import from +//! curl or Postman. + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; +use std::time::{Duration, SystemTime}; + +use anyhow::{bail, Context, Result}; +use clap::{Parser, Subcommand}; +use reqlite_core::cookies::CookieJar; +use reqlite_core::env::{find_env_dir, Environments}; +use reqlite_core::http::{HttpClient, RequestOptions}; +use reqlite_core::httpfile::{render_request, HttpFile}; +use reqlite_core::resolve::resolve_request; +use reqlite_core::CancelToken; +use reqlite_http_curl::CurlClient; + +#[derive(Parser)] +#[command(name = "reqlite", version, about = "Run requests from .http files")] +struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand)] +enum Command { + /// Send the requests in a .http file (all of them, or the one named). + Run { + file: PathBuf, + /// Only run the request with this `@name` or `### title`. + #[arg(long, short)] + name: Option, + /// Environment from http-client.env.json. + #[arg(long, short)] + env: Option, + /// Skip TLS certificate verification. + #[arg(long, short = 'k')] + insecure: bool, + /// Default timeout in seconds (a request's `@timeout` wins). + #[arg(long)] + timeout: Option, + /// Print only the response body. + #[arg(long, short)] + body_only: bool, + /// Pretty-print JSON bodies. + #[arg(long, short)] + pretty: bool, + /// Exit with an error when a response has status >= 400. + #[arg(long, short)] + fail: bool, + }, + /// Print the requests of a .http file as curl commands. + Curl { + file: PathBuf, + #[arg(long, short)] + name: Option, + #[arg(long, short)] + env: Option, + }, + /// Import from other tools. + #[command(subcommand)] + Import(Import), +} + +#[derive(Subcommand)] +enum Import { + /// Convert a curl command to a .http request (printed to stdout). + Curl { + /// The command; read from stdin when omitted. + command: Option, + }, + /// Convert a Postman v2.1 collection into a folder of .http files. + Postman { + collection: PathBuf, + out_dir: PathBuf, + /// Postman environment exports to turn into environments. + #[arg(long = "env")] + envs: Vec, + }, +} + +fn main() -> ExitCode { + let cli = Cli::parse(); + let rt = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .expect("tokio runtime"); + match rt.block_on(run(cli)) { + Ok(code) => code, + Err(e) => { + eprintln!("error: {e:#}"); + ExitCode::FAILURE + } + } +} + +struct Loaded { + file: HttpFile, + base_dir: PathBuf, + envs: Environments, + indices: Vec, +} + +fn load(file: &Path, name: Option<&str>, env: Option<&str>) -> Result { + let text = std::fs::read_to_string(file).with_context(|| format!("reading {}", file.display()))?; + let parsed = HttpFile::parse(text); + let base_dir = file + .parent() + .map(Path::to_path_buf) + .unwrap_or_else(|| PathBuf::from(".")); + let base_dir = if base_dir.as_os_str().is_empty() { + PathBuf::from(".") + } else { + base_dir + }; + let envs = match find_env_dir(&std::fs::canonicalize(&base_dir)?) { + Some(d) => Environments::load(&d)?, + None => Environments::default(), + }; + if let Some(e) = env { + if !envs.names().iter().any(|n| n == e) { + bail!("unknown environment `{e}` (have: {})", envs.names().join(", ")); + } + } + let indices: Vec = match name { + Some(n) => vec![parsed + .find_by_name(n) + .with_context(|| format!("no request named `{n}` in {}", file.display()))?], + None => (0..parsed.request_count()).collect(), + }; + if indices.is_empty() { + bail!("{} has no requests", file.display()); + } + Ok(Loaded { + file: parsed, + base_dir, + envs, + indices, + }) +} + +async fn run(cli: Cli) -> Result { + match cli.command { + Command::Run { + file, + name, + env, + insecure, + timeout, + body_only, + pretty, + fail, + } => { + let l = load(&file, name.as_deref(), env.as_deref())?; + let resolver = l.envs.resolver(env.as_deref(), &l.file.variables()); + let defaults = RequestOptions { + verify_tls: !insecure, + timeout: timeout.map(Duration::from_secs), + ..RequestOptions::default() + }; + let client = CurlClient::new(); + let mut jar = CookieJar::new(); + let mut code = ExitCode::SUCCESS; + let multiple = l.indices.len() > 1; + let mut out = std::io::stdout().lock(); + for i in l.indices { + let req = l.file.request(i).unwrap(); + let label = req + .display_name() + .map(str::to_string) + .unwrap_or_else(|| format!("#{}", i + 1)); + let mut resolved = resolve_request(req, &resolver, &l.base_dir, &defaults) + .with_context(|| format!("request {label}"))?; + if !req.directives.no_cookie_jar { + if let Some(c) = jar.header_for(&resolved.url, SystemTime::now()) { + if !resolved.headers.iter().any(|(n, _)| n.eq_ignore_ascii_case("cookie")) { + resolved.headers.push(("Cookie".into(), c)); + } + } + } + if multiple { + eprintln!("### {label}: {} {}", resolved.method, resolved.url); + } + let url = resolved.url.clone(); + let resp = match client.send(resolved, CancelToken::new()).await { + Ok(r) => r, + Err(e) => { + eprintln!("{label}: {e}"); + code = ExitCode::FAILURE; + continue; + } + }; + if !req.directives.no_cookie_jar { + jar.store(&url, resp.headers_named("set-cookie"), SystemTime::now()); + } + if !body_only { + writeln!(out, "{} {} {}", resp.http_version, resp.status, resp.reason)?; + for (n, v) in &resp.headers { + writeln!(out, "{n}: {v}")?; + } + writeln!(out)?; + } + let body = resp.body.read_all()?; + let printed = if pretty { + serde_json::from_slice::(&body) + .ok() + .and_then(|v| serde_json::to_vec_pretty(&v).ok()) + } else { + None + }; + out.write_all(printed.as_deref().unwrap_or(&body))?; + if !body.ends_with(b"\n") || printed.is_some() { + writeln!(out)?; + } + eprintln!( + "{label}: {} in {} ms, {} bytes", + resp.status, + resp.timings.total.as_millis(), + resp.size + ); + if fail && resp.status >= 400 { + code = ExitCode::FAILURE; + } + } + Ok(code) + } + Command::Curl { file, name, env } => { + let l = load(&file, name.as_deref(), env.as_deref())?; + let resolver = l.envs.resolver(env.as_deref(), &l.file.variables()); + for i in l.indices { + let r = resolve_request( + l.file.request(i).unwrap(), + &resolver, + &l.base_dir, + &RequestOptions::default(), + )?; + println!("{}", reqlite_core::export::curl::to_curl(&r)); + } + Ok(ExitCode::SUCCESS) + } + Command::Import(Import::Curl { command }) => { + let cmd = match command { + Some(c) => c, + None => std::io::read_to_string(std::io::stdin())?, + }; + let req = reqlite_core::import::curl::from_curl(&cmd)?; + print!("{}", render_request(&req, "\n")); + Ok(ExitCode::SUCCESS) + } + Command::Import(Import::Postman { + collection, + out_dir, + envs, + }) => { + let json = std::fs::read_to_string(&collection)?; + let env_texts: Vec = envs.iter().map(std::fs::read_to_string).collect::>()?; + let env_refs: Vec<&str> = env_texts.iter().map(String::as_str).collect(); + let imp = reqlite_core::import::postman::import(&json, &env_refs)?; + for (rel, text) in &imp.files { + let p = out_dir.join(rel); + std::fs::create_dir_all(p.parent().unwrap())?; + std::fs::write(&p, text)?; + println!("wrote {}", p.display()); + } + if let Some(e) = &imp.public_env { + std::fs::write(out_dir.join(reqlite_core::env::PUBLIC_FILE), e)?; + println!("wrote {}", reqlite_core::env::PUBLIC_FILE); + } + if let Some(e) = &imp.private_env { + std::fs::write(out_dir.join(reqlite_core::env::PRIVATE_FILE), e)?; + println!("wrote {} (keep it out of git)", reqlite_core::env::PRIVATE_FILE); + } + for w in &imp.warnings { + eprintln!("warning: {w}"); + } + Ok(ExitCode::SUCCESS) + } + } +} diff --git a/crates/cli/tests/e2e.rs b/crates/cli/tests/e2e.rs new file mode 100644 index 0000000..8120383 --- /dev/null +++ b/crates/cli/tests/e2e.rs @@ -0,0 +1,97 @@ +use std::process::Command; + +use wiremock::matchers::{body_string, header, method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +fn reqlite() -> Command { + Command::new(env!("CARGO_BIN_EXE_reqlite")) +} + +#[tokio::test] +async fn run_uses_env_files_cookies_and_names() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/login")) + .and(body_string("{\"user\": \"ada\"}")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("set-cookie", "session=s1; Path=/") + .set_body_string("{\"ok\":true}"), + ) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path("/me")) + .and(header("cookie", "session=s1")) + .and(header("authorization", "Bearer secret-token")) + .respond_with(ResponseTemplate::new(200).set_body_string("me")) + .mount(&server) + .await; + + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join("http-client.env.json"), + format!( + r#"{{ "dev": {{ "base_url": "{}" }}, "prod": {{ "base_url": "http://unused" }} }}"#, + server.uri() + ), + ) + .unwrap(); + std::fs::write( + dir.path().join("http-client.private.env.json"), + r#"{ "dev": { "token": "secret-token" } }"#, + ) + .unwrap(); + let file = dir.path().join("api.http"); + std::fs::write( + &file, + "### Login\nPOST {{base_url}}/login\nContent-Type: application/json\n\n{\"user\": \"ada\"}\n\n### Me\nGET {{base_url}}/me\nAuthorization: Bearer {{token}}\n", + ) + .unwrap(); + + let out = reqlite() + .args(["run", file.to_str().unwrap(), "--env", "dev", "--fail"]) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + out.status.success(), + "{stdout}\n{}", + String::from_utf8_lossy(&out.stderr) + ); + assert!(stdout.contains("HTTP/1.1 200 OK"), "{stdout}"); + assert!(stdout.contains("{\"ok\":true}")); + assert!(stdout.trim_end().ends_with("me"), "{stdout}"); + + let out = reqlite() + .args([ + "run", + file.to_str().unwrap(), + "--env", + "dev", + "--name", + "Login", + "--body-only", + "--pretty", + ]) + .output() + .unwrap(); + assert_eq!(String::from_utf8_lossy(&out.stdout), "{\n \"ok\": true\n}\n"); + + // Missing variables are reported, not sent. + let out = reqlite().args(["run", file.to_str().unwrap()]).output().unwrap(); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("unknown variable `base_url`")); +} + +#[test] +fn import_curl_prints_http() { + let out = reqlite() + .args(["import", "curl", "curl -X PUT https://x/y -H 'A: b' -d 'z=1'"]) + .output() + .unwrap(); + assert_eq!( + String::from_utf8_lossy(&out.stdout), + "PUT https://x/y\nA: b\nContent-Type: application/x-www-form-urlencoded\n\nz=1\n" + ); +} diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml new file mode 100644 index 0000000..dbdd5df --- /dev/null +++ b/crates/core/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "reqlite-core" +description = "Core model, .http parser and templating for reqlite. No UI, no network, no async runtime." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +publish.workspace = true + +[dependencies] +async-trait.workspace = true +base64.workspace = true +serde.workspace = true +serde_json.workspace = true +shell-words.workspace = true +tempfile.workspace = true +thiserror.workspace = true +uuid.workspace = true + +[dev-dependencies] +insta.workspace = true +tempfile.workspace = true diff --git a/crates/core/src/cancel.rs b/crates/core/src/cancel.rs new file mode 100644 index 0000000..4b6e80c --- /dev/null +++ b/crates/core/src/cancel.rs @@ -0,0 +1,96 @@ +//! A runtime-agnostic cancellation token. +//! +//! It plays the role of `tokio_util::sync::CancellationToken` without pulling +//! Tokio into `core`. It can be polled synchronously (for curl's progress +//! callback) or awaited (for `select!`). + +use std::future::Future; +use std::pin::Pin; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll, Waker}; + +#[derive(Clone, Default)] +pub struct CancelToken { + inner: Arc, +} + +#[derive(Default)] +struct Inner { + cancelled: AtomicBool, + wakers: Mutex>, +} + +impl std::fmt::Debug for CancelToken { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CancelToken") + .field("cancelled", &self.is_cancelled()) + .finish() + } +} + +impl PartialEq for CancelToken { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.inner, &other.inner) + } +} + +impl CancelToken { + pub fn new() -> Self { + Self::default() + } + + pub fn cancel(&self) { + self.inner.cancelled.store(true, Ordering::SeqCst); + let wakers = std::mem::take(&mut *self.inner.wakers.lock().unwrap()); + for w in wakers { + w.wake(); + } + } + + pub fn is_cancelled(&self) -> bool { + self.inner.cancelled.load(Ordering::SeqCst) + } + + /// A future that completes once [`cancel`](Self::cancel) has been called. + pub fn cancelled(&self) -> Cancelled { + Cancelled { token: self.clone() } + } +} + +pub struct Cancelled { + token: CancelToken, +} + +impl Future for Cancelled { + type Output = (); + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { + if self.token.is_cancelled() { + return Poll::Ready(()); + } + let mut wakers = self.token.inner.wakers.lock().unwrap(); + // Re-check under the lock so a concurrent cancel() cannot be missed. + if self.token.is_cancelled() { + return Poll::Ready(()); + } + if !wakers.iter().any(|w| w.will_wake(cx.waker())) { + wakers.push(cx.waker().clone()); + } + Poll::Pending + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cancel_is_shared_between_clones() { + let a = CancelToken::new(); + let b = a.clone(); + assert!(!b.is_cancelled()); + a.cancel(); + assert!(b.is_cancelled()); + } +} diff --git a/crates/core/src/collection.rs b/crates/core/src/collection.rs new file mode 100644 index 0000000..efe3f43 --- /dev/null +++ b/crates/core/src/collection.rs @@ -0,0 +1,139 @@ +//! A collection is a folder of `.http` files. Scanning builds the sidebar +//! tree (folder → file → requests) and parses every file. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use crate::httpfile::HttpFile; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Node { + Folder { + name: String, + path: PathBuf, + children: Vec, + }, + File { + name: String, + path: PathBuf, + }, +} + +impl Node { + pub fn name(&self) -> &str { + match self { + Node::Folder { name, .. } | Node::File { name, .. } => name, + } + } + + pub fn path(&self) -> &Path { + match self { + Node::Folder { path, .. } | Node::File { path, .. } => path, + } + } +} + +#[derive(Debug, Clone)] +pub struct Collection { + pub root: PathBuf, + pub tree: Node, + /// Parsed files by absolute path. + pub files: BTreeMap, +} + +pub fn is_http_file(path: &Path) -> bool { + matches!(path.extension().and_then(|e| e.to_str()), Some("http" | "rest")) +} + +fn skip_dir(name: &str) -> bool { + name.starts_with('.') || matches!(name, "node_modules" | "target") +} + +/// Scans `root` recursively. Folders without `.http` files are left out. +pub fn scan(root: &Path) -> std::io::Result { + let mut files = BTreeMap::new(); + let tree = scan_dir(root, &mut files)?.unwrap_or_else(|| Node::Folder { + name: dir_name(root), + path: root.to_path_buf(), + children: Vec::new(), + }); + Ok(Collection { + root: root.to_path_buf(), + tree, + files, + }) +} + +fn dir_name(p: &Path) -> String { + p.file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| p.display().to_string()) +} + +fn scan_dir(dir: &Path, files: &mut BTreeMap) -> std::io::Result> { + let mut entries: Vec<_> = std::fs::read_dir(dir)?.filter_map(Result::ok).collect(); + entries.sort_by_key(|e| e.file_name().to_string_lossy().to_lowercase()); + let mut folders = Vec::new(); + let mut leaves = Vec::new(); + for e in entries { + let path = e.path(); + let name = e.file_name().to_string_lossy().into_owned(); + let Ok(ft) = e.file_type() else { continue }; + if ft.is_dir() { + if skip_dir(&name) { + continue; + } + if let Some(n) = scan_dir(&path, files)? { + folders.push(n); + } + } else if is_http_file(&path) { + let text = std::fs::read_to_string(&path)?; + files.insert(path.clone(), HttpFile::parse(text)); + leaves.push(Node::File { name, path }); + } + } + if folders.is_empty() && leaves.is_empty() { + return Ok(None); + } + folders.extend(leaves); + Ok(Some(Node::Folder { + name: dir_name(dir), + path: dir.to_path_buf(), + children: folders, + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn scans_folders_files_and_requests() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + std::fs::write( + root.join("users.http"), + "### List\nGET /users\n\n### Get\nGET /users/1\n", + ) + .unwrap(); + std::fs::create_dir_all(root.join("orders/payloads")).unwrap(); + std::fs::write(root.join("orders/create.http"), "POST /orders\n").unwrap(); + std::fs::write(root.join("orders/payloads/order.json"), "{}").unwrap(); + std::fs::create_dir(root.join(".git")).unwrap(); + std::fs::write(root.join(".git/x.http"), "GET /").unwrap(); + std::fs::create_dir(root.join("empty")).unwrap(); + + let c = scan(root).unwrap(); + let Node::Folder { children, .. } = &c.tree else { + panic!() + }; + let names: Vec<&str> = children.iter().map(Node::name).collect(); + assert_eq!(names, vec!["orders", "users.http"]); + let Node::Folder { children: orders, .. } = &children[0] else { + panic!() + }; + assert_eq!(orders.len(), 1); + assert_eq!(c.files.len(), 2); + assert_eq!(c.files[&root.join("users.http")].request_count(), 2); + } +} diff --git a/crates/core/src/cookies.rs b/crates/core/src/cookies.rs new file mode 100644 index 0000000..a6d070f --- /dev/null +++ b/crates/core/src/cookies.rs @@ -0,0 +1,281 @@ +//! A small in-memory cookie jar (one per collection in the app). + +use std::time::{Duration, SystemTime}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Cookie { + pub name: String, + pub value: String, + pub domain: String, + /// Set without a `Domain` attribute: only sent to exactly this host. + pub host_only: bool, + pub path: String, + pub secure: bool, + pub http_only: bool, + pub expires: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct CookieJar { + cookies: Vec, +} + +/// The parts of a URL the jar needs. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UrlParts { + pub scheme: String, + pub host: String, + pub path: String, +} + +pub fn url_parts(url: &str) -> Option { + let (scheme, rest) = url.split_once("://")?; + let end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); + let authority = &rest[..end]; + let host_port = authority.rsplit_once('@').map(|(_, h)| h).unwrap_or(authority); + let host = if host_port.starts_with('[') { + host_port.split(']').next().unwrap_or("").trim_start_matches('[') + } else { + host_port.split(':').next().unwrap_or("") + }; + let path_q = &rest[end..]; + let path = path_q.split(['?', '#']).next().unwrap_or(""); + Some(UrlParts { + scheme: scheme.to_ascii_lowercase(), + host: host.to_ascii_lowercase(), + path: if path.is_empty() { "/".into() } else { path.into() }, + }) +} + +fn default_path(path: &str) -> String { + match path.rfind('/') { + Some(0) | None => "/".into(), + Some(i) => path[..i].into(), + } +} + +fn domain_matches(host: &str, domain: &str) -> bool { + host == domain || (host.ends_with(domain) && host[..host.len() - domain.len()].ends_with('.')) +} + +fn path_matches(req: &str, cookie: &str) -> bool { + req == cookie || (req.starts_with(cookie) && (cookie.ends_with('/') || req[cookie.len()..].starts_with('/'))) +} + +impl CookieJar { + pub fn new() -> Self { + Self::default() + } + + pub fn cookies(&self) -> &[Cookie] { + &self.cookies + } + + pub fn clear(&mut self) { + self.cookies.clear(); + } + + pub fn remove(&mut self, index: usize) { + if index < self.cookies.len() { + self.cookies.remove(index); + } + } + + /// Stores cookies from the `Set-Cookie` headers of a response to `url`. + pub fn store<'a>(&mut self, url: &str, set_cookies: impl IntoIterator, now: SystemTime) { + let Some(u) = url_parts(url) else { return }; + for sc in set_cookies { + if let Some(c) = parse_set_cookie(sc, &u, now) { + self.cookies + .retain(|o| !(o.name == c.name && o.domain == c.domain && o.path == c.path)); + if c.expires.is_none_or(|e| e > now) { + self.cookies.push(c); + } + } + } + } + + /// The `Cookie` header value for a request to `url`, if any cookie applies. + pub fn header_for(&self, url: &str, now: SystemTime) -> Option { + let u = url_parts(url)?; + let mut matching: Vec<&Cookie> = self + .cookies + .iter() + .filter(|c| { + c.expires.is_none_or(|e| e > now) + && (!c.secure || u.scheme == "https") + && if c.host_only { + u.host == c.domain + } else { + domain_matches(&u.host, &c.domain) + } + && path_matches(&u.path, &c.path) + }) + .collect(); + if matching.is_empty() { + return None; + } + // Longer paths first (RFC 6265 5.4). + matching.sort_by_key(|c| std::cmp::Reverse(c.path.len())); + Some( + matching + .iter() + .map(|c| format!("{}={}", c.name, c.value)) + .collect::>() + .join("; "), + ) + } +} + +fn parse_set_cookie(s: &str, u: &UrlParts, now: SystemTime) -> Option { + let mut parts = s.split(';'); + let (name, value) = parts.next()?.split_once('=')?; + let name = name.trim(); + if name.is_empty() { + return None; + } + let mut c = Cookie { + name: name.into(), + value: value.trim().trim_matches('"').into(), + domain: u.host.clone(), + host_only: true, + path: default_path(&u.path), + secure: false, + http_only: false, + expires: None, + }; + let mut max_age_set = false; + for attr in parts { + let (k, v) = attr.split_once('=').unwrap_or((attr, "")); + let (k, v) = (k.trim().to_ascii_lowercase(), v.trim()); + match k.as_str() { + "domain" if !v.is_empty() => { + let d = v.trim_start_matches('.').to_ascii_lowercase(); + if !domain_matches(&u.host, &d) { + return None; // a host can't set cookies for another domain + } + c.domain = d; + c.host_only = false; + } + "path" if v.starts_with('/') => c.path = v.into(), + "secure" => c.secure = true, + "httponly" => c.http_only = true, + "max-age" => { + if let Ok(n) = v.parse::() { + max_age_set = true; + c.expires = Some(if n <= 0 { + SystemTime::UNIX_EPOCH + } else { + now + Duration::from_secs(n as u64) + }); + } + } + "expires" if !max_age_set => { + if let Some(t) = parse_http_date(v) { + c.expires = Some(t); + } + } + _ => {} + } + } + Some(c) +} + +/// Parses `Sun, 06 Nov 1994 08:49:37 GMT` (and the `-` separated variant). +pub fn parse_http_date(s: &str) -> Option { + let s = s.replace('-', " "); + let mut it = s.split_whitespace(); + let first = it.next()?; + let day: i64 = if first.ends_with(',') { it.next()? } else { first }.parse().ok()?; + let month = match &it.next()?.to_ascii_lowercase()[..3] { + "jan" => 1, + "feb" => 2, + "mar" => 3, + "apr" => 4, + "may" => 5, + "jun" => 6, + "jul" => 7, + "aug" => 8, + "sep" => 9, + "oct" => 10, + "nov" => 11, + "dec" => 12, + _ => return None, + }; + let mut year: i64 = it.next()?.parse().ok()?; + if year < 100 { + year += if year < 70 { 2000 } else { 1900 }; + } + let hms: Vec = it.next()?.split(':').filter_map(|p| p.parse().ok()).collect(); + let [h, m, sec] = hms[..] else { return None }; + // Days from civil (Howard Hinnant). + let y = if month <= 2 { year - 1 } else { year }; + let era = y.div_euclid(400); + let yoe = y - era * 400; + let mp = (month + 9) % 12; + let doy = (153 * mp + 2) / 5 + day - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + let days = era * 146_097 + doe - 719_468; + let secs = days * 86_400 + h * 3600 + m * 60 + sec; + (secs >= 0).then(|| SystemTime::UNIX_EPOCH + Duration::from_secs(secs as u64)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn now() -> SystemTime { + SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000) + } + + #[test] + fn stores_and_sends_matching_cookies() { + let mut jar = CookieJar::new(); + jar.store( + "https://api.example.com/v1/login", + [ + "session=abc; Path=/; HttpOnly", + "pref=dark; Domain=example.com; Path=/v1", + "sec=1; Secure", + "evil=1; Domain=other.com", + ], + now(), + ); + assert_eq!(jar.cookies().len(), 3); + assert_eq!( + jar.header_for("https://api.example.com/v1/users", now()).as_deref(), + Some("pref=dark; sec=1; session=abc") + ); + assert_eq!( + jar.header_for("http://www.example.com/v1/x", now()).as_deref(), + Some("pref=dark") + ); + assert_eq!(jar.header_for("http://other.com/", now()), None); + } + + #[test] + fn expiry_and_deletion() { + let mut jar = CookieJar::new(); + jar.store( + "http://h/", + ["a=1; Max-Age=10", "b=2; Expires=Wed, 21 Oct 2015 07:28:00 GMT"], + now(), + ); + assert_eq!(jar.header_for("http://h/", now()).as_deref(), Some("a=1")); + assert_eq!(jar.header_for("http://h/", now() + Duration::from_secs(11)), None); + jar.store("http://h/", ["a=1; Max-Age=0"], now()); + assert!(jar.cookies().is_empty()); + } + + #[test] + fn http_dates() { + assert_eq!( + parse_http_date("Sun, 06 Nov 1994 08:49:37 GMT"), + Some(SystemTime::UNIX_EPOCH + Duration::from_secs(784_111_777)) + ); + assert_eq!( + parse_http_date("Sunday, 06-Nov-94 08:49:37 GMT"), + Some(SystemTime::UNIX_EPOCH + Duration::from_secs(784_111_777)) + ); + } +} diff --git a/crates/core/src/env.rs b/crates/core/src/env.rs new file mode 100644 index 0000000..1bc77f2 --- /dev/null +++ b/crates/core/src/env.rs @@ -0,0 +1,372 @@ +//! `http-client.env.json` and `http-client.private.env.json`. +//! +//! Both files have the shape `{ "env": { "var": "value" } }`. The special +//! `$shared` environment applies to every environment (JetBrains convention). +//! Non-string values (numbers, booleans, objects such as JetBrains' +//! `SSLConfiguration`) are kept and written back unchanged. + +use std::path::{Path, PathBuf}; + +use serde_json::{Map, Value}; + +use crate::template::{Resolver, VarSource}; + +pub const PUBLIC_FILE: &str = "http-client.env.json"; +pub const PRIVATE_FILE: &str = "http-client.private.env.json"; +pub const SHARED_ENV: &str = "$shared"; + +#[derive(Debug, thiserror::Error)] +pub enum EnvError { + #[error("{path}: {source}")] + Io { path: PathBuf, source: std::io::Error }, + #[error("{path}: {source}")] + Json { path: PathBuf, source: serde_json::Error }, + #[error("{path}: expected an object of environments")] + Shape { path: PathBuf }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EnvVar { + pub name: String, + pub value: String, + /// The original JSON value when it was not a plain string. + original: Option, +} + +impl EnvVar { + pub fn new(name: impl Into, value: impl Into) -> Self { + Self { + name: name.into(), + value: value.into(), + original: None, + } + } + + /// Objects and arrays aren't variables; they're shown read-only. + pub fn is_structured(&self) -> bool { + matches!(self.original, Some(Value::Object(_) | Value::Array(_))) + } + + fn to_json(&self) -> Value { + match &self.original { + Some(v) if scalar_string(v) == self.value || self.is_structured() => v.clone(), + _ => Value::String(self.value.clone()), + } + } +} + +fn scalar_string(v: &Value) -> String { + match v { + Value::String(s) => s.clone(), + Value::Null => String::new(), + other => other.to_string(), + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Environment { + pub name: String, + pub vars: Vec, +} + +impl Environment { + pub fn get(&self, name: &str) -> Option<&str> { + self.vars + .iter() + .find(|v| v.name == name && !v.is_structured()) + .map(|v| v.value.as_str()) + } + + pub fn set(&mut self, name: &str, value: impl Into) { + let value = value.into(); + match self.vars.iter_mut().find(|v| v.name == name) { + Some(v) => v.value = value, + None => self.vars.push(EnvVar::new(name, value)), + } + } +} + +/// The contents of one env file. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct EnvFile { + pub envs: Vec, +} + +impl EnvFile { + pub fn parse(text: &str, path: &Path) -> Result { + let value: Value = serde_json::from_str(text).map_err(|source| EnvError::Json { + path: path.to_path_buf(), + source, + })?; + let Value::Object(map) = value else { + return Err(EnvError::Shape { + path: path.to_path_buf(), + }); + }; + let mut envs = Vec::new(); + for (name, vars) in map { + let Value::Object(vars) = vars else { + return Err(EnvError::Shape { + path: path.to_path_buf(), + }); + }; + envs.push(Environment { + name, + vars: vars + .into_iter() + .map(|(k, v)| EnvVar { + name: k, + value: scalar_string(&v), + original: (!v.is_string()).then_some(v), + }) + .collect(), + }); + } + Ok(Self { envs }) + } + + pub fn to_json(&self) -> String { + let mut root = Map::new(); + for env in &self.envs { + let mut vars = Map::new(); + for v in &env.vars { + vars.insert(v.name.clone(), v.to_json()); + } + root.insert(env.name.clone(), Value::Object(vars)); + } + let mut s = serde_json::to_string_pretty(&Value::Object(root)).unwrap(); + s.push('\n'); + s + } + + pub fn env(&self, name: &str) -> Option<&Environment> { + self.envs.iter().find(|e| e.name == name) + } + + pub fn env_mut(&mut self, name: &str) -> &mut Environment { + if let Some(i) = self.envs.iter().position(|e| e.name == name) { + return &mut self.envs[i]; + } + self.envs.push(Environment { + name: name.to_string(), + vars: Vec::new(), + }); + self.envs.last_mut().unwrap() + } + + /// Variables of `env` with `$shared` underneath. + fn vars_for(&self, env: &str) -> Vec<(String, String)> { + let mut out: Vec<(String, String)> = Vec::new(); + for e in [SHARED_ENV, env] { + if let Some(e) = self.env(e) { + for v in e.vars.iter().filter(|v| !v.is_structured()) { + out.retain(|(n, _)| n != &v.name); + out.push((v.name.clone(), v.value.clone())); + } + } + } + out + } +} + +/// Both env files of a collection. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Environments { + pub public: EnvFile, + pub private: EnvFile, +} + +impl Environments { + /// Loads the env files in `dir`. Missing files are treated as empty. + pub fn load(dir: &Path) -> Result { + let read = |name: &str| -> Result { + let path = dir.join(name); + match std::fs::read_to_string(&path) { + Ok(text) if text.trim().is_empty() => Ok(EnvFile::default()), + Ok(text) => EnvFile::parse(&text, &path), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(EnvFile::default()), + Err(source) => Err(EnvError::Io { path, source }), + } + }; + Ok(Self { + public: read(PUBLIC_FILE)?, + private: read(PRIVATE_FILE)?, + }) + } + + /// Environment names from both files, in file order, without `$shared`. + pub fn names(&self) -> Vec { + let mut names: Vec = Vec::new(); + for e in self.public.envs.iter().chain(&self.private.envs) { + if e.name != SHARED_ENV && !names.contains(&e.name) { + names.push(e.name.clone()); + } + } + names + } + + pub fn is_private(&self, env: &str, var: &str) -> bool { + [env, SHARED_ENV] + .iter() + .any(|e| self.private.env(e).and_then(|e| e.get(var)).is_some()) + } + + /// Builds a resolver for `env` (or no environment) plus file variables. + pub fn resolver(&self, env: Option<&str>, file_vars: &[(String, String)]) -> Resolver { + let env = env.unwrap_or(SHARED_ENV); + Resolver::new() + .with_layer(VarSource::PrivateEnv, self.private.vars_for(env)) + .with_layer(VarSource::PublicEnv, self.public.vars_for(env)) + .with_layer(VarSource::File, file_vars.iter().cloned()) + } +} + +/// The directory whose env files apply to a `.http` file in `start`: the +/// nearest of `start` and its ancestors that has an env file. +pub fn find_env_dir(start: &Path) -> Option { + start + .ancestors() + .find(|d| d.join(PUBLIC_FILE).is_file() || d.join(PRIVATE_FILE).is_file()) + .map(Path::to_path_buf) +} + +/// Whether a `.gitignore` in `dir` or one of its parents (up to the +/// repository root) ignores the private env file. +pub fn private_file_ignored(dir: &Path) -> bool { + let mut cur = Some(dir); + while let Some(d) = cur { + if let Ok(text) = std::fs::read_to_string(d.join(".gitignore")) { + if text.lines().any(|l| gitignore_matches(l.trim(), PRIVATE_FILE)) { + return true; + } + } + if d.join(".git").exists() { + break; + } + cur = d.parent(); + } + false +} + +fn gitignore_matches(pattern: &str, file: &str) -> bool { + if pattern.is_empty() || pattern.starts_with('#') || pattern.starts_with('!') { + return false; + } + let p = pattern.trim_start_matches("**/").trim_start_matches('/'); + glob(p, file) +} + +/// Minimal glob with `*` and `?`. +fn glob(p: &str, s: &str) -> bool { + let (p, s) = (p.as_bytes(), s.as_bytes()); + let (mut pi, mut si, mut star, mut mark) = (0, 0, None, 0); + while si < s.len() { + if pi < p.len() && (p[pi] == b'?' || p[pi] == s[si]) { + pi += 1; + si += 1; + } else if pi < p.len() && p[pi] == b'*' { + star = Some(pi); + mark = si; + pi += 1; + } else if let Some(st) = star { + pi = st + 1; + mark += 1; + si = mark; + } else { + return false; + } + } + p[pi..].iter().all(|&c| c == b'*') +} + +/// Text to append to a `.gitignore` so the private env file is ignored. +pub fn gitignore_addition(existing: &str) -> String { + let mut s = String::new(); + if !existing.is_empty() && !existing.ends_with('\n') { + s.push('\n'); + } + s.push_str(PRIVATE_FILE); + s.push('\n'); + s +} + +#[cfg(test)] +mod tests { + use super::*; + + const PUBLIC: &str = r#"{ + "$shared": { "version": "v1", "base_url": "http://shared" }, + "dev": { "base_url": "http://localhost:8080", "port": 8080, "SSLConfiguration": { "verifyHostCertificate": false } }, + "prod": { "base_url": "https://api.example.com" } +}"#; + const PRIVATE: &str = r#"{ "dev": { "token": "dev-secret" }, "prod": { "token": "prod-secret" } }"#; + + fn envs() -> Environments { + Environments { + public: EnvFile::parse(PUBLIC, Path::new("pub")).unwrap(), + private: EnvFile::parse(PRIVATE, Path::new("priv")).unwrap(), + } + } + + #[test] + fn names_skip_shared() { + assert_eq!(envs().names(), vec!["dev", "prod"]); + } + + #[test] + fn resolves_with_shared_and_private() { + let r = envs().resolver(Some("dev"), &[("file_var".into(), "{{version}}".into())]); + assert_eq!( + r.resolve("{{base_url}}/{{version}}/{{port}}?t={{token}}&f={{file_var}}") + .unwrap(), + "http://localhost:8080/v1/8080?t=dev-secret&f=v1" + ); + assert!(r.resolve("{{SSLConfiguration}}").is_err()); + assert!(envs().is_private("dev", "token")); + assert!(!envs().is_private("dev", "base_url")); + } + + #[test] + fn write_keeps_non_string_values() { + let mut f = EnvFile::parse(PUBLIC, Path::new("pub")).unwrap(); + let again = EnvFile::parse(&f.to_json(), Path::new("pub")).unwrap(); + assert_eq!(f, again); + assert!(f.to_json().contains("\"port\": 8080")); + f.env_mut("dev").set("port", "9090"); + assert!(f.to_json().contains("\"port\": \"9090\"")); + f.env_mut("staging").set("base_url", "http://staging"); + assert!(f.to_json().contains("\"staging\": {")); + } + + #[test] + fn gitignore_patterns() { + for p in [ + "http-client.private.env.json", + "/http-client.private.env.json", + "**/http-client.private.env.json", + "*.private.env.json", + "*private*", + ] { + assert!(gitignore_matches(p, PRIVATE_FILE), "{p}"); + } + for p in [ + "# http-client.private.env.json", + "*.http", + "!http-client.private.env.json", + "", + ] { + assert!(!gitignore_matches(p, PRIVATE_FILE), "{p}"); + } + } + + #[test] + fn gitignore_lookup_walks_up_to_repo_root() { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join(".git")).unwrap(); + let sub = dir.path().join("api"); + std::fs::create_dir(&sub).unwrap(); + assert!(!private_file_ignored(&sub)); + std::fs::write(dir.path().join(".gitignore"), "target\n*.private.env.json\n").unwrap(); + assert!(private_file_ignored(&sub)); + } +} diff --git a/crates/core/src/export/curl.rs b/crates/core/src/export/curl.rs new file mode 100644 index 0000000..da56349 --- /dev/null +++ b/crates/core/src/export/curl.rs @@ -0,0 +1,135 @@ +//! "Copy as curl": a POSIX shell command from a [`ResolvedRequest`]. + +use crate::http::{Proxy, ResolvedBody, ResolvedPartBody, ResolvedRequest}; + +/// Quotes a word for POSIX shells. +pub fn shell_quote(s: &str) -> String { + if !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "-_./:=@%+,".contains(c)) { + return s.to_string(); + } + format!("'{}'", s.replace('\'', "'\\''")) +} + +pub fn to_curl(req: &ResolvedRequest) -> String { + let mut args: Vec = vec!["curl".into()]; + let has_body = !matches!(req.body, ResolvedBody::None); + let implied = matches!( + (&req.body, req.method.as_str()), + (ResolvedBody::None, "GET") + | ( + ResolvedBody::Bytes(_) | ResolvedBody::File(_) | ResolvedBody::Multipart(_), + "POST" + ) + ); + if req.method == "HEAD" && !has_body { + args.push("--head".into()); + } else if !implied { + args.push("-X".into()); + args.push(req.method.clone()); + } + args.push(shell_quote(&req.url)); + for (n, v) in &req.headers { + args.push("-H".into()); + args.push(shell_quote(&format!("{n}: {v}"))); + } + match &req.body { + ResolvedBody::None => {} + ResolvedBody::Bytes(b) => { + args.push("--data-raw".into()); + args.push(shell_quote(&String::from_utf8_lossy(b))); + } + ResolvedBody::File(p) => { + args.push("--data-binary".into()); + args.push(shell_quote(&format!("@{}", p.display()))); + } + ResolvedBody::Multipart(parts) => { + for p in parts { + let mut v = match &p.body { + ResolvedPartBody::Bytes(b) => format!("{}={}", p.name, String::from_utf8_lossy(b)), + ResolvedPartBody::File(f) => format!("{}=@{}", p.name, f.display()), + }; + if let Some(f) = &p.filename { + v.push_str(&format!(";filename={f}")); + } + if let Some(ct) = &p.content_type { + v.push_str(&format!(";type={ct}")); + } + args.push("-F".into()); + args.push(shell_quote(&v)); + } + } + } + let o = &req.options; + if o.follow_redirects { + args.push("-L".into()); + } + if !o.verify_tls { + args.push("-k".into()); + } + if let Some(t) = o.timeout { + args.push("--max-time".into()); + args.push(format!("{}", t.as_secs_f64())); + } + if let Some(t) = o.connect_timeout { + args.push("--connect-timeout".into()); + args.push(format!("{}", t.as_secs_f64())); + } + match o.http_version.as_deref() { + Some("HTTP/1.1") => args.push("--http1.1".into()), + Some("HTTP/2" | "HTTP/2.0") => args.push("--http2".into()), + _ => {} + } + match &o.proxy { + Proxy::System => {} + Proxy::None => args.push("--noproxy '*'".into()), + Proxy::Manual(p) => { + args.push("-x".into()); + args.push(shell_quote(p)); + } + } + if let Some(ca) = &o.ca_file { + args.push("--cacert".into()); + args.push(shell_quote(&ca.display().to_string())); + } + args.join(" ") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::http::RequestOptions; + + #[test] + fn exports() { + let req = ResolvedRequest { + method: "PUT".into(), + url: "https://x/a?b=1&c=2".into(), + headers: vec![("Content-Type".into(), "application/json".into())], + body: ResolvedBody::Bytes(b"{\"it's\": 1}".to_vec()), + options: RequestOptions { + follow_redirects: false, + ..Default::default() + }, + }; + assert_eq!( + to_curl(&req), + r#"curl -X PUT 'https://x/a?b=1&c=2' -H 'Content-Type: application/json' --data-raw '{"it'\''s": 1}'"# + ); + } + + #[test] + fn round_trips_through_import() { + let req = ResolvedRequest { + method: "POST".into(), + url: "http://localhost/x".into(), + headers: vec![("A".into(), "b c".into())], + body: ResolvedBody::Bytes(b"x=1".to_vec()), + options: RequestOptions::default(), + }; + let r = crate::import::curl::from_curl(&to_curl(&req)).unwrap(); + assert_eq!(r.method, crate::model::Method::Post); + assert_eq!(r.url, "http://localhost/x"); + assert_eq!(r.header("A"), Some("b c")); + assert_eq!(r.body, crate::model::Body::Text("x=1".into())); + } +} diff --git a/crates/core/src/export/mod.rs b/crates/core/src/export/mod.rs new file mode 100644 index 0000000..9ba4a4e --- /dev/null +++ b/crates/core/src/export/mod.rs @@ -0,0 +1,3 @@ +//! Exporting requests to other formats. + +pub mod curl; diff --git a/crates/core/src/http.rs b/crates/core/src/http.rs new file mode 100644 index 0000000..5ce8e01 --- /dev/null +++ b/crates/core/src/http.rs @@ -0,0 +1,276 @@ +//! The transport-facing types and the async [`HttpClient`] trait. +//! +//! [`ResolvedRequest`] is a request after variable substitution. It is the +//! only thing a transport sees, so "copy as curl" can be exact. + +use std::future::Future; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use crate::cancel::CancelToken; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ResolvedRequest { + pub method: String, + pub url: String, + pub headers: Vec<(String, String)>, + pub body: ResolvedBody, + pub options: RequestOptions, +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub enum ResolvedBody { + #[default] + None, + Bytes(Vec), + /// Streamed from disk. + File(PathBuf), + Multipart(Vec), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ResolvedPart { + pub name: String, + pub filename: Option, + pub content_type: Option, + pub body: ResolvedPartBody, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ResolvedPartBody { + Bytes(Vec), + File(PathBuf), +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub enum Proxy { + /// Use the system / environment proxy settings. + #[default] + System, + None, + Manual(String), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RequestOptions { + pub follow_redirects: bool, + pub max_redirects: u32, + pub timeout: Option, + pub connect_timeout: Option, + pub verify_tls: bool, + /// Extra CA bundle (PEM) in addition to the system store. + pub ca_file: Option, + pub proxy: Proxy, + /// `HTTP/1.1` or `HTTP/2` from the request line; `None` lets curl negotiate. + pub http_version: Option, + /// Bodies larger than this are written to a temp file. + pub spill_threshold: u64, +} + +impl Default for RequestOptions { + fn default() -> Self { + Self { + follow_redirects: true, + max_redirects: 20, + timeout: None, + connect_timeout: None, + verify_tls: true, + ca_file: None, + proxy: Proxy::System, + http_version: None, + spill_threshold: 5 * 1024 * 1024, + } + } +} + +/// A response body: in memory under the spill threshold, else a temp file +/// that is deleted when the last clone is dropped. +#[derive(Debug, Clone)] +pub enum BodyStore { + InMemory(Arc>), + TempFile(Arc), +} + +impl BodyStore { + pub fn empty() -> Self { + BodyStore::InMemory(Arc::new(Vec::new())) + } + + /// Reads the whole body (from disk if spilled). + pub fn read_all(&self) -> std::io::Result> { + match self { + BodyStore::InMemory(b) => Ok(b.as_ref().clone()), + BodyStore::TempFile(p) => std::fs::read(&**p), + } + } + + pub fn in_memory(&self) -> Option<&[u8]> { + match self { + BodyStore::InMemory(b) => Some(b), + BodyStore::TempFile(_) => None, + } + } + + pub fn is_spilled(&self) -> bool { + matches!(self, BodyStore::TempFile(_)) + } +} + +/// Cumulative times from the start of the request, as curl reports them. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Timings { + pub dns: Duration, + pub connect: Duration, + pub tls: Duration, + pub ttfb: Duration, + pub total: Duration, +} + +impl Timings { + /// `(label, phase duration)` pairs, each phase on its own. + pub fn phases(&self) -> [(&'static str, Duration); 5] { + let tls_end = self.tls.max(self.connect); + [ + ("DNS lookup", self.dns), + ("TCP connect", self.connect.saturating_sub(self.dns)), + ("TLS handshake", self.tls.saturating_sub(self.connect)), + ("Waiting (TTFB)", self.ttfb.saturating_sub(tls_end)), + ("Download", self.total.saturating_sub(self.ttfb)), + ] + } +} + +#[derive(Debug, Clone)] +pub struct Response { + pub status: u16, + pub reason: String, + pub http_version: String, + pub headers: Vec<(String, String)>, + pub body: BodyStore, + pub timings: Timings, + /// Body size in bytes (as received, after decompression). + pub size: u64, + /// The URL after redirects. + pub effective_url: String, +} + +impl Response { + pub fn header(&self, name: &str) -> Option<&str> { + self.headers + .iter() + .find(|(n, _)| n.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_str()) + } + + pub fn headers_named<'a>(&'a self, name: &'a str) -> impl Iterator { + self.headers + .iter() + .filter(move |(n, _)| n.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_str()) + } + + pub fn content_type(&self) -> &str { + self.header("content-type").unwrap_or("") + } +} + +/// The standard reason phrase for a status code (HTTP/2 has none on the wire). +pub fn canonical_reason(status: u16) -> &'static str { + match status { + 100 => "Continue", + 101 => "Switching Protocols", + 200 => "OK", + 201 => "Created", + 202 => "Accepted", + 203 => "Non-Authoritative Information", + 204 => "No Content", + 205 => "Reset Content", + 206 => "Partial Content", + 207 => "Multi-Status", + 300 => "Multiple Choices", + 301 => "Moved Permanently", + 302 => "Found", + 303 => "See Other", + 304 => "Not Modified", + 307 => "Temporary Redirect", + 308 => "Permanent Redirect", + 400 => "Bad Request", + 401 => "Unauthorized", + 402 => "Payment Required", + 403 => "Forbidden", + 404 => "Not Found", + 405 => "Method Not Allowed", + 406 => "Not Acceptable", + 407 => "Proxy Authentication Required", + 408 => "Request Timeout", + 409 => "Conflict", + 410 => "Gone", + 411 => "Length Required", + 412 => "Precondition Failed", + 413 => "Content Too Large", + 414 => "URI Too Long", + 415 => "Unsupported Media Type", + 416 => "Range Not Satisfiable", + 417 => "Expectation Failed", + 418 => "I'm a teapot", + 422 => "Unprocessable Content", + 425 => "Too Early", + 426 => "Upgrade Required", + 428 => "Precondition Required", + 429 => "Too Many Requests", + 431 => "Request Header Fields Too Large", + 451 => "Unavailable For Legal Reasons", + 500 => "Internal Server Error", + 501 => "Not Implemented", + 502 => "Bad Gateway", + 503 => "Service Unavailable", + 504 => "Gateway Timeout", + 505 => "HTTP Version Not Supported", + _ => "", + } +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum HttpError { + #[error("cancelled")] + Cancelled, + #[error("timed out")] + Timeout, + #[error("invalid URL: {0}")] + InvalidUrl(String), + #[error("could not resolve host: {0}")] + Dns(String), + #[error("could not connect: {0}")] + Connect(String), + #[error("TLS error: {0}")] + Tls(String), + #[error("I/O error: {0}")] + Io(String), + #[error("{0}")] + Other(String), +} + +/// An HTTP transport. Implementations must be cancel-safe: when `cancel` +/// fires, `send` should return [`HttpError::Cancelled`] promptly. +pub trait HttpClient: Send + Sync { + fn send( + &self, + req: ResolvedRequest, + cancel: CancelToken, + ) -> impl Future> + Send; +} + +/// Object-safe version of [`HttpClient`], for `Arc`. +/// Every `HttpClient` implements it. +#[async_trait::async_trait] +pub trait DynHttpClient: Send + Sync { + async fn send_dyn(&self, req: ResolvedRequest, cancel: CancelToken) -> Result; +} + +#[async_trait::async_trait] +impl DynHttpClient for T { + async fn send_dyn(&self, req: ResolvedRequest, cancel: CancelToken) -> Result { + self.send(req, cancel).await + } +} diff --git a/crates/core/src/httpfile/lexer.rs b/crates/core/src/httpfile/lexer.rs new file mode 100644 index 0000000..7cd2650 --- /dev/null +++ b/crates/core/src/httpfile/lexer.rs @@ -0,0 +1,118 @@ +//! Line-level helpers shared by the parser and the writer. + +/// A line without its terminator. +pub(crate) fn content(line: &str) -> &str { + line.strip_suffix('\n') + .map(|l| l.strip_suffix('\r').unwrap_or(l)) + .unwrap_or(line) +} + +pub(crate) fn is_separator(line: &str) -> bool { + line.starts_with("###") +} + +pub(crate) fn separator_title(line: &str) -> Option { + let t = content(line).trim_start_matches('#').trim(); + (!t.is_empty()).then(|| t.to_string()) +} + +pub(crate) fn is_blank(line: &str) -> bool { + content(line).trim().is_empty() +} + +/// The text of a `#` or `//` comment, without the marker. +pub(crate) fn comment_text(line: &str) -> Option<&str> { + let c = content(line).trim_start(); + if let Some(rest) = c.strip_prefix("//") { + Some(rest) + } else { + c.strip_prefix('#') + } +} + +/// `# @name value` → `("name", "value")`. Also accepts `@name=value`. +pub(crate) fn parse_directive(line: &str) -> Option<(String, String)> { + let text = comment_text(line)?.trim_start(); + let rest = text.strip_prefix('@')?; + let end = rest.find(|c: char| c.is_whitespace() || c == '=').unwrap_or(rest.len()); + let name = &rest[..end]; + if name.is_empty() { + return None; + } + let value = rest[end..].trim_start(); + let value = value.strip_prefix('=').unwrap_or(value).trim(); + Some((name.to_string(), value.to_string())) +} + +/// `@name = value` → `("name", "value")`. +pub(crate) fn parse_variable(line: &str) -> Option<(String, String)> { + let rest = content(line).trim_start().strip_prefix('@')?; + let eq = rest.find('=')?; + let name = rest[..eq].trim(); + if name.is_empty() || !name.chars().all(|c| c.is_alphanumeric() || "_-.".contains(c)) { + return None; + } + Some((name.to_string(), rest[eq + 1..].trim().to_string())) +} + +fn is_token_char(c: char) -> bool { + c.is_ascii_alphanumeric() || "!#$%&'*+-.^_`|~".contains(c) +} + +/// `Name: value` → `("Name", "value")`. +pub(crate) fn parse_header(text: &str) -> Option<(String, String)> { + let colon = text.find(':')?; + let name = text[..colon].trim(); + if name.is_empty() || !name.chars().all(is_token_char) { + return None; + } + Some((name.to_string(), text[colon + 1..].trim().to_string())) +} + +/// `# Name: value` → a disabled header. +pub(crate) fn parse_disabled_header(line: &str) -> Option<(String, String)> { + let text = comment_text(line)?.trim_start(); + if text.starts_with('@') { + return None; + } + parse_header(text) +} + +pub(crate) fn is_url_continuation(line: &str) -> bool { + let c = content(line); + let t = c.trim_start(); + if t.starts_with('?') || t.starts_with('&') { + return true; + } + // Indented path segments: JetBrains allows splitting the URL like this. + c.len() != t.len() && t.starts_with('/') && !t.starts_with("//") +} + +pub(crate) fn is_handler_start(line: &str) -> bool { + content(line).starts_with("> ") +} + +pub(crate) fn is_response_ref(line: &str) -> bool { + content(line).starts_with("<> ") +} + +/// Parses a duration directive value: `30`, `30s`, `500 ms`, `2 m`. +pub(crate) fn parse_duration(value: &str) -> Option { + let v = value.trim(); + let split = v.find(|c: char| !c.is_ascii_digit()).unwrap_or(v.len()); + let n: u64 = v[..split].parse().ok()?; + match v[split..].trim() { + "" | "s" | "sec" => Some(std::time::Duration::from_secs(n)), + "ms" => Some(std::time::Duration::from_millis(n)), + "m" | "min" => Some(std::time::Duration::from_secs(n * 60)), + _ => None, + } +} + +pub(crate) fn format_duration(d: std::time::Duration) -> String { + if d.subsec_millis() != 0 { + format!("{} ms", d.as_millis()) + } else { + d.as_secs().to_string() + } +} diff --git a/crates/core/src/httpfile/mod.rs b/crates/core/src/httpfile/mod.rs new file mode 100644 index 0000000..c1a5f70 --- /dev/null +++ b/crates/core/src/httpfile/mod.rs @@ -0,0 +1,289 @@ +//! Lossless `.http` file support (JetBrains HTTP Client / VS Code REST Client). +//! +//! The file is split into blocks at `###` separator lines, and every line of a +//! block is classified ([`LineKind`]) with its byte span. That line list is the +//! concrete syntax tree: concatenating the spans of all blocks gives back the +//! exact input, and editing a request only rewrites its own block. + +mod lexer; +mod parser; +mod writer; + +use std::ops::Range; + +pub use writer::render_request; + +use crate::model::Request; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum LineKind { + /// `### Title` + Separator, + Blank, + Comment, + /// `# @name value` / `// @no-redirect` + Directive, + /// `@name = value` + Variable, + RequestLine, + /// Indented `?a=1`, `&b=2` or `/path` continuation of the URL. + UrlContinuation, + Header, + /// A commented-out header: `# Name: value` + DisabledHeader, + Body, + /// `> {% … %}` (all its lines) or `> ./handler.js`. Kept, never run. + ResponseHandler, + /// `<> ./previous-response.json` + ResponseRef, + /// Something we don't understand; kept verbatim. + Unknown, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Line { + /// Byte range in the file, including the line terminator. + pub span: Range, + pub kind: LineKind, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Block { + /// Byte range in the file. Blocks are contiguous and cover the whole file. + pub span: Range, + pub lines: Vec, + pub request: Option, +} + +/// Identifies a request inside a file: by its name when it has one, and by +/// position otherwise. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct RequestKey { + pub name: Option, + pub index: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HttpFile { + text: String, + blocks: Vec, +} + +impl HttpFile { + pub fn parse(text: impl Into) -> Self { + let text = text.into(); + let blocks = parser::parse_blocks(&text); + Self { text, blocks } + } + + pub fn text(&self) -> &str { + &self.text + } + + /// Writes the file back from its syntax tree. Byte-identical to the input. + pub fn write(&self) -> String { + self.blocks.iter().map(|b| &self.text[b.span.clone()]).collect() + } + + pub fn blocks(&self) -> &[Block] { + &self.blocks + } + + /// The line terminator used by the file (`\r\n` if its first line uses it). + pub fn eol(&self) -> &'static str { + match self.text.find('\n') { + Some(i) if i > 0 && self.text.as_bytes()[i - 1] == b'\r' => "\r\n", + _ => "\n", + } + } + + pub fn requests(&self) -> impl Iterator { + self.blocks.iter().filter_map(|b| b.request.as_ref()) + } + + pub fn request(&self, index: usize) -> Option<&Request> { + self.requests().nth(index) + } + + pub fn request_count(&self) -> usize { + self.requests().count() + } + + pub fn key_of(&self, index: usize) -> Option { + self.request(index).map(|r| RequestKey { + name: r.display_name().map(str::to_string), + index, + }) + } + + /// Finds a request by name (if it has one and it's unique), else by index. + pub fn find(&self, key: &RequestKey) -> Option { + if let Some(name) = &key.name { + let matches: Vec = self + .requests() + .enumerate() + .filter(|(_, r)| r.display_name() == Some(name.as_str())) + .map(|(i, _)| i) + .collect(); + match matches.len() { + 1 => return Some(matches[0]), + 0 => return None, + _ if matches.contains(&key.index) => return Some(key.index), + _ => return Some(matches[0]), + } + } + (key.index < self.request_count()).then_some(key.index) + } + + pub fn find_by_name(&self, name: &str) -> Option { + self.requests().position(|r| r.display_name() == Some(name)) + } + + /// File-level variables (`@name = value`), in file order. + pub fn variables(&self) -> Vec<(String, String)> { + let mut vars = Vec::new(); + for block in &self.blocks { + for line in &block.lines { + if line.kind == LineKind::Variable { + if let Some(v) = lexer::parse_variable(lexer::content(&self.text[line.span.clone()])) { + vars.push(v); + } + } + } + } + vars + } + + fn request_block_index(&self, index: usize) -> Option { + self.blocks + .iter() + .enumerate() + .filter(|(_, b)| b.request.is_some()) + .nth(index) + .map(|(i, _)| i) + } + + /// The raw text of a request's block (what "copy as .http" copies). + pub fn request_text(&self, index: usize) -> Option<&str> { + let b = &self.blocks[self.request_block_index(index)?]; + Some(&self.text[b.span.clone()]) + } + + /// Returns the file text with request `index` replaced by `new`. Only that + /// request's byte span changes; if `new` has the same content as the + /// current request the text is returned unchanged. + pub fn replace_request(&self, index: usize, new: &Request) -> Option { + let bi = self.request_block_index(index)?; + let block = &self.blocks[bi]; + let old_text = &self.text[block.span.clone()]; + let new_text = writer::rewrite_block(old_text, block, new, self.eol()); + let mut out = String::with_capacity(self.text.len() + new_text.len()); + out.push_str(&self.text[..block.span.start]); + out.push_str(&new_text); + out.push_str(&self.text[block.span.end..]); + Some(out) + } + + /// Returns the file text without request `index`. + pub fn remove_request(&self, index: usize) -> Option { + let bi = self.request_block_index(index)?; + let span = self.blocks[bi].span.clone(); + let mut out = String::with_capacity(self.text.len()); + out.push_str(&self.text[..span.start]); + out.push_str(&self.text[span.end..]); + // Removing the first block can leave a file that starts mid-way + // through nothing in particular; that's fine, the next block starts + // with its own `###` line. + Some(out) + } + + /// Returns the file text with `new` inserted after request `after` + /// (or appended at the end when `after` is `None`). + pub fn insert_request(&self, after: Option, new: &Request) -> String { + let eol = self.eol(); + let mut rendered = render_request(new, eol); + if new.title.is_none() { + // A block needs a separator unless it is the very first one. + rendered = format!("###{eol}{rendered}"); + } + self.insert_request_text(after, &rendered) + } + + /// Inserts raw request text (a whole block, starting with `###`) after + /// request `after`, or at the end. Keeps one blank line between blocks. + pub fn insert_request_text(&self, after: Option, block: &str) -> String { + let eol = self.eol(); + let at = match after.and_then(|i| self.request_block_index(i)) { + Some(bi) => self.blocks[bi].span.end, + None => self.text.len(), + }; + let mut out = String::with_capacity(self.text.len() + block.len() + 4); + out.push_str(&self.text[..at]); + if !out.is_empty() { + if !out.ends_with('\n') { + out.push_str(eol); + } + if !out.ends_with(&format!("{eol}{eol}")) && !out.ends_with("\n\n") { + out.push_str(eol); + } + } + let block = block.trim_end_matches(['\r', '\n']); + out.push_str(block); + out.push_str(eol); + let rest = &self.text[at..]; + if !rest.is_empty() { + out.push_str(eol); + } + out.push_str(rest); + out + } + + /// Trailing blank lines of a block (the spacing before the next block). + fn trailing_blank(&self, bi: usize) -> &str { + let b = &self.blocks[bi]; + let mut start = b.span.end; + for l in b.lines.iter().rev() { + if l.kind != LineKind::Blank { + break; + } + start = l.span.start; + } + &self.text[start..b.span.end] + } + + /// The text of a request's block without its trailing blank lines (what + /// the Source tab shows). + pub fn request_source(&self, index: usize) -> Option<&str> { + let bi = self.request_block_index(index)?; + let b = &self.blocks[bi]; + let trailing = self.trailing_blank(bi).len(); + let text = &self.text[b.span.start..b.span.end - trailing]; + Some(text) + } + + /// Replaces a request's block with `text` (as edited in the Source tab), + /// keeping the original spacing before the next block. + pub fn replace_request_text(&self, index: usize, text: &str) -> Option { + let bi = self.request_block_index(index)?; + let span = self.blocks[bi].span.clone(); + let trailing = self.trailing_blank(bi); + let eol = self.eol(); + let mut out = String::with_capacity(self.text.len() + text.len()); + out.push_str(&self.text[..span.start]); + out.push_str(text); + // A line ending is needed if anything follows (or the old block had one). + let old_core = &self.text[span.start..span.end - trailing.len()]; + if !text.is_empty() + && !text.ends_with('\n') + && (old_core.ends_with('\n') || span.end < self.text.len() || !trailing.is_empty()) + { + out.push_str(eol); + } + out.push_str(trailing); + out.push_str(&self.text[span.end..]); + Some(out) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/core/src/httpfile/parser.rs b/crates/core/src/httpfile/parser.rs new file mode 100644 index 0000000..ed747fc --- /dev/null +++ b/crates/core/src/httpfile/parser.rs @@ -0,0 +1,363 @@ +//! Splits a file into blocks, classifies lines, and extracts requests. + +use std::path::PathBuf; + +use super::lexer::*; +use super::{Block, Line, LineKind}; +use crate::model::{Body, Directives, Header, Method, Part, PartBody, Request, SourceSpan}; + +pub(crate) fn parse_blocks(text: &str) -> Vec { + // Lines with their byte offsets. + let mut lines: Vec<(usize, &str)> = Vec::new(); + let mut off = 0; + for l in text.split_inclusive('\n') { + lines.push((off, l)); + off += l.len(); + } + + // Group into blocks at separator lines. + let mut groups: Vec> = vec![Vec::new()]; + for (o, l) in lines { + if is_separator(l) && !groups.last().unwrap().is_empty() { + groups.push(Vec::new()); + } + groups.last_mut().unwrap().push((o, l)); + } + + groups + .into_iter() + .filter(|g| !g.is_empty()) + .map(|g| parse_block(text, &g)) + .collect() +} + +#[derive(Clone, Copy, PartialEq)] +enum State { + Pre, + AfterRequestLine, + Headers, + Body, + Handler, + Tail, +} + +fn parse_block(text: &str, lines: &[(usize, &str)]) -> Block { + let start = lines[0].0; + let end = lines.last().map(|(o, l)| o + l.len()).unwrap(); + let mut out: Vec = Vec::with_capacity(lines.len()); + let mut state = State::Pre; + + for (i, &(o, l)) in lines.iter().enumerate() { + let kind = if i == 0 && is_separator(l) { + LineKind::Separator + } else { + match state { + State::Pre => { + if is_blank(l) { + LineKind::Blank + } else if parse_directive(l).is_some() { + LineKind::Directive + } else if comment_text(l).is_some() { + LineKind::Comment + } else if parse_variable(l).is_some() { + LineKind::Variable + } else { + state = State::AfterRequestLine; + LineKind::RequestLine + } + } + State::AfterRequestLine | State::Headers => { + if state == State::AfterRequestLine && is_url_continuation(l) { + LineKind::UrlContinuation + } else { + state = State::Headers; + if is_blank(l) { + state = State::Body; + LineKind::Blank + } else if parse_disabled_header(l).is_some() { + LineKind::DisabledHeader + } else if comment_text(l).is_some() { + LineKind::Comment + } else if parse_header(content(l)).is_some() { + LineKind::Header + } else if is_handler_start(l) { + state = handler_state(l); + LineKind::ResponseHandler + } else if is_response_ref(l) { + state = State::Tail; + LineKind::ResponseRef + } else { + LineKind::Unknown + } + } + } + State::Body => { + if is_handler_start(l) { + state = handler_state(l); + LineKind::ResponseHandler + } else if is_response_ref(l) { + state = State::Tail; + LineKind::ResponseRef + } else { + LineKind::Body + } + } + State::Handler => { + if content(l).contains("%}") { + state = State::Tail; + } + LineKind::ResponseHandler + } + State::Tail => { + if is_blank(l) { + LineKind::Blank + } else if is_handler_start(l) { + state = handler_state(l); + LineKind::ResponseHandler + } else if is_response_ref(l) { + LineKind::ResponseRef + } else if comment_text(l).is_some() { + LineKind::Comment + } else { + LineKind::Unknown + } + } + } + }; + out.push(Line { + span: o..o + l.len(), + kind, + }); + } + + // Trailing blank lines after the body are not part of it. + for line in out.iter_mut().rev() { + match line.kind { + LineKind::Body if is_blank(&text[line.span.clone()]) => line.kind = LineKind::Blank, + LineKind::Body => break, + LineKind::Blank | LineKind::ResponseHandler | LineKind::ResponseRef => {} + LineKind::Comment | LineKind::Unknown => {} + _ => break, + } + } + + let request = extract_request(text, &out, start..end); + Block { + span: start..end, + lines: out, + request, + } +} + +fn handler_state(line: &str) -> State { + let c = content(line); + if c.starts_with("> {%") && !c.contains("%}") { + State::Handler + } else { + State::Tail + } +} + +fn extract_request(text: &str, lines: &[Line], span: std::ops::Range) -> Option { + let line_text = |l: &Line| &text[l.span.clone()]; + let rl = lines.iter().find(|l| l.kind == LineKind::RequestLine)?; + + let mut req = Request { + source: SourceSpan { + start: span.start, + end: span.end, + }, + ..Request::default() + }; + + if let Some(first) = lines.first() { + if first.kind == LineKind::Separator { + req.title = separator_title(line_text(first)); + } + } + + for l in lines.iter().filter(|l| l.kind == LineKind::Directive) { + if let Some((name, value)) = parse_directive(line_text(l)) { + apply_directive(&mut req.directives, &mut req.name, &name, &value); + } + } + + // Request line: `METHOD URL [HTTP/x]` or just `URL`. + let tokens: Vec<&str> = content(line_text(rl)).split_whitespace().collect(); + let mut tokens = tokens.as_slice(); + if tokens.len() >= 2 && tokens[tokens.len() - 1].starts_with("HTTP/") { + req.http_version = Some(tokens[tokens.len() - 1].to_string()); + tokens = &tokens[..tokens.len() - 1]; + } + if tokens.len() >= 2 { + if let Some(m) = Method::parse(tokens[0]) { + req.method = m; + tokens = &tokens[1..]; + } + } + let mut url = tokens.join(" "); + for l in lines.iter().filter(|l| l.kind == LineKind::UrlContinuation) { + url.push_str(content(line_text(l)).trim()); + } + req.url = url; + + for l in lines { + match l.kind { + LineKind::Header => { + if let Some((n, v)) = parse_header(content(line_text(l))) { + req.headers.push(Header::new(n, v)); + } + } + LineKind::DisabledHeader => { + if let Some((n, v)) = parse_disabled_header(line_text(l)) { + req.headers.push(Header { + name: n, + value: v, + disabled: true, + }); + } + } + _ => {} + } + } + + let body_lines: Vec<&Line> = lines.iter().filter(|l| l.kind == LineKind::Body).collect(); + if let (Some(first), Some(last)) = (body_lines.first(), body_lines.last()) { + let raw = &text[first.span.start..last.span.end]; + let raw = content(raw); // drop the final terminator only + req.body = parse_body(raw, &req.headers); + } + + Some(req) +} + +pub(crate) fn apply_directive(d: &mut Directives, name_out: &mut Option, name: &str, value: &str) { + match name { + "name" if !value.is_empty() => *name_out = Some(value.to_string()), + "no-redirect" => d.no_redirect = true, + "no-cookie-jar" => d.no_cookie_jar = true, + "no-log" => d.no_log = true, + "timeout" if parse_duration(value).is_some() => d.timeout = parse_duration(value), + "connection-timeout" if parse_duration(value).is_some() => d.connection_timeout = parse_duration(value), + _ => d.other.push((name.to_string(), value.to_string())), + } +} + +fn file_ref(line: &str) -> Option<(PathBuf, bool)> { + let t = line.trim(); + if let Some(p) = t.strip_prefix("<@") { + let p = p.trim(); + return (!p.is_empty()).then(|| (PathBuf::from(p), true)); + } + let p = t.strip_prefix("< ")?.trim(); + (!p.is_empty()).then(|| (PathBuf::from(p), false)) +} + +fn parse_body(raw: &str, headers: &[Header]) -> Body { + let content_type = headers + .iter() + .find(|h| !h.disabled && h.name.eq_ignore_ascii_case("content-type")) + .map(|h| h.value.as_str()) + .unwrap_or(""); + if content_type.to_ascii_lowercase().starts_with("multipart/") { + if let Some(boundary) = boundary_param(content_type) { + if let Some(parts) = parse_multipart(raw, &boundary) { + return Body::Multipart { boundary, parts }; + } + } + } + if !raw.contains('\n') { + if let Some((path, substitute)) = file_ref(raw) { + return Body::FileRef { path, substitute }; + } + } + Body::Text(raw.to_string()) +} + +pub(crate) fn boundary_param(content_type: &str) -> Option { + content_type.split(';').skip(1).find_map(|p| { + let (k, v) = p.split_once('=')?; + k.trim() + .eq_ignore_ascii_case("boundary") + .then(|| v.trim().trim_matches('"').to_string()) + }) +} + +/// Parses the body of a multipart request. Returns `None` if it doesn't look +/// like one (then it's kept as plain text). +fn parse_multipart(raw: &str, boundary: &str) -> Option> { + let delim = format!("--{boundary}"); + let close = format!("--{boundary}--"); + let mut parts = Vec::new(); + let mut lines = raw.split_inclusive('\n').peekable(); + + // Skip anything before the first delimiter (should be nothing). + loop { + let l = lines.next()?; + if content(l).trim_end() == delim { + break; + } + if !is_blank(l) { + return None; + } + } + + loop { + // Part headers. + let mut headers = Vec::new(); + let mut name = None; + let mut filename = None; + loop { + let l = lines.next()?; + if is_blank(l) { + break; + } + let (n, v) = parse_header(content(l))?; + if n.eq_ignore_ascii_case("content-disposition") { + for p in v.split(';').skip(1) { + if let Some((k, val)) = p.split_once('=') { + let val = val.trim().trim_matches('"').to_string(); + match k.trim() { + "name" => name = Some(val), + "filename" => filename = Some(val), + _ => {} + } + } + } + } else { + headers.push(Header::new(n, v)); + } + } + // Part content up to the next delimiter. + let mut body = String::new(); + let mut closed = false; + let mut found = false; + for l in lines.by_ref() { + let c = content(l).trim_end(); + if c == delim || c == close { + closed = c == close; + found = true; + break; + } + body.push_str(l); + } + if !found { + return None; + } + let body = content(&body).to_string(); + let body = match file_ref(&body) { + Some((p, _)) if !body.contains('\n') => PartBody::File(p), + _ => PartBody::Text(body), + }; + parts.push(Part { + name: name?, + filename, + headers, + body, + }); + if closed { + break; + } + } + Some(parts) +} diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__01-simple-get.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__01-simple-get.http.snap new file mode 100644 index 0000000..eb6f5b3 --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__01-simple-get.http.snap @@ -0,0 +1,29 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..28] + RequestLine "GET https://httpbin.org/get\n" + => Request { + name: None, + title: None, + method: Get, + url: "https://httpbin.org/get", + http_version: None, + headers: [], + body: None, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 0, + end: 28, + }, + } + +variables: [] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__02-titles-and-names.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__02-titles-and-names.http.snap new file mode 100644 index 0000000..4b39f17 --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__02-titles-and-names.http.snap @@ -0,0 +1,130 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..73] + Separator "### List users\n" + RequestLine "GET {{base_url}}/users?limit=20\n" + Header "Accept: application/json\n" + Blank "\n" + => Request { + name: None, + title: Some( + "List users", + ), + method: Get, + url: "{{base_url}}/users?limit=20", + http_version: None, + headers: [ + Header { + name: "Accept", + value: "application/json", + disabled: false, + }, + ], + body: None, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 0, + end: 73, + }, + } + +block 1 [73..230] + Separator "### Create user\n" + Directive "# @name create-user\n" + Directive "# @timeout 30\n" + RequestLine "POST {{base_url}}/users\n" + Header "Content-Type: application/json\n" + Header "Authorization: Bearer {{token}}\n" + Blank "\n" + Body "{ \"name\": \"Ada\" }\n" + Blank "\n" + => Request { + name: Some( + "create-user", + ), + title: Some( + "Create user", + ), + method: Post, + url: "{{base_url}}/users", + http_version: None, + headers: [ + Header { + name: "Content-Type", + value: "application/json", + disabled: false, + }, + Header { + name: "Authorization", + value: "Bearer {{token}}", + disabled: false, + }, + ], + body: Text( + "{ \"name\": \"Ada\" }", + ), + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: Some( + 30s, + ), + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 73, + end: 230, + }, + } + +block 2 [230..345] + Separator "### Upload avatar\n" + RequestLine "POST {{base_url}}/users/1/avatar\n" + Header "Content-Type: application/octet-stream\n" + Blank "\n" + Body "< ./payloads/avatar.png\n" + => Request { + name: None, + title: Some( + "Upload avatar", + ), + method: Post, + url: "{{base_url}}/users/1/avatar", + http_version: None, + headers: [ + Header { + name: "Content-Type", + value: "application/octet-stream", + disabled: false, + }, + ], + body: FileRef { + path: "./payloads/avatar.png", + substitute: false, + }, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 230, + end: 345, + }, + } + +variables: [] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__03-file-variables.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__03-file-variables.http.snap new file mode 100644 index 0000000..917aba2 --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__03-file-variables.http.snap @@ -0,0 +1,35 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..131] + Variable "@host = localhost:8080\n" + Variable "@base = http://{{host}}/api\n" + Blank "\n" + Comment "# Comments before the first request\n" + Comment "// and in both styles\n" + Blank "\n" + RequestLine "GET {{base}}/health\n" + => Request { + name: None, + title: None, + method: Get, + url: "{{base}}/health", + http_version: None, + headers: [], + body: None, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 0, + end: 131, + }, + } + +variables: [("host", "localhost:8080"), ("base", "http://{{host}}/api")] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__04-query-continuation.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__04-query-continuation.http.snap new file mode 100644 index 0000000..3ce5ce5 --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__04-query-continuation.http.snap @@ -0,0 +1,42 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..142] + Separator "### Search with params on separate lines\n" + RequestLine "GET https://api.example.com/search\n" + UrlContinuation " ?q=rust\n" + UrlContinuation " &page=2\n" + UrlContinuation " &per_page=50\n" + Header "Accept: application/json\n" + => Request { + name: None, + title: Some( + "Search with params on separate lines", + ), + method: Get, + url: "https://api.example.com/search?q=rust&page=2&per_page=50", + http_version: None, + headers: [ + Header { + name: "Accept", + value: "application/json", + disabled: false, + }, + ], + body: None, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 0, + end: 142, + }, + } + +variables: [] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__05-comments-everywhere.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__05-comments-everywhere.http.snap new file mode 100644 index 0000000..0a43489 --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__05-comments-everywhere.http.snap @@ -0,0 +1,81 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..24] + Comment "# A file-level comment\n" + Blank "\n" +block 1 [24..205] + Separator "### Get thing\n" + Comment "// A comment before the request line\n" + Directive "# @name get-thing\n" + RequestLine "GET https://api.example.com/things/1\n" + DisabledHeader "# X-Debug: true\n" + Header "Accept: application/json\n" + Comment "// a stray comment among headers\n" + Blank "\n" + => Request { + name: Some( + "get-thing", + ), + title: Some( + "Get thing", + ), + method: Get, + url: "https://api.example.com/things/1", + http_version: None, + headers: [ + Header { + name: "X-Debug", + value: "true", + disabled: true, + }, + Header { + name: "Accept", + value: "application/json", + disabled: false, + }, + ], + body: None, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 24, + end: 205, + }, + } + +block 2 [205..291] + Separator "###\n" + Blank "\n" + Comment "# Unnamed request after a bare separator\n" + RequestLine "DELETE https://api.example.com/things/1\n" + => Request { + name: None, + title: None, + method: Delete, + url: "https://api.example.com/things/1", + http_version: None, + headers: [], + body: None, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 205, + end: 291, + }, + } + +variables: [] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__06-multipart.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__06-multipart.http.snap new file mode 100644 index 0000000..d997c68 --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__06-multipart.http.snap @@ -0,0 +1,78 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..349] + Separator "### Upload with form fields\n" + RequestLine "POST https://api.example.com/upload\n" + Header "Content-Type: multipart/form-data; boundary=WebAppBoundary\n" + Blank "\n" + Body "--WebAppBoundary\n" + Body "Content-Disposition: form-data; name=\"description\"\n" + Body "\n" + Body "A picture of a cat\n" + Body "--WebAppBoundary\n" + Body "Content-Disposition: form-data; name=\"file\"; filename=\"cat.png\"\n" + Body "Content-Type: image/png\n" + Body "\n" + Body "< ./cat.png\n" + Body "--WebAppBoundary--\n" + => Request { + name: None, + title: Some( + "Upload with form fields", + ), + method: Post, + url: "https://api.example.com/upload", + http_version: None, + headers: [ + Header { + name: "Content-Type", + value: "multipart/form-data; boundary=WebAppBoundary", + disabled: false, + }, + ], + body: Multipart { + boundary: "WebAppBoundary", + parts: [ + Part { + name: "description", + filename: None, + headers: [], + body: Text( + "A picture of a cat", + ), + }, + Part { + name: "file", + filename: Some( + "cat.png", + ), + headers: [ + Header { + name: "Content-Type", + value: "image/png", + disabled: false, + }, + ], + body: File( + "./cat.png", + ), + }, + ], + }, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 0, + end: 349, + }, + } + +variables: [] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__07-response-handler.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__07-response-handler.http.snap new file mode 100644 index 0000000..27cd867 --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__07-response-handler.http.snap @@ -0,0 +1,92 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..270] + Separator "### Login\n" + RequestLine "POST {{base_url}}/login\n" + Header "Content-Type: application/json\n" + Blank "\n" + Body "{\n" + Body " \"user\": \"ada\",\n" + Body " \"password\": \"{{password}}\"\n" + Body "}\n" + Blank "\n" + ResponseHandler "> {%\n" + ResponseHandler " client.global.set(\"token\", response.body.token);\n" + ResponseHandler " client.test(\"ok\", function() {\n" + ResponseHandler " client.assert(response.status === 200);\n" + ResponseHandler " });\n" + ResponseHandler "%}\n" + Blank "\n" + => Request { + name: None, + title: Some( + "Login", + ), + method: Post, + url: "{{base_url}}/login", + http_version: None, + headers: [ + Header { + name: "Content-Type", + value: "application/json", + disabled: false, + }, + ], + body: Text( + "{\n \"user\": \"ada\",\n \"password\": \"{{password}}\"\n}", + ), + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 0, + end: 270, + }, + } + +block 1 [270..389] + Separator "### Me\n" + RequestLine "GET {{base_url}}/me\n" + Header "Authorization: Bearer {{token}}\n" + Blank "\n" + ResponseHandler "> ./scripts/check-me.js\n" + Blank "\n" + ResponseRef "<> ./responses/me-2024-01-01.json\n" + => Request { + name: None, + title: Some( + "Me", + ), + method: Get, + url: "{{base_url}}/me", + http_version: None, + headers: [ + Header { + name: "Authorization", + value: "Bearer {{token}}", + disabled: false, + }, + ], + body: None, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 270, + end: 389, + }, + } + +variables: [] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__08-http-version.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__08-http-version.http.snap new file mode 100644 index 0000000..e6127b3 --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__08-http-version.http.snap @@ -0,0 +1,71 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..55] + Separator "### HTTP/2\n" + RequestLine "GET https://nghttp2.org/httpbin/get HTTP/2\n" + Blank "\n" + => Request { + name: None, + title: Some( + "HTTP/2", + ), + method: Get, + url: "https://nghttp2.org/httpbin/get", + http_version: Some( + "HTTP/2", + ), + headers: [], + body: None, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 0, + end: 55, + }, + } + +block 1 [55..129] + Separator "### HTTP/1.1 explicit\n" + RequestLine "GET https://example.com/ HTTP/1.1\n" + Header "Host: example.com\n" + => Request { + name: None, + title: Some( + "HTTP/1.1 explicit", + ), + method: Get, + url: "https://example.com/", + http_version: Some( + "HTTP/1.1", + ), + headers: [ + Header { + name: "Host", + value: "example.com", + disabled: false, + }, + ], + body: None, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 55, + end: 129, + }, + } + +variables: [] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__09-url-only.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__09-url-only.http.snap new file mode 100644 index 0000000..d0bb186 --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__09-url-only.http.snap @@ -0,0 +1,56 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..31] + RequestLine "https://example.com/no-method\n" + Blank "\n" + => Request { + name: None, + title: None, + method: Get, + url: "https://example.com/no-method", + http_version: None, + headers: [], + body: None, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 0, + end: 31, + }, + } + +block 1 [31..58] + Separator "###\n" + Blank "\n" + RequestLine "example.com/no-scheme\n" + => Request { + name: None, + title: None, + method: Get, + url: "example.com/no-scheme", + http_version: None, + headers: [], + body: None, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 31, + end: 58, + }, + } + +variables: [] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__10-directives.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__10-directives.http.snap new file mode 100644 index 0000000..18f9166 --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__10-directives.http.snap @@ -0,0 +1,50 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..196] + Separator "### All the directives\n" + Directive "# @name everything\n" + Directive "# @no-redirect\n" + Directive "# @no-cookie-jar\n" + Directive "# @no-log\n" + Directive "# @timeout 600\n" + Directive "# @connection-timeout 2 s\n" + Directive "# @some-future-directive with a value\n" + RequestLine "GET https://example.com/redirect\n" + => Request { + name: Some( + "everything", + ), + title: Some( + "All the directives", + ), + method: Get, + url: "https://example.com/redirect", + http_version: None, + headers: [], + body: None, + directives: Directives { + no_redirect: true, + no_cookie_jar: true, + no_log: true, + timeout: Some( + 600s, + ), + connection_timeout: Some( + 2s, + ), + other: [ + ( + "some-future-directive", + "with a value", + ), + ], + }, + source: SourceSpan { + start: 0, + end: 196, + }, + } + +variables: [] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__11-crlf.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__11-crlf.http.snap new file mode 100644 index 0000000..ba75ab5 --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__11-crlf.http.snap @@ -0,0 +1,72 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..107] + Separator "### Windows line endings\r\n" + RequestLine "POST https://example.com/crlf\r\n" + Header "Content-Type: text/plain\r\n" + Blank "\r\n" + Body "line one\r\n" + Body "line two\r\n" + Blank "\r\n" + => Request { + name: None, + title: Some( + "Windows line endings", + ), + method: Post, + url: "https://example.com/crlf", + http_version: None, + headers: [ + Header { + name: "Content-Type", + value: "text/plain", + disabled: false, + }, + ], + body: Text( + "line one\r\nline two", + ), + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 0, + end: 107, + }, + } + +block 1 [107..145] + Separator "### Second\r\n" + RequestLine "GET https://example.com/\r\n" + => Request { + name: None, + title: Some( + "Second", + ), + method: Get, + url: "https://example.com/", + http_version: None, + headers: [], + body: None, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 107, + end: 145, + }, + } + +variables: [] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__12-no-trailing-newline.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__12-no-trailing-newline.http.snap new file mode 100644 index 0000000..5900a17 --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__12-no-trailing-newline.http.snap @@ -0,0 +1,43 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..91] + Separator "### No trailing newline\n" + RequestLine "POST https://example.com/x\n" + Header "Content-Type: application/json\n" + Blank "\n" + Body "{\"a\": 1}" + => Request { + name: None, + title: Some( + "No trailing newline", + ), + method: Post, + url: "https://example.com/x", + http_version: None, + headers: [ + Header { + name: "Content-Type", + value: "application/json", + disabled: false, + }, + ], + body: Text( + "{\"a\": 1}", + ), + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 0, + end: 91, + }, + } + +variables: [] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__13-graphql.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__13-graphql.http.snap new file mode 100644 index 0000000..12f7afa --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__13-graphql.http.snap @@ -0,0 +1,51 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..169] + Separator "### GraphQL query\n" + RequestLine "POST https://api.github.com/graphql\n" + Header "Content-Type: application/json\n" + Header "Authorization: Bearer {{github_token}}\n" + Blank "\n" + Body "{\n" + Body " \"query\": \"query { viewer { login } }\"\n" + Body "}\n" + => Request { + name: None, + title: Some( + "GraphQL query", + ), + method: Post, + url: "https://api.github.com/graphql", + http_version: None, + headers: [ + Header { + name: "Content-Type", + value: "application/json", + disabled: false, + }, + Header { + name: "Authorization", + value: "Bearer {{github_token}}", + disabled: false, + }, + ], + body: Text( + "{\n \"query\": \"query { viewer { login } }\"\n}", + ), + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 0, + end: 169, + }, + } + +variables: [] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__14-form-urlencoded.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__14-form-urlencoded.http.snap new file mode 100644 index 0000000..0b95a34 --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__14-form-urlencoded.http.snap @@ -0,0 +1,45 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..195] + Separator "### OAuth token\n" + RequestLine "POST https://auth.example.com/oauth/token\n" + Header "Content-Type: application/x-www-form-urlencoded\n" + Blank "\n" + Body "grant_type=client_credentials&\n" + Body "client_id={{client_id}}&\n" + Body "client_secret={{client_secret}}\n" + => Request { + name: None, + title: Some( + "OAuth token", + ), + method: Post, + url: "https://auth.example.com/oauth/token", + http_version: None, + headers: [ + Header { + name: "Content-Type", + value: "application/x-www-form-urlencoded", + disabled: false, + }, + ], + body: Text( + "grant_type=client_credentials&\nclient_id={{client_id}}&\nclient_secret={{client_secret}}", + ), + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 0, + end: 195, + }, + } + +variables: [] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__15-substituted-file.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__15-substituted-file.http.snap new file mode 100644 index 0000000..1f4965a --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__15-substituted-file.http.snap @@ -0,0 +1,44 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..114] + Separator "### Body from a template file\n" + RequestLine "PUT {{base_url}}/orders/42\n" + Header "Content-Type: application/json\n" + Blank "\n" + Body "<@ ./payloads/order.json\n" + => Request { + name: None, + title: Some( + "Body from a template file", + ), + method: Put, + url: "{{base_url}}/orders/42", + http_version: None, + headers: [ + Header { + name: "Content-Type", + value: "application/json", + disabled: false, + }, + ], + body: FileRef { + path: "./payloads/order.json", + substitute: true, + }, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 0, + end: 114, + }, + } + +variables: [] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__16-custom-methods.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__16-custom-methods.http.snap new file mode 100644 index 0000000..69ba962 --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__16-custom-methods.http.snap @@ -0,0 +1,108 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..61] + Separator "### WebDAV\n" + RequestLine "PROPFIND https://dav.example.com/files/\n" + Header "Depth: 1\n" + Blank "\n" + => Request { + name: None, + title: Some( + "WebDAV", + ), + method: Custom( + "PROPFIND", + ), + url: "https://dav.example.com/files/", + http_version: None, + headers: [ + Header { + name: "Depth", + value: "1", + disabled: false, + }, + ], + body: None, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 0, + end: 61, + }, + } + +block 1 [61..171] + Separator "### Patch\n" + RequestLine "PATCH https://api.example.com/users/1\n" + Header "Content-Type: application/merge-patch+json\n" + Blank "\n" + Body "{\"name\":\"Grace\"}\n" + Blank "\n" + => Request { + name: None, + title: Some( + "Patch", + ), + method: Patch, + url: "https://api.example.com/users/1", + http_version: None, + headers: [ + Header { + name: "Content-Type", + value: "application/merge-patch+json", + disabled: false, + }, + ], + body: Text( + "{\"name\":\"Grace\"}", + ), + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 61, + end: 171, + }, + } + +block 2 [171..216] + Separator "### Options\n" + RequestLine "OPTIONS https://api.example.com/\n" + => Request { + name: None, + title: Some( + "Options", + ), + method: Options, + url: "https://api.example.com/", + http_version: None, + headers: [], + body: None, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 171, + end: 216, + }, + } + +variables: [] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__17-blank-lines-and-spacing.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__17-blank-lines-and-spacing.http.snap new file mode 100644 index 0000000..f7ecf42 --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__17-blank-lines-and-spacing.http.snap @@ -0,0 +1,83 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..2] + Blank "\n" + Blank "\n" +block 1 [2..58] + Separator "### Lots of space around\n" + Blank "\n" + Blank "\n" + RequestLine "GET https://example.com/a\n" + Blank "\n" + Blank "\n" + Blank "\n" + => Request { + name: None, + title: Some( + "Lots of space around", + ), + method: Get, + url: "https://example.com/a", + http_version: None, + headers: [], + body: None, + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 2, + end: 58, + }, + } + +block 2 [58..181] + Separator "### Body with blank lines inside\n" + RequestLine "POST https://example.com/b\n" + Header "Content-Type: text/plain\n" + Blank "\n" + Body "first paragraph\n" + Body "\n" + Body "second paragraph\n" + Blank "\n" + Blank "\n" + Blank "\n" + => Request { + name: None, + title: Some( + "Body with blank lines inside", + ), + method: Post, + url: "https://example.com/b", + http_version: None, + headers: [ + Header { + name: "Content-Type", + value: "text/plain", + disabled: false, + }, + ], + body: Text( + "first paragraph\n\nsecond paragraph", + ), + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 58, + end: 181, + }, + } + +variables: [] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__18-vscode-style.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__18-vscode-style.http.snap new file mode 100644 index 0000000..2d8d219 --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__18-vscode-style.http.snap @@ -0,0 +1,100 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..158] + Variable "@baseUrl = https://example.com/api\n" + Blank "\n" + Directive "# @name login\n" + RequestLine "POST {{baseUrl}}/api/login HTTP/1.1\n" + Header "Content-Type: application/x-www-form-urlencoded\n" + Blank "\n" + Body "name=foo&password=bar\n" + Blank "\n" + => Request { + name: Some( + "login", + ), + title: None, + method: Post, + url: "{{baseUrl}}/api/login", + http_version: Some( + "HTTP/1.1", + ), + headers: [ + Header { + name: "Content-Type", + value: "application/x-www-form-urlencoded", + disabled: false, + }, + ], + body: Text( + "name=foo&password=bar", + ), + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 0, + end: 158, + }, + } + +block 1 [158..368] + Separator "###\n" + Blank "\n" + Variable "@authToken = {{login.response.headers.X-AuthToken}}\n" + Blank "\n" + Directive "# @name createComment\n" + RequestLine "POST {{baseUrl}}/comments HTTP/1.1\n" + Header "Authorization: {{authToken}}\n" + Header "Content-Type: application/json\n" + Blank "\n" + Body "{\n" + Body " \"content\": \"fake content\"\n" + Body "}\n" + => Request { + name: Some( + "createComment", + ), + title: None, + method: Post, + url: "{{baseUrl}}/comments", + http_version: Some( + "HTTP/1.1", + ), + headers: [ + Header { + name: "Authorization", + value: "{{authToken}}", + disabled: false, + }, + Header { + name: "Content-Type", + value: "application/json", + disabled: false, + }, + ], + body: Text( + "{\n \"content\": \"fake content\"\n}", + ), + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 158, + end: 368, + }, + } + +variables: [("baseUrl", "https://example.com/api"), ("authToken", "{{login.response.headers.X-AuthToken}}")] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__19-only-comments.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__19-only-comments.http.snap new file mode 100644 index 0000000..829261e --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__19-only-comments.http.snap @@ -0,0 +1,9 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..73] + Comment "# This file has no requests yet.\n" + Comment "// Just notes.\n" + Variable "@base = http://localhost\n" +variables: [("base", "http://localhost")] diff --git a/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__20-json-with-hash-lines.http.snap b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__20-json-with-hash-lines.http.snap new file mode 100644 index 0000000..e3d285d --- /dev/null +++ b/crates/core/src/httpfile/snapshots/reqlite_core__httpfile__tests__20-json-with-hash-lines.http.snap @@ -0,0 +1,45 @@ +--- +source: crates/core/src/httpfile/tests.rs +expression: dump(&f) +--- +block 0 [0..160] + Separator "### Body lines starting with # or // are body, not comments\n" + RequestLine "POST https://example.com/markdown\n" + Header "Content-Type: text/markdown\n" + Blank "\n" + Body "# Heading\n" + Body "// not a comment\n" + Body "Some text\n" + => Request { + name: None, + title: Some( + "Body lines starting with # or // are body, not comments", + ), + method: Post, + url: "https://example.com/markdown", + http_version: None, + headers: [ + Header { + name: "Content-Type", + value: "text/markdown", + disabled: false, + }, + ], + body: Text( + "# Heading\n// not a comment\nSome text", + ), + directives: Directives { + no_redirect: false, + no_cookie_jar: false, + no_log: false, + timeout: None, + connection_timeout: None, + other: [], + }, + source: SourceSpan { + start: 0, + end: 160, + }, + } + +variables: [] diff --git a/crates/core/src/httpfile/tests.rs b/crates/core/src/httpfile/tests.rs new file mode 100644 index 0000000..0c4f8a6 --- /dev/null +++ b/crates/core/src/httpfile/tests.rs @@ -0,0 +1,318 @@ +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use super::*; +use crate::model::{Body, Header, Method, PartBody}; + +fn fixtures_dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/http") +} + +fn fixtures() -> Vec<(String, String)> { + let mut out: Vec<(String, String)> = std::fs::read_dir(fixtures_dir()) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|p| p.extension().is_some_and(|e| e == "http")) + .map(|p| { + ( + p.file_name().unwrap().to_string_lossy().into_owned(), + std::fs::read_to_string(&p).unwrap(), + ) + }) + .collect(); + out.sort(); + assert!(out.len() >= 15, "expected the fixture corpus, found {}", out.len()); + out +} + +/// A readable dump of the syntax tree and the extracted requests. +fn dump(f: &HttpFile) -> String { + let mut s = String::new(); + for (i, b) in f.blocks().iter().enumerate() { + s.push_str(&format!("block {i} [{}..{}]\n", b.span.start, b.span.end)); + for l in &b.lines { + let text = &f.text()[l.span.clone()]; + s.push_str(&format!(" {:<16} {:?}\n", format!("{:?}", l.kind), text)); + } + if let Some(r) = &b.request { + s.push_str(&format!(" => {r:#?}\n").replace('\n', "\n ")); + s.push('\n'); + } + } + s.push_str(&format!("variables: {:?}\n", f.variables())); + s +} + +#[test] +fn fixture_snapshots() { + for (name, text) in fixtures() { + let f = HttpFile::parse(text); + insta::assert_snapshot!(name, dump(&f)); + } +} + +#[test] +fn round_trip_is_byte_identical_for_every_fixture() { + for (name, text) in fixtures() { + let f = HttpFile::parse(text.clone()); + assert_eq!(f.write(), text, "{name}"); + // Blocks are contiguous and cover the whole file. + let mut pos = 0; + for b in f.blocks() { + assert_eq!(b.span.start, pos, "{name}"); + pos = b.span.end; + let mut lpos = b.span.start; + for l in &b.lines { + assert_eq!(l.span.start, lpos, "{name}"); + lpos = l.span.end; + } + assert_eq!(lpos, b.span.end, "{name}"); + } + assert_eq!(pos, text.len(), "{name}"); + } +} + +#[test] +fn replacing_a_request_with_itself_changes_nothing() { + for (name, text) in fixtures() { + let f = HttpFile::parse(text.clone()); + for i in 0..f.request_count() { + let r = f.request(i).unwrap().clone(); + assert_eq!(f.replace_request(i, &r).unwrap(), text, "{name} #{i}"); + } + } +} + +#[test] +fn editing_one_request_leaves_the_rest_of_the_file_byte_identical() { + for (name, text) in fixtures() { + let f = HttpFile::parse(text.clone()); + for i in 0..f.request_count() { + let mut r = f.request(i).unwrap().clone(); + r.url.push_str("/edited"); + r.headers.push(Header::new("X-Edited", "yes")); + let new_text = f.replace_request(i, &r).unwrap(); + let span = f.request(i).unwrap().source; + assert_eq!(&new_text[..span.start], &text[..span.start], "{name} #{i}: prefix"); + let suffix_len = text.len() - span.end; + assert_eq!( + &new_text[new_text.len() - suffix_len..], + &text[span.end..], + "{name} #{i}: suffix" + ); + + // The edit is visible and everything else about the request survives. + let g = HttpFile::parse(new_text); + assert_eq!(g.request_count(), f.request_count(), "{name} #{i}"); + let mut got = g.request(i).unwrap().clone(); + got.source = r.source; + assert_eq!(got, r, "{name} #{i}"); + for j in (0..f.request_count()).filter(|&j| j != i) { + assert!(g.request(j).unwrap().same_content(f.request(j).unwrap()), "{name} #{j}"); + } + } + } +} + +#[test] +fn parses_the_plan_example() { + let f = HttpFile::parse(std::fs::read_to_string(fixtures_dir().join("02-titles-and-names.http")).unwrap()); + let reqs: Vec<_> = f.requests().collect(); + assert_eq!(reqs.len(), 3); + assert_eq!(reqs[0].title.as_deref(), Some("List users")); + assert_eq!(reqs[0].url, "{{base_url}}/users?limit=20"); + assert_eq!(reqs[1].name.as_deref(), Some("create-user")); + assert_eq!(reqs[1].display_name(), Some("create-user")); + assert_eq!(reqs[1].method, Method::Post); + assert_eq!(reqs[1].directives.timeout, Some(Duration::from_secs(30))); + assert_eq!(reqs[1].body, Body::Text("{ \"name\": \"Ada\" }".into())); + assert_eq!( + reqs[2].body, + Body::FileRef { + path: "./payloads/avatar.png".into(), + substitute: false + } + ); +} + +#[test] +fn query_continuations_join_the_url() { + let f = HttpFile::parse("GET https://x/search\n ?q=rust\n &page=2\nAccept: */*\n"); + let r = f.request(0).unwrap(); + assert_eq!(r.url, "https://x/search?q=rust&page=2"); + assert_eq!(r.headers, vec![Header::new("Accept", "*/*")]); +} + +#[test] +fn multipart_parts() { + let f = HttpFile::parse(std::fs::read_to_string(fixtures_dir().join("06-multipart.http")).unwrap()); + let Body::Multipart { boundary, parts } = &f.request(0).unwrap().body else { + panic!("not multipart") + }; + assert_eq!(boundary, "WebAppBoundary"); + assert_eq!(parts.len(), 2); + assert_eq!(parts[0].body, PartBody::Text("A picture of a cat".into())); + assert_eq!(parts[1].filename.as_deref(), Some("cat.png")); + assert_eq!(parts[1].content_type(), Some("image/png")); + assert_eq!(parts[1].body, PartBody::File("./cat.png".into())); +} + +#[test] +fn handlers_are_not_part_of_the_body() { + let f = HttpFile::parse(std::fs::read_to_string(fixtures_dir().join("07-response-handler.http")).unwrap()); + let Body::Text(body) = &f.request(0).unwrap().body else { + panic!() + }; + assert!(body.starts_with('{') && body.ends_with('}'), "{body:?}"); + assert!(f.request(1).unwrap().body.is_none()); +} + +#[test] +fn render_and_reparse() { + let mut r = Request { + title: Some("New".into()), + name: Some("new-one".into()), + method: Method::Post, + url: "{{base}}/x".into(), + headers: vec![ + Header::new("Content-Type", "application/json"), + Header { + name: "X-Off".into(), + value: "1".into(), + disabled: true, + }, + ], + body: Body::Text("{\n \"a\": 1\n}".into()), + ..Request::default() + }; + r.directives.no_redirect = true; + r.directives.timeout = Some(Duration::from_millis(1500)); + let text = render_request(&r, "\n"); + insta::assert_snapshot!(text, @r#" + ### New + # @name new-one + # @no-redirect + # @timeout 1500 ms + POST {{base}}/x + Content-Type: application/json + # X-Off: 1 + + { + "a": 1 + } + "#); + let back = HttpFile::parse(text); + assert!(back.request(0).unwrap().same_content(&r)); +} + +#[test] +fn insert_and_remove() { + let text = "### A\nGET /a\n\n### B\nGET /b\n"; + let f = HttpFile::parse(text); + let new = Request { + url: "/new".into(), + ..Request::default() + }; + let inserted = f.insert_request(Some(0), &new); + assert_eq!(inserted, "### A\nGET /a\n\n###\nGET /new\n\n### B\nGET /b\n"); + let g = HttpFile::parse(inserted); + assert_eq!( + g.requests().map(|r| r.url.as_str()).collect::>(), + ["/a", "/new", "/b"] + ); + assert_eq!(g.remove_request(1).unwrap(), text); + + let appended = f.insert_request( + None, + &Request { + title: Some("C".into()), + ..new.clone() + }, + ); + assert_eq!(appended, "### A\nGET /a\n\n### B\nGET /b\n\n### C\nGET /new\n"); + let empty = HttpFile::parse(""); + assert_eq!(empty.insert_request(None, &new), "###\nGET /new\n"); +} + +#[test] +fn keys_find_requests_by_name_then_index() { + let f = HttpFile::parse("### A\nGET /a\n\n###\nGET /x\n\n### B\nGET /b\n"); + assert_eq!(f.key_of(2).unwrap().name.as_deref(), Some("B")); + assert_eq!( + f.find(&RequestKey { + name: Some("B".into()), + index: 0 + }), + Some(2) + ); + assert_eq!(f.find(&RequestKey { name: None, index: 1 }), Some(1)); + assert_eq!( + f.find(&RequestKey { + name: Some("gone".into()), + index: 1 + }), + None + ); +} + +#[test] +fn crlf_is_preserved_on_edit() { + let text = "### A\r\nGET /a\r\n\r\n### B\r\nGET /b\r\n"; + let f = HttpFile::parse(text); + assert_eq!(f.eol(), "\r\n"); + let mut r = f.request(0).unwrap().clone(); + r.headers.push(Header::new("X", "1")); + assert_eq!( + f.replace_request(0, &r).unwrap(), + "### A\r\nGET /a\r\nX: 1\r\n\r\n### B\r\nGET /b\r\n" + ); +} + +#[test] +fn adding_a_body_to_a_request_at_eof_without_newline() { + let f = HttpFile::parse("GET /a"); + let mut r = f.request(0).unwrap().clone(); + r.method = Method::Post; + r.body = Body::Text("hi".into()); + assert_eq!(f.replace_request(0, &r).unwrap(), "POST /a\n\nhi\n"); +} + +#[test] +fn removing_a_body_keeps_trailing_spacing_and_handlers() { + let text = "### A\nPOST /a\n\n{}\n\n> ./h.js\n\n### B\nGET /b\n"; + let f = HttpFile::parse(text); + let mut r = f.request(0).unwrap().clone(); + r.body = Body::None; + assert_eq!( + f.replace_request(0, &r).unwrap(), + "### A\nPOST /a\n\n> ./h.js\n\n### B\nGET /b\n" + ); +} + +#[test] +fn source_text_round_trip() { + let text = "### A\nGET /a\n# comment\n\n\n### B\nGET /b"; + let f = HttpFile::parse(text); + assert_eq!(f.request_source(0), Some("### A\nGET /a\n# comment\n")); + assert_eq!(f.request_source(1), Some("### B\nGET /b")); + for i in 0..2 { + let src = f.request_source(i).unwrap().to_string(); + assert_eq!(f.replace_request_text(i, &src).unwrap(), text); + } + assert_eq!( + f.replace_request_text(0, "### A2\nPOST /a\n").unwrap(), + "### A2\nPOST /a\n\n\n### B\nGET /b" + ); +} + +#[test] +fn moving_a_block_between_files() { + let from = HttpFile::parse("### A\nGET /a\n# keep me\n\n### B\nGET /b\n"); + let to = HttpFile::parse("### C\nGET /c\n"); + let moved = from.request_source(0).unwrap(); + assert_eq!(from.remove_request(0).unwrap(), "### B\nGET /b\n"); + assert_eq!( + to.insert_request_text(None, moved), + "### C\nGET /c\n\n### A\nGET /a\n# keep me\n" + ); +} diff --git a/crates/core/src/httpfile/writer.rs b/crates/core/src/httpfile/writer.rs new file mode 100644 index 0000000..740cf3d --- /dev/null +++ b/crates/core/src/httpfile/writer.rs @@ -0,0 +1,220 @@ +//! Rendering requests to `.http` text, and rewriting one block in place while +//! keeping everything we don't model (comments, handlers, spacing). + +use super::lexer::format_duration; +use super::{Block, LineKind}; +use crate::model::{Body, Header, PartBody, Request}; + +/// Renders a request as a fresh block (separator line only if it has a title). +pub fn render_request(req: &Request, eol: &str) -> String { + let mut out = String::new(); + if let Some(t) = &req.title { + out.push_str(&format!("### {t}{eol}")); + } + out.push_str(&render_directives(req, eol)); + out.push_str(&render_request_line(req, eol)); + out.push_str(&render_headers(&req.headers, eol)); + if !req.body.is_none() { + out.push_str(eol); + out.push_str(&render_body(&req.body, eol)); + } + out +} + +fn render_directives(req: &Request, eol: &str) -> String { + let d = &req.directives; + let mut out = String::new(); + if let Some(n) = &req.name { + out.push_str(&format!("# @name {n}{eol}")); + } + if d.no_redirect { + out.push_str(&format!("# @no-redirect{eol}")); + } + if d.no_cookie_jar { + out.push_str(&format!("# @no-cookie-jar{eol}")); + } + if d.no_log { + out.push_str(&format!("# @no-log{eol}")); + } + if let Some(t) = d.timeout { + out.push_str(&format!("# @timeout {}{eol}", format_duration(t))); + } + if let Some(t) = d.connection_timeout { + out.push_str(&format!("# @connection-timeout {}{eol}", format_duration(t))); + } + for (n, v) in &d.other { + if v.is_empty() { + out.push_str(&format!("# @{n}{eol}")); + } else { + out.push_str(&format!("# @{n} {v}{eol}")); + } + } + out +} + +fn render_request_line(req: &Request, eol: &str) -> String { + match &req.http_version { + Some(v) => format!("{} {} {v}{eol}", req.method, req.url), + None => format!("{} {}{eol}", req.method, req.url), + } +} + +fn render_headers(headers: &[Header], eol: &str) -> String { + let mut out = String::new(); + for h in headers { + if h.disabled { + out.push_str(&format!("# {}: {}{eol}", h.name, h.value)); + } else { + out.push_str(&format!("{}: {}{eol}", h.name, h.value)); + } + } + out +} + +/// Renders a body, ending with a line terminator. +pub(crate) fn render_body(body: &Body, eol: &str) -> String { + match body { + Body::None => String::new(), + Body::Text(t) => format!("{t}{eol}"), + Body::FileRef { path, substitute } => { + let marker = if *substitute { "<@" } else { "<" }; + format!("{marker} {}{eol}", path.display()) + } + Body::Multipart { boundary, parts } => { + let mut out = String::new(); + for p in parts { + out.push_str(&format!("--{boundary}{eol}")); + out.push_str(&format!("Content-Disposition: form-data; name=\"{}\"", p.name)); + if let Some(f) = &p.filename { + out.push_str(&format!("; filename=\"{f}\"")); + } + out.push_str(eol); + out.push_str(&render_headers(&p.headers, eol)); + out.push_str(eol); + match &p.body { + PartBody::Text(t) => out.push_str(&format!("{t}{eol}")), + PartBody::File(f) => out.push_str(&format!("< {}{eol}", f.display())), + } + } + out.push_str(&format!("--{boundary}--{eol}")); + out + } + } +} + +/// Rewrites a request block so it describes `new`, keeping comments, response +/// handlers and trailing spacing from the original. Parts of the request that +/// didn't change keep their original text. +// Index loops read best here: each range walks `kinds` and `lt` together. +#[allow(clippy::needless_range_loop)] +pub(crate) fn rewrite_block(old_text: &str, block: &Block, new: &Request, eol: &str) -> String { + let Some(old) = &block.request else { + return render_request(new, eol); + }; + if old.same_content(new) { + return old_text.to_string(); + } + let base = block.span.start; + let lt = |i: usize| { + let s = &block.lines[i].span; + &old_text[s.start - base..s.end - base] + }; + let kinds: Vec<&LineKind> = block.lines.iter().map(|l| &l.kind).collect(); + + let mut out = String::with_capacity(old_text.len() + 64); + let push = |out: &mut String, s: &str| { + if !out.is_empty() && !out.ends_with('\n') { + out.push_str(eol); + } + out.push_str(s); + }; + + let rl = kinds + .iter() + .position(|k| **k == LineKind::RequestLine) + .expect("request block has a request line"); + + // Separator. + let has_sep = kinds.first() == Some(&&LineKind::Separator); + if new.title == old.title { + if has_sep { + push(&mut out, lt(0)); + } + } else if let Some(t) = &new.title { + push(&mut out, &format!("### {t}{eol}")); + } else if has_sep { + push(&mut out, &format!("###{eol}")); + } + + // Lines before the request line: comments, variables, directives. + let directives_changed = old.directives != new.directives || old.name != new.name; + for i in usize::from(has_sep)..rl { + if *kinds[i] == LineKind::Directive && directives_changed { + continue; + } + push(&mut out, lt(i)); + } + if directives_changed { + push(&mut out, &render_directives(new, eol)); + } + + // Request line and URL continuations. + let mut i = rl + 1; + while i < kinds.len() && *kinds[i] == LineKind::UrlContinuation { + i += 1; + } + if old.method == new.method && old.url == new.url && old.http_version == new.http_version { + for j in rl..i { + push(&mut out, lt(j)); + } + } else { + push(&mut out, &render_request_line(new, eol)); + } + + // Header section: up to the first blank line (or body/handler). + let header_start = i; + while i < kinds.len() + && matches!( + kinds[i], + LineKind::Header | LineKind::DisabledHeader | LineKind::Comment | LineKind::Unknown + ) + { + i += 1; + } + if old.headers == new.headers { + for j in header_start..i { + push(&mut out, lt(j)); + } + } else { + push(&mut out, &render_headers(&new.headers, eol)); + for j in header_start..i { + if matches!(kinds[j], LineKind::Comment | LineKind::Unknown) { + push(&mut out, lt(j)); + } + } + } + + // Body: the blank separator line plus all body lines. + let last_body = kinds.iter().rposition(|k| **k == LineKind::Body); + let tail_start = match last_body { + Some(lb) if lb >= i => lb + 1, + _ => i, + }; + if old.body == new.body { + for j in i..tail_start { + push(&mut out, lt(j)); + } + } else if !new.body.is_none() { + push(&mut out, eol); + out.push_str(&render_body(&new.body, eol)); + } + + // Everything after: trailing blanks, response handlers, comments. + for j in tail_start..kinds.len() { + push(&mut out, lt(j)); + } + if old_text.ends_with('\n') && !out.ends_with('\n') { + out.push_str(eol); + } + out +} diff --git a/crates/core/src/import/curl.rs b/crates/core/src/import/curl.rs new file mode 100644 index 0000000..1e35c5c --- /dev/null +++ b/crates/core/src/import/curl.rs @@ -0,0 +1,437 @@ +//! Importing a curl command line (as copied from browser devtools, Unix or +//! Windows flavour) into a [`Request`]. + +use std::path::PathBuf; +use std::time::Duration; + +use crate::model::{Body, Header, Method, Part, PartBody, Request}; + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum CurlImportError { + #[error("not a curl command")] + NotCurl, + #[error("could not split the command into words: {0}")] + Tokenize(String), + #[error("option {0} needs a value")] + MissingValue(String), + #[error("no URL in the command")] + NoUrl, +} + +/// Whether `text` looks like a curl command (used to detect pastes into the +/// URL bar). +pub fn looks_like_curl(text: &str) -> bool { + let t = text.trim_start(); + t.starts_with("curl ") || t.starts_with("curl.exe ") || t.starts_with("curl\n") +} + +const MULTIPART_BOUNDARY: &str = "WebAppBoundary"; + +pub fn from_curl(cmd: &str) -> Result { + let words = tokenize(cmd)?; + let mut words = words.into_iter(); + match words.next().as_deref() { + Some("curl" | "curl.exe") => {} + _ => return Err(CurlImportError::NotCurl), + } + + let mut method: Option = None; + let mut url: Option = None; + let mut headers: Vec
= Vec::new(); + let mut data: Vec = Vec::new(); + let mut data_file: Option = None; + let mut parts: Vec = Vec::new(); + let mut get = false; + let mut head = false; + let mut req = Request::default(); + + // Expand `-XPOST` and `-sSL` style short options. + let mut args: Vec = Vec::new(); + for w in words { + if w.starts_with('-') && !w.starts_with("--") && w.len() > 2 { + let flag = &w[..2]; + if takes_value(flag) { + args.push(flag.to_string()); + args.push(w[2..].to_string()); + } else if w[1..].chars().all(|c| c.is_ascii_alphabetic()) { + for (i, c) in w[1..].char_indices() { + let f = format!("-{c}"); + if takes_value(&f) { + args.push(f); + args.push(w[1 + i + 1..].to_string()); + break; + } + args.push(f); + } + } else { + args.push(w); + } + } else { + args.push(w); + } + } + + let mut it = args.into_iter(); + while let Some(a) = it.next() { + let mut value = |name: &str| it.next().ok_or_else(|| CurlImportError::MissingValue(name.to_string())); + match a.as_str() { + "-X" | "--request" => method = Method::parse(&value(&a)?.to_ascii_uppercase()), + "-H" | "--header" => { + let h = value(&a)?; + if let Some((n, v)) = h.split_once(':') { + let v = v.trim(); + // `-H 'X;'` sends an empty header; `-H 'X:'` removes one. + if !v.is_empty() { + headers.push(Header::new(n.trim(), v)); + } + } else if let Some(n) = h.strip_suffix(';') { + headers.push(Header::new(n.trim(), "")); + } + } + "-d" | "--data" | "--data-ascii" | "--data-binary" => { + let v = value(&a)?; + match v.strip_prefix('@') { + Some(f) if f != "-" => data_file = Some(PathBuf::from(f)), + _ => data.push(v), + } + } + "--data-raw" => data.push(value(&a)?), + "--data-urlencode" => { + let v = value(&a)?; + data.push(match v.split_once('=') { + Some((k, val)) if !k.is_empty() => format!("{k}={}", urlencode(val)), + Some((_, val)) => urlencode(val), + None => urlencode(&v), + }); + } + "--json" => { + data.push(value(&a)?); + if !headers.iter().any(|h| h.name.eq_ignore_ascii_case("content-type")) { + headers.push(Header::new("Content-Type", "application/json")); + } + if !headers.iter().any(|h| h.name.eq_ignore_ascii_case("accept")) { + headers.push(Header::new("Accept", "application/json")); + } + } + "-F" | "--form" | "--form-string" => { + let v = value(&a)?; + if let Some(p) = parse_form(&v, a == "--form-string") { + parts.push(p); + } + } + "-u" | "--user" => { + let v = value(&a)?; + let (user, pass) = v.split_once(':').unwrap_or((&v, "")); + headers.push(Header::new("Authorization", format!("Basic {user} {pass}"))); + } + "-A" | "--user-agent" => headers.push(Header::new("User-Agent", value(&a)?)), + "-e" | "--referer" => headers.push(Header::new("Referer", value(&a)?)), + "-b" | "--cookie" => { + let v = value(&a)?; + if v.contains('=') { + headers.push(Header::new("Cookie", v)); + } + } + "--url" => url = Some(value(&a)?), + "-G" | "--get" => get = true, + "-I" | "--head" => head = true, + "-k" | "--insecure" => req.directives.other.push(("insecure".into(), String::new())), + "-m" | "--max-time" => req.directives.timeout = parse_secs(&value(&a)?), + "--connect-timeout" => req.directives.connection_timeout = parse_secs(&value(&a)?), + "--http1.1" => req.http_version = Some("HTTP/1.1".into()), + "--http2" | "--http2-prior-knowledge" => req.http_version = Some("HTTP/2".into()), + "-L" | "--location" | "--compressed" => {} + s if takes_value(s) => { + value(s)?; + } + s if s.starts_with('-') => {} // flags without a value we don't need + _ => { + if url.is_none() { + url = Some(a); + } + } + } + } + + let mut url = url.ok_or(CurlImportError::NoUrl)?; + // Let curl negotiate compression (and decode it), as `--compressed` does; + // a copied `br, zstd` list could ask for encodings we can't decode. + headers.retain(|h| !h.name.eq_ignore_ascii_case("accept-encoding")); + let has_ct = headers.iter().any(|h| h.name.eq_ignore_ascii_case("content-type")); + + if get && !data.is_empty() { + url.push(if url.contains('?') { '&' } else { '?' }); + url.push_str(&data.join("&")); + data.clear(); + } + + if !parts.is_empty() { + headers.retain(|h| !h.name.eq_ignore_ascii_case("content-type")); + headers.push(Header::new( + "Content-Type", + format!("multipart/form-data; boundary={MULTIPART_BOUNDARY}"), + )); + req.body = Body::Multipart { + boundary: MULTIPART_BOUNDARY.into(), + parts, + }; + } else if let Some(f) = data_file { + req.body = Body::FileRef { + path: f, + substitute: false, + }; + } else if !data.is_empty() { + req.body = Body::Text(data.join("&")); + if !has_ct { + headers.push(Header::new("Content-Type", "application/x-www-form-urlencoded")); + } + } + + req.method = match (method, head, req.body.is_none()) { + (Some(m), _, _) => m, + (None, true, _) => Method::Head, + (None, false, false) => Method::Post, + (None, false, true) => Method::Get, + }; + req.url = url; + req.headers = headers; + Ok(req) +} + +fn takes_value(flag: &str) -> bool { + matches!( + flag, + "-X" | "--request" + | "-H" + | "--header" + | "-d" + | "--data" + | "--data-ascii" + | "--data-binary" + | "--data-raw" + | "--data-urlencode" + | "--json" + | "-F" + | "--form" + | "--form-string" + | "-u" + | "--user" + | "-A" + | "--user-agent" + | "-e" + | "--referer" + | "-b" + | "--cookie" + | "--url" + | "-m" + | "--max-time" + | "--connect-timeout" + | "-o" + | "--output" + | "-w" + | "--write-out" + | "-x" + | "--proxy" + | "-U" + | "--proxy-user" + | "--cacert" + | "--capath" + | "-E" + | "--cert" + | "--key" + | "-c" + | "--cookie-jar" + | "--retry" + | "-K" + | "--config" + | "-T" + | "--upload-file" + | "--resolve" + | "--connect-to" + | "--max-redirs" + | "-r" + | "--range" + | "-z" + | "--time-cond" + ) +} + +fn parse_secs(v: &str) -> Option { + v.parse::().ok().map(Duration::from_secs_f64) +} + +fn urlencode(s: &str) -> String { + let mut out = String::new(); + for b in s.bytes() { + if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) { + out.push(b as char); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + +/// `name=value`, `name=@file;type=x/y;filename=z`, `name= Option { + let (name, rest) = v.split_once('=')?; + let mut segs = rest.split(';'); + let first = segs.next().unwrap_or(""); + let mut part = Part { + name: name.to_string(), + filename: None, + headers: Vec::new(), + body: PartBody::Text(first.to_string()), + }; + if literal { + part.body = PartBody::Text(rest.to_string()); + return Some(part); + } + if let Some(f) = first.strip_prefix('@') { + part.filename = std::path::Path::new(f) + .file_name() + .map(|n| n.to_string_lossy().into_owned()); + part.body = PartBody::File(PathBuf::from(f)); + } else if let Some(f) = first.strip_prefix('<') { + part.body = PartBody::File(PathBuf::from(f)); + } + for s in segs { + match s.split_once('=') { + Some(("type", t)) => part.headers.push(Header::new("Content-Type", t)), + Some(("filename", f)) => part.filename = Some(f.trim_matches('"').to_string()), + _ => {} + } + } + Some(part) +} + +/// Splits the command into words, handling `\`/`^`/`` ` `` line continuations, +/// Windows cmd `^` escapes and bash `$'…'` strings. +fn tokenize(cmd: &str) -> Result, CurlImportError> { + let mut s = cmd.trim().replace("\r\n", "\n"); + let cmd_style = s.contains("^\"") || s.contains("^\n"); + if cmd_style { + // cmd.exe: `^` escapes the next character, `^` + newline continues. + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars(); + while let Some(c) = chars.next() { + if c == '^' { + match chars.next() { + Some('\n') => out.push(' '), + Some(n) => out.push(n), + None => {} + } + } else { + out.push(c); + } + } + s = out; + } else if s.starts_with("curl.exe") { + s = powershell_to_posix(&s.replace("`\n", " ")); + } else { + s = s.replace("\\\n", " "); + } + let s = expand_ansi_c_quotes(&s); + shell_words::split(&s).map_err(|e| CurlImportError::Tokenize(e.to_string())) +} + +/// PowerShell quoting: `""` and `` `" `` inside double quotes are a literal +/// quote; backslashes are literal. +fn powershell_to_posix(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars().peekable(); + let mut in_double = false; + let mut in_single = false; + while let Some(c) = chars.next() { + match c { + '"' if !in_single => { + if in_double && chars.peek() == Some(&'"') { + chars.next(); + out.push_str("\\\""); + } else { + in_double = !in_double; + out.push('"'); + } + } + '\'' if !in_double => { + in_single = !in_single; + out.push(c); + } + '`' if in_double => match chars.next() { + Some('"') => out.push_str("\\\""), + Some('n') => out.push('\n'), + Some('t') => out.push('\t'), + Some(o) => out.push(o), + None => {} + }, + '\\' if in_double => out.push_str("\\\\"), + _ => out.push(c), + } + } + out +} + +/// Rewrites bash `$'…'` strings as plain single-quoted strings. +fn expand_ansi_c_quotes(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars().peekable(); + let mut in_single = false; + let mut in_double = false; + while let Some(c) = chars.next() { + match c { + '\'' if !in_double => { + in_single = !in_single; + out.push(c); + } + '"' if !in_single => { + in_double = !in_double; + out.push(c); + } + '\\' if !in_single => { + out.push(c); + if let Some(n) = chars.next() { + out.push(n); + } + } + '$' if !in_single && !in_double && chars.peek() == Some(&'\'') => { + chars.next(); + let mut val = String::new(); + while let Some(c) = chars.next() { + match c { + '\'' => break, + '\\' => match chars.next() { + Some('n') => val.push('\n'), + Some('t') => val.push('\t'), + Some('r') => val.push('\r'), + Some('0') => val.push('\0'), + Some('x') => { + let h: String = std::iter::from_fn(|| chars.next_if(|c| c.is_ascii_hexdigit())) + .take(2) + .collect(); + if let Ok(b) = u8::from_str_radix(&h, 16) { + val.push(b as char); + } + } + Some('u') => { + let h: String = std::iter::from_fn(|| chars.next_if(|c| c.is_ascii_hexdigit())) + .take(4) + .collect(); + if let Some(ch) = u32::from_str_radix(&h, 16).ok().and_then(char::from_u32) { + val.push(ch); + } + } + Some(o) => val.push(o), + None => {} + }, + o => val.push(o), + } + } + out.push('\''); + out.push_str(&val.replace('\'', "'\\''")); + out.push('\''); + } + _ => out.push(c), + } + } + out +} diff --git a/crates/core/src/import/mod.rs b/crates/core/src/import/mod.rs new file mode 100644 index 0000000..12ffc1a --- /dev/null +++ b/crates/core/src/import/mod.rs @@ -0,0 +1,4 @@ +//! Importing from other tools into `.http` requests. + +pub mod curl; +pub mod postman; diff --git a/crates/core/src/import/postman.rs b/crates/core/src/import/postman.rs new file mode 100644 index 0000000..77dd847 --- /dev/null +++ b/crates/core/src/import/postman.rs @@ -0,0 +1,387 @@ +//! Postman Collection v2.1 import. +//! +//! Folders become directories, and the requests directly inside a folder +//! become `###` blocks in one `.http` file named after the folder. Collection +//! variables go to `$shared` in `http-client.env.json`; Postman environment +//! exports become environments (secret values go to the private env file). +//! Auth is turned into headers, inherited auth is resolved per request, and +//! scripts are skipped with a warning. + +use std::path::PathBuf; + +use serde_json::Value; + +use crate::env::{EnvFile, SHARED_ENV}; +use crate::httpfile::render_request; +use crate::model::{Body, Header, Method, Part, PartBody, Request}; + +#[derive(Debug, thiserror::Error)] +pub enum PostmanError { + #[error("invalid JSON: {0}")] + Json(#[from] serde_json::Error), + #[error("not a Postman v2 collection (missing `info` or `item`)")] + NotCollection, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct PostmanImport { + /// Relative paths and contents of the `.http` files. + pub files: Vec<(PathBuf, String)>, + /// `http-client.env.json`, if there are any variables. + pub public_env: Option, + /// `http-client.private.env.json`, if any variable is secret. + pub private_env: Option, + pub warnings: Vec, +} + +const BOUNDARY: &str = "WebAppBoundary"; + +/// Imports a collection plus any number of Postman environment exports. +pub fn import(collection_json: &str, environment_jsons: &[&str]) -> Result { + let root: Value = serde_json::from_str(collection_json)?; + let (Some(info), Some(items)) = (root.get("info"), root.get("item").and_then(Value::as_array)) else { + return Err(PostmanError::NotCollection); + }; + let name = info.get("name").and_then(Value::as_str).unwrap_or("collection"); + + let mut out = PostmanImport::default(); + let mut ctx = Ctx { + out: &mut out, + used_paths: Vec::new(), + }; + let auth = root.get("auth").cloned(); + if has_script(&root) { + ctx.out + .warnings + .push(format!("Skipped collection-level scripts in \"{name}\"")); + } + ctx.folder(items, PathBuf::new(), &slug(name), auth.as_ref(), name); + + // Environments. + let mut public = EnvFile::default(); + let mut private = EnvFile::default(); + if let Some(vars) = root.get("variable").and_then(Value::as_array) { + for v in vars { + if let (Some(k), Some(val)) = (v.get("key").and_then(Value::as_str), v.get("value")) { + public.env_mut(SHARED_ENV).set(k, value_string(val)); + } + } + } + for env_json in environment_jsons { + let env: Value = serde_json::from_str(env_json)?; + let env_name = env + .get("name") + .and_then(Value::as_str) + .unwrap_or("imported") + .to_string(); + public.env_mut(&env_name); + for v in env.get("values").and_then(Value::as_array).into_iter().flatten() { + if v.get("enabled").and_then(Value::as_bool) == Some(false) { + continue; + } + let Some(k) = v.get("key").and_then(Value::as_str) else { + continue; + }; + let val = v.get("value").map(value_string).unwrap_or_default(); + if v.get("type").and_then(Value::as_str) == Some("secret") { + private.env_mut(&env_name).set(k, val); + } else { + public.env_mut(&env_name).set(k, val); + } + } + } + if !public.envs.is_empty() { + out.public_env = Some(public.to_json()); + } + if !private.envs.is_empty() { + out.private_env = Some(private.to_json()); + } + Ok(out) +} + +struct Ctx<'a> { + out: &'a mut PostmanImport, + used_paths: Vec, +} + +impl Ctx<'_> { + fn folder(&mut self, items: &[Value], dir: PathBuf, file_stem: &str, auth: Option<&Value>, label: &str) { + let mut text = String::new(); + for item in items { + let item_name = item.get("name").and_then(Value::as_str).unwrap_or("Untitled"); + if let Some(children) = item.get("item").and_then(Value::as_array) { + if has_script(item) { + self.out + .warnings + .push(format!("Skipped scripts on folder \"{label}/{item_name}\"")); + } + let sub_auth = item.get("auth").or(auth); + let sub = slug(item_name); + self.folder( + children, + dir.join(&sub), + &sub, + sub_auth, + &format!("{label}/{item_name}"), + ); + } else if let Some(r) = item.get("request") { + if has_script(item) { + self.out + .warnings + .push(format!("Skipped scripts on request \"{label}/{item_name}\"")); + } + let req = self.request(r, item_name, auth, &format!("{label}/{item_name}")); + if !text.is_empty() { + text.push('\n'); + } + text.push_str(&render_request(&req, "\n")); + } + } + if !text.is_empty() { + let mut path = dir.join(format!("{file_stem}.http")); + let mut n = 2; + while self.used_paths.contains(&path) { + path = dir.join(format!("{file_stem}-{n}.http")); + n += 1; + } + self.used_paths.push(path.clone()); + self.out.files.push((path, text)); + } + } + + fn request(&mut self, r: &Value, name: &str, inherited_auth: Option<&Value>, label: &str) -> Request { + let mut req = Request { + title: Some(name.to_string()), + ..Request::default() + }; + // A request can be just a URL string. + if let Some(url) = r.as_str() { + req.url = url.to_string(); + return req; + } + req.method = r + .get("method") + .and_then(Value::as_str) + .and_then(|m| Method::parse(&m.to_ascii_uppercase())) + .unwrap_or(Method::Get); + req.url = match r.get("url") { + Some(Value::String(s)) => s.clone(), + Some(u) => u.get("raw").and_then(Value::as_str).unwrap_or("").to_string(), + None => String::new(), + }; + for h in r.get("header").and_then(Value::as_array).into_iter().flatten() { + let (Some(k), Some(v)) = (h.get("key").and_then(Value::as_str), h.get("value")) else { + continue; + }; + req.headers.push(Header { + name: k.to_string(), + value: value_string(v), + disabled: h.get("disabled").and_then(Value::as_bool).unwrap_or(false), + }); + } + + let auth = match r.get("auth") { + Some(a) if a.get("type").and_then(Value::as_str) == Some("inherit") => inherited_auth, + Some(a) => Some(a), + None => inherited_auth, + }; + if let Some(a) = auth { + self.apply_auth(&mut req, a, label); + } + + if let Some(body) = r.get("body") { + if body.get("disabled").and_then(Value::as_bool) != Some(true) { + self.body(&mut req, body, label); + } + } + req + } + + fn apply_auth(&mut self, req: &mut Request, auth: &Value, label: &str) { + let ty = auth.get("type").and_then(Value::as_str).unwrap_or("noauth"); + let param = |key: &str| -> Option { + auth.get(ty)? + .as_array()? + .iter() + .find(|p| p.get("key").and_then(Value::as_str) == Some(key)) + .and_then(|p| p.get("value")) + .map(value_string) + }; + match ty { + "noauth" => {} + "bearer" => { + let token = param("token").unwrap_or_default(); + req.set_header("Authorization", format!("Bearer {token}")); + } + "basic" => { + let u = param("username").unwrap_or_default(); + let p = param("password").unwrap_or_default(); + req.set_header("Authorization", format!("Basic {u} {p}")); + } + "apikey" => { + let key = param("key").unwrap_or_else(|| "X-API-Key".into()); + let value = param("value").unwrap_or_default(); + if param("in").as_deref() == Some("query") { + let sep = if req.url.contains('?') { '&' } else { '?' }; + req.url = format!("{}{sep}{key}={value}", req.url); + } else { + req.set_header(&key, value); + } + } + other => self.out.warnings.push(format!( + "Unsupported auth type \"{other}\" on \"{label}\"; add the header by hand" + )), + } + } + + fn body(&mut self, req: &mut Request, body: &Value, label: &str) { + let mode = body.get("mode").and_then(Value::as_str).unwrap_or(""); + let set_ct = |req: &mut Request, ct: &str| { + if req.header("content-type").is_none() { + req.headers.push(Header::new("Content-Type", ct)); + } + }; + match mode { + "raw" => { + let raw = body.get("raw").and_then(Value::as_str).unwrap_or(""); + if raw.is_empty() { + return; + } + let lang = body + .pointer("/options/raw/language") + .and_then(Value::as_str) + .unwrap_or("text"); + let ct = match lang { + "json" => "application/json", + "xml" => "application/xml", + "html" => "text/html", + "javascript" => "application/javascript", + _ => "text/plain", + }; + set_ct(req, ct); + req.body = Body::Text(raw.replace("\r\n", "\n")); + } + "urlencoded" => { + let pairs: Vec = body + .get("urlencoded") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter(|p| p.get("disabled").and_then(Value::as_bool) != Some(true)) + .filter_map(|p| { + let k = p.get("key")?.as_str()?; + Some(format!("{k}={}", p.get("value").map(value_string).unwrap_or_default())) + }) + .collect(); + set_ct(req, "application/x-www-form-urlencoded"); + req.body = Body::Text(pairs.join("&")); + } + "formdata" => { + let mut parts = Vec::new(); + for p in body.get("formdata").and_then(Value::as_array).into_iter().flatten() { + if p.get("disabled").and_then(Value::as_bool) == Some(true) { + continue; + } + let Some(k) = p.get("key").and_then(Value::as_str) else { + continue; + }; + let mut part = Part { + name: k.to_string(), + filename: None, + headers: Vec::new(), + body: PartBody::Text(p.get("value").map(value_string).unwrap_or_default()), + }; + if let Some(ct) = p.get("contentType").and_then(Value::as_str) { + part.headers.push(Header::new("Content-Type", ct)); + } + if p.get("type").and_then(Value::as_str) == Some("file") { + let src = match p.get("src") { + Some(Value::String(s)) => s.clone(), + Some(Value::Array(a)) => a.first().and_then(Value::as_str).unwrap_or("").to_string(), + _ => String::new(), + }; + if src.is_empty() { + self.out + .warnings + .push(format!("Form file \"{k}\" on \"{label}\" has no file; set it by hand")); + } + part.filename = std::path::Path::new(&src) + .file_name() + .map(|n| n.to_string_lossy().into_owned()); + part.body = PartBody::File(PathBuf::from(src)); + } + parts.push(part); + } + req.remove_header("content-type"); + req.headers.push(Header::new( + "Content-Type", + format!("multipart/form-data; boundary={BOUNDARY}"), + )); + req.body = Body::Multipart { + boundary: BOUNDARY.into(), + parts, + }; + } + "file" => { + if let Some(src) = body.pointer("/file/src").and_then(Value::as_str) { + req.body = Body::FileRef { + path: PathBuf::from(src), + substitute: false, + }; + } + } + "graphql" => { + let q = body.pointer("/graphql/query").and_then(Value::as_str).unwrap_or(""); + let vars = body.pointer("/graphql/variables").and_then(Value::as_str).unwrap_or(""); + let vars: Value = serde_json::from_str(vars).unwrap_or(Value::Object(Default::default())); + let json = serde_json::json!({ "query": q, "variables": vars }); + set_ct(req, "application/json"); + req.body = Body::Text(serde_json::to_string_pretty(&json).unwrap()); + } + "" => {} + other => self + .out + .warnings + .push(format!("Unsupported body mode \"{other}\" on \"{label}\"")), + } + } +} + +fn has_script(item: &Value) -> bool { + item.get("event").and_then(Value::as_array).is_some_and(|events| { + events.iter().any(|e| { + let exec = e.pointer("/script/exec"); + match exec { + Some(Value::Array(lines)) => lines.iter().any(|l| l.as_str().is_some_and(|s| !s.trim().is_empty())), + Some(Value::String(s)) => !s.trim().is_empty(), + _ => false, + } + }) + }) +} + +fn value_string(v: &Value) -> String { + match v { + Value::String(s) => s.clone(), + Value::Null => String::new(), + other => other.to_string(), + } +} + +/// A file-system friendly name: lowercase, `-` separated. +pub fn slug(name: &str) -> String { + let mut out = String::new(); + for c in name.chars() { + if c.is_alphanumeric() { + out.extend(c.to_lowercase()); + } else if !out.ends_with('-') && !out.is_empty() { + out.push('-'); + } + } + let out = out.trim_end_matches('-').to_string(); + if out.is_empty() { + "untitled".into() + } else { + out + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs new file mode 100644 index 0000000..319ee47 --- /dev/null +++ b/crates/core/src/lib.rs @@ -0,0 +1,21 @@ +//! Core of reqlite: the request model, the lossless `.http` parser and writer, +//! environments, templating, collections and import/export. +//! +//! This crate has no UI, no network code and no async runtime. It only defines +//! the async [`http::HttpClient`] trait that the transport crates implement. + +pub mod cancel; +pub mod collection; +pub mod cookies; +pub mod env; +pub mod export; +pub mod http; +pub mod httpfile; +pub mod import; +pub mod model; +pub mod params; +pub mod resolve; +pub mod template; + +pub use cancel::CancelToken; +pub use model::{Body, Directives, Header, Method, Part, PartBody, Request, SourceSpan}; diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs new file mode 100644 index 0000000..7623336 --- /dev/null +++ b/crates/core/src/model.rs @@ -0,0 +1,223 @@ +//! The request model shared by the parser, the UI and the CLI. + +use std::path::PathBuf; +use std::time::Duration; + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum Method { + Get, + Post, + Put, + Patch, + Delete, + Head, + Options, + Trace, + Connect, + Custom(String), +} + +impl Method { + pub const COMMON: [Method; 7] = [ + Method::Get, + Method::Post, + Method::Put, + Method::Patch, + Method::Delete, + Method::Head, + Method::Options, + ]; + + pub fn as_str(&self) -> &str { + match self { + Method::Get => "GET", + Method::Post => "POST", + Method::Put => "PUT", + Method::Patch => "PATCH", + Method::Delete => "DELETE", + Method::Head => "HEAD", + Method::Options => "OPTIONS", + Method::Trace => "TRACE", + Method::Connect => "CONNECT", + Method::Custom(s) => s, + } + } + + /// Parses a method token. Unknown all-uppercase tokens become `Custom`. + pub fn parse(s: &str) -> Option { + Some(match s { + "GET" => Method::Get, + "POST" => Method::Post, + "PUT" => Method::Put, + "PATCH" => Method::Patch, + "DELETE" => Method::Delete, + "HEAD" => Method::Head, + "OPTIONS" => Method::Options, + "TRACE" => Method::Trace, + "CONNECT" => Method::Connect, + _ if !s.is_empty() && s.bytes().all(|b| b.is_ascii_uppercase() || b == b'-') => { + Method::Custom(s.to_string()) + } + _ => return None, + }) + } +} + +impl std::fmt::Display for Method { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.as_str()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Header { + pub name: String, + pub value: String, + /// A commented-out header (`# Name: value`). + pub disabled: bool, +} + +impl Header { + pub fn new(name: impl Into, value: impl Into) -> Self { + Self { + name: name.into(), + value: value.into(), + disabled: false, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub enum Body { + #[default] + None, + Text(String), + /// `< ./file` (sent as-is) or `<@ ./file` (variables substituted). + FileRef { + path: PathBuf, + substitute: bool, + }, + Multipart { + boundary: String, + parts: Vec, + }, +} + +impl Body { + pub fn is_none(&self) -> bool { + matches!(self, Body::None) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Part { + pub name: String, + pub filename: Option, + /// Headers of the part other than `Content-Disposition`. + pub headers: Vec
, + pub body: PartBody, +} + +impl Part { + pub fn content_type(&self) -> Option<&str> { + self.headers + .iter() + .find(|h| h.name.eq_ignore_ascii_case("content-type")) + .map(|h| h.value.as_str()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PartBody { + Text(String), + File(PathBuf), +} + +/// Per-request directives written as `# @directive value` comments. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Directives { + pub no_redirect: bool, + pub no_cookie_jar: bool, + pub no_log: bool, + pub timeout: Option, + pub connection_timeout: Option, + /// Directives we don't interpret, kept verbatim as `(name, value)`. + pub other: Vec<(String, String)>, +} + +/// Byte range of a request block in its source file. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct SourceSpan { + pub start: usize, + pub end: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Request { + /// From `# @name`. + pub name: Option, + /// From the `### Title` separator. + pub title: Option, + pub method: Method, + /// May contain `{{vars}}`; the query string lives in the URL. + pub url: String, + /// `HTTP/1.1`, `HTTP/2` … when given on the request line. + pub http_version: Option, + pub headers: Vec
, + pub body: Body, + pub directives: Directives, + pub source: SourceSpan, +} + +impl Default for Request { + fn default() -> Self { + Self { + name: None, + title: None, + method: Method::Get, + url: String::new(), + http_version: None, + headers: Vec::new(), + body: Body::None, + directives: Directives::default(), + source: SourceSpan::default(), + } + } +} + +impl Request { + /// The name shown in the UI and used to identify the request in its file: + /// `@name` if present, else the title. + pub fn display_name(&self) -> Option<&str> { + self.name.as_deref().or(self.title.as_deref()) + } + + pub fn header(&self, name: &str) -> Option<&str> { + self.headers + .iter() + .find(|h| !h.disabled && h.name.eq_ignore_ascii_case(name)) + .map(|h| h.value.as_str()) + } + + /// Sets (or adds) an enabled header, replacing the first one with this name. + pub fn set_header(&mut self, name: &str, value: impl Into) { + let value = value.into(); + if let Some(h) = self.headers.iter_mut().find(|h| h.name.eq_ignore_ascii_case(name)) { + h.value = value; + h.disabled = false; + } else { + self.headers.push(Header::new(name, value)); + } + } + + pub fn remove_header(&mut self, name: &str) { + self.headers.retain(|h| !h.name.eq_ignore_ascii_case(name)); + } + + /// Compares two requests ignoring their source position. + pub fn same_content(&self, other: &Request) -> bool { + let mut a = self.clone(); + a.source = other.source; + a == *other + } +} diff --git a/crates/core/src/params.rs b/crates/core/src/params.rs new file mode 100644 index 0000000..fd8065c --- /dev/null +++ b/crates/core/src/params.rs @@ -0,0 +1,133 @@ +//! Keeping a URL and its query-parameter table in sync. +//! +//! Parameters are kept as raw text (no percent-decoding) so that editing the +//! table and going back to the URL never changes anything the user didn't +//! touch, and `{{vars}}` survive untouched. + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Param { + pub key: String, + /// `None` for a bare `?flag` without `=`. + pub value: Option, +} + +impl Param { + pub fn new(key: impl Into, value: impl Into) -> Self { + Self { + key: key.into(), + value: Some(value.into()), + } + } +} + +/// Splits a URL into `(base, query, fragment)` without the `?` and `#`. +pub fn split_url(url: &str) -> (&str, Option<&str>, Option<&str>) { + let (rest, fragment) = match find_outside_vars(url, '#') { + Some(i) => (&url[..i], Some(&url[i + 1..])), + None => (url, None), + }; + match find_outside_vars(rest, '?') { + Some(i) => (&rest[..i], Some(&rest[i + 1..]), fragment), + None => (rest, None, fragment), + } +} + +/// Finds `c` outside of `{{…}}` placeholders. +fn find_outside_vars(s: &str, c: char) -> Option { + let mut depth = 0usize; + let b = s.as_bytes(); + let mut i = 0; + while i < b.len() { + if b[i] == b'{' && b.get(i + 1) == Some(&b'{') { + depth += 1; + i += 2; + continue; + } + if b[i] == b'}' && b.get(i + 1) == Some(&b'}') && depth > 0 { + depth -= 1; + i += 2; + continue; + } + if depth == 0 && b[i] == c as u8 { + return Some(i); + } + i += 1; + } + None +} + +pub fn parse_params(url: &str) -> Vec { + let (_, query, _) = split_url(url); + let Some(q) = query else { return Vec::new() }; + if q.is_empty() { + return Vec::new(); + } + q.split('&') + .map(|kv| match kv.split_once('=') { + Some((k, v)) => Param::new(k, v), + None => Param { + key: kv.to_string(), + value: None, + }, + }) + .collect() +} + +/// Rebuilds `url` with the given parameters. Rows with an empty key and value +/// are dropped (they are the "new row" placeholders in the table). +pub fn with_params(url: &str, params: &[Param]) -> String { + let (base, _, fragment) = split_url(url); + let query: Vec = params + .iter() + .filter(|p| !(p.key.is_empty() && p.value.as_deref().unwrap_or("").is_empty())) + .map(|p| match &p.value { + Some(v) => format!("{}={v}", p.key), + None => p.key.clone(), + }) + .collect(); + let mut out = base.to_string(); + if !query.is_empty() { + out.push('?'); + out.push_str(&query.join("&")); + } + if let Some(f) = fragment { + out.push('#'); + out.push_str(f); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trips() { + for url in [ + "http://x/a?b=1&c=2", + "{{base}}/users?limit={{n}}&flag", + "http://x/a?b=1#frag", + "http://x/a", + "http://x/a?q=a%20b&e=", + ] { + assert_eq!(with_params(url, &parse_params(url)), url, "{url}"); + } + } + + #[test] + fn edits_apply_to_the_url() { + let url = "{{base}}/users?limit=20#top"; + let mut p = parse_params(url); + assert_eq!(p, vec![Param::new("limit", "20")]); + p[0].value = Some("50".into()); + p.push(Param::new("sort", "name")); + p.push(Param::default()); + assert_eq!(with_params(url, &p), "{{base}}/users?limit=50&sort=name#top"); + assert_eq!(with_params(url, &[]), "{{base}}/users#top"); + } + + #[test] + fn question_marks_inside_vars_are_ignored() { + assert_eq!(split_url("{{a?b}}/x?y=1"), ("{{a?b}}/x", Some("y=1"), None)); + } +} diff --git a/crates/core/src/resolve.rs b/crates/core/src/resolve.rs new file mode 100644 index 0000000..6788e49 --- /dev/null +++ b/crates/core/src/resolve.rs @@ -0,0 +1,240 @@ +//! Turning a [`Request`] into a [`ResolvedRequest`]: variable substitution, +//! file references, Basic auth encoding and directives. + +use std::path::Path; + +use base64::Engine; + +use crate::http::{RequestOptions, ResolvedBody, ResolvedPart, ResolvedPartBody, ResolvedRequest}; +use crate::model::{Body, PartBody, Request}; +use crate::template::{Resolver, TemplateError}; + +#[derive(Debug, thiserror::Error)] +pub enum ResolveError { + #[error("{}", .0.iter().map(|e| e.to_string()).collect::>().join(", "))] + Template(Vec), + #[error("cannot read {path}: {source}")] + File { + path: std::path::PathBuf, + source: std::io::Error, + }, + #[error("the URL is empty")] + EmptyUrl, +} + +/// Resolves `req`. Relative file references are taken relative to `base_dir` +/// (the directory of the `.http` file). `defaults` provides the options that +/// directives don't override (proxy, TLS, default timeout …). +pub fn resolve_request( + req: &Request, + resolver: &Resolver, + base_dir: &Path, + defaults: &RequestOptions, +) -> Result { + let mut errors = Vec::new(); + let mut sub = |s: &str| match resolver.resolve(s) { + Ok(v) => v, + Err(e) => { + errors.extend(e); + s.to_string() + } + }; + + let mut url = sub(req.url.trim()); + if url.is_empty() { + return Err(ResolveError::EmptyUrl); + } + if !url.contains("://") { + url = format!("http://{url}"); + } + + let headers: Vec<(String, String)> = req + .headers + .iter() + .filter(|h| !h.disabled) + .map(|h| { + let value = sub(&h.value); + let value = if h.name.eq_ignore_ascii_case("authorization") { + encode_basic(&value) + } else { + value + }; + (sub(&h.name), value) + }) + .collect(); + + let read = |p: &Path| { + let path = base_dir.join(p); + std::fs::read(&path).map_err(|source| ResolveError::File { path, source }) + }; + + let body = match &req.body { + Body::None => ResolvedBody::None, + Body::Text(t) => ResolvedBody::Bytes(sub(t).into_bytes()), + Body::FileRef { + path, + substitute: false, + } => ResolvedBody::File(base_dir.join(path)), + Body::FileRef { path, substitute: true } => { + let text = String::from_utf8_lossy(&read(path)?).into_owned(); + ResolvedBody::Bytes(sub(&text).into_bytes()) + } + Body::Multipart { parts, .. } => ResolvedBody::Multipart( + parts + .iter() + .map(|p| ResolvedPart { + name: sub(&p.name), + filename: p.filename.as_deref().map(&mut sub), + content_type: p.content_type().map(&mut sub), + body: match &p.body { + PartBody::Text(t) => ResolvedPartBody::Bytes(sub(t).into_bytes()), + PartBody::File(f) => ResolvedPartBody::File(base_dir.join(f)), + }, + }) + .collect(), + ), + }; + + if !errors.is_empty() { + errors.dedup(); + return Err(ResolveError::Template(errors)); + } + + let mut options = defaults.clone(); + let d = &req.directives; + if d.no_redirect { + options.follow_redirects = false; + } + // reqlite extension, written by curl import for `-k`. + if d.other.iter().any(|(n, _)| n == "insecure") { + options.verify_tls = false; + } + if d.timeout.is_some() { + options.timeout = d.timeout; + } + if d.connection_timeout.is_some() { + options.connect_timeout = d.connection_timeout; + } + options.http_version = req.http_version.clone(); + + Ok(ResolvedRequest { + method: req.method.as_str().to_string(), + url, + headers, + body, + options, + }) +} + +/// `Basic user password` (JetBrains style) → `Basic base64(user:password)`. +/// An already-encoded `Basic xyz` value is left alone. +fn encode_basic(value: &str) -> String { + let Some(rest) = value.strip_prefix("Basic ") else { + return value.to_string(); + }; + let rest = rest.trim(); + match rest.split_once(' ') { + Some((user, pass)) if !user.is_empty() => { + let token = base64::engine::general_purpose::STANDARD.encode(format!("{user}:{}", pass.trim())); + format!("Basic {token}") + } + _ => { + // `Basic user:password` in clear text is also accepted. + if rest.contains(':') && base64::engine::general_purpose::STANDARD.decode(rest).is_err() { + format!("Basic {}", base64::engine::general_purpose::STANDARD.encode(rest)) + } else { + value.to_string() + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::httpfile::HttpFile; + use crate::template::VarSource; + + fn resolver() -> Resolver { + Resolver::new().with_layer( + VarSource::PublicEnv, + [("base", "http://localhost:1234"), ("user", "ada"), ("pass", "s3cret")], + ) + } + + #[test] + fn resolves_url_headers_body_and_directives() { + let f = HttpFile::parse( + "# @no-redirect\n# @timeout 5\nPOST {{base}}/users HTTP/1.1\nAuthorization: Basic {{user}} {{pass}}\n# X-Off: 1\n\n{\"u\": \"{{user}}\"}\n", + ); + let r = resolve_request( + f.request(0).unwrap(), + &resolver(), + Path::new("."), + &RequestOptions::default(), + ) + .unwrap(); + assert_eq!(r.method, "POST"); + assert_eq!(r.url, "http://localhost:1234/users"); + assert_eq!( + r.headers, + vec![("Authorization".into(), "Basic YWRhOnMzY3JldA==".into())] + ); + assert_eq!(r.body, ResolvedBody::Bytes(b"{\"u\": \"ada\"}".to_vec())); + assert!(!r.options.follow_redirects); + assert_eq!(r.options.timeout, Some(std::time::Duration::from_secs(5))); + assert_eq!(r.options.http_version.as_deref(), Some("HTTP/1.1")); + } + + #[test] + fn reports_all_unknown_variables() { + let f = HttpFile::parse("GET {{nope}}/x\nX-A: {{also_nope}}\n"); + let err = resolve_request( + f.request(0).unwrap(), + &resolver(), + Path::new("."), + &RequestOptions::default(), + ) + .unwrap_err(); + assert_eq!(err.to_string(), "unknown variable `nope`, unknown variable `also_nope`"); + } + + #[test] + fn adds_scheme_and_keeps_encoded_basic() { + let f = HttpFile::parse("GET example.com\nAuthorization: Basic YWRhOnMzY3JldA==\n"); + let r = resolve_request( + f.request(0).unwrap(), + &resolver(), + Path::new("."), + &RequestOptions::default(), + ) + .unwrap(); + assert_eq!(r.url, "http://example.com"); + assert_eq!(r.headers[0].1, "Basic YWRhOnMzY3JldA=="); + assert_eq!(encode_basic("Basic ada:pw"), "Basic YWRhOnB3"); + } + + #[test] + fn file_refs_resolve_relative_to_the_http_file() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("body.json"), "{\"u\":\"{{user}}\"}").unwrap(); + let f = HttpFile::parse("POST /x\n\n<@ ./body.json\n"); + let r = resolve_request( + f.request(0).unwrap(), + &resolver(), + dir.path(), + &RequestOptions::default(), + ) + .unwrap(); + assert_eq!(r.body, ResolvedBody::Bytes(b"{\"u\":\"ada\"}".to_vec())); + let f = HttpFile::parse("POST /x\n\n< ./body.json\n"); + let r = resolve_request( + f.request(0).unwrap(), + &resolver(), + dir.path(), + &RequestOptions::default(), + ) + .unwrap(); + assert_eq!(r.body, ResolvedBody::File(dir.path().join("./body.json"))); + } +} diff --git a/crates/core/src/template.rs b/crates/core/src/template.rs new file mode 100644 index 0000000..ab1e274 --- /dev/null +++ b/crates/core/src/template.rs @@ -0,0 +1,393 @@ +//! `{{name}}` placeholders: parsing, lookup and resolution. +//! +//! Lookup order (first match wins): private environment, public environment, +//! file variables, then `$`-prefixed built-ins (`{{$uuid}}`, `{{$timestamp}}`, +//! `{{$isoTimestamp}}`, `{{$randomInt}}`, `{{$randomInt 1 10}}`). +//! +//! `\{{` is an escaped, literal `{{`. + +use std::collections::HashMap; +use std::ops::Range; +use std::time::{SystemTime, UNIX_EPOCH}; + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum TemplateError { + #[error("unknown variable `{name}`")] + Unknown { name: String, span: Range }, + #[error("unclosed `{{{{` at byte {pos}")] + Unclosed { pos: usize }, + #[error("empty variable name at byte {pos}")] + Empty { pos: usize }, + #[error("variable `{name}` refers to itself (directly or indirectly)")] + Recursive { name: String }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Segment<'a> { + Lit(&'a str), + /// `span` covers the braces; `name` is trimmed. + Var { + name: &'a str, + span: Range, + }, +} + +/// Splits a template into literal and variable segments. +pub fn parse(s: &str) -> Result>, TemplateError> { + let mut out = Vec::new(); + let bytes = s.as_bytes(); + let mut lit_start = 0; + let mut i = 0; + while i + 1 < bytes.len() { + if bytes[i] == b'\\' && bytes[i + 1] == b'{' && bytes.get(i + 2) == Some(&b'{') { + if lit_start < i { + out.push(Segment::Lit(&s[lit_start..i])); + } + out.push(Segment::Lit("{{")); + i += 3; + lit_start = i; + continue; + } + if bytes[i] == b'{' && bytes[i + 1] == b'{' { + let Some(close) = s[i + 2..].find("}}") else { + return Err(TemplateError::Unclosed { pos: i }); + }; + let name = s[i + 2..i + 2 + close].trim(); + if name.is_empty() { + return Err(TemplateError::Empty { pos: i }); + } + if lit_start < i { + out.push(Segment::Lit(&s[lit_start..i])); + } + let end = i + 2 + close + 2; + out.push(Segment::Var { name, span: i..end }); + i = end; + lit_start = i; + continue; + } + i += 1; + } + if lit_start < s.len() { + out.push(Segment::Lit(&s[lit_start..])); + } + Ok(out) +} + +/// Lenient scan for highlighting: every well-formed `{{…}}` with its span. +pub fn find_vars(s: &str) -> Vec<(Range, String)> { + let mut out = Vec::new(); + let mut i = 0; + while let Some(open) = s[i..].find("{{") { + let start = i + open; + if start > 0 && s.as_bytes()[start - 1] == b'\\' { + i = start + 2; + continue; + } + let Some(close) = s[start + 2..].find("}}") else { + break; + }; + let end = start + 2 + close + 2; + out.push((start..end, s[start + 2..start + 2 + close].trim().to_string())); + i = end; + } + out +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum VarSource { + PrivateEnv, + PublicEnv, + File, + Builtin, +} + +/// Source of time and randomness for built-in variables (fixed in tests). +pub trait Dynamic: Send + Sync { + fn uuid(&self) -> String; + fn now(&self) -> SystemTime; + fn random_u32(&self) -> u32; +} + +pub struct SystemDynamic; + +impl Dynamic for SystemDynamic { + fn uuid(&self) -> String { + uuid::Uuid::new_v4().to_string() + } + fn now(&self) -> SystemTime { + SystemTime::now() + } + fn random_u32(&self) -> u32 { + let b = uuid::Uuid::new_v4().into_bytes(); + u32::from_le_bytes([b[0], b[1], b[2], b[3]]) + } +} + +pub struct Resolver { + layers: Vec<(VarSource, HashMap)>, + dynamic: Box, +} + +impl Default for Resolver { + fn default() -> Self { + Self { + layers: Vec::new(), + dynamic: Box::new(SystemDynamic), + } + } +} + +impl Resolver { + pub fn new() -> Self { + Self::default() + } + + pub fn with_dynamic(mut self, d: impl Dynamic + 'static) -> Self { + self.dynamic = Box::new(d); + self + } + + /// Adds a layer. Layers are consulted in [`VarSource`] order regardless of + /// the order they were added in. + pub fn with_layer, V: Into>( + mut self, + source: VarSource, + vars: impl IntoIterator, + ) -> Self { + let map = vars.into_iter().map(|(k, v)| (k.into(), v.into())).collect(); + self.layers.push((source, map)); + self.layers.sort_by_key(|(s, _)| *s as u8); + self + } + + /// The raw (unresolved) value of a variable and where it comes from. + pub fn lookup(&self, name: &str) -> Option<(String, VarSource)> { + for (src, map) in &self.layers { + if let Some(v) = map.get(name) { + return Some((v.clone(), *src)); + } + } + self.builtin(name).map(|v| (v, VarSource::Builtin)) + } + + pub fn is_defined(&self, name: &str) -> bool { + self.layers.iter().any(|(_, m)| m.contains_key(name)) || is_builtin(name) + } + + /// Resolves all placeholders. Variable values may contain placeholders + /// themselves. All unknown variables are reported, not just the first. + pub fn resolve(&self, s: &str) -> Result> { + let mut errors = Vec::new(); + let mut stack = Vec::new(); + let out = self.resolve_inner(s, &mut stack, &mut errors); + if errors.is_empty() { + Ok(out) + } else { + Err(errors) + } + } + + fn resolve_inner(&self, s: &str, stack: &mut Vec, errors: &mut Vec) -> String { + let segments = match parse(s) { + Ok(s) => s, + Err(e) => { + errors.push(e); + return s.to_string(); + } + }; + let mut out = String::with_capacity(s.len()); + for seg in segments { + match seg { + Segment::Lit(l) => out.push_str(l), + Segment::Var { name, span } => { + if stack.iter().any(|n| n == name) { + errors.push(TemplateError::Recursive { name: name.to_string() }); + continue; + } + match self.lookup(name) { + Some((v, VarSource::Builtin)) => out.push_str(&v), + Some((v, _)) => { + stack.push(name.to_string()); + out.push_str(&self.resolve_inner(&v, stack, errors)); + stack.pop(); + } + None => errors.push(TemplateError::Unknown { + name: name.to_string(), + span, + }), + } + } + } + } + out + } + + fn builtin(&self, name: &str) -> Option { + let mut parts = name.split_whitespace(); + let head = parts.next()?; + let args: Vec<&str> = parts.collect(); + Some(match head { + "$uuid" | "$random.uuid" | "$guid" => self.dynamic.uuid(), + "$timestamp" => unix_secs(self.dynamic.now()).to_string(), + "$isoTimestamp" => iso8601(self.dynamic.now()), + "$randomInt" | "$random.integer" => { + let (lo, hi) = match args.as_slice() { + [lo, hi] => (lo.parse::().ok()?, hi.parse::().ok()?), + [] => (0, 1000), + _ => return None, + }; + if hi <= lo { + return None; + } + let span = (hi - lo) as u64; + (lo + (self.dynamic.random_u32() as u64 % span) as i64).to_string() + } + _ => return None, + }) + } +} + +fn is_builtin(name: &str) -> bool { + matches!( + name.split_whitespace().next(), + Some("$uuid" | "$random.uuid" | "$guid" | "$timestamp" | "$isoTimestamp" | "$randomInt" | "$random.integer") + ) +} + +fn unix_secs(t: SystemTime) -> u64 { + t.duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) +} + +/// `YYYY-MM-DDTHH:MM:SS.mmmZ`, without a date crate. +pub fn iso8601(t: SystemTime) -> String { + let d = t.duration_since(UNIX_EPOCH).unwrap_or_default(); + let secs = d.as_secs() as i64; + let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400)); + // Civil-from-days (Howard Hinnant). + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z", + rem / 3600, + rem % 3600 / 60, + rem % 60, + d.subsec_millis() + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + struct Fixed; + impl Dynamic for Fixed { + fn uuid(&self) -> String { + "00000000-0000-4000-8000-000000000000".into() + } + fn now(&self) -> SystemTime { + UNIX_EPOCH + Duration::from_millis(1_700_000_000_123) + } + fn random_u32(&self) -> u32 { + 42 + } + } + + fn resolver() -> Resolver { + Resolver::new() + .with_dynamic(Fixed) + .with_layer( + VarSource::File, + [ + ("host", "file.example"), + ("only_file", "f"), + ("base", "https://{{host}}"), + ], + ) + .with_layer( + VarSource::PublicEnv, + [("host", "public.example"), ("token", "public-token")], + ) + .with_layer(VarSource::PrivateEnv, [("token", "secret")]) + } + + #[test] + fn table() { + let r = resolver(); + let cases: &[(&str, Result<&str, &str>)] = &[ + // Precedence: private > public > file. + ("{{token}}", Ok("secret")), + ("{{host}}", Ok("public.example")), + ("{{only_file}}", Ok("f")), + // Nested values are resolved with the same precedence. + ("{{base}}/users", Ok("https://public.example/users")), + // Whitespace inside braces. + ("{{ token }}", Ok("secret")), + // Literals and escaping. + ("no vars", Ok("no vars")), + ("", Ok("")), + ("a \\{{token}} b", Ok("a {{token}} b")), + ("{ single }", Ok("{ single }")), + // Built-ins. + ("{{$uuid}}", Ok("00000000-0000-4000-8000-000000000000")), + ("{{$timestamp}}", Ok("1700000000")), + ("{{$isoTimestamp}}", Ok("2023-11-14T22:13:20.123Z")), + ("{{$randomInt}}", Ok("42")), + ("{{$randomInt 10 20}}", Ok("12")), + // Errors. + ("{{missing}}", Err("unknown variable `missing`")), + ("{{token", Err("unclosed `{{` at byte 0")), + ("x{{ }}", Err("empty variable name at byte 1")), + ("{{$nope}}", Err("unknown variable `$nope`")), + ]; + for (input, expected) in cases { + let got = r.resolve(input).map_err(|e| e[0].to_string()); + let expected = expected.map(str::to_string).map_err(str::to_string); + assert_eq!(got, expected, "input: {input:?}"); + } + } + + #[test] + fn reports_every_unknown_variable() { + let errs = resolver().resolve("{{a}}/{{b}}").unwrap_err(); + assert_eq!(errs.len(), 2); + assert_eq!( + errs[1], + TemplateError::Unknown { + name: "b".into(), + span: 6..11 + } + ); + } + + #[test] + fn detects_recursion() { + let r = Resolver::new().with_layer(VarSource::File, [("a", "{{b}}"), ("b", "{{a}}")]); + let errs = r.resolve("{{a}}").unwrap_err(); + assert!(matches!(errs[0], TemplateError::Recursive { .. })); + } + + #[test] + fn lookup_reports_source() { + let r = resolver(); + assert_eq!(r.lookup("token"), Some(("secret".into(), VarSource::PrivateEnv))); + assert_eq!(r.lookup("host").unwrap().1, VarSource::PublicEnv); + assert_eq!(r.lookup("only_file").unwrap().1, VarSource::File); + assert_eq!(r.lookup("nope"), None); + } + + #[test] + fn find_vars_for_highlighting() { + assert_eq!( + find_vars("{{a}}/x/{{ b }}/\\{{c}}/{{open"), + vec![(0..5, "a".to_string()), (8..15, "b".to_string())] + ); + } +} diff --git a/crates/core/tests/import.rs b/crates/core/tests/import.rs new file mode 100644 index 0000000..116d954 --- /dev/null +++ b/crates/core/tests/import.rs @@ -0,0 +1,93 @@ +//! Snapshot tests for curl and Postman import over real-world fixtures. + +use std::path::{Path, PathBuf}; + +use reqlite_core::httpfile::{render_request, HttpFile}; +use reqlite_core::import::{curl, postman}; + +fn fixtures(sub: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../tests/fixtures") + .join(sub) +} + +#[test] +fn curl_commands() { + let mut files: Vec<_> = std::fs::read_dir(fixtures("curl")) + .unwrap() + .map(|e| e.unwrap().path()) + .collect(); + files.sort(); + assert!(files.len() >= 10); + for f in files { + let cmd = std::fs::read_to_string(&f).unwrap(); + assert!(curl::looks_like_curl(&cmd), "{}", f.display()); + let req = curl::from_curl(&cmd).unwrap_or_else(|e| panic!("{}: {e}", f.display())); + let http = render_request(&req, "\n"); + // What we write must parse back to the same request. + let back = HttpFile::parse(http.clone()); + assert!(back.request(0).unwrap().same_content(&req), "{}", f.display()); + // Pasting into the single-line URL field may drop the line breaks. + let flat = curl::from_curl(&cmd.replace(['\r', '\n'], "")).unwrap(); + assert_eq!(flat, req, "{} pasted as one line", f.display()); + let name = f.file_stem().unwrap().to_string_lossy().into_owned(); + insta::assert_snapshot!(format!("curl-{name}"), http); + } +} + +#[test] +fn rejects_non_curl() { + assert_eq!( + curl::from_curl("wget http://x").unwrap_err(), + curl::CurlImportError::NotCurl + ); + assert_eq!( + curl::from_curl("curl -H 'A: b'").unwrap_err(), + curl::CurlImportError::NoUrl + ); + assert!(matches!( + curl::from_curl("curl 'unterminated").unwrap_err(), + curl::CurlImportError::Tokenize(_) + )); +} + +#[test] +fn postman_collection_with_environment() { + let coll = std::fs::read_to_string(fixtures("postman/shop.postman_collection.json")).unwrap(); + let env = std::fs::read_to_string(fixtures("postman/shop-dev.postman_environment.json")).unwrap(); + let imp = postman::import(&coll, &[&env]).unwrap(); + + let mut out = String::new(); + for (path, text) in &imp.files { + out.push_str(&format!("==> {}\n{text}\n", path.display())); + // Every generated file is valid and lossless. + let f = HttpFile::parse(text.clone()); + assert_eq!(&f.write(), text); + assert!(f.request_count() > 0); + } + out.push_str(&format!( + "==> http-client.env.json\n{}\n", + imp.public_env.as_deref().unwrap_or("") + )); + out.push_str(&format!( + "==> http-client.private.env.json\n{}\n", + imp.private_env.as_deref().unwrap_or("") + )); + out.push_str("==> warnings\n"); + for w in &imp.warnings { + out.push_str(&format!("{w}\n")); + } + insta::assert_snapshot!("postman-shop", out); +} + +#[test] +fn postman_rejects_other_json() { + assert!(matches!( + postman::import("{}", &[]), + Err(postman::PostmanError::NotCollection) + )); + assert!(matches!( + postman::import("nope", &[]), + Err(postman::PostmanError::Json(_)) + )); +} diff --git a/crates/core/tests/random_files.rs b/crates/core/tests/random_files.rs new file mode 100644 index 0000000..41076c2 --- /dev/null +++ b/crates/core/tests/random_files.rs @@ -0,0 +1,128 @@ +//! A cheap, deterministic stand-in for fuzzing that runs on stable: build +//! many `.http` files from realistic line fragments and check the parser's +//! invariants on each. + +use reqlite_core::httpfile::HttpFile; +use reqlite_core::Header; + +const FRAGMENTS: &[&str] = &[ + "###", + "### Title", + "### spaced title ", + "", + "", + " ", + "# comment", + "// comment", + "# @name x", + "# @timeout 5", + "# @no-redirect", + "# @weird thing", + "@host = example.com", + "@ bad", + "GET http://{{host}}/a", + "POST /b HTTP/1.1", + "PUT https://x/y?z=1", + "https://bare.example", + "DELETE", + " ?a=1", + " &b=2", + " /more", + "Content-Type: application/json", + "Content-Type: multipart/form-data; boundary=B", + "X-A: 1", + "# X-Off: 2", + "not a header", + "{", + " \"a\": 1", + "}", + "< ./file.json", + "<@ ./tpl.json", + "--B", + "Content-Disposition: form-data; name=\"f\"", + "--B--", + "> {%", + " client.log(1);", + "%}", + "> ./h.js", + "<> ./prev.json", + "{{var}}", + "\u{feff}bom", + "ünïcödé: ✓", + "\t\ttabs", +]; + +/// xorshift64*: deterministic, no dependencies. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_f491_4f6c_dd1d) + } + fn below(&mut self, n: usize) -> usize { + (self.next() % n as u64) as usize + } +} + +#[test] +fn invariants_hold_for_generated_files() { + // REQLITE_FUZZ_CASES=200000 for a longer search. + let cases: usize = std::env::var("REQLITE_FUZZ_CASES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(3000); + let seed = std::env::var("REQLITE_FUZZ_SEED") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(0x5eed_1234_abcd_0001); + let mut rng = Rng(seed); + for case in 0..cases { + let lines = rng.below(40); + let eol = if rng.below(4) == 0 { "\r\n" } else { "\n" }; + let mut text = String::new(); + for _ in 0..lines { + text.push_str(FRAGMENTS[rng.below(FRAGMENTS.len())]); + text.push_str(eol); + } + if rng.below(3) == 0 { + text.truncate(text.trim_end_matches(['\r', '\n']).len()); + } + + let f = HttpFile::parse(text.clone()); + assert_eq!(f.write(), text, "case {case}: round trip\n{text:?}"); + for i in 0..f.request_count() { + let r = f.request(i).unwrap().clone(); + assert_eq!( + f.replace_request(i, &r).unwrap(), + text, + "case {case}: identity edit #{i}\n{text:?}" + ); + + // A real edit changes only this request's span. + let mut edited = r.clone(); + edited.headers.push(Header::new("X-Fuzz", "1")); + let out = f.replace_request(i, &edited).unwrap(); + assert_eq!( + &out[..r.source.start], + &text[..r.source.start], + "case {case}: prefix\n{text:?}" + ); + assert!(out.ends_with(&text[r.source.end..]), "case {case}: suffix\n{text:?}"); + let g = HttpFile::parse(out); + assert!( + g.requests().any(|q| q.header("X-Fuzz") == Some("1")), + "case {case}: edit visible\n{text:?}" + ); + + let src = f.request_source(i).unwrap().to_string(); + assert_eq!( + f.replace_request_text(i, &src).unwrap(), + text, + "case {case}: source round trip\n{text:?}" + ); + } + } +} diff --git a/crates/core/tests/snapshots/import__curl-chrome-bash-get.snap b/crates/core/tests/snapshots/import__curl-chrome-bash-get.snap new file mode 100644 index 0000000..f6aa9bb --- /dev/null +++ b/crates/core/tests/snapshots/import__curl-chrome-bash-get.snap @@ -0,0 +1,12 @@ +--- +source: crates/core/tests/import.rs +expression: http +--- +GET https://api.github.com/repos/rust-lang/rust/issues?state=open&per_page=5 +accept: application/vnd.github+json +accept-language: en-US,en;q=0.9,sv;q=0.8 +cache-control: no-cache +origin: https://github.com +priority: u=1, i +sec-fetch-mode: cors +user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 diff --git a/crates/core/tests/snapshots/import__curl-chrome-bash-post-ansi-c.snap b/crates/core/tests/snapshots/import__curl-chrome-bash-post-ansi-c.snap new file mode 100644 index 0000000..b19875f --- /dev/null +++ b/crates/core/tests/snapshots/import__curl-chrome-bash-post-ansi-c.snap @@ -0,0 +1,10 @@ +--- +source: crates/core/tests/import.rs +expression: http +--- +POST https://example.com/api/graphql +accept: */* +content-type: application/json +Cookie: session=abc123; theme=dark + +{"query":"query { me { name } }","note":"it's here\nnext line"} diff --git a/crates/core/tests/snapshots/import__curl-chrome-cmd-crlf.snap b/crates/core/tests/snapshots/import__curl-chrome-cmd-crlf.snap new file mode 100644 index 0000000..d7f13c2 --- /dev/null +++ b/crates/core/tests/snapshots/import__curl-chrome-cmd-crlf.snap @@ -0,0 +1,6 @@ +--- +source: crates/core/tests/import.rs +expression: http +--- +GET https://example.com/search?q=a%20b +accept: text/html diff --git a/crates/core/tests/snapshots/import__curl-chrome-cmd-post.snap b/crates/core/tests/snapshots/import__curl-chrome-cmd-post.snap new file mode 100644 index 0000000..d051924 --- /dev/null +++ b/crates/core/tests/snapshots/import__curl-chrome-cmd-post.snap @@ -0,0 +1,10 @@ +--- +source: crates/core/tests/import.rs +expression: http +--- +POST https://example.com/api/items?page=2&size=10 +accept: application/json +content-type: application/json +user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 + +{"name":"Widget 50%","price":9.5} diff --git a/crates/core/tests/snapshots/import__curl-firefox-posix-form.snap b/crates/core/tests/snapshots/import__curl-firefox-posix-form.snap new file mode 100644 index 0000000..b17ae5f --- /dev/null +++ b/crates/core/tests/snapshots/import__curl-firefox-posix-form.snap @@ -0,0 +1,10 @@ +--- +source: crates/core/tests/import.rs +expression: http +--- +POST https://httpbin.org/post +User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0 +Content-Type: application/x-www-form-urlencoded +Origin: https://httpbin.org + +a=1&b=two%20words diff --git a/crates/core/tests/snapshots/import__curl-firefox-posix-get.snap b/crates/core/tests/snapshots/import__curl-firefox-posix-get.snap new file mode 100644 index 0000000..efca8d4 --- /dev/null +++ b/crates/core/tests/snapshots/import__curl-firefox-posix-get.snap @@ -0,0 +1,11 @@ +--- +source: crates/core/tests/import.rs +expression: http +--- +GET https://developer.mozilla.org/api/v1/whoami +User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0 +Accept: */* +Accept-Language: en-US,en;q=0.5 +Referer: https://developer.mozilla.org/en-US/ +Connection: keep-alive +Sec-Fetch-Mode: cors diff --git a/crates/core/tests/snapshots/import__curl-firefox-windows.snap b/crates/core/tests/snapshots/import__curl-firefox-windows.snap new file mode 100644 index 0000000..008f584 --- /dev/null +++ b/crates/core/tests/snapshots/import__curl-firefox-windows.snap @@ -0,0 +1,8 @@ +--- +source: crates/core/tests/import.rs +expression: http +--- +PUT https://httpbin.org/anything +Content-Type: application/json + +{"ok":true} diff --git a/crates/core/tests/snapshots/import__curl-manual-basic-auth-insecure.snap b/crates/core/tests/snapshots/import__curl-manual-basic-auth-insecure.snap new file mode 100644 index 0000000..f3ef2d4 --- /dev/null +++ b/crates/core/tests/snapshots/import__curl-manual-basic-auth-insecure.snap @@ -0,0 +1,8 @@ +--- +source: crates/core/tests/import.rs +expression: http +--- +# @timeout 10 +# @insecure +DELETE https://localhost:8443/api/users/42 +Authorization: Basic admin s3cret diff --git a/crates/core/tests/snapshots/import__curl-manual-data-from-file.snap b/crates/core/tests/snapshots/import__curl-manual-data-from-file.snap new file mode 100644 index 0000000..0e89dbc --- /dev/null +++ b/crates/core/tests/snapshots/import__curl-manual-data-from-file.snap @@ -0,0 +1,8 @@ +--- +source: crates/core/tests/import.rs +expression: http +--- +PATCH https://api.example.com/users/1 +Content-Type: application/json + +< payloads/patch.json diff --git a/crates/core/tests/snapshots/import__curl-manual-get-with-data.snap b/crates/core/tests/snapshots/import__curl-manual-get-with-data.snap new file mode 100644 index 0000000..45a9a7e --- /dev/null +++ b/crates/core/tests/snapshots/import__curl-manual-get-with-data.snap @@ -0,0 +1,6 @@ +--- +source: crates/core/tests/import.rs +expression: http +--- +GET https://api.example.com/search?q=rust%20lang&page=2 +User-Agent: reqlite-test/1.0 diff --git a/crates/core/tests/snapshots/import__curl-manual-head-http2.snap b/crates/core/tests/snapshots/import__curl-manual-head-http2.snap new file mode 100644 index 0000000..f740c8f --- /dev/null +++ b/crates/core/tests/snapshots/import__curl-manual-head-http2.snap @@ -0,0 +1,5 @@ +--- +source: crates/core/tests/import.rs +expression: http +--- +HEAD https://example.com/ HTTP/2 diff --git a/crates/core/tests/snapshots/import__curl-manual-json-flag.snap b/crates/core/tests/snapshots/import__curl-manual-json-flag.snap new file mode 100644 index 0000000..c477874 --- /dev/null +++ b/crates/core/tests/snapshots/import__curl-manual-json-flag.snap @@ -0,0 +1,9 @@ +--- +source: crates/core/tests/import.rs +expression: http +--- +POST https://api.example.com/users +Content-Type: application/json +Accept: application/json + +{"name":"Ada"} diff --git a/crates/core/tests/snapshots/import__curl-manual-multipart.snap b/crates/core/tests/snapshots/import__curl-manual-multipart.snap new file mode 100644 index 0000000..0dc610d --- /dev/null +++ b/crates/core/tests/snapshots/import__curl-manual-multipart.snap @@ -0,0 +1,21 @@ +--- +source: crates/core/tests/import.rs +expression: http +--- +POST https://upload.example.com/v1/photos +Content-Type: multipart/form-data; boundary=WebAppBoundary + +--WebAppBoundary +Content-Disposition: form-data; name="title" + +Holiday photo +--WebAppBoundary +Content-Disposition: form-data; name="file"; filename="beach.jpg" +Content-Type: image/jpeg + +< ./photos/beach.jpg +--WebAppBoundary +Content-Disposition: form-data; name="meta" + +< ./meta.json +--WebAppBoundary-- diff --git a/crates/core/tests/snapshots/import__postman-shop.snap b/crates/core/tests/snapshots/import__postman-shop.snap new file mode 100644 index 0000000..96a65af --- /dev/null +++ b/crates/core/tests/snapshots/import__postman-shop.snap @@ -0,0 +1,94 @@ +--- +source: crates/core/tests/import.rs +expression: out +--- +==> products/admin/admin.http +### Delete product +DELETE {{baseUrl}}/products/1 +Authorization: Basic admin {{adminPass}} + +### Search (GraphQL) +POST {{baseUrl}}/graphql +Authorization: Basic admin {{adminPass}} +Content-Type: application/json + +{ + "query": "query { products { id name } }", + "variables": { + "first": 5 + } +} + +==> products/products.http +### List products +GET {{baseUrl}}/products?limit={{pageSize}}&sort=name +Accept: application/json +# X-Debug: 1 +Authorization: Bearer {{token}} + +### Create product +POST {{baseUrl}}/products +Authorization: Bearer {{token}} +Content-Type: application/json + +{ + "name": "Widget", + "price": 9.5 +} + +### Upload image +POST {{baseUrl}}/products/1/image +Authorization: Bearer {{token}} +Content-Type: multipart/form-data; boundary=WebAppBoundary + +--WebAppBoundary +Content-Disposition: form-data; name="caption" + +Front view +--WebAppBoundary +Content-Disposition: form-data; name="image"; filename="widget.png" + +< /home/me/widget.png +--WebAppBoundary-- + +==> auth/auth.http +### Token +POST https://auth.example.com/oauth/token +Content-Type: application/x-www-form-urlencoded + +grant_type=client_credentials&client_id={{clientId}} + +### API key ping +GET {{baseUrl}}/ping +X-Api-Key: {{apiKey}} + +### Digest thing +GET {{baseUrl}}/digest + +==> shop-api.http +### Health +GET {{baseUrl}}/health + +==> http-client.env.json +{ + "$shared": { + "baseUrl": "https://shop.example.com/api", + "pageSize": "20" + }, + "Shop dev": { + "baseUrl": "http://localhost:8080/api" + } +} + +==> http-client.private.env.json +{ + "Shop dev": { + "token": "dev-token-123", + "adminPass": "hunter2" + } +} + +==> warnings +Skipped scripts on request "Shop API/Products/List products" +Skipped scripts on request "Shop API/Auth/Token" +Unsupported auth type "digest" on "Shop API/Auth/Digest thing"; add the header by hand diff --git a/crates/http-curl/Cargo.toml b/crates/http-curl/Cargo.toml new file mode 100644 index 0000000..0089502 --- /dev/null +++ b/crates/http-curl/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "reqlite-http-curl" +description = "libcurl implementation of reqlite's async HttpClient." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +publish.workspace = true + +[dependencies] +reqlite-core.workspace = true +curl.workspace = true +tempfile.workspace = true +tokio.workspace = true +tracing.workspace = true + +[dev-dependencies] +rcgen.workspace = true +rustls.workspace = true +tokio = { workspace = true, features = ["net", "io-util"] } +tokio-rustls.workspace = true +wiremock.workspace = true diff --git a/crates/http-curl/src/lib.rs b/crates/http-curl/src/lib.rs new file mode 100644 index 0000000..42bb4b7 --- /dev/null +++ b/crates/http-curl/src/lib.rs @@ -0,0 +1,336 @@ +//! libcurl implementation of [`reqlite_core::http::HttpClient`]. +//! +//! v1 design (implementation plan §2.3): each request runs on Tokio's blocking +//! pool with its own curl `Easy2` handle. The async side races the blocking +//! task against the cancel token; curl's progress callback checks the same +//! token and aborts the transfer. + +use std::fs::File; +use std::io::{Read, Write}; +use std::sync::Arc; +use std::time::Duration; + +use curl::easy::{Easy2, Form, Handler, HttpVersion, List, ReadError, WriteError}; +use reqlite_core::http::{ + canonical_reason, BodyStore, HttpClient, HttpError, Proxy, ResolvedBody, ResolvedPartBody, ResolvedRequest, + Response, Timings, +}; +use reqlite_core::CancelToken; + +/// The libcurl-backed client. Cheap to clone; holds no connections (each +/// request uses a fresh handle in v1). +#[derive(Debug, Clone, Default)] +pub struct CurlClient { + _priv: (), +} + +impl CurlClient { + pub fn new() -> Self { + curl::init(); + Self { _priv: () } + } + + /// libcurl's version string, e.g. for an "about" box. + pub fn version() -> String { + let v = curl::Version::get(); + format!( + "libcurl {} ({}{})", + v.version(), + v.ssl_version().unwrap_or("no TLS"), + if v.feature_http2() { ", HTTP/2" } else { "" } + ) + } +} + +impl HttpClient for CurlClient { + async fn send(&self, req: ResolvedRequest, cancel: CancelToken) -> Result { + let token = cancel.clone(); + let task = tokio::task::spawn_blocking(move || perform(req, token)); + tokio::select! { + res = task => match res { + Ok(r) => r, + Err(e) => Err(HttpError::Other(format!("transfer task failed: {e}"))), + }, + _ = cancel.cancelled() => Err(HttpError::Cancelled), + } + } +} + +struct Collector { + cancel: CancelToken, + status_line: String, + headers: Vec<(String, String)>, + mem: Vec, + file: Option, + threshold: u64, + size: u64, + upload: Option>, + io_error: Option, +} + +impl Handler for Collector { + fn write(&mut self, data: &[u8]) -> Result { + if self.file.is_none() && (self.mem.len() + data.len()) as u64 > self.threshold { + let spill = tempfile::Builder::new() + .prefix("reqlite-response-") + .tempfile() + .and_then(|mut f| f.write_all(&self.mem).map(|_| f)); + match spill { + Ok(f) => { + self.file = Some(f); + self.mem = Vec::new(); + } + Err(e) => { + self.io_error = Some(e); + return Ok(0); + } + } + } + if let Some(f) = &mut self.file { + if let Err(e) = f.write_all(data) { + self.io_error = Some(e); + return Ok(0); + } + } else { + self.mem.extend_from_slice(data); + } + self.size += data.len() as u64; + Ok(data.len()) + } + + fn read(&mut self, buf: &mut [u8]) -> Result { + match &mut self.upload { + Some(r) => r.read(buf).map_err(|_| ReadError::Abort), + None => Ok(0), + } + } + + fn header(&mut self, data: &[u8]) -> bool { + let line = String::from_utf8_lossy(data); + let line = line.trim_end_matches(['\r', '\n']); + if line.starts_with("HTTP/") { + // A new response (redirect hop or after `100 Continue`). + self.status_line = line.to_string(); + self.headers.clear(); + } else if let Some((n, v)) = line.split_once(':') { + self.headers.push((n.trim().to_string(), v.trim().to_string())); + } + true + } + + fn progress(&mut self, _dltotal: f64, _dlnow: f64, _ultotal: f64, _ulnow: f64) -> bool { + !self.cancel.is_cancelled() + } +} + +fn perform(req: ResolvedRequest, cancel: CancelToken) -> Result { + let o = &req.options; + let mut easy = Easy2::new(Collector { + cancel: cancel.clone(), + status_line: String::new(), + headers: Vec::new(), + mem: Vec::new(), + file: None, + threshold: o.spill_threshold, + size: 0, + upload: None, + io_error: None, + }); + match setup(&mut easy, &req) { + Ok(()) => {} + Err(SetupError::Curl(e)) => return Err(map_error(&e, &cancel, None)), + Err(SetupError::Io(e)) => return Err(HttpError::Io(e)), + } + + tracing::debug!(method = %req.method, url = %req.url, "sending"); + if let Err(e) = easy.perform() { + let io = easy.get_mut().io_error.take(); + return Err(map_error(&e, &cancel, io)); + } + + let timings = Timings { + dns: easy.namelookup_time().unwrap_or_default(), + connect: easy.connect_time().unwrap_or_default(), + tls: easy.appconnect_time().unwrap_or_default(), + ttfb: easy.starttransfer_time().unwrap_or_default(), + total: easy.total_time().unwrap_or_default(), + }; + let status = easy.response_code().unwrap_or(0) as u16; + let effective_url = easy.effective_url().ok().flatten().unwrap_or(&req.url).to_string(); + + let c = easy.get_mut(); + let mut parts = c.status_line.splitn(3, ' '); + let http_version = parts.next().unwrap_or("").to_string(); + let _code = parts.next(); + let reason = match parts.next().map(str::trim) { + Some(r) if !r.is_empty() => r.to_string(), + _ => canonical_reason(status).to_string(), + }; + let body = match c.file.take() { + Some(mut f) => { + f.flush().map_err(|e| HttpError::Io(e.to_string()))?; + BodyStore::TempFile(Arc::new(f.into_temp_path())) + } + None => BodyStore::InMemory(Arc::new(std::mem::take(&mut c.mem))), + }; + + Ok(Response { + status, + reason, + http_version, + headers: std::mem::take(&mut c.headers), + body, + timings, + size: c.size, + effective_url, + }) +} + +enum SetupError { + Curl(curl::Error), + Io(String), +} + +impl From for SetupError { + fn from(e: curl::Error) -> Self { + SetupError::Curl(e) + } +} + +fn setup(easy: &mut Easy2, req: &ResolvedRequest) -> Result<(), SetupError> { + let o = &req.options; + easy.url(&req.url)?; + easy.progress(true)?; + easy.signal(false)?; + + let method = req.method.as_str(); + let has_body = !matches!(req.body, ResolvedBody::None); + match &req.body { + ResolvedBody::None => {} + ResolvedBody::Bytes(b) => { + easy.post(true)?; + easy.post_fields_copy(b)?; + } + ResolvedBody::File(path) => { + let f = File::open(path).map_err(|e| SetupError::Io(format!("{}: {e}", path.display())))?; + let len = f.metadata().map(|m| m.len()).unwrap_or(0); + easy.get_mut().upload = Some(Box::new(f)); + easy.post(true)?; + easy.post_field_size(len)?; + } + ResolvedBody::Multipart(parts) => { + let mut form = Form::new(); + for p in parts { + let mut part = form.part(&p.name); + match &p.body { + ResolvedPartBody::Bytes(b) => { + part.contents(b); + } + ResolvedPartBody::File(f) => { + part.file(f); + } + } + if let Some(fname) = &p.filename { + part.filename(fname); + } + if let Some(ct) = &p.content_type { + part.content_type(ct); + } + part.add() + .map_err(|e| SetupError::Io(format!("multipart part `{}`: {e}", p.name)))?; + } + easy.httppost(form)?; + } + } + match (method, has_body) { + ("GET", false) => easy.get(true)?, + ("HEAD", false) => easy.nobody(true)?, + ("POST", true) => {} + (m, _) => easy.custom_request(m)?, + } + + let mut list = List::new(); + let mut has_expect = false; + let mut has_accept_encoding = false; + let multipart = matches!(req.body, ResolvedBody::Multipart(_)); + for (n, v) in &req.headers { + // curl generates the multipart Content-Type (with its own boundary). + if multipart && n.eq_ignore_ascii_case("content-type") { + continue; + } + has_expect |= n.eq_ignore_ascii_case("expect"); + has_accept_encoding |= n.eq_ignore_ascii_case("accept-encoding"); + if v.is_empty() { + list.append(&format!("{n};"))?; + } else { + list.append(&format!("{n}: {v}"))?; + } + } + if !has_expect { + list.append("Expect:")?; + } + easy.http_headers(list)?; + if !has_accept_encoding { + // Advertise everything curl can decode and decode it transparently. + easy.accept_encoding("")?; + } + + easy.follow_location(o.follow_redirects)?; + easy.max_redirections(o.max_redirects)?; + if let Some(t) = o.timeout { + easy.timeout(t)?; + } + easy.connect_timeout(o.connect_timeout.unwrap_or(Duration::from_secs(30)))?; + easy.ssl_verify_peer(o.verify_tls)?; + easy.ssl_verify_host(o.verify_tls)?; + if let Some(ca) = &o.ca_file { + easy.cainfo(ca)?; + } + match &o.proxy { + Proxy::System => {} + Proxy::None => { + easy.proxy("")?; + easy.noproxy("*")?; + } + Proxy::Manual(p) => easy.proxy(p)?, + } + match o.http_version.as_deref() { + Some("HTTP/1.0") => easy.http_version(HttpVersion::V10)?, + Some("HTTP/1.1") => easy.http_version(HttpVersion::V11)?, + Some("HTTP/2" | "HTTP/2.0") => easy.http_version(HttpVersion::V2)?, + _ => easy.http_version(HttpVersion::V2TLS)?, + } + Ok(()) +} + +fn map_error(e: &curl::Error, cancel: &CancelToken, io: Option) -> HttpError { + let detail = || match e.extra_description() { + Some(x) => format!("{} ({x})", e.description()), + None => e.description().to_string(), + }; + if cancel.is_cancelled() || e.is_aborted_by_callback() { + HttpError::Cancelled + } else if let Some(io) = io { + HttpError::Io(io.to_string()) + } else if e.is_operation_timedout() { + HttpError::Timeout + } else if e.is_couldnt_resolve_host() || e.is_couldnt_resolve_proxy() { + HttpError::Dns(detail()) + } else if e.is_couldnt_connect() { + HttpError::Connect(detail()) + } else if e.is_ssl_connect_error() + || e.is_peer_failed_verification() + || e.is_ssl_certproblem() + || e.is_ssl_cacert_badfile() + || e.is_ssl_cipher() + || e.is_ssl_issuer_error() + { + HttpError::Tls(detail()) + } else if e.is_url_malformed() || e.is_unsupported_protocol() { + HttpError::InvalidUrl(detail()) + } else if e.is_read_error() || e.is_write_error() { + HttpError::Io(detail()) + } else { + HttpError::Other(detail()) + } +} diff --git a/crates/http-curl/tests/http.rs b/crates/http-curl/tests/http.rs new file mode 100644 index 0000000..a9fa50e --- /dev/null +++ b/crates/http-curl/tests/http.rs @@ -0,0 +1,317 @@ +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use reqlite_core::http::{ + BodyStore, HttpClient, HttpError, RequestOptions, ResolvedBody, ResolvedPart, ResolvedPartBody, ResolvedRequest, +}; +use reqlite_core::CancelToken; +use reqlite_http_curl::CurlClient; +use wiremock::matchers::{body_string, body_string_contains, header, method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +fn req(m: &str, url: String) -> ResolvedRequest { + ResolvedRequest { + method: m.into(), + url, + headers: Vec::new(), + body: ResolvedBody::None, + options: RequestOptions::default(), + } +} + +async fn send(r: ResolvedRequest) -> Result { + CurlClient::new().send(r, CancelToken::new()).await +} + +fn body_text(b: &BodyStore) -> String { + String::from_utf8(b.read_all().unwrap()).unwrap() +} + +#[tokio::test] +async fn every_method_with_and_without_body() { + let server = MockServer::start().await; + for m in ["GET", "DELETE", "OPTIONS", "HEAD"] { + Mock::given(method(m)) + .and(path("/m")) + .respond_with(ResponseTemplate::new(200).insert_header("x-method", m)) + .mount(&server) + .await; + } + for m in ["POST", "PUT", "PATCH", "DELETE"] { + Mock::given(method(m)) + .and(path("/b")) + .and(body_string(format!("body for {m}"))) + .respond_with(ResponseTemplate::new(201).set_body_string(format!("got {m}"))) + .mount(&server) + .await; + } + + for m in ["GET", "DELETE", "OPTIONS", "HEAD"] { + let r = send(req(m, format!("{}/m", server.uri()))).await.unwrap(); + assert_eq!(r.status, 200, "{m}"); + assert_eq!(r.header("x-method"), Some(m)); + } + for m in ["POST", "PUT", "PATCH", "DELETE"] { + let mut r = req(m, format!("{}/b", server.uri())); + r.body = ResolvedBody::Bytes(format!("body for {m}").into_bytes()); + let resp = send(r).await.unwrap(); + assert_eq!(resp.status, 201, "{m}"); + assert_eq!(resp.reason, "Created"); + assert_eq!(body_text(&resp.body), format!("got {m}")); + assert_eq!(resp.http_version, "HTTP/1.1"); + assert!(resp.timings.total > Duration::ZERO); + } +} + +#[tokio::test] +async fn sends_headers_and_file_and_multipart_bodies() { + let server = MockServer::start().await; + Mock::given(method("PUT")) + .and(path("/file")) + .and(header("x-test", "yes")) + .and(body_string("from disk")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/multi")) + .and(body_string_contains("name=\"field\"")) + .and(body_string_contains("value-1")) + .and(body_string_contains("filename=\"up.txt\"")) + .and(body_string_contains("file content")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + + let dir = tempfile::tempdir().unwrap(); + let f = dir.path().join("up.txt"); + std::fs::write(&f, "from disk").unwrap(); + let mut r = req("PUT", format!("{}/file", server.uri())); + r.headers.push(("X-Test".into(), "yes".into())); + r.body = ResolvedBody::File(f.clone()); + assert_eq!(send(r).await.unwrap().status, 200); + + std::fs::write(&f, "file content").unwrap(); + let mut r = req("POST", format!("{}/multi", server.uri())); + r.headers + .push(("Content-Type".into(), "multipart/form-data; boundary=X".into())); + r.body = ResolvedBody::Multipart(vec![ + ResolvedPart { + name: "field".into(), + filename: None, + content_type: None, + body: ResolvedPartBody::Bytes(b"value-1".to_vec()), + }, + ResolvedPart { + name: "upload".into(), + filename: Some("up.txt".into()), + content_type: Some("text/plain".into()), + body: ResolvedPartBody::File(f), + }, + ]); + assert_eq!(send(r).await.unwrap().status, 200); +} + +#[tokio::test] +async fn redirects_follow_or_not() { + let server = MockServer::start().await; + Mock::given(path("/old")) + .respond_with(ResponseTemplate::new(302).insert_header("location", "/new")) + .mount(&server) + .await; + Mock::given(path("/new")) + .respond_with(ResponseTemplate::new(200).set_body_string("new")) + .mount(&server) + .await; + + let r = send(req("GET", format!("{}/old", server.uri()))).await.unwrap(); + assert_eq!(r.status, 200); + assert_eq!(body_text(&r.body), "new"); + assert!(r.effective_url.ends_with("/new")); + assert!(r.header("location").is_none(), "headers are from the final hop"); + + let mut nr = req("GET", format!("{}/old", server.uri())); + nr.options.follow_redirects = false; + let r = send(nr).await.unwrap(); + assert_eq!(r.status, 302); + assert_eq!(r.header("location"), Some("/new")); +} + +#[tokio::test] +async fn timeout() { + let server = MockServer::start().await; + Mock::given(path("/slow")) + .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(3))) + .mount(&server) + .await; + let mut r = req("GET", format!("{}/slow", server.uri())); + r.options.timeout = Some(Duration::from_millis(300)); + let start = Instant::now(); + assert_eq!(send(r).await.unwrap_err(), HttpError::Timeout); + assert!(start.elapsed() < Duration::from_secs(2)); +} + +#[tokio::test] +async fn cancel_mid_transfer_ends_the_task_within_200ms() { + let server = MockServer::start().await; + Mock::given(path("/slow")) + .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(10))) + .mount(&server) + .await; + let cancel = CancelToken::new(); + let task = tokio::spawn({ + let cancel = cancel.clone(); + let r = req("GET", format!("{}/slow", server.uri())); + async move { CurlClient::new().send(r, cancel).await } + }); + tokio::time::sleep(Duration::from_millis(200)).await; + let cancelled_at = Instant::now(); + cancel.cancel(); + let res = task.await.unwrap(); + assert_eq!(res.unwrap_err(), HttpError::Cancelled); + assert!( + cancelled_at.elapsed() < Duration::from_millis(200), + "took {:?}", + cancelled_at.elapsed() + ); +} + +#[tokio::test] +async fn twenty_concurrent_requests() { + let server = MockServer::start().await; + Mock::given(path("/c")) + .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_millis(300))) + .expect(20) + .mount(&server) + .await; + let client = Arc::new(CurlClient::new()); + let start = Instant::now(); + let tasks: Vec<_> = (0..20) + .map(|_| { + let client = client.clone(); + let r = req("GET", format!("{}/c", server.uri())); + tokio::spawn(async move { client.send(r, CancelToken::new()).await }) + }) + .collect(); + for t in tasks { + assert_eq!(t.await.unwrap().unwrap().status, 200); + } + // In parallel, not one after the other (20 × 300 ms = 6 s). + assert!(start.elapsed() < Duration::from_secs(3), "{:?}", start.elapsed()); +} + +#[tokio::test] +async fn large_bodies_spill_to_a_temp_file() { + let server = MockServer::start().await; + let big = vec![b'x'; 6 * 1024 * 1024]; + Mock::given(path("/big")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(big.clone())) + .mount(&server) + .await; + Mock::given(path("/small")) + .respond_with(ResponseTemplate::new(200).set_body_string("small")) + .mount(&server) + .await; + + let r = send(req("GET", format!("{}/big", server.uri()))).await.unwrap(); + assert_eq!(r.size, big.len() as u64); + let BodyStore::TempFile(path) = &r.body else { + panic!("expected a spilled body") + }; + let path = path.to_path_buf(); + assert_eq!(r.body.read_all().unwrap().len(), big.len()); + drop(r); + assert!(!path.exists(), "temp file is removed with the response"); + + let r = send(req("GET", format!("{}/small", server.uri()))).await.unwrap(); + assert_eq!(r.body.in_memory(), Some(&b"small"[..])); +} + +#[tokio::test] +async fn connection_errors_are_classified() { + // Nothing listens on port 9 (discard) on CI-less dev machines. + let mut r = req("GET", "http://127.0.0.1:9/".into()); + r.options.connect_timeout = Some(Duration::from_secs(2)); + assert!(matches!(send(r).await.unwrap_err(), HttpError::Connect(_))); + let r = req("GET", "http://does-not-exist.invalid/".into()); + assert!(matches!(send(r).await.unwrap_err(), HttpError::Dns(_))); + let r = req("GET", "nope://x".into()); + assert!(matches!(send(r).await.unwrap_err(), HttpError::InvalidUrl(_))); +} + +mod tls { + use super::*; + use rcgen::{BasicConstraints, CertificateParams, CertifiedIssuer, DnType, IsCa, KeyPair}; + use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer}; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + /// A one-shot-per-connection HTTPS server with a certificate signed by a + /// fresh CA. Returns the port and the CA certificate in PEM. + async fn https_server() -> (u16, String) { + let mut ca_params = CertificateParams::new(Vec::::new()).unwrap(); + ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + // rcgen's default subject is the same for every cert; a CA with the + // leaf's name would make the leaf look self-signed. + ca_params.distinguished_name.push(DnType::CommonName, "reqlite test CA"); + let ca = CertifiedIssuer::self_signed(ca_params, KeyPair::generate().unwrap()).unwrap(); + let leaf_key = KeyPair::generate().unwrap(); + let leaf = CertificateParams::new(vec!["localhost".to_string()]) + .unwrap() + .signed_by(&leaf_key, &ca) + .unwrap(); + + let config = rustls::ServerConfig::builder() + .with_no_client_auth() + .with_single_cert( + vec![CertificateDer::from(leaf.der().to_vec())], + PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(leaf_key.serialize_der())), + ) + .unwrap(); + let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(config)); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { + loop { + let Ok((tcp, _)) = listener.accept().await else { return }; + let acceptor = acceptor.clone(); + tokio::spawn(async move { + let Ok(mut tls) = acceptor.accept(tcp).await else { + return; + }; + let mut buf = vec![0u8; 4096]; + let _ = tls.read(&mut buf).await; + let _ = tls + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 6\r\nConnection: close\r\n\r\nsecure") + .await; + let _ = tls.shutdown().await; + }); + } + }); + (port, ca.pem()) + } + + #[tokio::test] + async fn self_signed_certificate() { + let (port, ca_pem) = https_server().await; + let url = format!("https://localhost:{port}/"); + + // Untrusted by default. + let err = send(req("GET", url.clone())).await.unwrap_err(); + assert!(matches!(err, HttpError::Tls(_)), "{err:?}"); + + // Verification off. + let mut r = req("GET", url.clone()); + r.options.verify_tls = false; + let resp = send(r).await.unwrap(); + assert_eq!(body_text(&resp.body), "secure"); + assert!(resp.timings.tls >= resp.timings.connect); + + // Custom CA file. + let dir = tempfile::tempdir().unwrap(); + let ca = dir.path().join("ca.pem"); + std::fs::write(&ca, ca_pem).unwrap(); + let mut r = req("GET", url); + r.options.ca_file = Some(ca); + assert_eq!(send(r).await.unwrap().status, 200); + } +} diff --git a/deny.toml b/deny.toml new file mode 100644 index 0000000..e5cb6fb --- /dev/null +++ b/deny.toml @@ -0,0 +1,43 @@ +# cargo-deny configuration: licenses, advisories, bans and sources. +# Run with `just deny` (part of `just check`). + +[graph] +all-features = false + +[advisories] +# Unmaintained crates are reported but don't fail the build; vulnerabilities do. +unmaintained = "workspace" +yanked = "deny" + +[licenses] +confidence-threshold = 0.9 +allow = [ + "MIT", + "Apache-2.0", + "Apache-2.0 WITH LLVM-exception", + "BSD-2-Clause", + "BSD-3-Clause", + "0BSD", + "ISC", + "Zlib", + "Unicode-3.0", + "CC0-1.0", + "MPL-2.0", + "Unlicense", + # Bundled fonts in epaint_default_fonts. + "OFL-1.1", + "Ubuntu-font-1.0", +] + +[licenses.private] +ignore = true + +[bans] +multiple-versions = "allow" +wildcards = "deny" +allow-wildcard-paths = true + +[sources] +unknown-registry = "deny" +unknown-git = "deny" +allow-registry = ["https://github.com/rust-lang/crates.io-index"] diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml new file mode 100644 index 0000000..7f71d55 --- /dev/null +++ b/fuzz/Cargo.toml @@ -0,0 +1,24 @@ +# Fuzzing the .http parser (needs nightly): +# cargo install cargo-fuzz +# cargo +nightly fuzz run parse +[package] +name = "reqlite-fuzz" +version = "0.0.0" +publish = false +edition = "2021" + +[package.metadata] +cargo-fuzz = true + +[dependencies] +libfuzzer-sys = "0.4" +reqlite-core = { path = "../crates/core" } + +[[bin]] +name = "parse" +path = "fuzz_targets/parse.rs" +test = false +doc = false +bench = false + +[workspace] diff --git a/fuzz/fuzz_targets/parse.rs b/fuzz/fuzz_targets/parse.rs new file mode 100644 index 0000000..83e31b4 --- /dev/null +++ b/fuzz/fuzz_targets/parse.rs @@ -0,0 +1,16 @@ +#![no_main] + +use libfuzzer_sys::fuzz_target; +use reqlite_core::httpfile::HttpFile; + +fuzz_target!(|data: &str| { + let f = HttpFile::parse(data); + assert_eq!(f.write(), data); + for i in 0..f.request_count() { + let r = f.request(i).unwrap().clone(); + assert_eq!(f.replace_request(i, &r).unwrap(), data); + let src = f.request_source(i).unwrap().to_string(); + let again = HttpFile::parse(f.replace_request_text(i, &src).unwrap()); + assert_eq!(again.request_count(), f.request_count()); + } +}); diff --git a/implementation-plan.md b/implementation-plan.md new file mode 100644 index 0000000..eeedfab --- /dev/null +++ b/implementation-plan.md @@ -0,0 +1,374 @@ +# Implementation plan: Rust + egui API client + +This plan builds on [tech-stack.md](tech-stack.md). It has three parts: + +1. **Decisions** that are fixed up front, so later work doesn't revisit them. +2. **Architecture**: how the code is split up and how data flows through it. +3. **Milestones**: small vertical slices, each ending in something you can run and test. + +Working name: `reqlite` (rename freely). + +**Revision 3:** async with Tokio and `.http` files as the storage format (revision 2), and no CI for now (revision 3). Quality checks run locally with `just check`, and release builds are made by hand. All three were requested by Torbjörn. + +--- + +## 1. Decisions + +| Topic | Decision | Why | +|---|---|---| +| Language / edition | Rust stable, edition 2021, pinned with `rust-toolchain.toml` | Builds are reproducible on every machine. | +| UI | `eframe` + `egui` + `egui_extras` (syntax highlighting, tables) | Immediate mode keeps all state in plain structs, and one exe covers all platforms. | +| Renderer | eframe's default `wgpu` backend, with `glow` as a feature flag | `glow` is a fallback for old GPUs and VMs. | +| Async runtime | `tokio` (multi-thread runtime on background threads) + `tokio-util` (`CancellationToken`) | The UI thread stays egui's; all I/O (HTTP, file loading, watching) runs as Tokio tasks. | +| HTTP | `curl` crate with features `static-curl`, `http2`, `ssl` (Schannel on Windows, OpenSSL/rustls elsewhere), behind an async trait | It is faithful to how curl behaves, gives timings, and has a single binary with no DLLs. See section 2.3 for how it becomes async. | +| Async trait | Native `async fn` in traits, plus `async-trait` only where `dyn HttpClient` is needed | | +| Serialization | Own `.http` parser/writer in `core`; `serde_json` for environments, JSON bodies and Postman import; `toml` for app settings | | +| Storage format | `.http` files (JetBrains HTTP Client / VS Code REST Client syntax), with environments in `http-client.env.json` | Files are git friendly, human readable, and also open in JetBrains IDEs and VS Code. See section 2.4. | +| Errors | `thiserror` in libraries, `anyhow` only in the binaries | | +| Logging | `tracing` + `tracing-subscriber`, logged to a file in the app data directory | Bug reports can include the log. | +| Paths | `directories` crate for config, data and cache dirs | | +| Secrets | `http-client.private.env.json` (git-ignored, the convention both IDEs use), optionally backed by `keyring` | | +| File dialogs | `rfd` (async API) | Native dialogs on every platform. | +| Testing | `cargo test` + `#[tokio::test]`, `insta` (snapshots), `wiremock` (async HTTP mock server), `egui_kittest` (UI) | | +| Lint / format | `cargo fmt --check`, `cargo clippy -- -D warnings`, `cargo deny` (licenses, advisories), run locally through one `check` command (see below) | There is no CI, so a single local command keeps the bar consistent. | +| License | MIT or Apache-2.0 (your call) | It is compatible with egui and curl. | + +--- + +## 2. Architecture + +### 2.1 Workspace layout + +``` +reqlite/ + Cargo.toml # [workspace], shared deps in [workspace.dependencies] + rust-toolchain.toml + deny.toml + justfile # `just check` = fmt + clippy + test + deny; `just release` = static release build + crates/ + core/ # no UI, no network, no global state, no tokio dependency + src/model.rs # Request, Header, Body, Environment, Collection + src/template.rs # {{var}} parsing and resolution + src/http.rs # trait HttpClient (async), ResolvedRequest, Response, Timings, HttpError + src/httpfile/ # .http lexer, parser, writer (lossless round-trip) + src/env.rs # http-client.env.json + private.env.json + src/collection.rs # scan a folder of .http files into a tree + src/import/ # curl.rs, postman.rs + src/export/ # curl.rs + http-curl/ # impl HttpClient for libcurl (uses tokio) + app/ # egui binary + src/main.rs # builds the tokio runtime, starts eframe + src/state.rs # AppState (pure data) + src/action.rs # enum Action, fn update(&mut AppState, Action) -> Vec + src/effects.rs # spawns Effects as tokio tasks; results come back as Actions + src/ui/ # one module per panel; reads state, emits Actions + cli/ # `reqlite run api/users.http --env dev [--name create-user]` + tests/fixtures/ # sample .http files, env files, Postman exports, curl commands +``` + +**Dependency rule:** `app` and `cli` depend on `core` and `http-curl`, and `core` depends on neither. Enforce this by keeping UI, curl and Tokio crates out of `core`'s `Cargo.toml`. `core` only defines the async trait and stays runtime-agnostic. + +### 2.2 Data flow in the app (keeps the UI testable) + +``` + UI panels ──Action──▶ update(state, action) ──Effect──▶ effects runner (tokio::spawn) + ▲ │ │ HTTP, disk, dialogs, file watching + └──── reads AppState ◀────┘◀── Action via mpsc + ctx.request_repaint() ──┘ +``` + +**Runtime setup.** `main` builds a multi-thread Tokio runtime and keeps its `Handle` in the effects runner. eframe keeps the main thread. Do not use `#[tokio::main]` around eframe, because winit needs the main thread on macOS. + +**Pure update.** UI code only draws state and pushes `Action`s. `update` is a pure, synchronous function: it changes state and returns `Effect`s such as `Effect::SendRequest { tab_id, request, cancel }`, `Effect::SaveFile { .. }` or `Effect::LoadCollection(path)`. Most behaviour is tested by calling `update` directly. + +**Running effects.** The effects runner does `handle.spawn(async move { ... })` for each effect and sends the resulting `Action` back through a `tokio::sync::mpsc::UnboundedSender`. Each frame, the UI drains the matching receiver with `try_recv` (non-blocking). The task calls `egui::Context::request_repaint()` after sending, so the UI wakes immediately. + +**Cancellation.** Each in-flight request gets a `CancellationToken`, and `Action::CancelClicked` calls `.cancel()`. The HTTP layer races the transfer against `token.cancelled()`. + +**Concurrency.** Several tabs can send at once. Requests are independent tasks, and a `Semaphore` limits concurrency (default 8). + +### 2.3 Core types and the async HTTP layer + +```rust +pub struct Request { + pub name: Option, // from `# @name` or `### Title` + pub method: Method, // GET, POST, … or Custom(String) + pub url: String, // may contain {{vars}}; query lives in the URL + pub headers: Vec
, // Header { name, value, disabled } (disabled = commented out) + pub body: Body, // None | Text(String) | FileRef(PathBuf) (`< ./file.json`) + // | Multipart(Vec) + pub directives: Directives, // @no-redirect, @no-cookie-jar, @timeout, @connection-timeout … + pub source: SourceSpan, // file + byte range, for lossless rewrite +} + +pub trait HttpClient: Send + Sync { + async fn send(&self, req: ResolvedRequest, cancel: CancellationToken) + -> Result; +} + +pub struct Response { + pub status: u16, pub http_version: String, + pub headers: Vec<(String, String)>, + pub body: BodyStore, // InMemory(Bytes) under a threshold, else TempFile(PathBuf) + pub timings: Timings, // dns, connect, tls, ttfb, total + pub size: u64, +} +``` + +**Making libcurl async: two steps behind the same trait.** + +1. **v1: `tokio::task::spawn_blocking` around a curl `Easy2` handle.** + - The async side does `tokio::select!` on the blocking join handle and `cancel.cancelled()`. + - On cancel, it sets an `AtomicBool` that curl's progress callback checks, which aborts the transfer. + - This is simple, well understood, and works for the dozens of concurrent requests a desktop app needs. +2. **Later, if needed: a curl `Multi` driver.** One dedicated thread runs `Multi::perform`/`wait`, takes new handles over a channel, and completes each request through a `oneshot`. This gives true event-driven I/O and fewer threads, and the trait signature does not change. + +The ready-made option is `isahc` (an async client built on libcurl). Check its maintenance state and Schannel/static-build story in M1 before choosing it over the small wrapper above. + +`ResolvedRequest` is the request after variable substitution. It is the only thing the HTTP layer sees, which keeps `http-curl` simple and makes "copy as curl" exact. + +### 2.4 On-disk format: `.http` files + +A collection is a folder, and each `.http` file is a group of related requests. The folder tree in the sidebar mirrors the folders and files on disk. + +``` +my-api/ + http-client.env.json # committed: shared environments + http-client.private.env.json # git-ignored: secrets, same shape + .reqlite/collection.toml # optional: sidebar ordering, app-only settings + users.http + orders/ + create-order.http + payloads/order.json +``` + +```http +### List users +GET {{base_url}}/users?limit=20 +Accept: application/json + +### Create user +# @name create-user +# @timeout 30 +POST {{base_url}}/users +Content-Type: application/json +Authorization: Bearer {{token}} + +{ "name": "Ada" } + +### Upload avatar +POST {{base_url}}/users/1/avatar +Content-Type: application/octet-stream + +< ./payloads/avatar.png +``` + +```json +// http-client.env.json +{ "dev": { "base_url": "http://localhost:8080" }, + "prod": { "base_url": "https://api.example.com" } } +``` + +**What is supported** (the subset that JetBrains and VS Code REST Client largely agree on): + +- `###` request separators with an optional title. +- Request line `METHOD URL [HTTP/version]`, with query parameters allowed on continuation lines that start with `?` or `&`. +- Headers, then a blank line, then the body. +- `{{var}}` placeholders. +- File-level variables (`@base_url = …`). +- `< ./file` body references. +- `multipart/form-data` with boundaries. +- `# @name` and `# @no-redirect`, `# @no-cookie-jar`, `# @timeout`, `# @connection-timeout`. +- `#` and `//` comments. + +**Lossless round-trip is the key rule.** The parser keeps a concrete syntax tree, including comments, blank lines, unknown directives, and response-handler blocks (`> {% … %}` and `> ./script.js`). Editing one request in the UI rewrites only that request's byte span. A file the app does not fully understand still survives an edit untouched. These blocks are shown read-only in the UI, and scripts are not run. + +**Things the format doesn't have, and where they go instead:** + +- **Auth.** Auth is just headers (`Authorization: Bearer {{token}}`). The Auth tab is a helper that writes the header. For example, Basic auth writes `Authorization: Basic {{user}} {{password}}`, which JetBrains encodes automatically, and reqlite does the same. +- **Inherited auth and default headers per folder.** These are skipped in v1. Use environment variables instead. +- **Stable request IDs.** The identity of a request is its file plus its `@name` or title, and app-side state (history, open tabs) refers to that. + +### 2.5 App data (not in the collection) + +App data lives in `directories::ProjectDirs` and holds: + +- recent collections +- window and layout state (eframe persistence) +- request history (an append-only JSON Lines file, capped) +- logs + +--- + +## 3. Milestones + +Each milestone ends with `just check` passing and something you can demo. The size estimates are in "focused evenings" and are rough. + +### M0: Skeleton and local tooling (1–2) +- Create the workspace, toolchain pin, `deny.toml`, and empty crates. +- Add a `justfile` (or a small `xtask` crate if you prefer no extra tool): + - `just check` runs fmt, clippy, all tests, and `cargo deny`. + - `just release` makes a static release build. + - Optionally add a git pre-push hook that runs `just check`. +- **Prove the static libcurl build on Windows now** (`static-curl` needs a C compiler; the MSVC Build Tools are enough). +- `main` starts a Tokio runtime next to eframe, and a dummy async task updates a label, which proves the repaint wiring works. +- **Done when:** `just check` passes on your Windows machine, and the release exe opens an egui window fed by an async task when copied to another Windows machine without Rust installed. Linux and Mac builds are checked by hand when you get to them. + +### M1: `.http` parser and async HTTP, headless (4–6) +- **`core::httpfile`:** a lexer and parser into a concrete syntax tree, a writer, and `Request` extraction. +- **`core::env`:** load public and private env files, plus file-level variables. +- **`http-curl`:** + - `HttpClient` using `spawn_blocking` around a curl `Easy2` handle, as in section 2.3. + - Bodies, redirects, timeouts, TLS verify toggle, proxy, HTTP/2, timings. + - Spill the body to a temp file above 5 MB. + - Cancellation through `CancellationToken`. +- **`cli run [--name X] --env dev`** prints the status, headers and body. This makes the core usable before any UI exists. +- **Tests:** + - **Parser:** + - a fixture corpus with snapshots of the parsed tree; + - **round-trip `parse → write` is byte-identical for every fixture**; + - fuzzing with `cargo-fuzz` on the parser (optional, cheap to add). + - **HTTP:** `wiremock` integration tests for each method and body type, redirects, timeout, cancel mid-transfer, and 20 concurrent requests. + - **TLS:** a test with a self-signed certificate. +- **Done when:** `reqlite run users.http --env dev` works against real APIs on Windows, and the same file runs in JetBrains or VS Code. + +### M2: Minimal UI, one request (3–4) +- Layout: + - top bar with method, URL and Send/Cancel + - tabs for Params, Headers, Body and Auth (the Auth helper writes a header) + - a response panel with status, time, size, and tabs for Body, Headers and Timings +- Use the `AppState`, `Action`, `update` and `Effect` pattern with Tokio effects from section 2.2. +- The URL and the Params table stay in sync both ways. +- Response body: + - pretty-printed JSON with syntax highlighting + - a Raw mode + - images shown inline + - a "Save to file" option for anything else +- A **Source** tab shows the request as `.http` text and can be edited directly. Edits there and in the form views stay in sync through the parser. +- **Tests:** + - `update()` unit tests for URL and params sync, send and receive, and cancel. + - One `egui_kittest` smoke test using a fake async `HttpClient`. +- **Done when:** you can use it for day-to-day one-off requests. + +### M3: Collections (3–4) +- Scan a folder asynchronously for `.http` files and build the sidebar tree: folder, then file, then requests. +- Create, rename, delete and duplicate requests and files. Moving a request between files is a cut-and-insert of its span. +- Multiple open tabs with a dirty marker, Ctrl+S to save (a span rewrite only), and a prompt on close when there are unsaved changes. +- Watch the folder with `notify`, run through Tokio, to reload files changed outside the app, for example after `git pull` or an edit in VS Code. If the open tab has unsaved changes, show a conflict prompt. +- **Tests:** + - Editing one request leaves the rest of the file byte-identical. + - Saving an unchanged collection writes nothing. + - A watcher test with a temp directory. +- **Done when:** a collection can be committed to git, diffs read cleanly, and the same files work in your IDE. + +### M4: Environments and variables (2–3) +- `template.rs` parses `{{name}}` with clear errors for unknown variables or unclosed braces. It resolves in this order: + 1. private environment + 2. public environment + 3. file variables + 4. built-ins: `{{$uuid}}`, `{{$timestamp}}`, `{{$randomInt}}`, which match JetBrains' `$`-prefixed dynamic variables +- An environment picker in the top bar, and an environment editor that writes the JSON files. +- Values from the private file show as `••••` in the UI, and the app offers to add the private file to `.gitignore` if it is missing. +- Unresolved variables are highlighted in the URL and header fields, and hovering a variable shows its value. +- **Tests:** table-driven tests for `template.rs` covering precedence, missing variables, escaping and built-ins. +- **Done when:** the same collection works against dev and prod by switching environments. + +### M5: Import and export (3–4) +- **Import from curl:** + - Paste a curl command into the URL bar (detect `curl ` at the start), and it becomes `.http` text. + - Tokenize with `shell-words`, plus handling for Windows `^` line continuations. + - Support `-X`, `-H`, `-d`/`--data*`, `-F`, `-u`, `-k`, `-L`, `--compressed`, and `-b`. +- **Copy as curl** comes from the `ResolvedRequest`, and **copy as `.http`** is the raw request span. +- **Postman Collection v2.1 import:** + - Writes `.http` files plus `http-client.env.json`. + - Folders become directories and requests become `###` blocks. + - Pre-request and test scripts are skipped, and the import summary lists them as warnings. +- **Tests:** + - A fixtures folder of real-world curl commands (copied from Chrome and Firefox devtools on Windows and Unix) with snapshot results. + - A few Postman exports, with snapshots of the generated `.http` files. +- **Done when:** you can migrate your existing Postman collections. + +### M6: Everyday features (3–4) +- Auth helpers for Basic and Bearer. OAuth2 is post-v1. +- Cookie jar per collection, held in memory, respecting `@no-cookie-jar`, with a viewer. +- A history panel (last N requests sent), with a button to restore one into a new tab. +- Settings: default timeout, proxy (system, none or manual), TLS (system store, custom CA file), and font size and theme. +- Keyboard shortcuts: + + | Shortcut | Action | + |---|---| + | Ctrl+Enter | Send | + | Ctrl+T | New tab | + | Ctrl+W | Close tab | + | Ctrl+L | Focus the URL bar | + | Ctrl+P | Quick-open a request | + +- **Done when:** you no longer need Postman for your normal work. + +### M7: Robustness and release (3–4) +- **Large responses:** + - Virtualized line viewer (`ScrollArea::show_rows`). + - JSON is pretty-printed in a `spawn_blocking` task, with a "show raw" option. + - Search in the response with Ctrl+F. +- **Memory check:** measure idle and after-large-response RAM on Windows (the Tokio runtime adds a few MB at most), and note the binary size per release. +- **Windows packaging:** + - Embed an icon and version info with `winres`. + - Choose a portable zip and/or an MSI via `cargo-wix`. + - Code signing is optional; without it, SmartScreen shows a warning. +- **Linux and Mac:** AppImage or tarball, and a `.app` bundle via `cargo-bundle`. +- **Releases:** run `just release` on each OS by hand, tag the commit, and upload the files (for example to a GitHub Release). A release workflow can be added if CI comes later. +- **Done when:** v0.1.0 is downloadable and runs on a clean Windows machine with no extra installs. + +**Total: roughly 25–35 focused evenings to v0.1.0.** The `.http` parser adds a little to M1, but M3 gets simpler because there is no custom format to design. + +### Post-v1 backlog (in rough priority order) +- A curl `Multi` driver behind the same `HttpClient` trait (see section 2.3), if many concurrent requests ever matter. +- OAuth2 (authorization code + PKCE, client credentials) with token caching. +- Per-folder default headers and auth (an app-side extension in `.reqlite/`). +- Request chaining via `{{create-user.response.body.$.id}}`. This is VS Code REST Client syntax; JetBrains does chaining through scripts. +- OpenAPI import (generate `.http` files from a spec). +- WebSocket and Server-Sent Events (these fit naturally now that the app is async). +- GraphQL body type with schema fetch. +- Response diff between two history entries. +- Command palette. + +Deliberately out of scope: running response-handler scripts, test runners, mock servers and cloud sync. + +--- + +## 4. Testing strategy summary + +| Layer | How | When | +|---|---|---| +| `core` parser and writer | A fixture corpus, `insta` snapshots, byte-identical round-trips, optional fuzzing | `just check` | +| `core` template, env, import/export | Unit and table-driven tests, snapshots | `just check` | +| `http-curl` | `#[tokio::test]` against a `wiremock` server; cancel and concurrency tests; self-signed TLS test | `just check` | +| App logic | Call `update(state, action)` and assert on state and effects; run effects against a fake async `HttpClient` | `just check` | +| UI | A few `egui_kittest` smoke tests per panel | `just check` | +| End to end | `cli run` against fixture `.http` files and `wiremock` | `just check` | +| Compatibility | Fixture files that are checked to also run in JetBrains and VS Code REST Client (manual, per release) | Per release | +| Manual | A release checklist: Windows clean VM, corporate proxy, HiDPI/multi-monitor | Per release | + +**Rule of thumb:** if a bug can be reproduced without a window, the regression test goes in `core` or in `update()`, not in the UI tests. + +--- + +## 5. Risks and mitigations + +| Risk | Mitigation | +|---|---| +| The static libcurl build breaks on Windows or Mac | Proved in M0 on your own machine, and rechecked on each OS before a release. A fallback `reqwest` implementation of `HttpClient` (natively async) is possible thanks to the trait. | +| Mixing Tokio and the egui event loop | The runtime runs on its own threads, the UI never blocks on futures, and results arrive over a channel plus `request_repaint`. This is proven in M0. | +| Cancellation not stopping curl promptly | The progress callback checks the cancel flag every call. A test cancels a slow `wiremock` response and checks that the task ends within 200 ms. | +| `.http` dialect differences between JetBrains and VS Code | Support the common subset, keep unknown syntax verbatim (lossless parser), and document which dialect features are recognized. | +| Lossless parsing is harder than parse-and-reformat | A concrete syntax tree with byte spans from the start, and a byte-identical round-trip test over every fixture in `just check`. | +| egui text editing is too limited for large bodies | Body editing is capped and large bodies are view-only. Evaluate a code-editor crate only if it actually hurts. | +| egui breaking changes between versions | Pin versions and upgrade deliberately. UI code is isolated in `app/src/ui`. | +| Scope creep toward "Postman" | The out-of-scope list above. Scripts in `.http` files are preserved but never run. | + +--- + +## 6. First concrete steps + +1. Create the repository, the workspace skeleton and the `justfile` (M0). +2. Build a static Windows exe where an async task updates the egui window, and check that it runs on a machine without Rust installed. +3. Collect 15–20 real `.http` fixture files (your own requests, plus examples from the JetBrains and VS Code REST Client docs), then write the parser test-first against them (M1). diff --git a/justfile b/justfile new file mode 100644 index 0000000..a11eeb7 --- /dev/null +++ b/justfile @@ -0,0 +1,69 @@ +# reqlite tasks. Install `just` and `cargo-deny`: +# cargo install --locked just cargo-deny + +set windows-shell := ["powershell.exe", "-NoLogo", "-Command"] + +# The quality bar: format, lint, test, licenses/advisories. +check: fmt-check clippy test deny + +fmt: + cargo fmt --all + +fmt-check: + cargo fmt --all -- --check + +clippy: + cargo clippy --workspace --all-targets -- -D warnings + +test: + cargo test --workspace + +deny: + cargo deny check + +# Accept changed insta snapshots after reviewing them. +snapshots: + INSTA_UPDATE=always cargo test --workspace + +# Static release build of the GUI and the CLI (libcurl is linked in). +release: + cargo build --release --workspace + @echo "Binaries are in target/release/: reqlite-gui and reqlite" + +# The GUI with the OpenGL renderer, for old GPUs, VMs and remote desktops. +release-glow: + cargo build --release -p reqlite-app --features glow + +run *ARGS: + cargo run -p reqlite-app -- {{ARGS}} + +cli *ARGS: + cargo run -p reqlite-cli -- {{ARGS}} + +# Install a git pre-push hook that runs `just check`. +install-hook: + printf '#!/bin/sh\nexec just check\n' > .git/hooks/pre-push + chmod +x .git/hooks/pre-push + +# Linux tarball: target/dist/reqlite--linux-.tar.gz +package-linux: release + #!/usr/bin/env sh + set -eu + version=$(cargo pkgid -p reqlite-app | sed 's/.*[#@]//') + name="reqlite-${version}-linux-$(uname -m)" + dir="target/dist/${name}" + rm -rf "$dir" && mkdir -p "$dir" + cp target/release/reqlite-gui target/release/reqlite "$dir/" + cp crates/app/assets/icon.png "$dir/reqlite.png" + cp crates/app/assets/reqlite.desktop README.md "$dir/" + tar -C target/dist -czf "target/dist/${name}.tar.gz" "$name" + echo "target/dist/${name}.tar.gz" + +# Windows portable zip: target\dist\reqlite--windows-x86_64.zip +package-windows: release + $version = (cargo pkgid -p reqlite-app) -replace '.*[#@]', ''; \ + $dir = "target/dist/reqlite-$version-windows-x86_64"; \ + New-Item -ItemType Directory -Force -Path $dir | Out-Null; \ + Copy-Item target/release/reqlite-gui.exe, target/release/reqlite.exe, README.md -Destination $dir; \ + Compress-Archive -Force -Path $dir -DestinationPath "$dir.zip"; \ + Write-Output "$dir.zip" diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..68c0ea2 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "1.98.1" +components = ["rustfmt", "clippy"] diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..7530651 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1 @@ +max_width = 120 diff --git a/tests/fixtures/curl/chrome-bash-get.txt b/tests/fixtures/curl/chrome-bash-get.txt new file mode 100644 index 0000000..5bf260d --- /dev/null +++ b/tests/fixtures/curl/chrome-bash-get.txt @@ -0,0 +1,8 @@ +curl 'https://api.github.com/repos/rust-lang/rust/issues?state=open&per_page=5' \ + -H 'accept: application/vnd.github+json' \ + -H 'accept-language: en-US,en;q=0.9,sv;q=0.8' \ + -H 'cache-control: no-cache' \ + -H 'origin: https://github.com' \ + -H 'priority: u=1, i' \ + -H 'sec-fetch-mode: cors' \ + -H 'user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36' diff --git a/tests/fixtures/curl/chrome-bash-post-ansi-c.txt b/tests/fixtures/curl/chrome-bash-post-ansi-c.txt new file mode 100644 index 0000000..f57eca3 --- /dev/null +++ b/tests/fixtures/curl/chrome-bash-post-ansi-c.txt @@ -0,0 +1,5 @@ +curl 'https://example.com/api/graphql' \ + -H 'accept: */*' \ + -H 'content-type: application/json' \ + -b 'session=abc123; theme=dark' \ + --data-raw $'{"query":"query { me { name } }","note":"it\'s here\\nnext line"}' diff --git a/tests/fixtures/curl/chrome-cmd-crlf.txt b/tests/fixtures/curl/chrome-cmd-crlf.txt new file mode 100644 index 0000000..d4c099f --- /dev/null +++ b/tests/fixtures/curl/chrome-cmd-crlf.txt @@ -0,0 +1,3 @@ +curl ^"https://example.com/search?q=a^%20b^" ^ + -H ^"accept: text/html^" ^ + --compressed diff --git a/tests/fixtures/curl/chrome-cmd-post.txt b/tests/fixtures/curl/chrome-cmd-post.txt new file mode 100644 index 0000000..f3413e0 --- /dev/null +++ b/tests/fixtures/curl/chrome-cmd-post.txt @@ -0,0 +1,5 @@ +curl ^"https://example.com/api/items?page=2^&size=10^" ^ + -H ^"accept: application/json^" ^ + -H ^"content-type: application/json^" ^ + -H ^"user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36^" ^ + --data-raw ^"^{^\^"name^\^":^\^"Widget 50^%^\^",^\^"price^\^":9.5^}^" diff --git a/tests/fixtures/curl/firefox-posix-form.txt b/tests/fixtures/curl/firefox-posix-form.txt new file mode 100644 index 0000000..35ef2d4 --- /dev/null +++ b/tests/fixtures/curl/firefox-posix-form.txt @@ -0,0 +1 @@ +curl 'https://httpbin.org/post' -X POST -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0' -H 'Content-Type: application/x-www-form-urlencoded' -H 'Origin: https://httpbin.org' --data-raw 'a=1&b=two%20words' diff --git a/tests/fixtures/curl/firefox-posix-get.txt b/tests/fixtures/curl/firefox-posix-get.txt new file mode 100644 index 0000000..92847e8 --- /dev/null +++ b/tests/fixtures/curl/firefox-posix-get.txt @@ -0,0 +1 @@ +curl 'https://developer.mozilla.org/api/v1/whoami' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0' -H 'Accept: */*' -H 'Accept-Language: en-US,en;q=0.5' -H 'Accept-Encoding: gzip, deflate, br, zstd' -H 'Referer: https://developer.mozilla.org/en-US/' -H 'Connection: keep-alive' -H 'Sec-Fetch-Mode: cors' diff --git a/tests/fixtures/curl/firefox-windows.txt b/tests/fixtures/curl/firefox-windows.txt new file mode 100644 index 0000000..fb8263b --- /dev/null +++ b/tests/fixtures/curl/firefox-windows.txt @@ -0,0 +1 @@ +curl.exe "https://httpbin.org/anything" -X PUT -H "Content-Type: application/json" --data-raw "{""ok"":true}" diff --git a/tests/fixtures/curl/manual-basic-auth-insecure.txt b/tests/fixtures/curl/manual-basic-auth-insecure.txt new file mode 100644 index 0000000..2e3ac27 --- /dev/null +++ b/tests/fixtures/curl/manual-basic-auth-insecure.txt @@ -0,0 +1 @@ +curl -sSLk -u admin:s3cret -XDELETE https://localhost:8443/api/users/42 --max-time 10 diff --git a/tests/fixtures/curl/manual-data-from-file.txt b/tests/fixtures/curl/manual-data-from-file.txt new file mode 100644 index 0000000..bbec773 --- /dev/null +++ b/tests/fixtures/curl/manual-data-from-file.txt @@ -0,0 +1,3 @@ +curl -X PATCH https://api.example.com/users/1 \ + -H "Content-Type: application/json" \ + --data-binary @payloads/patch.json diff --git a/tests/fixtures/curl/manual-get-with-data.txt b/tests/fixtures/curl/manual-get-with-data.txt new file mode 100644 index 0000000..2281d86 --- /dev/null +++ b/tests/fixtures/curl/manual-get-with-data.txt @@ -0,0 +1 @@ +curl -G https://api.example.com/search --data-urlencode 'q=rust lang' -d page=2 -A 'reqlite-test/1.0' diff --git a/tests/fixtures/curl/manual-head-http2.txt b/tests/fixtures/curl/manual-head-http2.txt new file mode 100644 index 0000000..80a11e9 --- /dev/null +++ b/tests/fixtures/curl/manual-head-http2.txt @@ -0,0 +1 @@ +curl -I --http2 https://example.com/ diff --git a/tests/fixtures/curl/manual-json-flag.txt b/tests/fixtures/curl/manual-json-flag.txt new file mode 100644 index 0000000..c22ad4f --- /dev/null +++ b/tests/fixtures/curl/manual-json-flag.txt @@ -0,0 +1 @@ +curl --json '{"name":"Ada"}' https://api.example.com/users diff --git a/tests/fixtures/curl/manual-multipart.txt b/tests/fixtures/curl/manual-multipart.txt new file mode 100644 index 0000000..71bce92 --- /dev/null +++ b/tests/fixtures/curl/manual-multipart.txt @@ -0,0 +1 @@ +curl -F 'title=Holiday photo' -F 'file=@./photos/beach.jpg;type=image/jpeg' -F 'meta=<./meta.json' https://upload.example.com/v1/photos diff --git a/tests/fixtures/http/01-simple-get.http b/tests/fixtures/http/01-simple-get.http new file mode 100644 index 0000000..7de0b04 --- /dev/null +++ b/tests/fixtures/http/01-simple-get.http @@ -0,0 +1 @@ +GET https://httpbin.org/get diff --git a/tests/fixtures/http/02-titles-and-names.http b/tests/fixtures/http/02-titles-and-names.http new file mode 100644 index 0000000..ca781dd --- /dev/null +++ b/tests/fixtures/http/02-titles-and-names.http @@ -0,0 +1,18 @@ +### List users +GET {{base_url}}/users?limit=20 +Accept: application/json + +### Create user +# @name create-user +# @timeout 30 +POST {{base_url}}/users +Content-Type: application/json +Authorization: Bearer {{token}} + +{ "name": "Ada" } + +### Upload avatar +POST {{base_url}}/users/1/avatar +Content-Type: application/octet-stream + +< ./payloads/avatar.png diff --git a/tests/fixtures/http/03-file-variables.http b/tests/fixtures/http/03-file-variables.http new file mode 100644 index 0000000..ef18251 --- /dev/null +++ b/tests/fixtures/http/03-file-variables.http @@ -0,0 +1,7 @@ +@host = localhost:8080 +@base = http://{{host}}/api + +# Comments before the first request +// and in both styles + +GET {{base}}/health diff --git a/tests/fixtures/http/04-query-continuation.http b/tests/fixtures/http/04-query-continuation.http new file mode 100644 index 0000000..5f65770 --- /dev/null +++ b/tests/fixtures/http/04-query-continuation.http @@ -0,0 +1,6 @@ +### Search with params on separate lines +GET https://api.example.com/search + ?q=rust + &page=2 + &per_page=50 +Accept: application/json diff --git a/tests/fixtures/http/05-comments-everywhere.http b/tests/fixtures/http/05-comments-everywhere.http new file mode 100644 index 0000000..1b58ce6 --- /dev/null +++ b/tests/fixtures/http/05-comments-everywhere.http @@ -0,0 +1,14 @@ +# A file-level comment + +### Get thing +// A comment before the request line +# @name get-thing +GET https://api.example.com/things/1 +# X-Debug: true +Accept: application/json +// a stray comment among headers + +### + +# Unnamed request after a bare separator +DELETE https://api.example.com/things/1 diff --git a/tests/fixtures/http/06-multipart.http b/tests/fixtures/http/06-multipart.http new file mode 100644 index 0000000..fbbfb1d --- /dev/null +++ b/tests/fixtures/http/06-multipart.http @@ -0,0 +1,14 @@ +### Upload with form fields +POST https://api.example.com/upload +Content-Type: multipart/form-data; boundary=WebAppBoundary + +--WebAppBoundary +Content-Disposition: form-data; name="description" + +A picture of a cat +--WebAppBoundary +Content-Disposition: form-data; name="file"; filename="cat.png" +Content-Type: image/png + +< ./cat.png +--WebAppBoundary-- diff --git a/tests/fixtures/http/07-response-handler.http b/tests/fixtures/http/07-response-handler.http new file mode 100644 index 0000000..23a457c --- /dev/null +++ b/tests/fixtures/http/07-response-handler.http @@ -0,0 +1,23 @@ +### Login +POST {{base_url}}/login +Content-Type: application/json + +{ + "user": "ada", + "password": "{{password}}" +} + +> {% + client.global.set("token", response.body.token); + client.test("ok", function() { + client.assert(response.status === 200); + }); +%} + +### Me +GET {{base_url}}/me +Authorization: Bearer {{token}} + +> ./scripts/check-me.js + +<> ./responses/me-2024-01-01.json diff --git a/tests/fixtures/http/08-http-version.http b/tests/fixtures/http/08-http-version.http new file mode 100644 index 0000000..7bd6aa8 --- /dev/null +++ b/tests/fixtures/http/08-http-version.http @@ -0,0 +1,6 @@ +### HTTP/2 +GET https://nghttp2.org/httpbin/get HTTP/2 + +### HTTP/1.1 explicit +GET https://example.com/ HTTP/1.1 +Host: example.com diff --git a/tests/fixtures/http/09-url-only.http b/tests/fixtures/http/09-url-only.http new file mode 100644 index 0000000..2ff2ec1 --- /dev/null +++ b/tests/fixtures/http/09-url-only.http @@ -0,0 +1,5 @@ +https://example.com/no-method + +### + +example.com/no-scheme diff --git a/tests/fixtures/http/10-directives.http b/tests/fixtures/http/10-directives.http new file mode 100644 index 0000000..5ec78cb --- /dev/null +++ b/tests/fixtures/http/10-directives.http @@ -0,0 +1,9 @@ +### All the directives +# @name everything +# @no-redirect +# @no-cookie-jar +# @no-log +# @timeout 600 +# @connection-timeout 2 s +# @some-future-directive with a value +GET https://example.com/redirect diff --git a/tests/fixtures/http/11-crlf.http b/tests/fixtures/http/11-crlf.http new file mode 100644 index 0000000..3ef6c02 --- /dev/null +++ b/tests/fixtures/http/11-crlf.http @@ -0,0 +1,9 @@ +### Windows line endings +POST https://example.com/crlf +Content-Type: text/plain + +line one +line two + +### Second +GET https://example.com/ diff --git a/tests/fixtures/http/12-no-trailing-newline.http b/tests/fixtures/http/12-no-trailing-newline.http new file mode 100644 index 0000000..c331f7f --- /dev/null +++ b/tests/fixtures/http/12-no-trailing-newline.http @@ -0,0 +1,5 @@ +### No trailing newline +POST https://example.com/x +Content-Type: application/json + +{"a": 1} \ No newline at end of file diff --git a/tests/fixtures/http/13-graphql.http b/tests/fixtures/http/13-graphql.http new file mode 100644 index 0000000..2b3c4c8 --- /dev/null +++ b/tests/fixtures/http/13-graphql.http @@ -0,0 +1,8 @@ +### GraphQL query +POST https://api.github.com/graphql +Content-Type: application/json +Authorization: Bearer {{github_token}} + +{ + "query": "query { viewer { login } }" +} diff --git a/tests/fixtures/http/14-form-urlencoded.http b/tests/fixtures/http/14-form-urlencoded.http new file mode 100644 index 0000000..4d1444d --- /dev/null +++ b/tests/fixtures/http/14-form-urlencoded.http @@ -0,0 +1,7 @@ +### OAuth token +POST https://auth.example.com/oauth/token +Content-Type: application/x-www-form-urlencoded + +grant_type=client_credentials& +client_id={{client_id}}& +client_secret={{client_secret}} diff --git a/tests/fixtures/http/15-substituted-file.http b/tests/fixtures/http/15-substituted-file.http new file mode 100644 index 0000000..e41261e --- /dev/null +++ b/tests/fixtures/http/15-substituted-file.http @@ -0,0 +1,5 @@ +### Body from a template file +PUT {{base_url}}/orders/42 +Content-Type: application/json + +<@ ./payloads/order.json diff --git a/tests/fixtures/http/16-custom-methods.http b/tests/fixtures/http/16-custom-methods.http new file mode 100644 index 0000000..12cbe5b --- /dev/null +++ b/tests/fixtures/http/16-custom-methods.http @@ -0,0 +1,12 @@ +### WebDAV +PROPFIND https://dav.example.com/files/ +Depth: 1 + +### Patch +PATCH https://api.example.com/users/1 +Content-Type: application/merge-patch+json + +{"name":"Grace"} + +### Options +OPTIONS https://api.example.com/ diff --git a/tests/fixtures/http/17-blank-lines-and-spacing.http b/tests/fixtures/http/17-blank-lines-and-spacing.http new file mode 100644 index 0000000..6306922 --- /dev/null +++ b/tests/fixtures/http/17-blank-lines-and-spacing.http @@ -0,0 +1,19 @@ + + +### Lots of space around + + +GET https://example.com/a + + + +### Body with blank lines inside +POST https://example.com/b +Content-Type: text/plain + +first paragraph + +second paragraph + + + diff --git a/tests/fixtures/http/18-vscode-style.http b/tests/fixtures/http/18-vscode-style.http new file mode 100644 index 0000000..df1d68c --- /dev/null +++ b/tests/fixtures/http/18-vscode-style.http @@ -0,0 +1,20 @@ +@baseUrl = https://example.com/api + +# @name login +POST {{baseUrl}}/api/login HTTP/1.1 +Content-Type: application/x-www-form-urlencoded + +name=foo&password=bar + +### + +@authToken = {{login.response.headers.X-AuthToken}} + +# @name createComment +POST {{baseUrl}}/comments HTTP/1.1 +Authorization: {{authToken}} +Content-Type: application/json + +{ + "content": "fake content" +} diff --git a/tests/fixtures/http/19-only-comments.http b/tests/fixtures/http/19-only-comments.http new file mode 100644 index 0000000..6f53e1a --- /dev/null +++ b/tests/fixtures/http/19-only-comments.http @@ -0,0 +1,3 @@ +# This file has no requests yet. +// Just notes. +@base = http://localhost diff --git a/tests/fixtures/http/20-json-with-hash-lines.http b/tests/fixtures/http/20-json-with-hash-lines.http new file mode 100644 index 0000000..0ac9409 --- /dev/null +++ b/tests/fixtures/http/20-json-with-hash-lines.http @@ -0,0 +1,7 @@ +### Body lines starting with # or // are body, not comments +POST https://example.com/markdown +Content-Type: text/markdown + +# Heading +// not a comment +Some text diff --git a/tests/fixtures/postman/shop-dev.postman_environment.json b/tests/fixtures/postman/shop-dev.postman_environment.json new file mode 100644 index 0000000..cf94eab --- /dev/null +++ b/tests/fixtures/postman/shop-dev.postman_environment.json @@ -0,0 +1,11 @@ +{ + "id": "3b0f6f2e-2222-4c1d-8e9a-77a1d0c0ab12", + "name": "Shop dev", + "values": [ + { "key": "baseUrl", "value": "http://localhost:8080/api", "type": "default", "enabled": true }, + { "key": "token", "value": "dev-token-123", "type": "secret", "enabled": true }, + { "key": "adminPass", "value": "hunter2", "type": "secret", "enabled": true }, + { "key": "old", "value": "x", "type": "default", "enabled": false } + ], + "_postman_variable_scope": "environment" +} diff --git a/tests/fixtures/postman/shop.postman_collection.json b/tests/fixtures/postman/shop.postman_collection.json new file mode 100644 index 0000000..ae2d64e --- /dev/null +++ b/tests/fixtures/postman/shop.postman_collection.json @@ -0,0 +1,164 @@ +{ + "info": { + "_postman_id": "8f1c2b6e-1111-4a3b-9c55-0d6f2a7b9e01", + "name": "Shop API", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "auth": { + "type": "bearer", + "bearer": [{ "key": "token", "value": "{{token}}", "type": "string" }] + }, + "event": [ + { "listen": "prerequest", "script": { "type": "text/javascript", "exec": [""] } } + ], + "variable": [ + { "key": "baseUrl", "value": "https://shop.example.com/api" }, + { "key": "pageSize", "value": 20 } + ], + "item": [ + { + "name": "Health", + "request": { + "auth": { "type": "noauth" }, + "method": "GET", + "header": [], + "url": { "raw": "{{baseUrl}}/health", "host": ["{{baseUrl}}"], "path": ["health"] } + } + }, + { + "name": "Products", + "item": [ + { + "name": "List products", + "request": { + "method": "GET", + "header": [ + { "key": "Accept", "value": "application/json" }, + { "key": "X-Debug", "value": "1", "disabled": true } + ], + "url": { + "raw": "{{baseUrl}}/products?limit={{pageSize}}&sort=name", + "host": ["{{baseUrl}}"], + "path": ["products"], + "query": [ + { "key": "limit", "value": "{{pageSize}}" }, + { "key": "sort", "value": "name" } + ] + } + }, + "event": [ + { + "listen": "test", + "script": { "exec": ["pm.test(\"ok\", () => pm.response.to.have.status(200));"], "type": "text/javascript" } + } + ] + }, + { + "name": "Create product", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"name\": \"Widget\",\r\n \"price\": 9.5\r\n}", + "options": { "raw": { "language": "json" } } + }, + "url": "{{baseUrl}}/products" + } + }, + { + "name": "Upload image", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "formdata", + "formdata": [ + { "key": "caption", "value": "Front view", "type": "text" }, + { "key": "image", "type": "file", "src": "/home/me/widget.png" }, + { "key": "draft", "value": "true", "type": "text", "disabled": true } + ] + }, + "url": "{{baseUrl}}/products/1/image" + } + }, + { + "name": "Admin", + "auth": { + "type": "basic", + "basic": [ + { "key": "password", "value": "{{adminPass}}", "type": "string" }, + { "key": "username", "value": "admin", "type": "string" } + ] + }, + "item": [ + { + "name": "Delete product", + "request": { "method": "DELETE", "header": [], "url": "{{baseUrl}}/products/1" } + }, + { + "name": "Search (GraphQL)", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "graphql", + "graphql": { "query": "query { products { id name } }", "variables": "{\"first\": 5}" } + }, + "url": "{{baseUrl}}/graphql" + } + } + ] + } + ] + }, + { + "name": "Auth", + "item": [ + { + "name": "Token", + "request": { + "auth": { "type": "noauth" }, + "method": "POST", + "header": [], + "body": { + "mode": "urlencoded", + "urlencoded": [ + { "key": "grant_type", "value": "client_credentials" }, + { "key": "client_id", "value": "{{clientId}}" }, + { "key": "scope", "value": "shop", "disabled": true } + ] + }, + "url": "https://auth.example.com/oauth/token" + }, + "event": [ + { "listen": "test", "script": { "exec": ["pm.environment.set('token', pm.response.json().access_token);"] } } + ] + }, + { + "name": "API key ping", + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { "key": "key", "value": "X-Api-Key" }, + { "key": "value", "value": "{{apiKey}}" }, + { "key": "in", "value": "header" } + ] + }, + "method": "GET", + "url": "{{baseUrl}}/ping" + } + }, + { + "name": "Digest thing", + "request": { + "auth": { "type": "digest", "digest": [] }, + "method": "GET", + "url": "{{baseUrl}}/digest" + } + } + ] + } + ] +}