Skip to main content

olai_codegen/codegen/
config.rs

1//! Configuration types for code generation.
2//!
3//! Split out of [`super`] so the parent module focuses on generation orchestration.
4//! Re-exported from [`super`] (and `crate`) so the public API path is unchanged.
5
6use std::path::PathBuf;
7
8use crate::error::{Error, Result};
9
10/// Wire protocol a *generated* client speaks.
11///
12/// A single client layer. The set of layers to emit is [`ClientProtocols`]; a server that exposes
13/// both REST and ConnectRPC for the same proto can emit both from one generation run.
14///
15/// - [`ClientProtocol::Rest`]: the HTTP/JSON low-level client ([`super::client`]) plus fluent
16///   builders. Methods are routed from `google.api.http`; a method without an annotation has no
17///   route and is skipped by the REST emitter.
18/// - [`ClientProtocol::Connect`]: fluent builders over the **connect-rust** (BSR plugin) generated
19///   `{Service}Client<T>`, dispatched via [`connectrpc`](https://docs.rs/connectrpc). No
20///   `google.api.http` annotation is required — the whole request message is the body, and
21///   required-vs-optional partitioning comes purely from `google.api.field_behavior`.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23pub enum ClientProtocol {
24    /// HTTP/JSON client routed from `google.api.http` (the historical default).
25    #[default]
26    Rest,
27    /// ConnectRPC client layered over the connect-rust generated service client.
28    Connect,
29}
30
31impl ClientProtocol {
32    /// The convention subdirectory name for this protocol's client when both are emitted side by
33    /// side (`<service>/rest/`, `<service>/connect/`).
34    pub(crate) fn subdir(self) -> &'static str {
35        match self {
36            ClientProtocol::Rest => "rest",
37            ClientProtocol::Connect => "connect",
38        }
39    }
40}
41
42/// Which client protocol layer(s) to emit.
43///
44/// Analysis is protocol-agnostic (REST analysis is a superset of what ConnectRPC needs), so this is
45/// purely an *emit-time* selection. Emitting both is supported: a server fronting the same proto
46/// over REST and ConnectRPC can hand out either client.
47///
48/// File layout:
49/// - exactly one protocol: emitted **flat** under `<service>/` (`<service>/client.rs`,
50///   `<service>/builders.rs`) — unchanged from single-protocol output.
51/// - both: each protocol gets its own convention subdir (`<service>/rest/`, `<service>/connect/`),
52///   re-exported from `<service>/mod.rs`.
53///
54/// Defaults to REST only, so existing output is unchanged.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct ClientProtocols {
57    /// Emit the REST (HTTP/JSON) client.
58    pub rest: bool,
59    /// Emit the ConnectRPC client.
60    pub connect: bool,
61}
62
63impl Default for ClientProtocols {
64    fn default() -> Self {
65        Self {
66            rest: true,
67            connect: false,
68        }
69    }
70}
71
72impl ClientProtocols {
73    /// Whether more than one protocol is selected (drives the subdir-vs-flat layout decision).
74    pub(crate) fn is_multi(self) -> bool {
75        self.rest && self.connect
76    }
77
78    /// The selected protocols, in deterministic order (REST before Connect).
79    pub(crate) fn selected(self) -> Vec<ClientProtocol> {
80        let mut v = Vec::new();
81        if self.rest {
82            v.push(ClientProtocol::Rest);
83        }
84        if self.connect {
85            v.push(ClientProtocol::Connect);
86        }
87        v
88    }
89}
90
91/// Protobuf runtime that the *generated* code is expected to consume.
92///
93/// This selects the ABI that emitted clients, handlers, and builders are shaped for —
94/// i.e. how generated code reads and writes the consuming project's model types. It does
95/// **not** affect how `olai-codegen` itself parses descriptors.
96///
97/// - [`Runtime::Prost`] (default): models are [prost](https://docs.rs/prost)-generated —
98///   open enums are bare `i32`, singular message fields are `Option<Box<T>>`.
99/// - [`Runtime::Buffa`]: models are [buffa](https://github.com/anthropics/buffa)-generated —
100///   open enums are `EnumValue<E>`, singular message fields are `MessageField<T>`, and the
101///   runtime provides native serde JSON (no separate `pbjson` layer).
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
103pub enum Runtime {
104    /// prost-generated models (the historical default).
105    #[default]
106    Prost,
107    /// buffa-generated models.
108    Buffa,
109}
110
111/// Validated model import path derived from a `{service}` template string.
112///
113/// Constructed once from [`CodeGenConfig`] template fields. `resolve` performs the
114/// `{service}` substitution and parses the result as a [`syn::Path`], catching
115/// malformed templates at construction time rather than at code-generation time.
116#[derive(Debug, Clone)]
117pub struct ModelsPath {
118    template: String,
119}
120
121impl ModelsPath {
122    /// Build a `ModelsPath` from a template string containing `{service}` and,
123    /// optionally, `{version}`.
124    ///
125    /// Performs a test substitution at construction to validate the template.
126    pub fn new(template: &str) -> Result<Self> {
127        let test = template
128            .replace("{service}", "test")
129            .replace("{version}", "v1");
130        syn::parse_str::<syn::Path>(&test).map_err(|e| Error::InvalidModelsPathTemplate {
131            template: template.to_string(),
132            source: e,
133        })?;
134        Ok(Self::from_template(template))
135    }
136
137    /// Wrap a template without the construction-time validation done by [`ModelsPath::new`].
138    ///
139    /// For callers that already validated the template (e.g. `generate_code` validates both
140    /// templates up front, so per-service handlers needn't re-parse on every `models_path()`
141    /// call). `resolve`/`try_resolve` still parse the final substituted path.
142    pub(crate) fn from_template(template: &str) -> Self {
143        Self {
144            template: template.to_string(),
145        }
146    }
147
148    /// Replace `{service}` with `service` and return the parsed [`syn::Path`], erroring if the
149    /// substitution does not parse.
150    ///
151    /// `new` only proves the template parses for the literal `test`; a real service segment that
152    /// isn't a valid path component (leading digit, hyphen, reserved word) can still fail here.
153    /// Call this once per service up front (see [`ModelsPath::validate_for`]) so failures surface
154    /// as a clean [`Error::InvalidModelsPathTemplate`] before generation rather than panicking.
155    pub fn try_resolve(&self, service: &str, version: &str) -> Result<syn::Path> {
156        let path = self.substitute(service, version);
157        syn::parse_str(&path).map_err(|source| Error::InvalidModelsPathTemplate {
158            template: path,
159            source,
160        })
161    }
162
163    /// The template prefix before `{service}`, without the trailing `::` (`crate::models` for
164    /// `crate::models::{service}::v1`). `None` when there is none.
165    pub(crate) fn root(&self) -> Option<&str> {
166        let (prefix, _) = self.template.split_once("{service}")?;
167        let root = prefix.trim_end_matches(':');
168        (!root.is_empty()).then_some(root)
169    }
170
171    /// Validate that `service` substitutes into a parseable path. Used up front, per service.
172    ///
173    /// Validates against the conventional `v1` version; the actual version segment is a plain
174    /// path component derived from the proto package, so it cannot make a `{service}`-valid
175    /// template fail to parse.
176    pub fn validate_for(&self, service: &str) -> Result<()> {
177        self.try_resolve(service, "v1").map(|_| ())
178    }
179
180    /// Replace `{service}`/`{version}` and return the parsed [`syn::Path`].
181    ///
182    /// # Panics
183    ///
184    /// Panics if the substituted path doesn't parse. Generation validates every service segment
185    /// up front via [`ModelsPath::validate_for`], so this is unreachable on the generation path;
186    /// prefer [`ModelsPath::try_resolve`] anywhere that hasn't already validated.
187    pub fn resolve(&self, service: &str, version: &str) -> syn::Path {
188        let path = self.substitute(service, version);
189        syn::parse_str(&path)
190            .unwrap_or_else(|e| panic!("Invalid models path `{path}` after substitution: {e}"))
191    }
192
193    /// Substitute the `{service}` and `{version}` placeholders. A template without `{version}`
194    /// is left as-is for that placeholder, preserving any literal version it already encodes.
195    fn substitute(&self, service: &str, version: &str) -> String {
196        self.template
197            .replace("{service}", service)
198            .replace("{version}", version)
199    }
200}
201
202/// Configuration for language-binding code generation (Python / Node.js).
203#[derive(Debug, Clone)]
204pub struct BindingsConfig {
205    /// Name of the aggregate client struct (e.g. `"MyServiceClient"`).
206    pub aggregate_client_name: String,
207    /// Rust crate name used in `use` statements for the client crate
208    /// (e.g. `"my_service_client"`).
209    ///
210    /// This must be set explicitly because the crate name may not match the
211    /// snake_case form of `aggregate_client_name` (e.g. `"MyServiceClient"`
212    /// snake_cases to `"my_service_client"`).
213    pub client_crate_name: String,
214    /// Fully-qualified Python error type (e.g. `"PyMyServiceError"`).
215    pub py_error_type: String,
216    /// Fully-qualified Python result alias (e.g. `"PyMyServiceResult"`).
217    pub py_result_type: String,
218    /// Name of the NAPI error extension trait (e.g. `"NapiErrorExt"`).
219    pub napi_error_ext_trait: String,
220    /// Base class name for TypeScript errors (e.g. `"MyServiceError"`).
221    pub ts_error_base_class: String,
222    /// Prefix used in native NAPI error messages (e.g. `"UC"`).
223    pub ts_error_code_prefix: String,
224    /// The Python API. Required with the `python` output; see [`PythonOptions`].
225    pub python: Option<PythonOptions>,
226}
227
228/// Shape of the generated Python (PyO3) API.
229///
230/// The model classes are frozen, `eq`, with a Python-style `repr`, and only the models that a
231/// request takes get a keyword constructor. Enums are `enum.StrEnum` classes (Python 3.11+) in
232/// `<package>/_enums.py`, without the zero `*_UNSPECIFIED` member. The extension module is a
233/// declarative `#[pymodule]` with the proto comments as docs, so PyO3's introspection
234/// (`experimental-inspect`) writes the `.pyi`. The methods block on the Tokio runtime of the
235/// generated `codegen/runtime.rs` (needs `tokio`), which the module also installs for the
236/// `_async` methods. Client errors raise the PyO3 exception classes of the generated
237/// `codegen/error.rs`, which read them through its `ApiErrorAnswer` trait: implemented there for
238/// the error of [`RestClientOptions::error_module`], else by the binding crate.
239#[derive(Debug, Clone)]
240pub struct PythonOptions {
241    /// The pure-Python package that gets `_enums.py` and the public modules.
242    pub package: PyPackageConfig,
243    /// Name of the base exception class (e.g. `MyServiceError`): the class with `message`,
244    /// `code`, `status` and `details` that the subclasses per kind of HTTP error status extend.
245    pub error_base_class: String,
246    /// The extension module (e.g. `my_pkg._core`): the generated `#[pymodule]`. Classes of a
247    /// package `a.<service>.v1` go in the submodule `<module>.<service>`, the root client and
248    /// the exceptions in `<module>`.
249    pub module: String,
250    /// Every client method also gets a `<name>_async` twin returning an `asyncio.Future`. Needs
251    /// `pyo3-async-runtimes` with `tokio-runtime`.
252    pub async_methods: bool,
253    /// Optional parameters are keyword-only; constructors take `REQUIRED` fields positionally.
254    pub keyword_only: bool,
255    /// Write `<package>/<service>.py` per submodule of [`module`](Self::module), re-exporting
256    /// its classes and enums.
257    pub public_modules: bool,
258    /// The `User-Agent` product of the Python client (`<product>/<binding crate version>`).
259    /// Needs the `reqwest` transport.
260    pub user_agent: Option<String>,
261    /// Hand-written classes and functions of the binding crate (Rust paths, e.g.
262    /// `crate::extras::PyHelper`) that the extension module also exports.
263    pub exports: Vec<String>,
264}
265
266/// Where the generated pure-Python files go.
267#[derive(Debug, Clone)]
268pub struct PyPackageConfig {
269    /// Directory of the Python package (e.g. `python/my_pkg`).
270    pub dir: PathBuf,
271    /// Import name of the package (e.g. `my_pkg`).
272    pub name: String,
273}
274
275/// Configuration for code generation, including import paths and output directories.
276///
277/// Construct this struct directly and set the fields you need.
278#[derive(Debug, Clone)]
279pub struct CodeGenConfig {
280    /// Fully-qualified path to the request context type used in handler methods.
281    ///
282    /// Default: `"crate::api::RequestContext"`
283    pub context_type_path: String,
284
285    /// Fully-qualified path to the `Result` alias used in generated handler and client code.
286    /// The clients use the `Result` of the generated error module instead when
287    /// [`RestClientOptions::error_module`] is set.
288    ///
289    /// Default: `"crate::Result"`
290    pub result_type_path: String,
291
292    /// Template for the external model import path. `{service}` is replaced with the service's
293    /// base path (e.g. `"catalogs"`).
294    ///
295    /// Example: `"my_common::models::{service}::v1"`
296    pub models_path_template: String,
297
298    /// Template for crate-local model import path. `{service}` is replaced with the service's
299    /// base path.
300    ///
301    /// Default: `"crate::models::{service}::v1"`
302    pub models_path_crate_template: String,
303
304    /// Output directory configuration.
305    pub output: CodeGenOutput,
306
307    /// When `true`, generate `labels.rs` with `Resource` / `ObjectLabel` enums derived
308    /// from `google.api.resource` annotations. Requires `output.models` to be `Some`.
309    ///
310    /// Store-specific output (`Label` impl, `RESOURCE_DESCRIPTORS`) is only emitted when
311    /// `generate_store_integration` is also `true`.
312    pub generate_resource_enum: bool,
313
314    /// When `true` (and `generate_resource_enum` is set), emit the `olai_store` integration
315    /// code in `labels.rs`:
316    /// - `impl olai_store::Label for ObjectLabel`
317    /// - `pub static RESOURCE_DESCRIPTORS: &[olai_store::ResourceTypeDescriptor<ObjectLabel>]`
318    ///
319    /// Set to `false` for crates that use the enums without a store dependency.
320    pub generate_store_integration: bool,
321
322    /// Fully-qualified path to the `Error` type used in generated `TryFrom<Resource>` impls.
323    ///
324    /// E.g. `"crate::Error"`. When `None`, `TryFrom` impls are not generated.
325    pub error_type_path: Option<String>,
326
327    /// When `true` and `generate_resource_enum` is set, emit `TryFrom<Object>`/`TryFrom<T>`
328    /// and `ResourceExt` impl blocks in `labels.rs` for all resource types that have an
329    /// `IDENTIFIER`-annotated field, plus a `qualified_name()` inherent method on each
330    /// resource type.
331    pub generate_object_conversions: bool,
332
333    /// Configuration for language-binding generation. Required when `output.python`,
334    /// `output.node`, or `output.node_ts` is `Some`.
335    pub bindings: Option<BindingsConfig>,
336
337    /// Crate name for the resource store types used in generated `RESOURCE_DESCRIPTORS`.
338    ///
339    /// Default: `"olai_store"`
340    pub resource_store_crate_name: String,
341
342    /// Protobuf runtime the generated code is shaped for. See [`Runtime`].
343    ///
344    /// Defaults to [`Runtime::Prost`] for backward compatibility.
345    pub runtime: Runtime,
346
347    /// Fully-qualified path to the HTTP transport type that generated clients store and call.
348    ///
349    /// The transport must expose the surface generated client bodies use: per-verb builder
350    /// methods (`get`/`post`/`patch`/`delete`/`put`) returning a request builder with
351    /// `.json(..)`/`.query(..)`/`.send()`, whose response has `.status()`/`.bytes()`.
352    /// [`olai_http::CloudClient`](https://docs.rs/olai-http) satisfies this.
353    ///
354    /// Defaults to `"olai_http::CloudClient"`, so native output is unchanged. A WASM/browser
355    /// client points this at a lightweight reqwest-Fetch transport that has no `ring`/`tokio`
356    /// dependency and lets the browser attach the session.
357    pub transport_type_path: String,
358
359    /// Force dual-transport client emission (the `cfg`-gated `CloudClient`/`WasmClient`
360    /// `Transport` alias) even when no WASM `#[wasm_bindgen]` bindings output is
361    /// configured. See [`dual_transport`](Self::dual_transport).
362    ///
363    /// Defaults to `false`. Setting `output.wasm` also turns dual-transport on;
364    /// this flag exists so a project can build the same client crate for native
365    /// and `wasm32` *without* pulling in the JS binding layer.
366    pub dual_transport: bool,
367
368    /// Which client protocol layer(s) to emit. See [`ClientProtocols`].
369    ///
370    /// Defaults to REST only, so existing HTTP/JSON output is unchanged.
371    pub client_protocols: ClientProtocols,
372
373    /// Import path of the **connect-rust** (BSR plugin) generated client module, used only when
374    /// [`client_protocols`](Self::client_protocols) includes Connect.
375    ///
376    /// The generated Connect builder layer references the connect-rust client type as
377    /// `<connect_client_path>::{Service}Client`. The path should resolve to the module that
378    /// holds the per-service `{Service}Client<T>` structs (e.g.
379    /// `"headwaters_proto::connect_gen::headwaters::read::v1"`).
380    ///
381    /// Required (non-`None`) whenever Connect is selected and client output is enabled; ignored for
382    /// REST-only output.
383    pub connect_client_path: Option<String>,
384
385    /// Wire-format and error options of the REST client. See [`RestClientOptions`].
386    pub rest_client: RestClientOptions,
387}
388
389/// Wire-format and error options of the generated REST client. Every option is off by default.
390#[derive(Debug, Clone, Default)]
391pub struct RestClientOptions {
392    /// Write 64-bit integers as JSON numbers instead of proto3-JSON strings, and whole numbers
393    /// of `google.protobuf.Value`/`Struct`/`ListValue` as integers (`1`, not `1.0`). Emits a
394    /// `json_int64` module into the models `mod.rs` that the `trestle` CLI points buffa's helpers
395    /// at (see [`CodeGenConfig::json_int64_module_path`]). Reading accepts both forms. Buffa only.
396    pub json_int64_as_number: bool,
397
398    /// Parse responses with buffa's `ignore_unknown_enum_values`: an unknown enum name becomes
399    /// the zero value instead of failing the response. Buffa only.
400    pub ignore_unknown_enum_values: bool,
401
402    /// Generate the client error module (`error.rs`); the clients then return its `Result`
403    /// instead of [`CodeGenConfig::result_type_path`]. When `None`, the crate supplies
404    /// `crate::error::parse_error_response`.
405    pub error_module: Option<ErrorModuleConfig>,
406
407    /// RPCs (`package.Service.Method`) whose request body is sent form-encoded.
408    pub form_encoded_methods: Vec<String>,
409
410    /// RPCs (`package.Service.Method`) whose request body keeps the path fields, for APIs that
411    /// want them in both places.
412    pub path_fields_in_body_methods: Vec<String>,
413
414    /// Proto packages whose query keys are the JSON (lowerCamelCase) names. Elsewhere a query
415    /// key is the proto name, or the field's explicit `json_name`.
416    pub json_query_packages: Vec<String>,
417
418    /// The `User-Agent` product of the generated `reqwest` transport
419    /// (`<product>/<client crate version>`); not sent in the browser. Needs that transport.
420    pub user_agent: Option<String>,
421
422    /// Gate each service behind a cargo feature named after its model package
423    /// (`my.catalogs.v1` → `catalogs`): the service modules, the aggregate client's accessors
424    /// and imports, and the child navigators of resource clients (on the child's feature). The
425    /// client crate declares the features.
426    pub resource_features: bool,
427
428    /// Implement the server handler traits for the per-service clients. See
429    /// [`ClientHandlerImpls`].
430    pub handler_impls: Option<ClientHandlerImpls>,
431}
432
433/// `impl <Handler> for <ServiceClient>` per service, forwarding each trait method to the client
434/// method of the same name, so a client serves its service from an upstream server. The impls
435/// go in `<service>/handler.rs`, gated on [`feature`](Self::feature) and left out on `wasm32`
436/// (the client futures are not `Send` there). The client error must convert into the handler
437/// error (`impl From<client::Error> for handlers::Error`). The request context is ignored.
438#[derive(Debug, Clone, PartialEq, Eq)]
439pub struct ClientHandlerImpls {
440    /// The crate with the handler traits (e.g. `my_handlers`). A service's trait is
441    /// `<crate_path>::<service base path>::<Handler>`, the result type `<crate_path>::Result`.
442    pub crate_path: String,
443    /// The client crate feature that enables the impls.
444    pub feature: String,
445    /// Services (by base path, e.g. `temporary_credentials`) whose impl the crate writes by hand.
446    pub skip: Vec<String>,
447}
448
449/// Shape of the JSON error body that the generated error module reads, such as
450/// `{"error_code": "NOT_FOUND", "message": "…", "details": […]}`. A body that is not such an
451/// object becomes the message.
452#[derive(Debug, Clone)]
453pub struct ErrorModuleConfig {
454    /// Key of the error code; its lowerCamelCase form is also read. Default `error_code`.
455    pub code_field: String,
456    /// Key of the message. Default `message`.
457    pub message_field: String,
458    /// Key of the details array. Default `details`.
459    pub details_field: Option<String>,
460    /// Fully-qualified proto enum (e.g. `.my.errors.v1.ErrorCode`) of the error codes. The
461    /// error exposes the code as that enum; an unknown code stays a string.
462    pub code_enum: Option<String>,
463    /// More keys of the code, tried in order (e.g. OAuth's `error`).
464    pub more_code_fields: Vec<String>,
465    /// More keys of the message, tried in order (e.g. OAuth's `error_description`).
466    pub more_message_fields: Vec<String>,
467    /// Keys under which some answers nest the error object (`{"error": {"message": …}}`).
468    pub envelope_fields: Vec<String>,
469}
470
471impl Default for ErrorModuleConfig {
472    fn default() -> Self {
473        Self {
474            code_field: "error_code".into(),
475            message_field: "message".into(),
476            details_field: Some("details".into()),
477            code_enum: None,
478            more_code_fields: Vec::new(),
479            more_message_fields: Vec::new(),
480            envelope_fields: Vec::new(),
481        }
482    }
483}
484
485/// Default transport type path: the cloud client used by native (non-WASM) generated code.
486pub const DEFAULT_TRANSPORT_TYPE_PATH: &str = "olai_http::CloudClient";
487
488impl CodeGenConfig {
489    /// Whether generated clients use the default cloud transport (`olai_http::CloudClient`).
490    ///
491    /// Controls emission of cloud-specific aggregate constructors (`new_unauthenticated`,
492    /// `new_with_token`), which only make sense for `CloudClient`. A custom transport (e.g. the
493    /// WASM/browser one) gets only the generic `new(transport, base_url)`.
494    pub fn uses_default_transport(&self) -> bool {
495        self.transport_type_path == DEFAULT_TRANSPORT_TYPE_PATH
496    }
497
498    /// Whether generated clients use the generated `reqwest` transport
499    /// ([`REQWEST_TRANSPORT_TYPE_PATH`](super::REQWEST_TRANSPORT_TYPE_PATH)).
500    pub fn uses_reqwest_transport(&self) -> bool {
501        !self.dual_transport() && self.transport_type_path == super::REQWEST_TRANSPORT_TYPE_PATH
502    }
503
504    /// Whether the generated client also builds for `wasm32`, where the transport's futures are
505    /// not `Send`, so the builders box them as `Local*` there.
506    pub fn builds_for_wasm(&self) -> bool {
507        self.dual_transport() || self.uses_reqwest_transport()
508    }
509
510    /// Whether the generated client should carry **both** transports, selected at
511    /// compile time by `cfg(target_arch = "wasm32")` — `CloudClient` for native
512    /// targets, `olai_http_wasm::WasmClient` for the browser.
513    ///
514    /// Enabled when WASM bindings output is requested (`output.wasm`), or when
515    /// [`dual_transport`](Self::dual_transport) is set explicitly: a project that
516    /// wants a browser client needs the same client crate to build both ways
517    /// (native for server-side/tests, wasm32 for the frontend). Native-only
518    /// projects leave both unset and keep the single
519    /// [`transport_type_path`](Self::transport_type_path) transport with no WASM
520    /// dependency.
521    ///
522    /// The explicit flag decouples the transport alias from the JS binding layer:
523    /// `output.wasm` additionally emits `#[wasm_bindgen]` bindings, whereas
524    /// `dual_transport = true` alone emits only the `cfg`-gated `Transport` alias.
525    pub fn dual_transport(&self) -> bool {
526        self.output.wasm.is_some() || self.dual_transport
527    }
528
529    /// The crate-local path of the `json_int64` module (e.g. `crate::models::json_int64`), for
530    /// [`ModelRewrites::int64_module`](crate::postprocess::ModelRewrites::int64_module). `None`
531    /// unless [`RestClientOptions::json_int64_as_number`] is set.
532    pub fn json_int64_module_path(&self) -> Option<String> {
533        if !self.rest_client.json_int64_as_number {
534            return None;
535        }
536        let models_path = ModelsPath::from_template(&self.models_path_crate_template);
537        Some(format!("{}::json_int64", models_path.root()?))
538    }
539
540    /// The crate-local path of the `json_value` module (e.g. `crate::models::json_value`), for
541    /// [`ModelRewrites::json_value_module`](crate::postprocess::ModelRewrites::json_value_module).
542    /// `None` unless [`RestClientOptions::json_int64_as_number`] is set.
543    pub fn json_value_module_path(&self) -> Option<String> {
544        if !self.rest_client.json_int64_as_number {
545            return None;
546        }
547        let models_path = ModelsPath::from_template(&self.models_path_crate_template);
548        Some(format!("{}::json_value", models_path.root()?))
549    }
550
551    /// The `Result` type of the generated clients: the generated error module's with
552    /// [`RestClientOptions::error_module`], else [`result_type_path`](Self::result_type_path).
553    pub(crate) fn client_result_path(&self) -> syn::Path {
554        let path = match self.rest_client.error_module {
555            Some(_) => format!("{}::Result", super::error_module::CLIENT_ERROR_MODULE),
556            None => self.result_type_path.clone(),
557        };
558        syn::parse_str(&path).expect("valid result_type_path")
559    }
560
561    /// The module of `parse_error_response`: the generated error module with
562    /// [`RestClientOptions::error_module`], else `crate::error`.
563    pub(crate) fn client_error_module(&self) -> syn::Path {
564        let path = match self.rest_client.error_module {
565            Some(_) => super::error_module::CLIENT_ERROR_MODULE,
566            None => "crate::error",
567        };
568        syn::parse_str(path).expect("valid module path")
569    }
570
571    /// The Python options of the bindings config. Only for the `python` output, which
572    /// [`validate_options`](Self::validate_options) checks has them.
573    pub(crate) fn python_options(&self) -> &PythonOptions {
574        self.bindings
575            .as_ref()
576            .and_then(|b| b.python.as_ref())
577            .expect("validated: the python output has `BindingsConfig::python`")
578    }
579
580    /// Check the options that need other options.
581    pub(crate) fn validate_options(&self) -> Result<()> {
582        let needs = |what: &str, requirement: &str| {
583            Err(Error::Build(format!("`{what}` needs {requirement}")))
584        };
585        if self.output.server.is_some() && self.output.common.is_none() {
586            return needs(
587                "CodeGenOutput::server",
588                "`CodeGenOutput::common` (the Axum extractors)",
589            );
590        }
591        if self.rest_client.user_agent.is_some() && !self.uses_reqwest_transport() {
592            return needs(
593                "RestClientOptions::user_agent",
594                "the generated `reqwest` transport",
595            );
596        }
597        if self.output.python.is_some() {
598            let Some(python) = self.bindings.as_ref().and_then(|b| b.python.as_ref()) else {
599                return needs("CodeGenOutput::python", "`BindingsConfig::python`");
600            };
601            for path in &python.exports {
602                syn::parse_str::<syn::Path>(path).map_err(|source| Error::InvalidRustPath {
603                    path: path.clone(),
604                    message: "PythonOptions::exports".to_string(),
605                    source,
606                })?;
607            }
608            if python.user_agent.is_some() && !self.uses_reqwest_transport() {
609                return needs(
610                    "PythonOptions::user_agent",
611                    "the generated `reqwest` transport",
612                );
613            }
614        }
615        if self.rest_client.json_int64_as_number
616            && ModelsPath::from_template(&self.models_path_crate_template)
617                .root()
618                .is_none()
619        {
620            return needs(
621                "RestClientOptions::json_int64_as_number",
622                "a `models_path_crate_template` of the form `<models root>::{service}::...`",
623            );
624        }
625        Ok(())
626    }
627
628    /// Validate this config without running code generation.
629    ///
630    /// Checks that:
631    /// - `models_path_template` and `models_path_crate_template` produce valid Rust paths after
632    ///   `{service}` substitution.
633    /// - `bindings` is `Some` whenever `output.python`, `output.node`, `output.node_ts`, or
634    ///   `output.wasm` is `Some`; `output.python` also needs `BindingsConfig::python`.
635    /// - the REST client and Python options that need other options have them.
636    ///
637    /// Call this at construction time to surface misconfiguration early, before generation runs.
638    pub fn validate(&self) -> Result<()> {
639        ModelsPath::new(&self.models_path_template)?;
640        ModelsPath::new(&self.models_path_crate_template)?;
641        let wants_bindings = self.output.python.is_some()
642            || self.output.node.is_some()
643            || self.output.node_ts.is_some()
644            || self.output.wasm.is_some();
645        if wants_bindings && self.bindings.is_none() {
646            return Err(Error::MissingBindingsConfig);
647        }
648        // The Connect client layers over the connect-rust generated client, whose import path the
649        // emitter needs. Only required when client output is actually requested.
650        if self.client_protocols.connect
651            && self.output.client.is_some()
652            && self.connect_client_path.is_none()
653        {
654            return Err(Error::MissingConnectClientPath);
655        }
656        // Language bindings call into the REST aggregate client, so they need REST enabled.
657        if wants_bindings && !self.client_protocols.rest {
658            return Err(Error::BindingsRequireRest);
659        }
660        self.validate_options()
661    }
662}
663
664/// Output directory configuration for code generation.
665///
666/// All outputs are optional — set to `None` to skip that output entirely. For example, a
667/// server-only crate can omit `client`, and a client-only crate can omit `server` and
668/// `common`.
669#[derive(Debug, Clone)]
670pub struct CodeGenOutput {
671    /// Output directory for the Axum request extractors. Generation is skipped when `None`; the
672    /// `server` output needs it.
673    pub common: Option<PathBuf>,
674    /// Parent models directory (e.g. `crates/common/src/models`).
675    ///
676    /// When `Some`, the generator writes `labels.rs`, `pyo3_impls.rs`, and `mod.rs`
677    /// into a subdirectory named [`models_subdir`](CodeGenOutput::models_subdir)
678    /// inside this path. The buf proto plugin co-locates the compiled model files
679    /// (`<pkg>.rs` / `.serde.rs` / `.tonic.rs`) in that same subdirectory, so the
680    /// `mod.rs` includes them with `include!("./<pkg>.rs")`.
681    pub models: Option<PathBuf>,
682    /// Name of the generated subdirectory inside [`models`](CodeGenOutput::models).
683    ///
684    /// Defaults to `"_gen"`.
685    pub models_subdir: String,
686    /// Output directory for server-side handler and route code. Generation is skipped when `None`.
687    pub server: Option<PathBuf>,
688    /// Output directory for HTTP client code. Generation is skipped when `None`.
689    pub client: Option<PathBuf>,
690    /// Whether to also emit ergonomic resource-scoped clients (`<service>/resource.rs`) alongside
691    /// the low-level per-service client and builders.
692    ///
693    /// A scoped client (e.g. `CatalogClient` bound to a name) captures the resource's name
694    /// components and exposes `get`/`update`/`delete` (+ resource-targeted custom RPCs) returning
695    /// the matching builder. Only emitted for resource-scoped services, and only when
696    /// [`client`](CodeGenOutput::client) is `Some`. Defaults to `false`.
697    pub generate_resource_clients: bool,
698    /// Output directory for Python bindings. Generation is skipped when `None`.
699    pub python: Option<PathBuf>,
700    /// Output directory for Node.js NAPI bindings. Generation is skipped when `None`.
701    pub node: Option<PathBuf>,
702    /// Output directory for Node.js TypeScript client. Generation is skipped when `None`.
703    pub node_ts: Option<PathBuf>,
704    /// Output directory for WASM/browser `#[wasm_bindgen]` bindings + `.d.ts`. Generation is
705    /// skipped when `None`.
706    ///
707    /// Emits a `#[wasm_bindgen]` wrapper layer over the generated (WASM-transport) clients plus a
708    /// `client.d.ts` for JS/TS consumers. Request/response values cross the boundary as plain JS
709    /// objects via `serde-wasm-bindgen`, so this pairs with `runtime: Buffa` (serde-native models)
710    /// and `transport_type_path = "olai_http_wasm::WasmClient"`.
711    pub wasm: Option<PathBuf>,
712}
713
714impl CodeGenOutput {
715    /// Absolute path of the generated subdirectory (`models/models_subdir`), if `models` is set.
716    pub fn models_subdir_path(&self) -> Option<PathBuf> {
717        self.models.as_ref().map(|m| m.join(&self.models_subdir))
718    }
719}