From 46b9ca466518f794df89b9b077b3aae9f8579af9 Mon Sep 17 00:00:00 2001 From: James Wilson Date: Thu, 22 Oct 2026 15:45:16 +0100 Subject: [PATCH 1/9] move type info to separate crate --- CHANGELOG.md | 3 + Cargo.lock | 9 ++ Cargo.toml | 4 +- PUBLISHING.md | 5 +- README.md | 3 +- seamless-info/Cargo.toml | 27 ++++ seamless-info/LICENSE | 25 ++++ seamless-info/README.md | 12 ++ seamless-info/src/lib.rs | 146 ++++++++++++++++++++ seamless-info/tests/serde_roundtrip.rs | 85 ++++++++++++ seamless-macros/src/body/mod.rs | 4 +- seamless/Cargo.toml | 3 +- seamless/README.md | 3 +- seamless/src/api/api.rs | 26 +--- seamless/src/api/info.rs | 106 ++------------ seamless/src/api/mod.rs | 5 +- seamless/src/lib.rs | 3 +- seamless/tests/api_body_02_runtime_tests.rs | 2 +- 18 files changed, 341 insertions(+), 130 deletions(-) create mode 100644 seamless-info/Cargo.toml create mode 100644 seamless-info/LICENSE create mode 100644 seamless-info/README.md create mode 100644 seamless-info/src/lib.rs create mode 100644 seamless-info/tests/serde_roundtrip.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 6857ec3..97819e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # 0.14.0 +- Move `RouteInfo`, `ApiBodyInfo` and `ApiBodyType` into a new `no_std` `seamless-info` crate, whose only dependency is `serde`. Its `serialize` and `deserialize` features derive `Serialize` and `Deserialize` respectively, so the info returned from `Api::info()` can now be deserialized (eg to generate a client from it). The types are re-exported from `seamless::api` and `seamless` as before. +- **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..c5ed368 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -416,6 +416,7 @@ dependencies = [ "hyper", "hyper-util", "pretty_assertions", + "seamless-info", "seamless_macros", "serde", "serde_json", @@ -426,6 +427,14 @@ dependencies = [ "uuid", ] +[[package]] +name = "seamless-info" +version = "0.14.0" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "seamless_macros" version = "0.14.0" diff --git a/Cargo.toml b/Cargo.toml index fd4fd7e..8a32037 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,7 @@ [workspace] members = [ "seamless", + "seamless-info", "seamless-macros" ] resolver = "3" @@ -18,9 +19,10 @@ keywords = ["api", "http", "rpc", "json"] # Workspace crates seamless = { path = "seamless" } seamless_macros = { version = "0.14.0", path = "seamless-macros" } +seamless-info = { version = "0.14.0", path = "seamless-info", default-features = false } # Dependencies -serde = { version = "1", features = ["derive"] } +serde = { version = "1", default-features = false, features = ["derive", "alloc"] } serde_json = "1" http = "1" futures = "0.3.34" diff --git a/PUBLISHING.md b/PUBLISHING.md index db93235..e72c408 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,10 @@ git push origin master --tags ## Publish -Publish the macro crate first since the main crate depends on it existing. +Publish the macro and info crates first since the main crate depends on them existing. ``` (cd seamless-macros && cargo publish) +(cd seamless-info && cargo publish) (cd seamless && cargo publish) ``` \ No newline at end of file diff --git a/README.md b/README.md index 503b8e2..f470f18 100644 --- a/README.md +++ b/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-info/Cargo.toml b/seamless-info/Cargo.toml new file mode 100644 index 0000000..bfcc1da --- /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 = [] +# 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..7eb3d53 --- /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..241e375 --- /dev/null +++ b/seamless-info/src/lib.rs @@ -0,0 +1,146 @@ +//! 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, + }, +} diff --git a/seamless-info/tests/serde_roundtrip.rs b/seamless-info/tests/serde_roundtrip.rs new file mode 100644 index 0000000..f8ef0a9 --- /dev/null +++ b/seamless-info/tests/serde_roundtrip.rs @@ -0,0 +1,85 @@ +#![cfg(all(feature = "serialize", feature = "deserialize"))] + +use seamless_info::{ApiBodyInfo, ApiBodyType, RouteInfo}; + +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/Cargo.toml b/seamless/Cargo.toml index 5f3374d..2465595 100644 --- a/seamless/Cargo.toml +++ b/seamless/Cargo.toml @@ -18,10 +18,11 @@ keywords.workspace = true default = ["uuid"] [dependencies] -serde.workspace = true +serde = { workspace = true, features = ["std"] } serde_json.workspace = true 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..b7ddb91 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..71285ec 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 @@ -249,26 +248,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..d9dd276 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_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 }) From 4e5a0a8724c55ad0d4ec87f89f8b12f5ee92e1ae Mon Sep 17 00:00:00 2001 From: James Wilson Date: Thu, 22 Oct 2026 15:53:16 +0100 Subject: [PATCH 2/9] crate name to use underscore, test no_std in CI --- .github/workflows/ci.yml | 20 ++++++++++++++++++++ Cargo.lock | 4 ++-- Cargo.toml | 2 +- PUBLISHING.md | 8 +++----- README.md | 2 +- seamless-info/Cargo.toml | 2 +- seamless-info/README.md | 2 +- seamless/Cargo.toml | 2 +- seamless/README.md | 2 +- seamless/src/lib.rs | 2 +- 10 files changed, 32 insertions(+), 14 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d3c09fd..962dd8b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,3 +56,23 @@ 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) + 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 any of + # its dependencies, for any combination of its features) starts 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 diff --git a/Cargo.lock b/Cargo.lock index c5ed368..250a1be 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -416,7 +416,7 @@ dependencies = [ "hyper", "hyper-util", "pretty_assertions", - "seamless-info", + "seamless_info", "seamless_macros", "serde", "serde_json", @@ -428,7 +428,7 @@ dependencies = [ ] [[package]] -name = "seamless-info" +name = "seamless_info" version = "0.14.0" dependencies = [ "serde", diff --git a/Cargo.toml b/Cargo.toml index 8a32037..e708b7c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ keywords = ["api", "http", "rpc", "json"] # Workspace crates seamless = { path = "seamless" } seamless_macros = { version = "0.14.0", path = "seamless-macros" } -seamless-info = { version = "0.14.0", path = "seamless-info", default-features = false } +seamless_info = { version = "0.14.0", path = "seamless-info", default-features = false } # Dependencies serde = { version = "1", default-features = false, features = ["derive", "alloc"] } diff --git a/PUBLISHING.md b/PUBLISHING.md index e72c408..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 the root `Cargo.toml` (both `workspace.package.version` and the `seamless_macros` and `seamless-info` workspace dependency versions). +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,10 +40,8 @@ git push origin master --tags ## Publish -Publish the macro and info crates first since the main crate depends on them existing. +Run this in the workspace to publish everything ``` -(cd seamless-macros && cargo publish) -(cd seamless-info && cargo publish) -(cd seamless && cargo publish) +cargo publish ``` \ No newline at end of file diff --git a/README.md b/README.md index f470f18..1fda5e6 100644 --- a/README.md +++ b/README.md @@ -206,7 +206,7 @@ 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. -The types describing this info live in the `no_std` `seamless-info` crate (and are re-exported from `seamless::api`). +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 index bfcc1da..42d1e4d 100644 --- a/seamless-info/Cargo.toml +++ b/seamless-info/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "seamless-info" +name = "seamless_info" readme = "README.md" description = """ The no_std types describing a 'seamless' API, eg as returned from `Api::info()` diff --git a/seamless-info/README.md b/seamless-info/README.md index 7eb3d53..1c9d14d 100644 --- a/seamless-info/README.md +++ b/seamless-info/README.md @@ -1,4 +1,4 @@ -# seamless-info +# seamless_info The types describing a [seamless](https://crates.io/crates/seamless) API, as returned from `Api::info()`. diff --git a/seamless/Cargo.toml b/seamless/Cargo.toml index 2465595..072747f 100644 --- a/seamless/Cargo.toml +++ b/seamless/Cargo.toml @@ -22,7 +22,7 @@ serde = { workspace = true, features = ["std"] } serde_json.workspace = true http.workspace = true seamless_macros.workspace = true -seamless-info = { workspace = true, features = ["serialize"] } +seamless_info = { workspace = true, features = ["serialize"] } futures.workspace = true bytes.workspace = true diff --git a/seamless/README.md b/seamless/README.md index b7ddb91..24418db 100644 --- a/seamless/README.md +++ b/seamless/README.md @@ -206,7 +206,7 @@ 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. -The types describing this info live in the `no_std` `seamless-info` crate (and are re-exported from `seamless::api`). +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/lib.rs b/seamless/src/lib.rs index d9dd276..b783e95 100644 --- a/seamless/src/lib.rs +++ b/seamless/src/lib.rs @@ -212,7 +212,7 @@ 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. -The types describing this info live in the `no_std` `seamless-info` crate (and are re-exported from `seamless::api`). +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: From b472842e152fe6c5ec9bec4bb04412347d3da990 Mon Sep 17 00:00:00 2001 From: James Wilson Date: Thu, 22 Oct 2026 17:04:00 +0100 Subject: [PATCH 3/9] add seamless-ts crate for generating TypeScript from RouteInfo --- .github/workflows/ci.yml | 8 +- CHANGELOG.md | 3 +- Cargo.lock | 11 + Cargo.toml | 7 +- seamless-info/Cargo.toml | 2 +- seamless-info/src/lib.rs | 89 +++ seamless-info/tests/serde_roundtrip.rs | 85 --- seamless-ts/Cargo.toml | 24 + seamless-ts/LICENSE | 25 + seamless-ts/README.md | 18 + seamless-ts/src/lib.rs | 909 +++++++++++++++++++++++++ seamless/Cargo.toml | 2 +- seamless/src/api/api.rs | 11 +- seamless/tests/api_base_path.rs | 12 + 14 files changed, 1110 insertions(+), 96 deletions(-) delete mode 100644 seamless-info/tests/serde_roundtrip.rs create mode 100644 seamless-ts/Cargo.toml create mode 100644 seamless-ts/LICENSE create mode 100644 seamless-ts/README.md create mode 100644 seamless-ts/src/lib.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 962dd8b..c65fc66 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -58,7 +58,7 @@ jobs: - run: cargo test --workspace --all-features no_std: - name: no_std (seamless_info) + name: no_std (seamless_info, seamless_ts) runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 @@ -66,8 +66,8 @@ jobs: with: targets: thumbv7em-none-eabi - uses: Swatinem/rust-cache@v2 - # thumbv7em-none-eabi has no std, so this fails if seamless_info (or any of - # its dependencies, for any combination of its features) starts relying on std. + # 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) @@ -76,3 +76,5 @@ jobs: 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 97819e4..e258071 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,9 @@ # 0.14.0 -- Move `RouteInfo`, `ApiBodyInfo` and `ApiBodyType` into a new `no_std` `seamless-info` crate, whose only dependency is `serde`. Its `serialize` and `deserialize` features derive `Serialize` and `Deserialize` respectively, so the info returned from `Api::info()` can now be deserialized (eg to generate a client from it). The types are re-exported from `seamless::api` and `seamless` as before. +- **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`. +- Add a `no_std` `seamless-ts` crate, whose `generate_client()` function takes the JSON serialized info for an API (from `Api::info()`) and generates a type safe TypeScript client from it. - **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 250a1be..4557bd9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -447,6 +447,17 @@ dependencies = [ "syn 3.0.4", ] +[[package]] +name = "seamless_ts" +version = "0.14.0" +dependencies = [ + "pretty_assertions", + "seamless", + "seamless_info", + "serde_json", + "thiserror", +] + [[package]] name = "serde" version = "1.0.229" diff --git a/Cargo.toml b/Cargo.toml index e708b7c..494b32d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,8 @@ members = [ "seamless", "seamless-info", - "seamless-macros" + "seamless-macros", + "seamless-ts" ] resolver = "3" @@ -23,10 +24,11 @@ seamless_info = { version = "0.14.0", path = "seamless-info", default-features = # Dependencies serde = { version = "1", default-features = false, features = ["derive", "alloc"] } -serde_json = "1" +serde_json = { version = "1", default-features = false, features = ["alloc"] } http = "1" futures = "0.3.34" bytes = "1" +thiserror = { version = "2", default-features = false } uuid = "1" syn = { version = "3", features = ["full", "extra-traits"] } quote = "1" @@ -35,7 +37,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/seamless-info/Cargo.toml b/seamless-info/Cargo.toml index 42d1e4d..08d13aa 100644 --- a/seamless-info/Cargo.toml +++ b/seamless-info/Cargo.toml @@ -14,7 +14,7 @@ categories.workspace = true keywords.workspace = true [features] -default = [] +default = ["serialize", "deserialize"] # Derive `serde::Serialize` on all types. serialize = ["dep:serde"] # Derive `serde::Deserialize` on all types. diff --git a/seamless-info/src/lib.rs b/seamless-info/src/lib.rs index 241e375..4502392 100644 --- a/seamless-info/src/lib.rs +++ b/seamless-info/src/lib.rs @@ -144,3 +144,92 @@ pub enum ApiBodyType { 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-info/tests/serde_roundtrip.rs b/seamless-info/tests/serde_roundtrip.rs deleted file mode 100644 index f8ef0a9..0000000 --- a/seamless-info/tests/serde_roundtrip.rs +++ /dev/null @@ -1,85 +0,0 @@ -#![cfg(all(feature = "serialize", feature = "deserialize"))] - -use seamless_info::{ApiBodyInfo, ApiBodyType, RouteInfo}; - -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-ts/Cargo.toml b/seamless-ts/Cargo.toml new file mode 100644 index 0000000..e383b17 --- /dev/null +++ b/seamless-ts/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "seamless_ts" +readme = "README.md" +description = """ +Generate a type safe TypeScript client 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..5012550 --- /dev/null +++ b/seamless-ts/README.md @@ -0,0 +1,18 @@ +# seamless_ts + +Generate a type safe TypeScript client for a [seamless](https://crates.io/crates/seamless) API. + +This crate is `no_std` (it needs `alloc`). It exposes a single function, `generate_client`, which +takes the JSON produced by serializing the result of `seamless::Api::info()` and hands back +TypeScript source code containing: + +- A type for the response of each route (eg `UsersGetById`), and a type for its request body + (eg `UsersGetByIdParams`) if it isn't a `GET` route. +- A `CreateApiClient` function which, given a function that knows how to make requests to the API, + returns a client object with a typed method for each route, grouped by the dot or slash separated + parts of the route name (eg `client.users.getById(params)` for the route `users.get_by_id`). + +```rust,ignore +let info_json = serde_json::to_string(&api.info()).unwrap(); +let typescript = seamless_ts::generate_client(&info_json).unwrap(); +``` diff --git a/seamless-ts/src/lib.rs b/seamless-ts/src/lib.rs new file mode 100644 index 0000000..ce043fb --- /dev/null +++ b/seamless-ts/src/lib.rs @@ -0,0 +1,909 @@ +//! Generate a type safe TypeScript client for a [seamless](https://docs.rs/seamless) API. +//! +//! This crate is `no_std` (though it requires `alloc`). See [`generate_client()`]. + +// 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::borrow::ToOwned; +use alloc::collections::BTreeMap; +use alloc::string::String; +use alloc::vec::Vec; +use core::fmt::{self, Write}; +use seamless_info::{ApiBodyInfo, ApiBodyType, RouteInfo}; + +const INDENT: &str = " "; + +/// Take the JSON obtained by serializing the [`Vec`] for some API (ie the result of +/// calling `seamless::Api::info()`), and generate TypeScript for a type safe client for +/// the API from it. +/// +/// The generated TypeScript contains: +/// +/// - A type for the response of each route, named after the route (eg `UsersGetById` for +/// the route `users.get_by_id`), and if the route isn't a `GET` route, a type for the +/// request body too (eg `UsersGetByIdParams`). +/// - A `createApiClient` function. This takes a function capable of making requests to the +/// API, of the form `(method: string, route: string, params?: any, opts?: O) => Promise`, +/// where `method` is the route's HTTP method (eg `"GET"` or `"POST"`), and returns +/// a client object with a typed method for each route. Routes are grouped by the `.` or `/` +/// separated parts of their names, so the route `users.get_by_id` is called with +/// `client.users.getById(params, opts)`. +/// +/// # Errors +/// +/// Errors if the JSON provided can't be deserialized into an [`Vec`], if a route name +/// can't be turned into names in the generated TypeScript, or if two routes would end up with the +/// same name in the generated TypeScript. +pub fn generate_client(route_info: &str) -> Result { + 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))); + + let routes: Vec> = routes.iter().map(Route::new).collect::>()?; + check_type_names(&routes)?; + let client = build_client_tree(&routes)?; + + let mut out = String::new(); + write_ts(&mut out, &routes, &client).expect("writing to a String can't fail"); + Ok(out) +} + +/// An error generating the TypeScript client. +#[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 route name is empty, or one of its `.` or `/` separated parts contains no letters + /// or digits, so it can't be named in the generated TypeScript. + #[error("The route '{0}' can't be named in the generated TypeScript")] + InvalidRouteName(String), + /// Two routes would both produce TypeScript types with the given name. + #[error( + "The routes '{first_route}' and '{second_route}' would both generate the TypeScript type '{type_name}'" + )] + DuplicateTypeName { + /// The name of the TypeScript type. + type_name: String, + /// The first route that produces this type name. + first_route: String, + /// The second route that produces this type name. + second_route: String, + }, + /// Two routes would both be found at the same place in the client object + /// (or one route would need to be in the middle of the path to another). + #[error( + "The routes '{first_route}' and '{second_route}' would clash at '{client_path}' in the generated client" + )] + DuplicateClientPath { + /// The path in the client object, eg `users.getById`. + client_path: String, + /// The first route that is placed here. + first_route: String, + /// The second route that is placed here. + second_route: String, + }, +} + +/// A route, along with the names we'll use for it in the generated TypeScript. +struct Route<'a> { + info: &'a RouteInfo, + /// Name of the response type, eg `UsersGetById`. + type_name: String, + /// Name of the params type, eg `UsersGetByIdParams`, if this route takes a request body. + params_type_name: Option, + /// Where in the client object this route lives, eg `["users", "getById"]`. + client_path: Vec, +} + +impl<'a> Route<'a> { + fn new(info: &'a RouteInfo) -> Result { + let segments: Vec<&str> = info + .name + .split(['.', '/']) + .filter(|s| !s.is_empty()) + .collect(); + + let client_path: Vec = segments.iter().map(|s| camel_case(s)).collect(); + if client_path.is_empty() || client_path.iter().any(|s| s.is_empty()) { + return Err(Error::InvalidRouteName(info.name.clone())); + } + + let mut type_name: String = segments.iter().map(|s| pascal_case(s)).collect(); + if type_name.starts_with(|c: char| c.is_ascii_digit()) { + type_name.insert(0, '_'); + } + + // Routes that aren't GET routes are expected to be given a body. + let params_type_name = (!info.method.eq_ignore_ascii_case("GET")).then(|| { + let mut name = type_name.clone(); + name.push_str("Params"); + name + }); + + Ok(Route { + info, + type_name, + params_type_name, + client_path, + }) + } +} + +/// Ensure that no two routes produce the same TypeScript type names. +fn check_type_names(routes: &[Route<'_>]) -> Result<(), Error> { + let mut seen: BTreeMap<&str, &str> = BTreeMap::new(); + for route in routes { + let names = core::iter::once(&route.type_name).chain(&route.params_type_name); + for type_name in names { + if let Some(first_route) = seen.insert(type_name, &route.info.name) { + return Err(Error::DuplicateTypeName { + type_name: type_name.clone(), + first_route: first_route.to_owned(), + second_route: route.info.name.clone(), + }); + } + } + } + Ok(()) +} + +/// A node in the client object; either a route function or an object containing more nodes. +enum ClientNode<'r, 'a> { + Route(&'r Route<'a>), + Group(BTreeMap<&'r str, ClientNode<'r, 'a>>), +} + +impl<'r, 'a> ClientNode<'r, 'a> { + /// The name of some route found at or below this node (for error messages). + fn some_route_name(&self) -> &'a str { + match self { + ClientNode::Route(route) => &route.info.name, + ClientNode::Group(group) => group + .values() + .next() + .map(ClientNode::some_route_name) + .unwrap_or_default(), + } + } +} + +/// Group the routes into the shape of the client object that we'll generate. +fn build_client_tree<'r, 'a>( + routes: &'r [Route<'a>], +) -> Result>, Error> { + let mut tree = BTreeMap::new(); + for route in routes { + let clash = |existing: &ClientNode<'_, '_>, depth: usize| Error::DuplicateClientPath { + client_path: route.client_path[..=depth].join("."), + first_route: existing.some_route_name().to_owned(), + second_route: route.info.name.clone(), + }; + + let (last, parents) = route + .client_path + .split_last() + .expect("client paths are never empty"); + + let mut group = &mut tree; + for (depth, key) in parents.iter().enumerate() { + let node = group + .entry(key.as_str()) + .or_insert_with(|| ClientNode::Group(BTreeMap::new())); + group = match node { + ClientNode::Group(g) => g, + route => return Err(clash(route, depth)), + }; + } + if let Some(existing) = group.get(last.as_str()) { + return Err(clash(existing, parents.len())); + } + group.insert(last.as_str(), ClientNode::Route(route)); + } + Ok(tree) +} + +fn write_ts( + out: &mut String, + routes: &[Route<'_>], + client: &BTreeMap<&str, ClientNode<'_, '_>>, +) -> fmt::Result { + writeln!(out, "// THIS IS AN AUTO GENERATED FILE. DO NOT EDIT")?; + + // The types for each route, separated by two blank lines: + for (idx, route) in routes.iter().enumerate() { + let info = route.info; + out.push_str(if idx == 0 { "\n" } else { "\n\n" }); + write_route_comment(out, route, "/*", 0)?; + write!(out, "export type {} = ", route.type_name)?; + write_type(out, &info.response_type.ty, 0)?; + writeln!(out)?; + if let Some(params_type_name) = &route.params_type_name { + write!(out, "export type {params_type_name} = ")?; + write_type(out, &info.request_type.ty, 0)?; + writeln!(out)?; + } + } + + // The client: + out.push_str(concat!( + "\n", + "/**\n", + " * Instantiate a fully typed API client from the above, given an\n", + " * 'api' function that's capable of taking an HTTP method, a route\n", + " * string and params (if not GET), and making a request to the backend\n", + " * to return the expected response type.\n", + " */\n", + "export function createApiClient(api: (method: string, route: string, params?: any, opts?: O) => Promise) {\n", + )); + write!(out, "{INDENT}return ")?; + write_client_group(out, client, 1)?; + writeln!(out, "\n}}") +} + +/// Write an object in the client containing the nodes given. +fn write_client_group( + out: &mut String, + group: &BTreeMap<&str, ClientNode<'_, '_>>, + indent: usize, +) -> fmt::Result { + if group.is_empty() { + return write!(out, "{{}}"); + } + writeln!(out, "{{")?; + for (idx, (key, node)) in group.iter().enumerate() { + if idx > 0 { + writeln!(out, ",")?; + } + match node { + ClientNode::Group(group) => { + write_indent(out, indent + 1)?; + write!(out, "{}: ", PropertyKey(key))?; + write_client_group(out, group, indent + 1)?; + } + ClientNode::Route(route) => { + write_route_comment(out, route, "/**", indent + 1)?; + write_indent(out, indent + 1)?; + write!(out, "{}: function(", PropertyKey(key))?; + if let Some(params_type_name) = &route.params_type_name { + write!(out, "params: {params_type_name}, ")?; + } + writeln!(out, "opts?: O): Promise<{}> {{", route.type_name)?; + write_indent(out, indent + 2)?; + let params = if route.params_type_name.is_some() { + "params" + } else { + "undefined" + }; + writeln!( + out, + "return api({}, {}, {params}, opts)", + SingleQuoted(&route.info.method), + SingleQuoted(&route.info.name) + )?; + write_indent(out, indent + 1)?; + write!(out, "}}")?; + } + } + } + writeln!(out)?; + write_indent(out, indent)?; + write!(out, "}}") +} + +/// Write a comment like the following, with the given opening (eg `/*` or `/**`): +/// +/// ```text +/// /* +/// * POST /users.get_by_id +/// * +/// * Route description +/// */ +/// ``` +fn write_route_comment( + out: &mut String, + route: &Route<'_>, + open: &str, + indent: usize, +) -> fmt::Result { + let info = route.info; + write_indent(out, indent)?; + writeln!(out, "{open}")?; + 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 String, 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. +fn write_doc_comment(out: &mut String, 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, " */") +} + +/// 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 String, 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 String, + 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) +} + +fn write_indent(out: &mut String, indent: usize) -> fmt::Result { + for _ in 0..indent { + out.push_str(INDENT); + } + Ok(()) +} + +/// Split some name like `get_by_id` or `get-by-id` into its words. +fn words(s: &str) -> impl Iterator { + s.split(|c: char| !c.is_alphanumeric()) + .filter(|w| !w.is_empty()) +} + +/// Write a word with its first character uppercased or lowercased. +fn push_word(out: &mut String, word: &str, upper: bool) { + let mut chars = word.chars(); + if let Some(first) = chars.next() { + if upper { + out.extend(first.to_uppercase()); + } else { + out.extend(first.to_lowercase()); + } + out.push_str(chars.as_str()); + } +} + +/// `get_by_id` => `GetById`. +fn pascal_case(s: &str) -> String { + let mut out = String::new(); + for word in words(s) { + push_word(&mut out, word, true); + } + out +} + +/// `get_by_id` => `getById`. +fn camel_case(s: &str) -> String { + let mut out = String::new(); + for (idx, word) in words(s).enumerate() { + push_word(&mut out, word, idx > 0); + } + out +} + +/// Display an object key, quoting it if it isn't a valid identifier. +struct PropertyKey<'a>(&'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. +struct DoubleQuoted<'a>(&'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. +struct SingleQuoted<'a>(&'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(()) + } +} + +#[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, + } + + // 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 + +/* + * POST /gadgets.tune + * + * Tune a gadget. + * + * It's *\/ quite + * a "good" route + */ +export type GadgetsTune = boolean +export type GadgetsTuneParams = { + /** How much to tune by */ + amount?: number + /** + * Some + * multi-line docs. + */ + type: string +} + + +/* + * POST /gadgets.upload + * + * Upload a gadget + */ +export type GadgetsUpload = { + [key: string]: any +} +export type GadgetsUploadParams = Blob + + +/* + * POST /shelf/stack_items + * + * Stack some items on the shelf + */ +export type ShelfStackItems = null +export type ShelfStackItemsParams = { + items: ({ + /** Variant tag */ + kind: "Crate" + width: number + } | { + /** Variant tag */ + kind: "Ball" + /** The ball radius */ + radius: number + })[] +} + + +/* + * GET /widgets.list_all + * + * List all of the widgets + */ +export type WidgetsListAll = ({ + colour: "Red" | "Blue" | null + /** The widget name */ + name: string + size: [number, number] +})[] + +/** + * Instantiate a fully typed API client from the above, given an + * 'api' function that's capable of taking an HTTP method, a route + * string and params (if not GET), and making a request to the backend + * to return the expected response type. + */ +export function createApiClient(api: (method: string, route: string, params?: any, opts?: O) => Promise) { + return { + gadgets: { + /** + * POST /gadgets.tune + * + * Tune a gadget. + * + * It's *\/ quite + * a "good" route + */ + tune: function(params: GadgetsTuneParams, opts?: O): Promise { + return api('POST', 'gadgets.tune', params, opts) + }, + /** + * POST /gadgets.upload + * + * Upload a gadget + */ + upload: function(params: GadgetsUploadParams, opts?: O): Promise { + return api('POST', 'gadgets.upload', params, opts) + } + }, + shelf: { + /** + * POST /shelf/stack_items + * + * Stack some items on the shelf + */ + stackItems: function(params: ShelfStackItemsParams, opts?: O): Promise { + return api('POST', 'shelf/stack_items', params, opts) + } + }, + widgets: { + /** + * GET /widgets.list_all + * + * List all of the widgets + */ + listAll: function(opts?: O): Promise { + return api('GET', 'widgets.list_all', undefined, opts) + } + } + } +} +"#; + + #[test] + fn generates_expected_client() { + let info = serde_json::to_string(&example_api().info()).unwrap(); + let ts = generate_client(&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 route = |name: &str, method: &str| { + json!({ + "name": name, + "method": method, + "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 info = json!([ + route("flim/flam", "PUT"), + route("it's/2nd-route", "GET"), + route("top", "GET"), + ]); + let ts = generate_client(&info.to_string()).unwrap(); + + assert!(ts.contains( + r#"export type FlimFlam = { + empty: {} + lit: "it's \"quoted\"" + maybe?: boolean + "not-an-ident": unknown +} +export type FlimFlamParams = null"# + )); + assert!(ts.contains("return api('PUT', 'flim/flam', params, opts)")); + assert!(ts.contains("export type ItS2ndRoute = {")); + assert!(ts.contains( + r#" itS: { + /** + * GET /it's/2nd-route + */ + "2ndRoute": function(opts?: O): Promise { + return api('GET', 'it\'s/2nd-route', undefined, opts) + } + },"# + )); + assert!(ts.contains( + " top: function(opts?: O): Promise {\n return api('GET', 'top', undefined, opts)\n }\n }\n}\n" + )); + } + + #[test] + fn empty_api() { + let ts = generate_client("[]").unwrap(); + assert!(ts.ends_with(" return {}\n}\n")); + } + + fn route(name: &str) -> Value { + json!({ + "name": name, + "method": "GET", + "description": "", + "request_type": { "description": "", "shape": { "type": "Null" } }, + "response_type": { "description": "", "shape": { "type": "Null" } } + }) + } + + #[test] + fn errors_on_invalid_json() { + let err = generate_client(r#"[{ "name": "foo" }]"#).unwrap_err(); + assert!(matches!(err, Error::Deserialize(_))); + } + + #[test] + fn errors_on_unnameable_routes() { + for name in ["", "/", "foo.-", "foo.-.bar"] { + let info = json!([route(name)]).to_string(); + let err = generate_client(&info).unwrap_err(); + assert!( + matches!(&err, Error::InvalidRouteName(n) if n == name), + "unexpected error for '{name}': {err:?}" + ); + } + } + + #[test] + fn errors_on_clashing_type_names() { + let info = json!([route("foo.bar_baz"), route("foo_bar.baz")]).to_string(); + let err = generate_client(&info).unwrap_err(); + assert_eq!( + err.to_string(), + "The routes 'foo.bar_baz' and 'foo_bar.baz' would both generate the TypeScript type 'FooBarBaz'" + ); + } + + #[test] + fn errors_on_clashing_client_paths() { + let info = json!([route("foo"), route("foo.bar")]).to_string(); + let err = generate_client(&info).unwrap_err(); + assert_eq!( + err.to_string(), + "The routes 'foo' and 'foo.bar' would clash at 'foo' in the generated client" + ); + + let info = json!([route("foo.bar"), route("foo.bar_")]).to_string(); + let err = generate_client(&info).unwrap_err(); + assert!(matches!(err, Error::DuplicateTypeName { .. })); + + let info = json!([route("foo.bar.baz"), route("foo.bar")]).to_string(); + let err = generate_client(&info).unwrap_err(); + assert_eq!( + err.to_string(), + "The routes 'foo.bar' and 'foo.bar.baz' would clash at 'foo.bar' in the generated client" + ); + } +} diff --git a/seamless/Cargo.toml b/seamless/Cargo.toml index 072747f..82f0746 100644 --- a/seamless/Cargo.toml +++ b/seamless/Cargo.toml @@ -19,7 +19,7 @@ default = ["uuid"] [dependencies] serde = { workspace = true, features = ["std"] } -serde_json.workspace = true +serde_json = { workspace = true, features = ["std"] } http.workspace = true seamless_macros.workspace = true seamless_info = { workspace = true, features = ["serialize"] } diff --git a/seamless/src/api/api.rs b/seamless/src/api/api.rs index 71285ec..256f698 100644 --- a/seamless/src/api/api.rs +++ b/seamless/src/api/api.rs @@ -55,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 /// /// ``` @@ -77,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) @@ -88,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 { 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("//"); +} From 17afbfd5c6d5a223c07c8eee501e1daf6f661fb6 Mon Sep 17 00:00:00 2001 From: James Wilson Date: Thu, 22 Oct 2026 17:22:04 +0100 Subject: [PATCH 4/9] Add seamless-ts-bin crate for genetating TypeScript code from an API interface --- CHANGELOG.md | 3 +- Cargo.lock | 142 +++++++++++++++++++++++++++++++++++- Cargo.toml | 5 +- seamless-ts-bin/Cargo.toml | 22 ++++++ seamless-ts-bin/LICENSE | 25 +++++++ seamless-ts-bin/README.md | 18 +++++ seamless-ts-bin/src/main.rs | 80 ++++++++++++++++++++ seamless-ts/README.md | 11 ++- seamless-ts/src/lib.rs | 84 +++++++++++++-------- 9 files changed, 348 insertions(+), 42 deletions(-) create mode 100644 seamless-ts-bin/Cargo.toml create mode 100644 seamless-ts-bin/LICENSE create mode 100644 seamless-ts-bin/README.md create mode 100644 seamless-ts-bin/src/main.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index e258071..b6b01be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,8 @@ - **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`. -- Add a `no_std` `seamless-ts` crate, whose `generate_client()` function takes the JSON serialized info for an API (from `Api::info()`) and generates a type safe TypeScript client from it. +- Add a `no_std` `seamless-ts` crate, whose `generate_client()` function takes the JSON serialized info for an API (from `Api::info()`) and writes a type safe TypeScript client generated from it to any `core::fmt::Write`. +- 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`) and writes a TypeScript client for it to stdout. - **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 4557bd9..d63d62f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,56 @@ # It is not intended for manual editing. version = 4 +[[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", +] + +[[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", +] + [[package]] name = "autocfg" version = "1.1.0" @@ -84,6 +134,52 @@ 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 = "diff" version = "0.1.13" @@ -211,6 +307,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 +404,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" @@ -358,6 +466,12 @@ 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" @@ -382,18 +496,18 @@ 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", ] @@ -458,6 +572,14 @@ dependencies = [ "thiserror", ] +[[package]] +name = "seamless_ts_bin" +version = "0.14.0" +dependencies = [ + "clap", + "seamless_ts", +] + [[package]] name = "serde" version = "1.0.229" @@ -557,6 +679,12 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "syn" version = "2.0.90" @@ -769,6 +897,12 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc" +[[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" diff --git a/Cargo.toml b/Cargo.toml index 494b32d..5060e65 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,8 @@ members = [ "seamless", "seamless-info", "seamless-macros", - "seamless-ts" + "seamless-ts", + "seamless-ts-bin" ] resolver = "3" @@ -21,6 +22,7 @@ keywords = ["api", "http", "rpc", "json"] seamless = { path = "seamless" } seamless_macros = { version = "0.14.0", path = "seamless-macros" } seamless_info = { version = "0.14.0", path = "seamless-info", default-features = false } +seamless_ts = { version = "0.14.0", path = "seamless-ts" } # Dependencies serde = { version = "1", default-features = false, features = ["derive", "alloc"] } @@ -29,6 +31,7 @@ http = "1" futures = "0.3.34" bytes = "1" thiserror = { version = "2", default-features = false } +clap = { version = "4.6.7", features = ["derive"] } uuid = "1" syn = { version = "3", features = ["full", "extra-traits"] } quote = "1" diff --git a/seamless-ts-bin/Cargo.toml b/seamless-ts-bin/Cargo.toml new file mode 100644 index 0000000..b894e8e --- /dev/null +++ b/seamless-ts-bin/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "seamless_ts_bin" +readme = "README.md" +description = """ +A CLI tool to generate a type safe TypeScript client 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 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..e48e56a --- /dev/null +++ b/seamless-ts-bin/README.md @@ -0,0 +1,18 @@ +# seamless_ts_bin + +A `seamless-ts` command line tool which generates a type safe TypeScript client for 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 or from a file given with `--file`, and writes the generated TypeScript to stdout. Any +errors are written to stderr. + +```sh +cargo install seamless_ts_bin + +# Read the API info from stdin: +curl https://example.com/api/meta.info | seamless-ts > client.ts + +# Or read it from a file: +seamless-ts --file api-info.json > client.ts +``` diff --git a/seamless-ts-bin/src/main.rs b/seamless-ts-bin/src/main.rs new file mode 100644 index 0000000..e16f663 --- /dev/null +++ b/seamless-ts-bin/src/main.rs @@ -0,0 +1,80 @@ +use clap::Parser; +use std::fmt; +use std::io::{self, BufWriter, Read, Write}; +use std::path::PathBuf; +use std::process::ExitCode; + +/// Generate a type safe TypeScript client from the JSON info describing a seamless API. +/// +/// The API info is read from stdin, or from the file given by --file, 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, +} + +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 { + None => { + let mut s = String::new(); + io::stdin() + .read_to_string(&mut s) + .map_err(|e| format!("Could not read from stdin: {e}"))?; + s + } + Some(path) => std::fs::read_to_string(&path) + .map_err(|e| format!("Could not read '{}': {e}", path.display()))?, + }; + + 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_client(&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/README.md b/seamless-ts/README.md index 5012550..388923b 100644 --- a/seamless-ts/README.md +++ b/seamless-ts/README.md @@ -3,16 +3,19 @@ Generate a type safe TypeScript client for a [seamless](https://crates.io/crates/seamless) API. This crate is `no_std` (it needs `alloc`). It exposes a single function, `generate_client`, which -takes the JSON produced by serializing the result of `seamless::Api::info()` and hands back -TypeScript source code containing: +takes the JSON produced by serializing the result of `seamless::Api::info()` and writes +TypeScript source code to any `core::fmt::Write` (eg a `String`) containing: - A type for the response of each route (eg `UsersGetById`), and a type for its request body (eg `UsersGetByIdParams`) if it isn't a `GET` route. -- A `CreateApiClient` function which, given a function that knows how to make requests to the API, +- A `createApiClient` function which, given a function that knows how to make requests to the API, returns a client object with a typed method for each route, grouped by the dot or slash separated parts of the route name (eg `client.users.getById(params)` for the route `users.get_by_id`). ```rust,ignore let info_json = serde_json::to_string(&api.info()).unwrap(); -let typescript = seamless_ts::generate_client(&info_json).unwrap(); +let mut typescript = String::new(); +seamless_ts::generate_client(&info_json, &mut typescript).unwrap(); ``` + +To generate a client from the command line, see the `seamless-ts` binary in the `seamless_ts_bin` crate. diff --git a/seamless-ts/src/lib.rs b/seamless-ts/src/lib.rs index ce043fb..efe7a99 100644 --- a/seamless-ts/src/lib.rs +++ b/seamless-ts/src/lib.rs @@ -18,8 +18,8 @@ use seamless_info::{ApiBodyInfo, ApiBodyType, RouteInfo}; const INDENT: &str = " "; /// Take the JSON obtained by serializing the [`Vec`] for some API (ie the result of -/// calling `seamless::Api::info()`), and generate TypeScript for a type safe client for -/// the API from it. +/// calling `seamless::Api::info()`), and write TypeScript for a type safe client for the API +/// to the [`Write`] implementation provided (eg a [`String`]). /// /// The generated TypeScript contains: /// @@ -37,8 +37,9 @@ const INDENT: &str = " "; /// /// Errors if the JSON provided can't be deserialized into an [`Vec`], if a route name /// can't be turned into names in the generated TypeScript, or if two routes would end up with the -/// same name in the generated TypeScript. -pub fn generate_client(route_info: &str) -> Result { +/// same name in the generated TypeScript. Nothing is written in any of these cases. Also errors +/// if writing to `out` fails, in which case some of the output may already have been written. +pub fn generate_client(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))); @@ -47,9 +48,7 @@ pub fn generate_client(route_info: &str) -> Result { check_type_names(&routes)?; let client = build_client_tree(&routes)?; - let mut out = String::new(); - write_ts(&mut out, &routes, &client).expect("writing to a String can't fail"); - Ok(out) + write_ts(out, &routes, &client).map_err(Error::Write) } /// An error generating the TypeScript client. @@ -58,6 +57,9 @@ 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), /// The route name is empty, or one of its `.` or `/` separated parts contains no letters /// or digits, so it can't be named in the generated TypeScript. #[error("The route '{0}' can't be named in the generated TypeScript")] @@ -207,8 +209,8 @@ fn build_client_tree<'r, 'a>( Ok(tree) } -fn write_ts( - out: &mut String, +fn write_ts( + out: &mut W, routes: &[Route<'_>], client: &BTreeMap<&str, ClientNode<'_, '_>>, ) -> fmt::Result { @@ -217,7 +219,7 @@ fn write_ts( // The types for each route, separated by two blank lines: for (idx, route) in routes.iter().enumerate() { let info = route.info; - out.push_str(if idx == 0 { "\n" } else { "\n\n" }); + out.write_str(if idx == 0 { "\n" } else { "\n\n" })?; write_route_comment(out, route, "/*", 0)?; write!(out, "export type {} = ", route.type_name)?; write_type(out, &info.response_type.ty, 0)?; @@ -230,7 +232,7 @@ fn write_ts( } // The client: - out.push_str(concat!( + out.write_str(concat!( "\n", "/**\n", " * Instantiate a fully typed API client from the above, given an\n", @@ -239,15 +241,15 @@ fn write_ts( " * to return the expected response type.\n", " */\n", "export function createApiClient(api: (method: string, route: string, params?: any, opts?: O) => Promise) {\n", - )); + ))?; write!(out, "{INDENT}return ")?; write_client_group(out, client, 1)?; writeln!(out, "\n}}") } /// Write an object in the client containing the nodes given. -fn write_client_group( - out: &mut String, +fn write_client_group( + out: &mut W, group: &BTreeMap<&str, ClientNode<'_, '_>>, indent: usize, ) -> fmt::Result { @@ -304,8 +306,8 @@ fn write_client_group( /// * Route description /// */ /// ``` -fn write_route_comment( - out: &mut String, +fn write_route_comment( + out: &mut W, route: &Route<'_>, open: &str, indent: usize, @@ -331,7 +333,7 @@ fn write_route_comment( } /// Write each line of some text as ` * line`, as part of a block comment. -fn write_comment_lines(out: &mut String, text: &str, indent: usize) -> fmt::Result { +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(); @@ -346,7 +348,11 @@ fn write_comment_lines(out: &mut String, text: &str, indent: usize) -> fmt::Resu /// Write a doc comment for some object property. Single line descriptions are written /// as `/** description */`, and longer ones are written as a block. -fn write_doc_comment(out: &mut String, description: &str, indent: usize) -> fmt::Result { +fn write_doc_comment( + out: &mut W, + description: &str, + indent: usize, +) -> fmt::Result { let description = description.trim(); if description.is_empty() { return Ok(()); @@ -363,7 +369,7 @@ fn write_doc_comment(out: &mut String, description: &str, indent: usize) -> fmt: /// 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 String, ty: &ApiBodyType, indent: usize) -> fmt::Result { +fn write_type(out: &mut W, ty: &ApiBodyType, indent: usize) -> fmt::Result { match ty { ApiBodyType::String => write!(out, "string"), ApiBodyType::Number => write!(out, "number"), @@ -430,8 +436,8 @@ fn write_type(out: &mut String, ty: &ApiBodyType, indent: usize) -> fmt::Result } /// Write out a single property of an object, eg `key?: string`, along with its description. -fn write_object_property( - out: &mut String, +fn write_object_property( + out: &mut W, key: &str, value: &ApiBodyInfo, indent: usize, @@ -458,9 +464,9 @@ fn write_object_property( writeln!(out) } -fn write_indent(out: &mut String, indent: usize) -> fmt::Result { +fn write_indent(out: &mut W, indent: usize) -> fmt::Result { for _ in 0..indent { - out.push_str(INDENT); + out.write_str(INDENT)?; } Ok(()) } @@ -631,6 +637,12 @@ mod tests { r#type: String, } + fn generate(route_info: &str) -> Result { + let mut out = String::new(); + generate_client(route_info, &mut out)?; + Ok(out) + } + // The handlers are never called; we only care about the types they describe. fn never() -> T { unimplemented!() @@ -774,7 +786,7 @@ export function createApiClient(api: (method: string, route: string, #[test] fn generates_expected_client() { let info = serde_json::to_string(&example_api().info()).unwrap(); - let ts = generate_client(&info).unwrap(); + let ts = generate(&info).unwrap(); // Handy for checking the output with `tsc`: if let Some(path) = std::env::var_os("SEAMLESS_TS_OUT") { @@ -814,7 +826,7 @@ export function createApiClient(api: (method: string, route: string, route("it's/2nd-route", "GET"), route("top", "GET"), ]); - let ts = generate_client(&info.to_string()).unwrap(); + let ts = generate(&info.to_string()).unwrap(); assert!(ts.contains( r#"export type FlimFlam = { @@ -844,7 +856,7 @@ export type FlimFlamParams = null"# #[test] fn empty_api() { - let ts = generate_client("[]").unwrap(); + let ts = generate("[]").unwrap(); assert!(ts.ends_with(" return {}\n}\n")); } @@ -858,9 +870,17 @@ export type FlimFlamParams = null"# }) } + #[test] + fn writes_nothing_on_error() { + let info = json!([route("foo"), route("foo.bar")]).to_string(); + let mut out = String::new(); + assert!(generate_client(&info, &mut out).is_err()); + assert_eq!(out, ""); + } + #[test] fn errors_on_invalid_json() { - let err = generate_client(r#"[{ "name": "foo" }]"#).unwrap_err(); + let err = generate(r#"[{ "name": "foo" }]"#).unwrap_err(); assert!(matches!(err, Error::Deserialize(_))); } @@ -868,7 +888,7 @@ export type FlimFlamParams = null"# fn errors_on_unnameable_routes() { for name in ["", "/", "foo.-", "foo.-.bar"] { let info = json!([route(name)]).to_string(); - let err = generate_client(&info).unwrap_err(); + let err = generate(&info).unwrap_err(); assert!( matches!(&err, Error::InvalidRouteName(n) if n == name), "unexpected error for '{name}': {err:?}" @@ -879,7 +899,7 @@ export type FlimFlamParams = null"# #[test] fn errors_on_clashing_type_names() { let info = json!([route("foo.bar_baz"), route("foo_bar.baz")]).to_string(); - let err = generate_client(&info).unwrap_err(); + let err = generate(&info).unwrap_err(); assert_eq!( err.to_string(), "The routes 'foo.bar_baz' and 'foo_bar.baz' would both generate the TypeScript type 'FooBarBaz'" @@ -889,18 +909,18 @@ export type FlimFlamParams = null"# #[test] fn errors_on_clashing_client_paths() { let info = json!([route("foo"), route("foo.bar")]).to_string(); - let err = generate_client(&info).unwrap_err(); + let err = generate(&info).unwrap_err(); assert_eq!( err.to_string(), "The routes 'foo' and 'foo.bar' would clash at 'foo' in the generated client" ); let info = json!([route("foo.bar"), route("foo.bar_")]).to_string(); - let err = generate_client(&info).unwrap_err(); + let err = generate(&info).unwrap_err(); assert!(matches!(err, Error::DuplicateTypeName { .. })); let info = json!([route("foo.bar.baz"), route("foo.bar")]).to_string(); - let err = generate_client(&info).unwrap_err(); + let err = generate(&info).unwrap_err(); assert_eq!( err.to_string(), "The routes 'foo.bar' and 'foo.bar.baz' would clash at 'foo.bar' in the generated client" From c0cbef74a1982bd6bf716e3666dd3ba29629b552 Mon Sep 17 00:00:00 2001 From: James Wilson Date: Thu, 22 Oct 2026 17:36:06 +0100 Subject: [PATCH 5/9] README tweak --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1fda5e6..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. From 5f75d8632b1ceb49e64065671008a80d06c14380 Mon Sep 17 00:00:00 2001 From: James Wilson Date: Fri, 23 Oct 2026 11:42:23 +0100 Subject: [PATCH 6/9] generate only types, not an API function, for more flexibility --- CHANGELOG.md | 7 +- seamless-ts-bin/Cargo.toml | 2 +- seamless-ts-bin/README.md | 6 +- seamless-ts-bin/src/main.rs | 4 +- seamless-ts/Cargo.toml | 2 +- seamless-ts/README.md | 22 +- seamless-ts/src/fmt_helpers.rs | 156 +++++++ seamless-ts/src/lib.rs | 823 +++++++-------------------------- 8 files changed, 356 insertions(+), 666 deletions(-) create mode 100644 seamless-ts/src/fmt_helpers.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index b6b01be..6bfcd00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,10 +1,13 @@ +# Unreleased + +- Add a `no_std` `seamless-ts` crate, whose `generate_client()` 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. +- 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`) 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`. -- Add a `no_std` `seamless-ts` crate, whose `generate_client()` function takes the JSON serialized info for an API (from `Api::info()`) and writes a type safe TypeScript client generated from it to any `core::fmt::Write`. -- 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`) and writes a TypeScript client for it to stdout. - **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/seamless-ts-bin/Cargo.toml b/seamless-ts-bin/Cargo.toml index b894e8e..c0c013a 100644 --- a/seamless-ts-bin/Cargo.toml +++ b/seamless-ts-bin/Cargo.toml @@ -2,7 +2,7 @@ name = "seamless_ts_bin" readme = "README.md" description = """ -A CLI tool to generate a type safe TypeScript client from the info describing a 'seamless' API +A CLI tool to generate TypeScript types from the info describing a 'seamless' API """ version.workspace = true diff --git a/seamless-ts-bin/README.md b/seamless-ts-bin/README.md index e48e56a..1c5e954 100644 --- a/seamless-ts-bin/README.md +++ b/seamless-ts-bin/README.md @@ -1,6 +1,6 @@ # seamless_ts_bin -A `seamless-ts` command line tool which generates a type safe TypeScript client for a +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 @@ -11,8 +11,8 @@ errors are written to stderr. cargo install seamless_ts_bin # Read the API info from stdin: -curl https://example.com/api/meta.info | seamless-ts > client.ts +curl https://example.com/api/meta.info | seamless-ts > api.ts # Or read it from a file: -seamless-ts --file api-info.json > client.ts +seamless-ts --file api-info.json > api.ts ``` diff --git a/seamless-ts-bin/src/main.rs b/seamless-ts-bin/src/main.rs index e16f663..d8f7b69 100644 --- a/seamless-ts-bin/src/main.rs +++ b/seamless-ts-bin/src/main.rs @@ -4,7 +4,7 @@ use std::io::{self, BufWriter, Read, Write}; use std::path::PathBuf; use std::process::ExitCode; -/// Generate a type safe TypeScript client from the JSON info describing a seamless API. +/// Generate TypeScript types from the JSON info describing a seamless API. /// /// The API info is read from stdin, or from the file given by --file, and the /// generated TypeScript is written to stdout. @@ -41,7 +41,7 @@ fn run(args: Args) -> Result<(), String> { 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_client(&route_info, &mut out) { + match seamless_ts::generate_types(&route_info, &mut out) { Ok(()) => {} Err(seamless_ts::Error::Write(_)) => { return Err(write_error(out.take_error())); diff --git a/seamless-ts/Cargo.toml b/seamless-ts/Cargo.toml index e383b17..8bb4dd7 100644 --- a/seamless-ts/Cargo.toml +++ b/seamless-ts/Cargo.toml @@ -2,7 +2,7 @@ name = "seamless_ts" readme = "README.md" description = """ -Generate a type safe TypeScript client from the info describing a 'seamless' API +Generate TypeScript types from the info describing a 'seamless' API """ version.workspace = true diff --git a/seamless-ts/README.md b/seamless-ts/README.md index 388923b..a3f2bb5 100644 --- a/seamless-ts/README.md +++ b/seamless-ts/README.md @@ -1,16 +1,22 @@ # seamless_ts -Generate a type safe TypeScript client for a [seamless](https://crates.io/crates/seamless) API. +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_client`, which takes the JSON produced by serializing the result of `seamless::Api::info()` and writes -TypeScript source code to any `core::fmt::Write` (eg a `String`) containing: +TypeScript to any `core::fmt::Write` (eg a `String`). The TypeScript exports a single `Api` type, +which maps each route name to its HTTP method, request body type (`params`, unless it's a `GET` +route) and response type (`result`), and can be used to build a type safe client for the API: -- A type for the response of each route (eg `UsersGetById`), and a type for its request body - (eg `UsersGetByIdParams`) if it isn't a `GET` route. -- A `createApiClient` function which, given a function that knows how to make requests to the API, - returns a client object with a typed method for each route, grouped by the dot or slash separated - parts of the route name (eg `client.users.getById(params)` for the route `users.get_by_id`). +```ts +export type Api = { + 'users.get_by_id': { + method: 'POST' + params: { id: string } + result: { id: string, name: string } + } +} +``` ```rust,ignore let info_json = serde_json::to_string(&api.info()).unwrap(); @@ -18,4 +24,4 @@ let mut typescript = String::new(); seamless_ts::generate_client(&info_json, &mut typescript).unwrap(); ``` -To generate a client from the command line, see the `seamless-ts` binary in the `seamless_ts_bin` crate. +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 index efe7a99..154f4ff 100644 --- a/seamless-ts/src/lib.rs +++ b/seamless-ts/src/lib.rs @@ -1,6 +1,6 @@ -//! Generate a type safe TypeScript client for a [seamless](https://docs.rs/seamless) API. +//! Generate TypeScript types describing a [seamless](https://docs.rs/seamless) API. //! -//! This crate is `no_std` (though it requires `alloc`). See [`generate_client()`]. +//! 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)] @@ -8,50 +8,55 @@ extern crate alloc; -use alloc::borrow::ToOwned; -use alloc::collections::BTreeMap; 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}; -const INDENT: &str = " "; +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 for a type safe client for the API -/// to the [`Write`] implementation provided (eg a [`String`]). +/// calling `seamless::Api::info()`), and write TypeScript describing the API to the [`Write`] +/// implementation provided (eg a [`String`]). /// -/// The generated TypeScript contains: +/// The generated TypeScript exports a single `Api` type, which maps each route name to its +/// HTTP method, the type of its request body (`params`, unless it's a `GET` route) and the +/// type of its response (`result`). For example: /// -/// - A type for the response of each route, named after the route (eg `UsersGetById` for -/// the route `users.get_by_id`), and if the route isn't a `GET` route, a type for the -/// request body too (eg `UsersGetByIdParams`). -/// - A `createApiClient` function. This takes a function capable of making requests to the -/// API, of the form `(method: string, route: string, params?: any, opts?: O) => Promise`, -/// where `method` is the route's HTTP method (eg `"GET"` or `"POST"`), and returns -/// a client object with a typed method for each route. Routes are grouped by the `.` or `/` -/// separated parts of their names, so the route `users.get_by_id` is called with -/// `client.users.getById(params, opts)`. +/// ```ts +/// export type Api = { +/// 'users.get_by_id': { +/// method: 'POST' +/// params: { id: string } +/// result: { id: string, name: string } +/// } +/// } +/// ``` +/// +/// This can be used to build a type safe client for the API. /// /// # Errors /// -/// Errors if the JSON provided can't be deserialized into an [`Vec`], if a route name -/// can't be turned into names in the generated TypeScript, or if two routes would end up with the -/// same name in the generated TypeScript. Nothing is written in any of these cases. Also errors -/// if writing to `out` fails, in which case some of the output may already have been written. -pub fn generate_client(route_info: &str, out: &mut W) -> Result<(), Error> { +/// 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_types(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))); - let routes: Vec> = routes.iter().map(Route::new).collect::>()?; - check_type_names(&routes)?; - let client = build_client_tree(&routes)?; + // 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, &client).map_err(Error::Write) + write_ts(out, &routes).map_err(Error::Write) } -/// An error generating the TypeScript client. +/// An error generating the TypeScript. #[derive(Debug, thiserror::Error)] pub enum Error { /// The JSON provided could not be deserialized into an [`Vec`]. @@ -60,311 +65,42 @@ pub enum Error { /// The generated TypeScript could not be written to the output. #[error("Could not write the generated TypeScript")] Write(fmt::Error), - /// The route name is empty, or one of its `.` or `/` separated parts contains no letters - /// or digits, so it can't be named in the generated TypeScript. - #[error("The route '{0}' can't be named in the generated TypeScript")] - InvalidRouteName(String), - /// Two routes would both produce TypeScript types with the given name. - #[error( - "The routes '{first_route}' and '{second_route}' would both generate the TypeScript type '{type_name}'" - )] - DuplicateTypeName { - /// The name of the TypeScript type. - type_name: String, - /// The first route that produces this type name. - first_route: String, - /// The second route that produces this type name. - second_route: String, - }, - /// Two routes would both be found at the same place in the client object - /// (or one route would need to be in the middle of the path to another). - #[error( - "The routes '{first_route}' and '{second_route}' would clash at '{client_path}' in the generated client" - )] - DuplicateClientPath { - /// The path in the client object, eg `users.getById`. - client_path: String, - /// The first route that is placed here. - first_route: String, - /// The second route that is placed here. - second_route: String, - }, -} - -/// A route, along with the names we'll use for it in the generated TypeScript. -struct Route<'a> { - info: &'a RouteInfo, - /// Name of the response type, eg `UsersGetById`. - type_name: String, - /// Name of the params type, eg `UsersGetByIdParams`, if this route takes a request body. - params_type_name: Option, - /// Where in the client object this route lives, eg `["users", "getById"]`. - client_path: Vec, -} - -impl<'a> Route<'a> { - fn new(info: &'a RouteInfo) -> Result { - let segments: Vec<&str> = info - .name - .split(['.', '/']) - .filter(|s| !s.is_empty()) - .collect(); - - let client_path: Vec = segments.iter().map(|s| camel_case(s)).collect(); - if client_path.is_empty() || client_path.iter().any(|s| s.is_empty()) { - return Err(Error::InvalidRouteName(info.name.clone())); - } - - let mut type_name: String = segments.iter().map(|s| pascal_case(s)).collect(); - if type_name.starts_with(|c: char| c.is_ascii_digit()) { - type_name.insert(0, '_'); - } - - // Routes that aren't GET routes are expected to be given a body. - let params_type_name = (!info.method.eq_ignore_ascii_case("GET")).then(|| { - let mut name = type_name.clone(); - name.push_str("Params"); - name - }); - - Ok(Route { - info, - type_name, - params_type_name, - client_path, - }) - } -} - -/// Ensure that no two routes produce the same TypeScript type names. -fn check_type_names(routes: &[Route<'_>]) -> Result<(), Error> { - let mut seen: BTreeMap<&str, &str> = BTreeMap::new(); - for route in routes { - let names = core::iter::once(&route.type_name).chain(&route.params_type_name); - for type_name in names { - if let Some(first_route) = seen.insert(type_name, &route.info.name) { - return Err(Error::DuplicateTypeName { - type_name: type_name.clone(), - first_route: first_route.to_owned(), - second_route: route.info.name.clone(), - }); - } - } - } - Ok(()) -} - -/// A node in the client object; either a route function or an object containing more nodes. -enum ClientNode<'r, 'a> { - Route(&'r Route<'a>), - Group(BTreeMap<&'r str, ClientNode<'r, 'a>>), + /// 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), } -impl<'r, 'a> ClientNode<'r, 'a> { - /// The name of some route found at or below this node (for error messages). - fn some_route_name(&self) -> &'a str { - match self { - ClientNode::Route(route) => &route.info.name, - ClientNode::Group(group) => group - .values() - .next() - .map(ClientNode::some_route_name) - .unwrap_or_default(), - } - } -} - -/// Group the routes into the shape of the client object that we'll generate. -fn build_client_tree<'r, 'a>( - routes: &'r [Route<'a>], -) -> Result>, Error> { - let mut tree = BTreeMap::new(); - for route in routes { - let clash = |existing: &ClientNode<'_, '_>, depth: usize| Error::DuplicateClientPath { - client_path: route.client_path[..=depth].join("."), - first_route: existing.some_route_name().to_owned(), - second_route: route.info.name.clone(), - }; - - let (last, parents) = route - .client_path - .split_last() - .expect("client paths are never empty"); - - let mut group = &mut tree; - for (depth, key) in parents.iter().enumerate() { - let node = group - .entry(key.as_str()) - .or_insert_with(|| ClientNode::Group(BTreeMap::new())); - group = match node { - ClientNode::Group(g) => g, - route => return Err(clash(route, depth)), - }; - } - if let Some(existing) = group.get(last.as_str()) { - return Err(clash(existing, parents.len())); - } - group.insert(last.as_str(), ClientNode::Route(route)); - } - Ok(tree) -} - -fn write_ts( - out: &mut W, - routes: &[Route<'_>], - client: &BTreeMap<&str, ClientNode<'_, '_>>, -) -> fmt::Result { +fn write_ts(out: &mut W, routes: &[RouteInfo]) -> fmt::Result { writeln!(out, "// THIS IS AN AUTO GENERATED FILE. DO NOT EDIT")?; - - // The types for each route, separated by two blank lines: - for (idx, route) in routes.iter().enumerate() { - let info = route.info; - out.write_str(if idx == 0 { "\n" } else { "\n\n" })?; - write_route_comment(out, route, "/*", 0)?; - write!(out, "export type {} = ", route.type_name)?; - write_type(out, &info.response_type.ty, 0)?; - writeln!(out)?; - if let Some(params_type_name) = &route.params_type_name { - write!(out, "export type {params_type_name} = ")?; - write_type(out, &info.request_type.ty, 0)?; - writeln!(out)?; - } - } - - // The client: - out.write_str(concat!( - "\n", - "/**\n", - " * Instantiate a fully typed API client from the above, given an\n", - " * 'api' function that's capable of taking an HTTP method, a route\n", - " * string and params (if not GET), and making a request to the backend\n", - " * to return the expected response type.\n", - " */\n", - "export function createApiClient(api: (method: string, route: string, params?: any, opts?: O) => Promise) {\n", - ))?; - write!(out, "{INDENT}return ")?; - write_client_group(out, client, 1)?; - writeln!(out, "\n}}") -} - -/// Write an object in the client containing the nodes given. -fn write_client_group( - out: &mut W, - group: &BTreeMap<&str, ClientNode<'_, '_>>, - indent: usize, -) -> fmt::Result { - if group.is_empty() { - return write!(out, "{{}}"); - } - writeln!(out, "{{")?; - for (idx, (key, node)) in group.iter().enumerate() { - if idx > 0 { - writeln!(out, ",")?; - } - match node { - ClientNode::Group(group) => { - write_indent(out, indent + 1)?; - write!(out, "{}: ", PropertyKey(key))?; - write_client_group(out, group, indent + 1)?; - } - ClientNode::Route(route) => { - write_route_comment(out, route, "/**", indent + 1)?; - write_indent(out, indent + 1)?; - write!(out, "{}: function(", PropertyKey(key))?; - if let Some(params_type_name) = &route.params_type_name { - write!(out, "params: {params_type_name}, ")?; - } - writeln!(out, "opts?: O): Promise<{}> {{", route.type_name)?; - write_indent(out, indent + 2)?; - let params = if route.params_type_name.is_some() { - "params" - } else { - "undefined" - }; - writeln!( - out, - "return api({}, {}, {params}, opts)", - SingleQuoted(&route.info.method), - SingleQuoted(&route.info.name) - )?; - write_indent(out, indent + 1)?; - write!(out, "}}")?; - } - } - } writeln!(out)?; - write_indent(out, indent)?; - write!(out, "}}") -} - -/// Write a comment like the following, with the given opening (eg `/*` or `/**`): -/// -/// ```text -/// /* -/// * POST /users.get_by_id -/// * -/// * Route description -/// */ -/// ``` -fn write_route_comment( - out: &mut W, - route: &Route<'_>, - open: &str, - indent: usize, -) -> fmt::Result { - let info = route.info; - write_indent(out, indent)?; - writeln!(out, "{open}")?; - 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)?; + writeln!(out, "/**")?; + writeln!(out, " * The routes provided by our API")?; + writeln!(out, " */")?; + if routes.is_empty() { + return writeln!(out, "export type Api = {{}}"); } - 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))?; + writeln!(out, "export type Api = {{")?; + 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. + if !route.method.eq_ignore_ascii_case("GET") { + write_indent(out, 2)?; + write!(out, "params: ")?; + 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, "}}")?; } - Ok(()) -} - -/// Write a doc comment for some object property. Single line descriptions are written -/// as `/** description */`, and longer ones are written as a block. -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, " */") + writeln!(out, "}}") } /// Write out the TypeScript type corresponding to some [`ApiBodyType`]. The first line is @@ -464,124 +200,6 @@ fn write_object_property( writeln!(out) } -fn write_indent(out: &mut W, indent: usize) -> fmt::Result { - for _ in 0..indent { - out.write_str(INDENT)?; - } - Ok(()) -} - -/// Split some name like `get_by_id` or `get-by-id` into its words. -fn words(s: &str) -> impl Iterator { - s.split(|c: char| !c.is_alphanumeric()) - .filter(|w| !w.is_empty()) -} - -/// Write a word with its first character uppercased or lowercased. -fn push_word(out: &mut String, word: &str, upper: bool) { - let mut chars = word.chars(); - if let Some(first) = chars.next() { - if upper { - out.extend(first.to_uppercase()); - } else { - out.extend(first.to_lowercase()); - } - out.push_str(chars.as_str()); - } -} - -/// `get_by_id` => `GetById`. -fn pascal_case(s: &str) -> String { - let mut out = String::new(); - for word in words(s) { - push_word(&mut out, word, true); - } - out -} - -/// `get_by_id` => `getById`. -fn camel_case(s: &str) -> String { - let mut out = String::new(); - for (idx, word) in words(s).enumerate() { - push_word(&mut out, word, idx > 0); - } - out -} - -/// Display an object key, quoting it if it isn't a valid identifier. -struct PropertyKey<'a>(&'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. -struct DoubleQuoted<'a>(&'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. -struct SingleQuoted<'a>(&'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(()) - } -} - #[cfg(test)] mod tests { use super::*; @@ -639,7 +257,7 @@ mod tests { fn generate(route_info: &str) -> Result { let mut out = String::new(); - generate_client(route_info, &mut out)?; + generate_types(route_info, &mut out)?; Ok(out) } @@ -667,124 +285,83 @@ mod tests { const EXPECTED: &str = r#"// THIS IS AN AUTO GENERATED FILE. DO NOT EDIT -/* - * POST /gadgets.tune - * - * Tune a gadget. - * - * It's *\/ quite - * a "good" route +/** + * The routes provided by our API */ -export type GadgetsTune = boolean -export type GadgetsTuneParams = { - /** How much to tune by */ - amount?: number +export type Api = { /** - * Some - * multi-line docs. + * POST /gadgets.tune + * + * Tune a gadget. + * + * It's *\/ quite + * a "good" route */ - type: string -} - - -/* - * POST /gadgets.upload - * - * Upload a gadget - */ -export type GadgetsUpload = { - [key: string]: any -} -export type GadgetsUploadParams = Blob - - -/* - * POST /shelf/stack_items - * - * Stack some items on the shelf - */ -export type ShelfStackItems = null -export type ShelfStackItemsParams = { - items: ({ - /** Variant tag */ - kind: "Crate" - width: number - } | { - /** Variant tag */ - kind: "Ball" - /** The ball radius */ - radius: number - })[] -} - - -/* - * GET /widgets.list_all - * - * List all of the widgets - */ -export type WidgetsListAll = ({ - colour: "Red" | "Blue" | null - /** The widget name */ - name: string - size: [number, number] -})[] - -/** - * Instantiate a fully typed API client from the above, given an - * 'api' function that's capable of taking an HTTP method, a route - * string and params (if not GET), and making a request to the backend - * to return the expected response type. - */ -export function createApiClient(api: (method: string, route: string, params?: any, opts?: O) => Promise) { - return { - gadgets: { + 'gadgets.tune': { + method: 'POST' + params: { + /** How much to tune by */ + amount?: number /** - * POST /gadgets.tune - * - * Tune a gadget. - * - * It's *\/ quite - * a "good" route + * Some + * multi-line docs. */ - tune: function(params: GadgetsTuneParams, opts?: O): Promise { - return api('POST', 'gadgets.tune', params, opts) - }, - /** - * POST /gadgets.upload - * - * Upload a gadget - */ - upload: function(params: GadgetsUploadParams, opts?: O): Promise { - return api('POST', 'gadgets.upload', params, opts) - } - }, - shelf: { - /** - * POST /shelf/stack_items - * - * Stack some items on the shelf - */ - stackItems: function(params: ShelfStackItemsParams, opts?: O): Promise { - return api('POST', 'shelf/stack_items', params, opts) - } - }, - widgets: { - /** - * GET /widgets.list_all - * - * List all of the widgets - */ - listAll: function(opts?: O): Promise { - return api('GET', 'widgets.list_all', undefined, opts) - } + 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' + result: ({ + colour: "Red" | "Blue" | null + /** The widget name */ + name: string + size: [number, number] + })[] + } } "#; #[test] - fn generates_expected_client() { + fn generates_expected_types() { let info = serde_json::to_string(&example_api().info()).unwrap(); let ts = generate(&info).unwrap(); @@ -798,86 +375,64 @@ export function createApiClient(api: (method: string, route: string, #[test] fn unusual_names_and_types() { - let route = |name: &str, method: &str| { - json!({ - "name": name, - "method": method, + let info = json!([{ + "name": "it's/a-route", + "method": "PUT", + "description": "", + "request_type": { "description": "", "shape": { "type": "Null" } }, + "response_type": { "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\"" } } - } + "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 info = json!([ - route("flim/flam", "PUT"), - route("it's/2nd-route", "GET"), - route("top", "GET"), - ]); + } + }]); let ts = generate(&info.to_string()).unwrap(); - assert!(ts.contains( - r#"export type FlimFlam = { - empty: {} - lit: "it's \"quoted\"" - maybe?: boolean - "not-an-ident": unknown + assert!(ts.ends_with( + 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 + } + } } -export type FlimFlamParams = null"# - )); - assert!(ts.contains("return api('PUT', 'flim/flam', params, opts)")); - assert!(ts.contains("export type ItS2ndRoute = {")); - assert!(ts.contains( - r#" itS: { - /** - * GET /it's/2nd-route - */ - "2ndRoute": function(opts?: O): Promise { - return api('GET', 'it\'s/2nd-route', undefined, opts) - } - },"# - )); - assert!(ts.contains( - " top: function(opts?: O): Promise {\n return api('GET', 'top', undefined, opts)\n }\n }\n}\n" +"# )); } #[test] fn empty_api() { let ts = generate("[]").unwrap(); - assert!(ts.ends_with(" return {}\n}\n")); + assert!(ts.ends_with("export type Api = {}\n")); } - fn route(name: &str) -> Value { + fn route(name: &str, method: &str) -> Value { json!({ "name": name, - "method": "GET", + "method": method, "description": "", "request_type": { "description": "", "shape": { "type": "Null" } }, "response_type": { "description": "", "shape": { "type": "Null" } } }) } - #[test] - fn writes_nothing_on_error() { - let info = json!([route("foo"), route("foo.bar")]).to_string(); - let mut out = String::new(); - assert!(generate_client(&info, &mut out).is_err()); - assert_eq!(out, ""); - } - #[test] fn errors_on_invalid_json() { let err = generate(r#"[{ "name": "foo" }]"#).unwrap_err(); @@ -885,45 +440,15 @@ export type FlimFlamParams = null"# } #[test] - fn errors_on_unnameable_routes() { - for name in ["", "/", "foo.-", "foo.-.bar"] { - let info = json!([route(name)]).to_string(); - let err = generate(&info).unwrap_err(); - assert!( - matches!(&err, Error::InvalidRouteName(n) if n == name), - "unexpected error for '{name}': {err:?}" - ); - } - } - - #[test] - fn errors_on_clashing_type_names() { - let info = json!([route("foo.bar_baz"), route("foo_bar.baz")]).to_string(); - let err = generate(&info).unwrap_err(); - assert_eq!( - err.to_string(), - "The routes 'foo.bar_baz' and 'foo_bar.baz' would both generate the TypeScript type 'FooBarBaz'" - ); - } - - #[test] - fn errors_on_clashing_client_paths() { - let info = json!([route("foo"), route("foo.bar")]).to_string(); - let err = generate(&info).unwrap_err(); - assert_eq!( - err.to_string(), - "The routes 'foo' and 'foo.bar' would clash at 'foo' in the generated client" - ); - - let info = json!([route("foo.bar"), route("foo.bar_")]).to_string(); - let err = generate(&info).unwrap_err(); - assert!(matches!(err, Error::DuplicateTypeName { .. })); - - let info = json!([route("foo.bar.baz"), route("foo.bar")]).to_string(); - let err = generate(&info).unwrap_err(); - assert_eq!( - err.to_string(), - "The routes 'foo.bar' and 'foo.bar.baz' would clash at 'foo.bar' in the generated client" - ); + 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_types(&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"); } } From 5ac4083dc91c4dbdf5936c0c8b844b7e3e7c7c41 Mon Sep 17 00:00:00 2001 From: James Wilson Date: Fri, 23 Oct 2026 12:10:25 +0100 Subject: [PATCH 7/9] allow --url and --header/-H to be given to seamless-ts to parse api info from some URL --- CHANGELOG.md | 2 +- Cargo.lock | 293 ++++++++++++++++++++++++++++++++++-- Cargo.toml | 1 + seamless-ts-bin/Cargo.toml | 1 + seamless-ts-bin/README.md | 10 +- seamless-ts-bin/src/main.rs | 44 +++++- 6 files changed, 330 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6bfcd00..d4ac029 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,7 @@ # Unreleased - Add a `no_std` `seamless-ts` crate, whose `generate_client()` 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. -- 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`) and writes the generated TypeScript to stdout. +- 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 diff --git a/Cargo.lock b/Cargo.lock index d63d62f..6e65649 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # 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" @@ -38,7 +44,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -49,7 +55,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -122,12 +128,28 @@ 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" @@ -180,6 +202,15 @@ 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" @@ -192,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" @@ -295,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" @@ -424,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" @@ -449,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" @@ -457,7 +523,7 @@ checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "wasi", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -474,9 +540,9 @@ 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" @@ -512,6 +578,55 @@ 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" @@ -578,6 +693,7 @@ version = "0.14.0" dependencies = [ "clap", "seamless_ts", + "ureq", ] [[package]] @@ -654,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" @@ -676,7 +804,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -685,6 +813,12 @@ 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" @@ -759,7 +893,7 @@ dependencies = [ "pin-project-lite", "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -897,6 +1031,47 @@ 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" @@ -915,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" @@ -952,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" @@ -961,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" @@ -973,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 5060e65..53de0ec 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,7 @@ 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" diff --git a/seamless-ts-bin/Cargo.toml b/seamless-ts-bin/Cargo.toml index c0c013a..c506285 100644 --- a/seamless-ts-bin/Cargo.toml +++ b/seamless-ts-bin/Cargo.toml @@ -20,3 +20,4 @@ path = "src/main.rs" [dependencies] seamless_ts.workspace = true clap.workspace = true +ureq.workspace = true diff --git a/seamless-ts-bin/README.md b/seamless-ts-bin/README.md index 1c5e954..0399a71 100644 --- a/seamless-ts-bin/README.md +++ b/seamless-ts-bin/README.md @@ -4,14 +4,20 @@ 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 or from a file given with `--file`, and writes the generated TypeScript to stdout. Any +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: -curl https://example.com/api/meta.info | seamless-ts > api.ts +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 index d8f7b69..93d2774 100644 --- a/seamless-ts-bin/src/main.rs +++ b/seamless-ts-bin/src/main.rs @@ -6,14 +6,37 @@ 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 given by --file, and the -/// generated TypeScript is written to stdout. +/// 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 { @@ -27,16 +50,25 @@ fn main() -> ExitCode { } fn run(args: Args) -> Result<(), String> { - let route_info = match args.file { - None => { + 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 } - Some(path) => std::fs::read_to_string(&path) - .map_err(|e| format!("Could not read '{}': {e}", path.display()))?, }; let mut out = IoWriter::new(BufWriter::new(io::stdout().lock())); From 28ce6c22fff932d508f2a3fc141944aa2cf2824d Mon Sep 17 00:00:00 2001 From: James Wilson Date: Fri, 23 Oct 2026 13:06:19 +0100 Subject: [PATCH 8/9] generate method verb object too to facilitate making a typesafe api --- CHANGELOG.md | 2 +- seamless-ts-bin/src/main.rs | 2 +- seamless-ts/README.md | 15 +++-- seamless-ts/src/lib.rs | 108 ++++++++++++++++++++++++++++-------- 4 files changed, 98 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d4ac029..2b368ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Unreleased -- Add a `no_std` `seamless-ts` crate, whose `generate_client()` 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. +- 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 diff --git a/seamless-ts-bin/src/main.rs b/seamless-ts-bin/src/main.rs index 93d2774..030ab3d 100644 --- a/seamless-ts-bin/src/main.rs +++ b/seamless-ts-bin/src/main.rs @@ -73,7 +73,7 @@ fn run(args: Args) -> Result<(), String> { 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_types(&route_info, &mut out) { + match seamless_ts::generate(&route_info, &mut out) { Ok(()) => {} Err(seamless_ts::Error::Write(_)) => { return Err(write_error(out.take_error())); diff --git a/seamless-ts/README.md b/seamless-ts/README.md index a3f2bb5..e24a54b 100644 --- a/seamless-ts/README.md +++ b/seamless-ts/README.md @@ -2,11 +2,12 @@ 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_client`, which +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 a single `Api` type, -which maps each route name to its HTTP method, request body type (`params`, unless it's a `GET` -route) and response type (`result`), and can be used to build a type safe client for the API: +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 = { @@ -16,12 +17,16 @@ export type Api = { 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_client(&info_json, &mut typescript).unwrap(); +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/lib.rs b/seamless-ts/src/lib.rs index 154f4ff..f9fdbed 100644 --- a/seamless-ts/src/lib.rs +++ b/seamless-ts/src/lib.rs @@ -22,9 +22,10 @@ mod fmt_helpers; /// calling `seamless::Api::info()`), and write TypeScript describing the API to the [`Write`] /// implementation provided (eg a [`String`]). /// -/// The generated TypeScript exports a single `Api` type, which maps each route name to its -/// HTTP method, the type of its request body (`params`, unless it's a `GET` route) and the -/// type of its response (`result`). For example: +/// 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 = { @@ -34,16 +35,43 @@ mod fmt_helpers; /// 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. +/// 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_types(route_info: &str, out: &mut W) -> Result<(), Error> { +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))); @@ -76,10 +104,10 @@ fn write_ts(out: &mut W, routes: &[RouteInfo]) -> fmt::Result writeln!(out, "/**")?; writeln!(out, " * The routes provided by our API")?; writeln!(out, " */")?; - if routes.is_empty() { - return writeln!(out, "export type Api = {{}}"); + write!(out, "export type Api = {{")?; + if !routes.is_empty() { + writeln!(out)?; } - writeln!(out, "export type Api = {{")?; for route in routes { write_route_comment(out, route, 1)?; write_indent(out, 1)?; @@ -87,12 +115,14 @@ fn write_ts(out: &mut W, routes: &[RouteInfo]) -> fmt::Result write_indent(out, 2)?; writeln!(out, "method: {}", SingleQuoted(&route.method))?; // Routes that aren't GET routes are expected to be given a body. - if !route.method.eq_ignore_ascii_case("GET") { - write_indent(out, 2)?; - write!(out, "params: ")?; + 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)?; } + writeln!(out)?; write_indent(out, 2)?; write!(out, "result: ")?; write_type(out, &route.response_type.ty, 2)?; @@ -100,7 +130,27 @@ fn write_ts(out: &mut W, routes: &[RouteInfo]) -> fmt::Result write_indent(out, 1)?; writeln!(out, "}}")?; } - 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 @@ -255,9 +305,9 @@ mod tests { r#type: String, } - fn generate(route_info: &str) -> Result { + fn generate_string(route_info: &str) -> Result { let mut out = String::new(); - generate_types(route_info, &mut out)?; + generate(route_info, &mut out)?; Ok(out) } @@ -350,6 +400,7 @@ export type Api = { */ 'widgets.list_all': { method: 'GET' + params: undefined result: ({ colour: "Red" | "Blue" | null /** The widget name */ @@ -358,12 +409,22 @@ export type Api = { })[] } } + +/** + * 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(&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") { @@ -396,9 +457,9 @@ export type Api = { } } }]); - let ts = generate(&info.to_string()).unwrap(); + let ts = generate_string(&info.to_string()).unwrap(); - assert!(ts.ends_with( + assert!(ts.contains( r#" /** * PUT /it's/a-route */ @@ -415,12 +476,15 @@ export type Api = { } "# )); + assert!( + ts.ends_with("export const methods = {\n 'it\\'s/a-route': 'PUT',\n} as const\n") + ); } #[test] fn empty_api() { - let ts = generate("[]").unwrap(); - assert!(ts.ends_with("export type Api = {}\n")); + 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 { @@ -435,7 +499,7 @@ export type Api = { #[test] fn errors_on_invalid_json() { - let err = generate(r#"[{ "name": "foo" }]"#).unwrap_err(); + let err = generate_string(r#"[{ "name": "foo" }]"#).unwrap_err(); assert!(matches!(err, Error::Deserialize(_))); } @@ -447,7 +511,7 @@ export type Api = { route("foo", "GET") ]); let mut out = String::new(); - let err = generate_types(&info.to_string(), &mut out).unwrap_err(); + 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"); } From cd1e970b7aa748b3fbd8fb71326cd120edf4bb21 Mon Sep 17 00:00:00 2001 From: James Wilson Date: Fri, 23 Oct 2026 13:08:17 +0100 Subject: [PATCH 9/9] Bump to 0.15.0 --- CHANGELOG.md | 2 +- Cargo.lock | 10 +++++----- Cargo.toml | 8 ++++---- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b368ae..65ccf55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,4 @@ -# Unreleased +# 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. diff --git a/Cargo.lock b/Cargo.lock index 6e65649..68eeb91 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -635,7 +635,7 @@ checksum = "7b4b9743ed687d4b4bcedf9ff5eaa7398495ae14e61cba0a295704edbc7decde" [[package]] name = "seamless" -version = "0.14.0" +version = "0.15.0" dependencies = [ "axum", "bytes", @@ -658,7 +658,7 @@ dependencies = [ [[package]] name = "seamless_info" -version = "0.14.0" +version = "0.15.0" dependencies = [ "serde", "serde_json", @@ -666,7 +666,7 @@ dependencies = [ [[package]] name = "seamless_macros" -version = "0.14.0" +version = "0.15.0" dependencies = [ "proc-macro2", "quote", @@ -678,7 +678,7 @@ dependencies = [ [[package]] name = "seamless_ts" -version = "0.14.0" +version = "0.15.0" dependencies = [ "pretty_assertions", "seamless", @@ -689,7 +689,7 @@ dependencies = [ [[package]] name = "seamless_ts_bin" -version = "0.14.0" +version = "0.15.0" dependencies = [ "clap", "seamless_ts", diff --git a/Cargo.toml b/Cargo.toml index 53de0ec..f96425d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ members = [ resolver = "3" [workspace.package] -version = "0.14.0" +version = "0.15.0" authors = ["James Wilson "] edition = "2024" license = "MIT" @@ -20,9 +20,9 @@ keywords = ["api", "http", "rpc", "json"] [workspace.dependencies] # Workspace crates seamless = { path = "seamless" } -seamless_macros = { version = "0.14.0", path = "seamless-macros" } -seamless_info = { version = "0.14.0", path = "seamless-info", default-features = false } -seamless_ts = { version = "0.14.0", path = "seamless-ts" } +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", default-features = false, features = ["derive", "alloc"] }