diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d3c09fd..c65fc66 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,3 +56,25 @@ jobs: - uses: Swatinem/rust-cache@v2 # Unit, integration (incl. trybuild compile tests), examples and doc tests. - run: cargo test --workspace --all-features + + no_std: + name: no_std (seamless_info, seamless_ts) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@stable + with: + targets: thumbv7em-none-eabi + - uses: Swatinem/rust-cache@v2 + # thumbv7em-none-eabi has no std, so this fails if seamless_info or seamless_ts + # (or any of their dependencies, for any combination of features) start relying on std. + - name: Build (no features) + run: cargo build -p seamless_info --target thumbv7em-none-eabi + - name: Build (serialize) + run: cargo build -p seamless_info --target thumbv7em-none-eabi --features serialize + - name: Build (deserialize) + run: cargo build -p seamless_info --target thumbv7em-none-eabi --features deserialize + - name: Build (all features) + run: cargo build -p seamless_info --target thumbv7em-none-eabi --all-features + - name: Build seamless_ts + run: cargo build -p seamless_ts --target thumbv7em-none-eabi diff --git a/CHANGELOG.md b/CHANGELOG.md index 6857ec3..65ccf55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ +# 0.15.0 + +- Add a `no_std` `seamless-ts` crate, whose `generate_types()` function takes the JSON serialized info for an API (from `Api::info()`) and writes TypeScript to any `core::fmt::Write`, exporting an `Api` type which describes the method, params and result type of every route, and a readonly `methods` object holding the method of every route for use at runtime. +- Add a `seamless_ts_bin` crate providing a `seamless-ts` CLI tool, which reads the JSON serialized info for an API from stdin (or a file given with `--file`, or a URL given with `--url`, optionally sending headers given with `-H`/`--header`) and writes the generated TypeScript to stdout. + # 0.14.0 +- **Breaking:** `Api::add()` now panics if given an empty path (or one made up only of slashes). +- **Breaking:** `ApiBodyType::Object { keys }` is now a `BTreeMap` rather than a `HashMap`, since `HashMap` isn't available in `no_std`. Object keys are now serialized in a stable (sorted) order as a result. +- `ApiBody` is now implemented for `BTreeMap`. - **Breaking:** Remove the `IntoBody` trait. Unwrap body types directly instead, either by pattern matching in the handler arguments (eg `|Capped(FromJson(body)): Capped, N>| ...`) or via `.0`. - **Breaking:** `Option` is now described as `OneOf [T, Null]` (ie `T | null`) rather than `Optional`, since serde serializes `None` as `null`. Previously, clients generated from the info would wrongly expect the key to be omitted. - Add `#[api_body(optional)]` for `Option` fields in `ApiBody` structs and enum variants. The field is described as `Optional` (ie `{ key?: T }`), is omitted from the JSON when `None`, and is treated as `None` when missing. diff --git a/Cargo.lock b/Cargo.lock index 718f1aa..68eeb91 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,62 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[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 = "autocfg" version = "1.1.0" @@ -72,18 +128,89 @@ dependencies = [ "syn 2.0.90", ] +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "bytes" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "325918d6fe32f23b19878fe4b34794ae41fc19ddbe53b10571a4874d44ffd39b" +[[package]] +name = "cc" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[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.4", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + [[package]] name = "diff" version = "0.1.13" @@ -96,6 +223,23 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "fnv" version = "1.0.7" @@ -199,6 +343,17 @@ dependencies = [ "slab", ] +[[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 = "glob" version = "0.3.1" @@ -211,6 +366,12 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "http" version = "1.2.0" @@ -302,6 +463,12 @@ dependencies = [ "hashbrown", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itoa" version = "1.0.5" @@ -316,12 +483,9 @@ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "log" -version = "0.4.17" +version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" -dependencies = [ - "cfg-if", -] +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" [[package]] name = "matchit" @@ -341,6 +505,16 @@ version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" +[[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" @@ -349,7 +523,7 @@ checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "wasi", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -358,11 +532,17 @@ version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f61fba1741ea2b3d6a1e3178721804bb716a68a6aeba1149b5d52e3d464ea66" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "percent-encoding" -version = "2.2.0" +version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" [[package]] name = "pin-project-lite" @@ -382,22 +562,71 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.92" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.37" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "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.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "ryu" version = "1.0.12" @@ -406,7 +635,7 @@ checksum = "7b4b9743ed687d4b4bcedf9ff5eaa7398495ae14e61cba0a295704edbc7decde" [[package]] name = "seamless" -version = "0.14.0" +version = "0.15.0" dependencies = [ "axum", "bytes", @@ -416,6 +645,7 @@ dependencies = [ "hyper", "hyper-util", "pretty_assertions", + "seamless_info", "seamless_macros", "serde", "serde_json", @@ -426,9 +656,17 @@ dependencies = [ "uuid", ] +[[package]] +name = "seamless_info" +version = "0.15.0" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "seamless_macros" -version = "0.14.0" +version = "0.15.0" dependencies = [ "proc-macro2", "quote", @@ -438,6 +676,26 @@ dependencies = [ "syn 3.0.4", ] +[[package]] +name = "seamless_ts" +version = "0.15.0" +dependencies = [ + "pretty_assertions", + "seamless", + "seamless_info", + "serde_json", + "thiserror", +] + +[[package]] +name = "seamless_ts_bin" +version = "0.15.0" +dependencies = [ + "clap", + "seamless_ts", + "ureq", +] + [[package]] name = "serde" version = "1.0.229" @@ -512,6 +770,18 @@ dependencies = [ "serde", ] +[[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 = "slab" version = "0.4.7" @@ -534,9 +804,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] +[[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 = "syn" version = "2.0.90" @@ -611,7 +893,7 @@ dependencies = [ "pin-project-lite", "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -749,6 +1031,53 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" +dependencies = [ + "base64", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "uuid" version = "1.2.2" @@ -761,6 +1090,15 @@ version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "winapi" version = "0.3.9" @@ -798,6 +1136,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -807,6 +1154,70 @@ 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", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[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_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[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_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[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_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "winnow" version = "1.0.4" @@ -819,6 +1230,18 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[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" diff --git a/Cargo.toml b/Cargo.toml index fd4fd7e..f96425d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,12 +1,15 @@ [workspace] members = [ "seamless", - "seamless-macros" + "seamless-info", + "seamless-macros", + "seamless-ts", + "seamless-ts-bin" ] resolver = "3" [workspace.package] -version = "0.14.0" +version = "0.15.0" authors = ["James Wilson "] edition = "2024" license = "MIT" @@ -17,14 +20,19 @@ keywords = ["api", "http", "rpc", "json"] [workspace.dependencies] # Workspace crates seamless = { path = "seamless" } -seamless_macros = { version = "0.14.0", path = "seamless-macros" } +seamless_macros = { version = "0.15.0", path = "seamless-macros" } +seamless_info = { version = "0.15.0", path = "seamless-info", default-features = false } +seamless_ts = { version = "0.15.0", path = "seamless-ts" } # Dependencies -serde = { version = "1", features = ["derive"] } -serde_json = "1" +serde = { version = "1", default-features = false, features = ["derive", "alloc"] } +serde_json = { version = "1", default-features = false, features = ["alloc"] } http = "1" futures = "0.3.34" bytes = "1" +thiserror = { version = "2", default-features = false } +clap = { version = "4.6.7", features = ["derive"] } +ureq = "3.5.0" uuid = "1" syn = { version = "3", features = ["full", "extra-traits"] } quote = "1" @@ -33,7 +41,6 @@ proc-macro2 = "1" # Dev dependencies trybuild = "1.0.120" pretty_assertions = "1" -thiserror = "2" tokio = { version = "1.1.0", features = ["rt", "rt-multi-thread", "macros", "net"] } tokio-util = { version = "0.6.7", features = ["compat"] } axum = { version = "0.8.9", features = ["macros"] } diff --git a/PUBLISHING.md b/PUBLISHING.md index db93235..cb6ff39 100644 --- a/PUBLISHING.md +++ b/PUBLISHING.md @@ -23,7 +23,7 @@ Copy any doc changes from `seamless/lib.rs` to the edited versions of `seamless/ ## Bump versions -Bump the version in `seamless/Cargo.toml` and `seamless-macros/Cargo.toml`. +Bump the version in the root `Cargo.toml` (both `workspace.package.version` and the `seamless_macros` and `seamless_info` workspace dependency versions). ## Update CHANGELOG.md @@ -40,9 +40,8 @@ git push origin master --tags ## Publish -Publish the macro crate first since the main crate depends on it existing. +Run this in the workspace to publish everything ``` -(cd seamless-macros && cargo publish) -(cd seamless && cargo publish) +cargo publish ``` \ No newline at end of file diff --git a/README.md b/README.md index 503b8e2..24418db 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ [![Docs.rs](https://img.shields.io/docsrs/seamless)](https://docs.rs/seamless) [![CI](https://github.com/jsdw/seamless/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/jsdw/seamless/actions/workflows/ci.yml) -[See the examples](./seamless/examples/) +[See the examples](https://github.com/jsdw/seamless/tree/master/seamless/examples) Seamless provides a way to declare a simple RPC style HTTP API, and from this declaration can hand back enough information that we can generate a type safe HTTP client for interacting with it. @@ -206,7 +206,8 @@ At some point, you'll probably want to get information about the shape of the AP and generate a typed API client (this is, after all, the main selling point of this library). To do this, use the `Api::info()` function. -Probably the best way to see what shapes this info can take is by looking at `api/info.rs`. +The types describing this info live in the `no_std` `seamless_info` crate (and are re-exported from `seamless::api`). +Enable its `deserialize` feature to read the info back in, for instance to generate a typed API client from it. Here's an example: diff --git a/seamless-info/Cargo.toml b/seamless-info/Cargo.toml new file mode 100644 index 0000000..08d13aa --- /dev/null +++ b/seamless-info/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "seamless_info" +readme = "README.md" +description = """ +The no_std types describing a 'seamless' API, eg as returned from `Api::info()` +""" + +version.workspace = true +authors.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +categories.workspace = true +keywords.workspace = true + +[features] +default = ["serialize", "deserialize"] +# Derive `serde::Serialize` on all types. +serialize = ["dep:serde"] +# Derive `serde::Deserialize` on all types. +deserialize = ["dep:serde"] + +[dependencies] +serde = { workspace = true, optional = true } + +[dev-dependencies] +serde_json.workspace = true diff --git a/seamless-info/LICENSE b/seamless-info/LICENSE new file mode 100644 index 0000000..5210252 --- /dev/null +++ b/seamless-info/LICENSE @@ -0,0 +1,25 @@ +Copyright 2021 James Wilson + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/seamless-info/README.md b/seamless-info/README.md new file mode 100644 index 0000000..1c9d14d --- /dev/null +++ b/seamless-info/README.md @@ -0,0 +1,12 @@ +# seamless_info + +The types describing a [seamless](https://crates.io/crates/seamless) API, as returned from `Api::info()`. + +This crate is `no_std` (it needs `alloc`) and has no dependencies other than `serde`, which is only +pulled in if one of the following features is enabled: + +- `serialize`: derive `serde::Serialize` on all types. +- `deserialize`: derive `serde::Deserialize` on all types. + +`seamless` enables `serialize` so that it can hand back the API information. Enable `deserialize` +to read that information back in, for instance in order to generate an API client from it. diff --git a/seamless-info/src/lib.rs b/seamless-info/src/lib.rs new file mode 100644 index 0000000..4502392 --- /dev/null +++ b/seamless-info/src/lib.rs @@ -0,0 +1,235 @@ +//! The types used to describe a [seamless](https://docs.rs/seamless) API. A list of +//! [`RouteInfo`]s is what `seamless::Api::info()` hands back, and contains enough +//! information to generate a type safe client for the API. +//! +//! This crate is `no_std` (though it requires `alloc`), and has no dependencies other than +//! `serde`. Enable the `serialize` and/or `deserialize` features to derive +//! [`serde::Serialize`] and/or [`serde::Deserialize`] on every type here. + +#![no_std] +#![warn(missing_docs)] + +extern crate alloc; + +use alloc::boxed::Box; +use alloc::collections::BTreeMap; +use alloc::string::String; +use alloc::vec::Vec; + +#[cfg(feature = "deserialize")] +use serde::Deserialize; +#[cfg(feature = "serialize")] +use serde::Serialize; + +/// Information about a single route. +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub struct RouteInfo { + /// The name/path that the HTTP request needs to contain + /// in order to match this route. + pub name: String, + /// The HTTP method expected in order for an HTTP request to + /// match this route, as a string. + pub method: String, + /// The description of the route, as set by `RouteBuilder::description()` in seamless. + pub description: String, + /// The shape of the data expected to be provided as part of the HTTP request + /// for this route. This doesn't care about the wire format that the data is provided in, + /// though the type information is somewhat related to what the possible types that can + /// be sent and received via JSON. + /// + /// Types can use seamless' `ApiBody` macro, or implement its `ApiBody` trait manually, + /// in order to describe the shape and documentation that they should hand back. + pub request_type: ApiBodyInfo, + /// The shape of the data that is returned from this API route. + pub response_type: ApiBodyInfo, +} + +/// A representation of some type, including its description and shape. +/// This is given back for anything which implements seamless' `ApiBody` trait, +/// and is automatically generated if one uses seamless' `ApiBody` macro on some type. +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub struct ApiBodyInfo { + /// A human friendly description of the type. When using seamless' `ApiBody` + /// macro, this will be automatically populated based on the doc comments on the type. + pub description: String, + /// The shape of the type. This should correspond to the JSON returned when + /// serializing the type. If you use seamless' `ApiBody` macro, this is + /// guaranteed to be the case. + #[cfg_attr( + any(feature = "serialize", feature = "deserialize"), + serde(rename = "shape") + )] + pub ty: ApiBodyType, +} + +/// An enum representing the shape of the JSON that is provided or output from the API. +/// There is a straightforward mapping from this to TypeScript types. +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +#[cfg_attr( + any(feature = "serialize", feature = "deserialize"), + serde(tag = "type") +)] +pub enum ApiBodyType { + /// Corresponds to the TypeScript type `string`. + String, + /// Corresponds to the TypeScript type `number`. + Number, + /// Corresponds to the TypeScript type `boolean`. + Boolean, + /// Corresponds to the TypeScript type `null`. + Null, + /// Corresponds to the TypeScript type `any`. + /// + /// This is used when the shape cannot be statically determined, and we want to + /// indicate that any type can be provided. In many cases [`ApiBodyType::Unknown`] + /// may be preferred. + Any, + /// Corresponds to the TypeScript type `unknown`. + /// + /// This is used when the shape cannot be statically determined, and we want to + /// indicate that we're not sure what the type is, unlike [`ApiBodyType::Any`] + /// which hints that *any* type can be provided. + Unknown, + /// Indicate that we expect binary data to be provided. This may correspond to + /// `Blob` in a UI. + Binary, + /// An array of values of one type, where each value has the type `value`, eg + /// `string[]` or `number[]`. + ArrayOf { + /// The type of all of the values in the array. + value: Box, + }, + /// A fixed length array of values that can be of mixed types, eg + /// `[string, number, Foo]`. + TupleOf { + /// A list of each of the types in this fixed length array. + values: Vec, + }, + /// An object where the keys are strings and the values are all of the same type, eg + /// `{ [key: string]: Foo }`. + ObjectOf { + /// The type of all of the values in the object/map. + value: Box, + }, + /// An object whose keys and value types are known at compile time, eg + /// `{ foo: string, bar: boolean, wibble: Foo }`. + Object { + /// The property name and type of each entry in the object. + keys: BTreeMap, + }, + /// The type is one of several variants, eg + /// `string | number | Foo`. + OneOf { + /// Each of the possible types that this can be. + values: Vec, + }, + /// The type is a string literal with a specific value, eg + /// `"stringvalue"`. + StringLiteral { + /// The exact string literal that we expect. + literal: String, + }, + /// The object key may be omitted, eg `{ key?: Foo }`. This is expected to be used + /// on struct fields in conjunction with serde's `skip_serializing_if = Option::is_none` + /// attribute. Adding `#[api_body(optional)]` on a field when using seamless' `ApiBody` + /// macro emits this, as well as the corresponding serde attribute. + Optional { + /// The type that is optional. + value: Box, + }, +} + +#[cfg(all(test, feature = "serialize", feature = "deserialize"))] +mod tests { + use super::*; + use alloc::borrow::ToOwned; + use alloc::vec; + + fn info(description: &str, ty: ApiBodyType) -> ApiBodyInfo { + ApiBodyInfo { + description: description.to_owned(), + ty, + } + } + + #[test] + fn route_info_roundtrips_through_json() { + let route = RouteInfo { + name: "maths/divide".to_owned(), + method: "POST".to_owned(), + description: "Divide two numbers".to_owned(), + request_type: info( + "Input", + ApiBodyType::Object { + keys: [ + ("a".to_owned(), info("", ApiBodyType::Number)), + ( + "b".to_owned(), + info( + "", + ApiBodyType::Optional { + value: Box::new(info("", ApiBodyType::Number)), + }, + ), + ), + ] + .into_iter() + .collect(), + }, + ), + response_type: info( + "Output", + ApiBodyType::OneOf { + values: vec![ + info( + "", + ApiBodyType::StringLiteral { + literal: "Nope".to_owned(), + }, + ), + info( + "", + ApiBodyType::TupleOf { + values: vec![ + info("", ApiBodyType::String), + info("", ApiBodyType::Null), + ], + }, + ), + info( + "", + ApiBodyType::ArrayOf { + value: Box::new(info("", ApiBodyType::Binary)), + }, + ), + info( + "", + ApiBodyType::ObjectOf { + value: Box::new(info("", ApiBodyType::Unknown)), + }, + ), + info("", ApiBodyType::Any), + info("", ApiBodyType::Boolean), + ], + }, + ), + }; + + let json = serde_json::to_value(vec![route.clone()]).unwrap(); + let back: Vec = serde_json::from_value(json.clone()).unwrap(); + assert_eq!(back, vec![route]); + + // Spot check the wire format: + assert_eq!(json[0]["request_type"]["shape"]["type"], "Object"); + assert_eq!( + json[0]["request_type"]["shape"]["keys"]["b"]["shape"]["type"], + "Optional" + ); + } +} diff --git a/seamless-macros/src/body/mod.rs b/seamless-macros/src/body/mod.rs index 97c1175..37be41f 100644 --- a/seamless-macros/src/body/mod.rs +++ b/seamless-macros/src/body/mod.rs @@ -123,7 +123,7 @@ pub fn parse_enum(e: syn::ItemEnum, attrs: Attrs) -> syn::Result { quote! { keys.insert(#name.to_owned(), #info); } }); quote! {{ - let mut keys = std::collections::HashMap::new(); + let mut keys = ::std::collections::BTreeMap::new(); keys.insert(#serde_tag.to_owned(), #tag_info); #(#entries)* #api::ApiBodyInfo { @@ -223,7 +223,7 @@ pub fn parse_struct(s: syn::ItemStruct, attrs: Attrs) -> syn::Result #api::ApiBodyStructInfo { - let mut fields = std::collections::HashMap::new(); + let mut fields = ::std::collections::BTreeMap::new(); #(#entries)* #api::ApiBodyStructInfo { description: #docs.to_owned(), diff --git a/seamless-ts-bin/Cargo.toml b/seamless-ts-bin/Cargo.toml new file mode 100644 index 0000000..c506285 --- /dev/null +++ b/seamless-ts-bin/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "seamless_ts_bin" +readme = "README.md" +description = """ +A CLI tool to generate TypeScript types from the info describing a 'seamless' API +""" + +version.workspace = true +authors.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +categories.workspace = true +keywords.workspace = true + +[[bin]] +name = "seamless-ts" +path = "src/main.rs" + +[dependencies] +seamless_ts.workspace = true +clap.workspace = true +ureq.workspace = true diff --git a/seamless-ts-bin/LICENSE b/seamless-ts-bin/LICENSE new file mode 100644 index 0000000..5210252 --- /dev/null +++ b/seamless-ts-bin/LICENSE @@ -0,0 +1,25 @@ +Copyright 2021 James Wilson + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/seamless-ts-bin/README.md b/seamless-ts-bin/README.md new file mode 100644 index 0000000..0399a71 --- /dev/null +++ b/seamless-ts-bin/README.md @@ -0,0 +1,24 @@ +# seamless_ts_bin + +A `seamless-ts` command line tool which generates TypeScript types describing a +[seamless](https://crates.io/crates/seamless) API, using the `seamless_ts` crate. + +It takes the JSON produced by serializing the result of `seamless::Api::info()`, either from +stdin, from a file given with `--file`, or from a URL given with `--url`, and writes the generated TypeScript to stdout. Any +errors are written to stderr. + +```sh +cargo install seamless_ts_bin + +# Fetch the API info from a URL: +seamless-ts --url https://example.com/api/meta.info > api.ts + +# Headers can be sent along with the request (as many as you like): +seamless-ts --url https://example.com/api/meta.info -H 'Authorization: Bearer foo' > api.ts + +# Read the API info from stdin: +cat api-info.json | seamless-ts > api.ts + +# Or read it from a file: +seamless-ts --file api-info.json > api.ts +``` diff --git a/seamless-ts-bin/src/main.rs b/seamless-ts-bin/src/main.rs new file mode 100644 index 0000000..030ab3d --- /dev/null +++ b/seamless-ts-bin/src/main.rs @@ -0,0 +1,112 @@ +use clap::Parser; +use std::fmt; +use std::io::{self, BufWriter, Read, Write}; +use std::path::PathBuf; +use std::process::ExitCode; + +/// Generate TypeScript types from the JSON info describing a seamless API. +/// +/// The API info is read from stdin, or from the file or URL given by --file or +/// --url, and the generated TypeScript is written to stdout. +#[derive(Parser)] +#[command(name = "seamless-ts", version)] +struct Args { + /// Read the API info from this file instead of stdin. + #[arg(short, long, value_name = "PATH")] + file: Option, + /// Fetch the API info from this URL instead of stdin. + #[arg(short, long, value_name = "URL", conflicts_with = "file")] + url: Option, + /// A header to send when fetching from --url, eg 'Authorization: Bearer foo'. + /// Can be given multiple times. + // Dev note: --header/-H for consistency with curl. + #[arg( + short = 'H', + long = "header", + value_name = "HEADER", + value_parser = parse_header, + requires = "url", + conflicts_with = "file" + )] + headers: Vec<(String, String)>, +} + +/// Parse a header given as 'Name: value'. +fn parse_header(header: &str) -> Result<(String, String), String> { + let (name, value) = header + .split_once(':') + .ok_or("expected a header like 'Name: value'")?; + Ok((name.trim().to_owned(), value.trim().to_owned())) +} + +fn main() -> ExitCode { + match run(Args::parse()) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("Error: {e}"); + ExitCode::FAILURE + } + } +} + +fn run(args: Args) -> Result<(), String> { + let route_info = match (args.file, args.url) { + (Some(path), _) => std::fs::read_to_string(&path) + .map_err(|e| format!("Could not read '{}': {e}", path.display()))?, + (_, Some(url)) => args + .headers + .iter() + .fold(ureq::get(&url), |req, (name, value)| { + req.header(name, value) + }) + .call() + .and_then(|mut res| res.body_mut().read_to_string()) + .map_err(|e| format!("Could not fetch '{url}': {e}"))?, + (None, None) => { + let mut s = String::new(); + io::stdin() + .read_to_string(&mut s) + .map_err(|e| format!("Could not read from stdin: {e}"))?; + s + } + }; + + let mut out = IoWriter::new(BufWriter::new(io::stdout().lock())); + let write_error = |e: io::Error| format!("Could not write to stdout: {e}"); + match seamless_ts::generate(&route_info, &mut out) { + Ok(()) => {} + Err(seamless_ts::Error::Write(_)) => { + return Err(write_error(out.take_error())); + } + Err(e) => return Err(e.to_string()), + } + out.inner.flush().map_err(write_error) +} + +/// Adapts an [`io::Write`] to a [`fmt::Write`], keeping hold of any IO error +/// so that we can report it (since [`fmt::Error`] carries no information). +struct IoWriter { + inner: W, + error: Option, +} + +impl IoWriter { + fn new(inner: W) -> Self { + IoWriter { inner, error: None } + } + + fn take_error(&mut self) -> io::Error { + self.error + .take() + .unwrap_or_else(|| io::Error::other("formatting error")) + } +} + +impl fmt::Write for IoWriter { + fn write_str(&mut self, s: &str) -> fmt::Result { + self.inner.write_all(s.as_bytes()).map_err(|e| { + self.error = Some(e); + fmt::Error + }) + } +} diff --git a/seamless-ts/Cargo.toml b/seamless-ts/Cargo.toml new file mode 100644 index 0000000..8bb4dd7 --- /dev/null +++ b/seamless-ts/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "seamless_ts" +readme = "README.md" +description = """ +Generate TypeScript types from the info describing a 'seamless' API +""" + +version.workspace = true +authors.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +categories.workspace = true +keywords.workspace = true + +[dependencies] +seamless_info = { workspace = true, features = ["deserialize"] } +serde_json.workspace = true +thiserror.workspace = true + +[dev-dependencies] +seamless.workspace = true +serde_json = { workspace = true, features = ["std"] } +pretty_assertions.workspace = true diff --git a/seamless-ts/LICENSE b/seamless-ts/LICENSE new file mode 100644 index 0000000..5210252 --- /dev/null +++ b/seamless-ts/LICENSE @@ -0,0 +1,25 @@ +Copyright 2021 James Wilson + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/seamless-ts/README.md b/seamless-ts/README.md new file mode 100644 index 0000000..e24a54b --- /dev/null +++ b/seamless-ts/README.md @@ -0,0 +1,32 @@ +# seamless_ts + +Generate TypeScript types describing a [seamless](https://crates.io/crates/seamless) API. + +This crate is `no_std` (it needs `alloc`). It exposes a single function, `generate_types`, which +takes the JSON produced by serializing the result of `seamless::Api::info()` and writes +TypeScript to any `core::fmt::Write` (eg a `String`). The TypeScript exports an `Api` type, which +maps each route name to its HTTP method, request body type (`params`, which is `undefined` for `GET` +routes) and response type (`result`), and a readonly `methods` object mapping each route name to its +HTTP method for use at runtime. Together, these can be used to build a type safe client for the API: + +```ts +export type Api = { + 'users.get_by_id': { + method: 'POST' + params: { id: string } + result: { id: string, name: string } + } +} + +export const methods = { + 'users.get_by_id': 'POST', +} as const +``` + +```rust,ignore +let info_json = serde_json::to_string(&api.info()).unwrap(); +let mut typescript = String::new(); +seamless_ts::generate_types(&info_json, &mut typescript).unwrap(); +``` + +To generate these types from the command line, see the `seamless-ts` binary in the `seamless_ts_bin` crate. diff --git a/seamless-ts/src/fmt_helpers.rs b/seamless-ts/src/fmt_helpers.rs new file mode 100644 index 0000000..8f61df6 --- /dev/null +++ b/seamless-ts/src/fmt_helpers.rs @@ -0,0 +1,156 @@ +//! Helpers for formatting the generated TypeScript. + +use core::fmt::{self, Write}; +use seamless_info::RouteInfo; + +const INDENT: &str = " "; + +/// Write `indent` levels of indentation. +pub fn write_indent(out: &mut W, indent: usize) -> fmt::Result { + for _ in 0..indent { + out.write_str(INDENT)?; + } + Ok(()) +} + +/// Write a doc comment for a route like the following: +/// +/// ```text +/// /** +/// * POST /users.get_by_id +/// * +/// * Route description +/// */ +/// ``` +pub fn write_route_comment( + out: &mut W, + info: &RouteInfo, + indent: usize, +) -> fmt::Result { + write_indent(out, indent)?; + writeln!(out, "/**")?; + write_indent(out, indent)?; + writeln!( + out, + " * {} /{}", + Comment(&info.method), + Comment(info.name.trim_start_matches('/')) + )?; + let description = info.description.trim(); + if !description.is_empty() { + write_indent(out, indent)?; + writeln!(out, " *")?; + write_comment_lines(out, description, indent)?; + } + write_indent(out, indent)?; + writeln!(out, " */") +} + +/// Write each line of some text as ` * line`, as part of a block comment. +fn write_comment_lines(out: &mut W, text: &str, indent: usize) -> fmt::Result { + for line in text.lines() { + write_indent(out, indent)?; + let line = line.trim(); + if line.is_empty() { + writeln!(out, " *")?; + } else { + writeln!(out, " * {}", Comment(line))?; + } + } + Ok(()) +} + +/// Write a doc comment for some object property. Single line descriptions are written +/// as `/** description */`, and longer ones are written as a block. +pub fn write_doc_comment( + out: &mut W, + description: &str, + indent: usize, +) -> fmt::Result { + let description = description.trim(); + if description.is_empty() { + return Ok(()); + } + write_indent(out, indent)?; + if !description.contains('\n') { + return writeln!(out, "/** {} */", Comment(description)); + } + writeln!(out, "/**")?; + write_comment_lines(out, description, indent)?; + write_indent(out, indent)?; + writeln!(out, " */") +} + +/// Display an object key, quoting it if it isn't a valid identifier. +pub struct PropertyKey<'a>(pub &'a str); + +impl fmt::Display for PropertyKey<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut chars = self.0.chars(); + let is_ident = chars + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$') + && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$'); + if is_ident { + f.write_str(self.0) + } else { + DoubleQuoted(self.0).fmt(f) + } + } +} + +/// Display a string as a double quoted string literal. +pub struct DoubleQuoted<'a>(pub &'a str); + +impl fmt::Display for DoubleQuoted<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write_quoted(f, self.0, '"') + } +} + +/// Display a string as a single quoted string literal. +pub struct SingleQuoted<'a>(pub &'a str); + +impl fmt::Display for SingleQuoted<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write_quoted(f, self.0, '\'') + } +} + +fn write_quoted(f: &mut fmt::Formatter<'_>, s: &str, quote: char) -> fmt::Result { + f.write_char(quote)?; + for c in s.chars() { + match c { + '\\' => f.write_str("\\\\")?, + '\n' => f.write_str("\\n")?, + '\r' => f.write_str("\\r")?, + '\t' => f.write_str("\\t")?, + c if c == quote => { + f.write_char('\\')?; + f.write_char(c)?; + } + c if c.is_control() || c == '\u{2028}' || c == '\u{2029}' => { + write!(f, "\\u{{{:x}}}", c as u32)?; + } + c => f.write_char(c)?, + } + } + f.write_char(quote) +} + +/// Display some text such that it can't end the comment that it's in. +struct Comment<'a>(&'a str); + +impl fmt::Display for Comment<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut parts = self.0.split("*/"); + if let Some(first) = parts.next() { + f.write_str(first)?; + } + for part in parts { + f.write_str("*\\/")?; + f.write_str(part)?; + } + Ok(()) + } +} diff --git a/seamless-ts/src/lib.rs b/seamless-ts/src/lib.rs new file mode 100644 index 0000000..f9fdbed --- /dev/null +++ b/seamless-ts/src/lib.rs @@ -0,0 +1,518 @@ +//! Generate TypeScript types describing a [seamless](https://docs.rs/seamless) API. +//! +//! This crate is `no_std` (though it requires `alloc`). See [`generate_types()`]. + +// Tests use std (eg via the ApiBody macro), so only be no_std outside of them. +#![cfg_attr(not(test), no_std)] +#![warn(missing_docs)] + +extern crate alloc; + +use alloc::string::String; +use alloc::vec::Vec; +use core::fmt::{self, Write}; +use fmt_helpers::{ + DoubleQuoted, PropertyKey, SingleQuoted, write_doc_comment, write_indent, write_route_comment, +}; +use seamless_info::{ApiBodyInfo, ApiBodyType, RouteInfo}; + +mod fmt_helpers; + +/// Take the JSON obtained by serializing the [`Vec`] for some API (ie the result of +/// calling `seamless::Api::info()`), and write TypeScript describing the API to the [`Write`] +/// implementation provided (eg a [`String`]). +/// +/// The generated TypeScript exports an `Api` type, which maps each route name to its HTTP +/// method, the type of its request body (`params`, which is `undefined` for `GET` routes) and +/// the type of its response (`result`). Since types don't exist at runtime, it also exports a +/// readonly `methods` object mapping each route name to its HTTP method. For example: +/// +/// ```ts +/// export type Api = { +/// 'users.get_by_id': { +/// method: 'POST' +/// params: { id: string } +/// result: { id: string, name: string } +/// } +/// } +/// +/// export const methods = { +/// 'users.get_by_id': 'POST', +/// } as const +/// ``` +/// +/// This can be used to build a type safe client for the API, for instance something like: +/// +/// ```ts +/// type Params = Api[R]['params'] extends undefined ? [] : [Api[R]['params']] +/// +/// async function api(route: R, ...[params]: Params): Promise { +/// let method = methods[route]; +/// +/// let res = await fetch('url', { +/// method, +/// body: JSON.stringify(params) +/// }) +/// +/// let body = await res.json() +/// +/// if (!res.ok) { +/// // This depends on how you handle seamless errors: +/// throw new Error(body.message) +/// } else { +/// // This is the response body from seamless if all is well: +/// return body +/// } +/// } +/// ``` +/// +/// # Errors +/// +/// Errors if the JSON provided can't be deserialized into an [`Vec`], or if two +/// routes have the same name. Nothing is written in either case. Also errors if writing to +/// `out` fails, in which case some of the output may already have been written. +pub fn generate(route_info: &str, out: &mut W) -> Result<(), Error> { + let mut routes: Vec = + serde_json::from_str(route_info).map_err(Error::Deserialize)?; + routes.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.method.cmp(&b.method))); + + // Routes are keyed by name in the generated type, so names must be unique. + if let Some(pair) = routes.windows(2).find(|pair| pair[0].name == pair[1].name) { + return Err(Error::DuplicateRouteName(pair[0].name.clone())); + } + + write_ts(out, &routes).map_err(Error::Write) +} + +/// An error generating the TypeScript. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The JSON provided could not be deserialized into an [`Vec`]. + #[error("Could not deserialize the API info: {0}")] + Deserialize(serde_json::Error), + /// The generated TypeScript could not be written to the output. + #[error("Could not write the generated TypeScript")] + Write(fmt::Error), + /// More than one route has the given name (eg the same path with different methods). + #[error("More than one route has the name '{0}'")] + DuplicateRouteName(String), +} + +fn write_ts(out: &mut W, routes: &[RouteInfo]) -> fmt::Result { + writeln!(out, "// THIS IS AN AUTO GENERATED FILE. DO NOT EDIT")?; + writeln!(out)?; + writeln!(out, "/**")?; + writeln!(out, " * The routes provided by our API")?; + writeln!(out, " */")?; + write!(out, "export type Api = {{")?; + if !routes.is_empty() { + writeln!(out)?; + } + for route in routes { + write_route_comment(out, route, 1)?; + write_indent(out, 1)?; + writeln!(out, "{}: {{", SingleQuoted(&route.name))?; + write_indent(out, 2)?; + writeln!(out, "method: {}", SingleQuoted(&route.method))?; + // Routes that aren't GET routes are expected to be given a body. + write_indent(out, 2)?; + write!(out, "params: ")?; + if route.method.eq_ignore_ascii_case("GET") { + write!(out, "undefined")?; + } else { + write_type(out, &route.request_type.ty, 2)?; + } + writeln!(out)?; + write_indent(out, 2)?; + write!(out, "result: ")?; + write_type(out, &route.response_type.ty, 2)?; + writeln!(out)?; + write_indent(out, 1)?; + writeln!(out, "}}")?; + } + writeln!(out, "}}")?; + + // The methods are also needed at runtime, in order to make requests: + writeln!(out)?; + writeln!(out, "/**")?; + writeln!(out, " * The HTTP method of each route")?; + writeln!(out, " */")?; + write!(out, "export const methods = {{")?; + if !routes.is_empty() { + writeln!(out)?; + } + for route in routes { + write_indent(out, 1)?; + writeln!( + out, + "{}: {},", + SingleQuoted(&route.name), + SingleQuoted(&route.method) + )?; + } + writeln!(out, "}} as const") +} + +/// Write out the TypeScript type corresponding to some [`ApiBodyType`]. The first line is +/// written wherever we currently are, and any further lines are indented by `indent`. +fn write_type(out: &mut W, ty: &ApiBodyType, indent: usize) -> fmt::Result { + match ty { + ApiBodyType::String => write!(out, "string"), + ApiBodyType::Number => write!(out, "number"), + ApiBodyType::Boolean => write!(out, "boolean"), + ApiBodyType::Null => write!(out, "null"), + ApiBodyType::Any => write!(out, "any"), + ApiBodyType::Unknown => write!(out, "unknown"), + ApiBodyType::Binary => write!(out, "Blob"), + ApiBodyType::ArrayOf { value } => { + write!(out, "(")?; + write_type(out, &value.ty, indent)?; + write!(out, ")[]") + } + ApiBodyType::TupleOf { values } => { + write!(out, "[")?; + for (idx, value) in values.iter().enumerate() { + if idx > 0 { + write!(out, ", ")?; + } + write_type(out, &value.ty, indent)?; + } + write!(out, "]") + } + ApiBodyType::ObjectOf { value } => { + writeln!(out, "{{")?; + write_indent(out, indent + 1)?; + write!(out, "[key: string]: ")?; + write_type(out, &value.ty, indent + 1)?; + writeln!(out)?; + write_indent(out, indent)?; + write!(out, "}}") + } + ApiBodyType::Object { keys } => { + if keys.is_empty() { + return write!(out, "{{}}"); + } + writeln!(out, "{{")?; + for (key, value) in keys { + write_object_property(out, key, value, indent + 1)?; + } + write_indent(out, indent)?; + write!(out, "}}") + } + ApiBodyType::OneOf { values } => { + if values.is_empty() { + return write!(out, "never"); + } + for (idx, value) in values.iter().enumerate() { + if idx > 0 { + write!(out, " | ")?; + } + write_type(out, &value.ty, indent)?; + } + Ok(()) + } + ApiBodyType::StringLiteral { literal } => write!(out, "{}", DoubleQuoted(literal)), + // Optional only really makes sense as the type of an object property, which is + // handled in `write_object_property`. Elsewhere, the value may be undefined. + ApiBodyType::Optional { value } => { + write_type(out, &value.ty, indent)?; + write!(out, " | undefined") + } + } +} + +/// Write out a single property of an object, eg `key?: string`, along with its description. +fn write_object_property( + out: &mut W, + key: &str, + value: &ApiBodyInfo, + indent: usize, +) -> fmt::Result { + let (optional, inner) = match &value.ty { + ApiBodyType::Optional { value: inner } => (true, &**inner), + _ => (false, value), + }; + let description = if value.description.is_empty() { + &inner.description + } else { + &value.description + }; + + write_doc_comment(out, description, indent)?; + write_indent(out, indent)?; + write!( + out, + "{}{}: ", + PropertyKey(key), + if optional { "?" } else { "" } + )?; + write_type(out, &inner.ty, indent)?; + writeln!(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::string::ToString; + use pretty_assertions::assert_eq; + use seamless::{ + api::{Api, ApiBody}, + handler::{ + body::{FromBinary, FromJson}, + response::ToJson, + }, + }; + use serde_json::{Map, Value, json}; + + /// A widget + #[ApiBody] + struct Widget { + /// The widget name + name: String, + size: (u8, u8), + colour: Option, + } + + #[ApiBody] + enum Colour { + Red, + Blue, + } + + #[ApiBody] + struct StackRequest { + items: Vec, + } + + #[ApiBody] + enum Item { + Crate { + width: u8, + }, + Ball { + /// The ball radius + radius: f64, + }, + } + + #[ApiBody] + struct TuneParams { + /// How much to tune by + #[api_body(optional)] + amount: Option, + /// Some + /// multi-line docs. + r#type: String, + } + + fn generate_string(route_info: &str) -> Result { + let mut out = String::new(); + generate(route_info, &mut out)?; + Ok(out) + } + + // The handlers are never called; we only care about the types they describe. + fn never() -> T { + unimplemented!() + } + + fn example_api() -> Api { + let mut api = Api::new(); + api.add("widgets.list_all") + .description("List all of the widgets") + .handler(|| async { ToJson(never::>()) }); + api.add("shelf/stack_items") + .description("Stack some items on the shelf") + .handler(|FromJson(_): FromJson| ToJson(())); + api.add("gadgets.upload") + .description("Upload a gadget") + .handler(|_: FromBinary| ToJson(never::>())); + api.add("gadgets.tune") + .description("Tune a gadget.\n\nIt's */ quite\na \"good\" route") + .handler(|FromJson(_): FromJson| ToJson(true)); + api + } + + const EXPECTED: &str = r#"// THIS IS AN AUTO GENERATED FILE. DO NOT EDIT + +/** + * The routes provided by our API + */ +export type Api = { + /** + * POST /gadgets.tune + * + * Tune a gadget. + * + * It's *\/ quite + * a "good" route + */ + 'gadgets.tune': { + method: 'POST' + params: { + /** How much to tune by */ + amount?: number + /** + * Some + * multi-line docs. + */ + type: string + } + result: boolean + } + /** + * POST /gadgets.upload + * + * Upload a gadget + */ + 'gadgets.upload': { + method: 'POST' + params: Blob + result: { + [key: string]: any + } + } + /** + * POST /shelf/stack_items + * + * Stack some items on the shelf + */ + 'shelf/stack_items': { + method: 'POST' + params: { + items: ({ + /** Variant tag */ + kind: "Crate" + width: number + } | { + /** Variant tag */ + kind: "Ball" + /** The ball radius */ + radius: number + })[] + } + result: null + } + /** + * GET /widgets.list_all + * + * List all of the widgets + */ + 'widgets.list_all': { + method: 'GET' + params: undefined + result: ({ + colour: "Red" | "Blue" | null + /** The widget name */ + name: string + size: [number, number] + })[] + } +} + +/** + * The HTTP method of each route + */ +export const methods = { + 'gadgets.tune': 'POST', + 'gadgets.upload': 'POST', + 'shelf/stack_items': 'POST', + 'widgets.list_all': 'GET', +} as const +"#; + + #[test] + fn generates_expected_types() { + let info = serde_json::to_string(&example_api().info()).unwrap(); + let ts = generate_string(&info).unwrap(); + + // Handy for checking the output with `tsc`: + if let Some(path) = std::env::var_os("SEAMLESS_TS_OUT") { + std::fs::write(path, &ts).unwrap(); + } + + assert_eq!(ts, EXPECTED); + } + + #[test] + fn unusual_names_and_types() { + let info = json!([{ + "name": "it's/a-route", + "method": "PUT", + "description": "", + "request_type": { "description": "", "shape": { "type": "Null" } }, + "response_type": { + "description": "", + "shape": { + "type": "Object", + "keys": { + "not-an-ident": { "description": "", "shape": { "type": "Unknown" } }, + "maybe": { + "description": "", + "shape": { "type": "Optional", "value": { "description": "", "shape": { "type": "Boolean" } } } + }, + "empty": { "description": "", "shape": { "type": "Object", "keys": {} } }, + "lit": { "description": "", "shape": { "type": "StringLiteral", "literal": "it's \"quoted\"" } } + } + } + } + }]); + let ts = generate_string(&info.to_string()).unwrap(); + + assert!(ts.contains( + r#" /** + * PUT /it's/a-route + */ + 'it\'s/a-route': { + method: 'PUT' + params: null + result: { + empty: {} + lit: "it's \"quoted\"" + maybe?: boolean + "not-an-ident": unknown + } + } +} +"# + )); + assert!( + ts.ends_with("export const methods = {\n 'it\\'s/a-route': 'PUT',\n} as const\n") + ); + } + + #[test] + fn empty_api() { + let ts = generate_string("[]").unwrap(); + assert!(ts.ends_with("export type Api = {}\n\n/**\n * The HTTP method of each route\n */\nexport const methods = {} as const\n")); + } + + fn route(name: &str, method: &str) -> Value { + json!({ + "name": name, + "method": method, + "description": "", + "request_type": { "description": "", "shape": { "type": "Null" } }, + "response_type": { "description": "", "shape": { "type": "Null" } } + }) + } + + #[test] + fn errors_on_invalid_json() { + let err = generate_string(r#"[{ "name": "foo" }]"#).unwrap_err(); + assert!(matches!(err, Error::Deserialize(_))); + } + + #[test] + fn errors_on_duplicate_route_names() { + let info = json!([ + route("foo", "POST"), + route("bar", "GET"), + route("foo", "GET") + ]); + let mut out = String::new(); + let err = generate(&info.to_string(), &mut out).unwrap_err(); + assert_eq!(err.to_string(), "More than one route has the name 'foo'"); + assert_eq!(out, "", "nothing should be written on error"); + } +} diff --git a/seamless/Cargo.toml b/seamless/Cargo.toml index 5f3374d..82f0746 100644 --- a/seamless/Cargo.toml +++ b/seamless/Cargo.toml @@ -18,10 +18,11 @@ keywords.workspace = true default = ["uuid"] [dependencies] -serde.workspace = true -serde_json.workspace = true +serde = { workspace = true, features = ["std"] } +serde_json = { workspace = true, features = ["std"] } http.workspace = true seamless_macros.workspace = true +seamless_info = { workspace = true, features = ["serialize"] } futures.workspace = true bytes.workspace = true diff --git a/seamless/README.md b/seamless/README.md index cb9b44f..24418db 100644 --- a/seamless/README.md +++ b/seamless/README.md @@ -206,7 +206,8 @@ At some point, you'll probably want to get information about the shape of the AP and generate a typed API client (this is, after all, the main selling point of this library). To do this, use the `Api::info()` function. -Probably the best way to see what shapes this info can take is by looking at `api/info.rs`. +The types describing this info live in the `no_std` `seamless_info` crate (and are re-exported from `seamless::api`). +Enable its `deserialize` feature to read the info back in, for instance to generate a typed API client from it. Here's an example: diff --git a/seamless/src/api/api.rs b/seamless/src/api/api.rs index ed6bed6..256f698 100644 --- a/seamless/src/api/api.rs +++ b/seamless/src/api/api.rs @@ -1,10 +1,9 @@ use super::error::ApiError; -use super::info::ApiBodyInfo; use crate::handler::{ Handler, IntoHandler, request::AsyncReadBody, response::Body as ResponseBody, }; use http::{Method, Request, Response}; -use serde::Serialize; +use seamless_info::RouteInfo; use std::collections::HashMap; /// The entry point; you can create an instance of this and then add API routes to it @@ -56,6 +55,12 @@ impl Api { /// If you add a route at the same path and requiring the same method as an existing route, /// the existing route will be silently overwritten. /// + /// Leading and trailing slashes are ignored, so `"/foo/"` is the same path as `"foo"`. + /// + /// # Panics + /// + /// Panics if the path is empty, or consists only of slashes. + /// /// # Examples /// /// ``` @@ -78,7 +83,9 @@ impl Api { /// } /// ``` pub fn add>(&mut self, path: P) -> RouteBuilder<'_> { - RouteBuilder::new(self, path.into()) + let path = path.into().trim_matches('/').to_owned(); + assert!(!path.is_empty(), "Routes cannot be added at an empty path"); + RouteBuilder::new(self, path) } // Add a route given the individual parts (for internal use) @@ -89,7 +96,6 @@ impl Api { handler_fn: HandlerFn, ) { let handler = handler_fn.into_handler(); - let path = path.trim_matches('/').to_owned(); self.routes.insert( (handler.method.clone(), path), Route { @@ -249,26 +255,3 @@ impl RouteError { } } } - -/// Information about a single route. -#[derive(Debug, Clone, PartialEq, Serialize)] -pub struct RouteInfo { - /// The name/path that the [`http::Request`] needs to contain - /// in order to match this route. - pub name: String, - /// The HTTP method expected in order for a [`http::Request`] to - /// match this route, as a string. - pub method: String, - /// The description of the route as set by [`RouteBuilder::description()`] - pub description: String, - /// The shape of the data expected to be provided as part of the [`http::Request`] - /// for this route. This doesn't care about the wire format that the data is provided in, - /// though the type information is somewhat related to what the possible types that can - /// be sent and received via JSON. - /// - /// Types can use the [`macro@crate::ApiBody`] macro, or implement [`type@crate::api::ApiBody`] - /// manually in order to describe the shape and documentation that they should hand back. - pub request_type: ApiBodyInfo, - /// The shape of the data that is returned from this API route. - pub response_type: ApiBodyInfo, -} diff --git a/seamless/src/api/info.rs b/seamless/src/api/info.rs index 1c7b69c..730a386 100644 --- a/seamless/src/api/info.rs +++ b/seamless/src/api/info.rs @@ -1,21 +1,5 @@ -use serde::Serialize; -use std::collections::HashMap; - -/// A representation of some type, including its description and shape. -/// This is given back for anything which implements the [`trait@crate::ApiBody`] trait, -/// and is automatically generated if one uses the [`macro@crate::ApiBody`] macro on some type. -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -pub struct ApiBodyInfo { - /// A human friendly description of the type. When using the - /// [`ApiBody`](seamless_macros::ApiBody) macro, this will be automatically - /// populated based on the doc comments on the type. - pub description: String, - /// The shape of the type. This should correspond to the JSON returned when - /// serializing the type. If you use the [`ApiBody`](seamless_macros::ApiBody) - /// macro, this is guaranteed to be the case. - #[serde(rename = "shape")] - pub ty: ApiBodyType, -} +use seamless_info::{ApiBodyInfo, ApiBodyType}; +use std::collections::{BTreeMap, HashMap}; // Primarily for internal use; structs can // be converted directly to this, so we know at the @@ -24,81 +8,7 @@ pub struct ApiBodyInfo { #[doc(hidden)] pub struct ApiBodyStructInfo { pub description: String, - pub fields: HashMap, -} - -/// An enum representing the shape of the JSON that is provided or output from the API. -/// There is a straightforward mapping from this to TypeScript types. -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(tag = "type")] -pub enum ApiBodyType { - /// Corresponds to the TypeScript type `string`. - String, - /// Corresponds to the TypeScript type `number`. - Number, - /// Corresponds to the TypeScript type `boolean`. - Boolean, - /// Corresponds to the TypeScript type `null`. - Null, - /// Corresponds to the TypeScript type `any`. - /// - /// This is used when the shape cannot be statically determined, and we want to - /// indicate that any type can be provided. In many cases [`ApiBodyType::Unknown`] - /// may be preferred. - Any, - /// Corresponds to the TypeScript type `unknown`. - /// - /// This is used when the shape cannot be statically determined, and we want to - /// indicate that we're not sure what the type is, unlike [`ApiBodyType::Any`] - /// which hints that *any* type can be provided. - Unknown, - /// Indicate that we expect binary data to be provided. This may correspond to - /// `Blob` in a UI. - Binary, - /// An array of values of one type, where each value has the type `value`, eg - /// `string[]` or `number[]`. - ArrayOf { - /// The type of all of the values in the array. - value: Box, - }, - /// A fixed length array of values that can be of mixed types, eg - /// `[string, number, Foo]`. - TupleOf { - /// A list of each of the types in this fixed length array. - values: Vec, - }, - /// An object where the keys are strings and the values are all of the same type, eg - /// `{ [key: string]: Foo }`. - ObjectOf { - /// The type of all of the values in the object/map. - value: Box, - }, - /// An object whose keys and value types are known at compile time, eg - /// `{ foo: string, bar: boolean, wibble: Foo }`. - Object { - /// The property name and type of each entry in the object. - keys: HashMap, - }, - /// The type is one of several variants, eg - /// `string | number | Foo`. - OneOf { - /// Each of the possible types that this can be. - values: Vec, - }, - /// The type is a string literal with a specific value, eg - /// `"stringvalue"`. - StringLiteral { - /// The exact string literal that we expect. - literal: String, - }, - /// The object key may be omitted, eg `{ key?: Foo }`. This is expected to be used - /// on struct fields in conjunction with serde's `skip_serializing_if = Option::is_none` - /// attribute. Adding `#[api_body(optional)]` on a field when using the `ApiBody` macro - /// emits this, as well as the corresponding serde attribute. - Optional { - /// The type that is optional. - value: Box, - }, + pub fields: BTreeMap, } /// Any type that implements this trait can be described in terms of [`ApiBodyInfo`], and @@ -159,6 +69,16 @@ impl ApiBody for HashMap { } } } +impl ApiBody for BTreeMap { + fn api_body_info() -> ApiBodyInfo { + ApiBodyInfo { + description: String::new(), + ty: ApiBodyType::ObjectOf { + value: Box::new(T::api_body_info()), + }, + } + } +} // Serde serializes `None` as `null`, so the Option type is `T | null`. impl ApiBody for Option { diff --git a/seamless/src/api/mod.rs b/seamless/src/api/mod.rs index e716c77..32a4e4e 100644 --- a/seamless/src/api/mod.rs +++ b/seamless/src/api/mod.rs @@ -7,9 +7,10 @@ mod api; mod error; mod info; -pub use api::{Api, RouteBuilder, RouteError, RouteInfo}; +pub use api::{Api, RouteBuilder, RouteError}; pub use error::ApiError; -pub use info::{ApiBody, ApiBodyInfo, ApiBodyType}; +pub use info::ApiBody; +pub use seamless_info::{ApiBodyInfo, ApiBodyType, RouteInfo}; // Export these on top of the types, so that you don't need to // import `seamless::api::ApiBody` AND `seamless::ApiBody` for diff --git a/seamless/src/lib.rs b/seamless/src/lib.rs index 51f94be..b783e95 100644 --- a/seamless/src/lib.rs +++ b/seamless/src/lib.rs @@ -212,7 +212,8 @@ At some point, you'll probably want to get information about the shape of the AP and generate a typed API client (this is, after all, the main selling point of this library). To do this, use the [`Api::info()`] function. -Probably the best way to see what shapes this info can take is by looking at `api/info.rs`. +The types describing this info live in the `no_std` `seamless_info` crate (and are re-exported from `seamless::api`). +Enable its `deserialize` feature to read the info back in, for instance to generate a typed API client from it. Here's an example: diff --git a/seamless/tests/api_base_path.rs b/seamless/tests/api_base_path.rs index 0837cf0..051b791 100644 --- a/seamless/tests/api_base_path.rs +++ b/seamless/tests/api_base_path.rs @@ -58,3 +58,15 @@ async fn empty_base_path_matches_everything() { assert!(found(&api, "/v2/foo").await, "base {base:?}"); } } + +#[test] +#[should_panic(expected = "Routes cannot be added at an empty path")] +fn empty_route_path_panics() { + Api::new().add(""); +} + +#[test] +#[should_panic(expected = "Routes cannot be added at an empty path")] +fn slash_only_route_path_panics() { + Api::new_with_base_path("/api").add("//"); +} diff --git a/seamless/tests/api_body_02_runtime_tests.rs b/seamless/tests/api_body_02_runtime_tests.rs index ed9611c..c6ab019 100644 --- a/seamless/tests/api_body_02_runtime_tests.rs +++ b/seamless/tests/api_body_02_runtime_tests.rs @@ -4,7 +4,7 @@ use seamless::api::{ApiBodyInfo, ApiBodyType}; macro_rules! map { ( $($key:expr => $val:expr),* ) => ({ - let mut m = std::collections::HashMap::new(); + let mut m = std::collections::BTreeMap::new(); $( m.insert($key, $val); )* m })