carbon-1: a union member that is itself a union with several tags joins the outer tag, so SessionLogItem routes log.synced to LogSynced and its tag() delegates to the inner enum. carbon-2: Schema.NonEmptyArray(T) is Vec<T>, so form fields and tool content are typed (FormField, ToolContent). carbon-3: Ref_1 twins that Rust decodes the same as Ref share its type (FormInfo, ShellInfo, FormAnswer, the inbox payloads, message parts). carbon-4: untagged unions get a generated Deserialize that skips a member whose required literal field holds another value, so an LSP server entry with disabled: false keeps its command. carbon-5: generated errors implement TaggedError, and DeclaredError::decode checks the tag. Call sites in crates/store and crates/ui follow the renamed types.
6.5 KiB
F.2: type mapping of the generated API client
script/gen/api.ts calls compile(ClientApi, …) with the options of the Promise client
(packages/client/script/generate.ts:56-61). It projects every schema to its encoded (wire) form, or to
its decoded form for query fields as the Promise client does, normalizes declarations as
codegenAsts does (packages/httpapi-codegen/src/index.ts:1507-1550), and feeds them to
SchemaRepresentation.toRepresentations. The emitter in script/rust/ walks the representations and
writes crates/api/src/generated/{types,methods}.rs.
Types
| Representation | Rust |
|---|---|
| Named reference to an object | pub struct named by identifierPart($ref) (Session.Info becomes SessionInfo) |
| Named reference to a string (branded IDs, paths) | newtype pub struct SessionID(pub String), #[serde(transparent)] |
| Named reference to anything else | pub type alias, or the enum below |
| Anonymous object | struct named <Parent><Field> (for union members <Parent><Tag>), deduplicated by name and shape |
| Object with index signatures only | BTreeMap<String, T> |
| Object with fields and an index signature | struct with #[serde(flatten)] extra: BTreeMap<String, T> |
String, template literal, single string literal |
String |
Number with an isInt check |
i64, else f64 |
Boolean |
bool |
Unknown, Any, Schema.Json, other declarations |
serde_json::Value |
Uint8Array (binary bodies and responses) |
bytes::Bytes |
Array with rest only, or Schema.NonEmptyArray(T) ([T, ...T[]]) |
Vec<T>; a tuple becomes a Rust tuple |
Ref_1 that differs from Ref only in what Rust cannot see |
the type of Ref (see below) |
Fields of type Never |
dropped (they can only be absent) |
Fields:
- An optional field becomes
Option<T>withdefaultandskip_serializing_if = "Option::is_none". - A nullable field (
T | null) becomesOption<T>. Optional and nullable together becomesOption<Option<T>>withde::double_option, so absent (None) andnull(Some(None)) stay distinct. - Unknown fields are ignored (no
deny_unknown_fields), so a newer server's additions decode.
Twins: a schema reached both through REST (after the JSON transport) and through the event stream comes
out as Ref and Ref_1. Types.sameRust compares them as Rust would decode them: it ignores
annotations and checks other than isInt, treats Unknown, Any, and declarations alike, treats
null and undefined members alike, and drops the JSON transport's "Infinity", "-Infinity", and
"NaN" literals beside a number. Equal twins share the type of Ref, as httpapi-codegen collapses
them. Twins that really differ (Session.Inbox.MovePayload has LocationRef on one side and
LocationPublicRef on the other) keep two types.
Unions
Nested unions are flattened, and null and undefined members become Option. The rest falls in one
of four kinds:
-
String literals only. An enum with one unit variant per literal and
Unknown(String). ItsDeserializeandSerializeare written out by the emitter, so an unknown literal decodes. -
String literals and
String(string suggestions).String. -
Objects that share a discriminator field whose value in every member is a literal, a union of literals, or a template literal with a literal prefix. Candidate keys in order:
type,_tag, and then the first shared field that separates the members. The enum has one newtype variant per member andUnknown(serde_json::Value). ItsDeserializeis generated by hand: it buffers aValue, reads the tag, matches exact literals first and then template prefixes (rpc.becomes theRpcvariant, which keeps the full name in itstypefield), and decodes the member withserde_json::from_value. A known tag that fails to decode is an error, notUnknown, so emitter mistakes show; an unknown tag or a missing tag isUnknown.Serializewrites the member as it is. Member structs keep the tag field as aString, so a variant shared by several tags still knows its tag.A member may itself be a union of objects. With one shared tag (
Session.Message.Compaction, tagged inside bystatus),tag()returns that tag. With several (Session.Event.DurableinsideSessionLogItem), every tag routes to the member, the inner enum must be tagged by the same key (the emitter fails otherwise), andtag()delegates to it.#[serde(tag = "...")]is not used: serde rejects a payload on#[serde(other)], and it cannot route a prefix (plan.review-carbon.md, carbon-3). -
Anything else (
String | Object,Boolean | Object, objects told apart by required fields). An enum with variants in schema order and a lastUnknown(serde_json::Value), serialized untagged. Its generatedDeserializetries the members in order. It skips an object member when one of its required literal fields holds another value: the Rust field is a plainboolorString, so without the checkConfig.LSP.Entrywould read{ command, disabled: false }as{ disabled: true }.
Declared errors: every generated *Error struct implements error::TaggedError with its _tag (or
name). DeclaredError::decode::<T>() rejects a body with another tag, as the TypeScript is<Error>
guards do, and DeclaredError::is::<T>() checks only the tag.
Methods
- One
async fnper endpoint onClient, named by the client path in snake case (session.message.getbecomessession_message_get,experimental.session.logbecomesexperimental_session_log). - Inputs are flattened as in the Promise client: one
<Prefix>Inputstruct with every params, query, headers, and payload field. An opaque payload is onepayloadfield. A trailing*path adds apathfield encoded per segment. An input whose fields are all optional derivesDefault. - Every method takes
&RequestOptions(per-call headers). { data }envelopes are unwrapped. A no-content endpoint returns(). A binary endpoint returnsBytes; a binary payload is sent asapplication/octet-stream.- An SSE endpoint returns
SseResponse<T>: the checked response body and the event type. F.3 parses it into a stream ofT. - Query values serialize to JSON values and are bracket-encoded like
appendQuery(packages/client/src/promise/generated/client.ts:2795-2810). - A response with a declared status decodes into
Error::Declaredwith the status,_tag, message, and the body as aValue; any other status isError::UnexpectedStatus. Other failures map to the remainingClientErrorreasons.