Skip to main content

plexus_macros/
lib.rs

1//! # plexus-macros
2//!
3//! Procedural macros for **Plexus RPC** activations. Your Rust function
4//! signature IS the schema — the macros extract method names, parameter
5//! types, return types, doc comments, deprecation metadata, child routing,
6//! and typed request extraction from the source.
7//!
8//! See the crate-level [`README`](https://github.com/hypermemetic/plexus-macros/blob/main/README.md)
9//! for a comprehensive example covering every option, a deep-dive on
10//! request forwarding (`PlexusRequest` + `request = ...`), and a
11//! per-macro reference.
12//!
13//! # Quick example
14//!
15//! ```ignore
16//! use futures::Stream;
17//! use async_stream::stream;
18//! use plexus_macros::PlexusRequest;
19//!
20//! #[derive(PlexusRequest)]
21//! pub struct BashRequest {
22//!     #[from_cookie("access_token")]
23//!     auth_token: String,
24//! }
25//!
26//! pub struct Bash;
27//!
28//! #[plexus_macros::activation(            // namespace "bash", implicitly
29//!     version = "1.0.0",
30//!     description = "Execute bash commands and stream output",
31//!     request = BashRequest,
32//! )]
33//! impl Bash {
34//!     /// Execute a bash command and stream output.
35//!     #[plexus_macros::method]
36//!     async fn execute(
37//!         &self,
38//!         command: String,
39//!         #[activation_param] auth_token: String,
40//!     ) -> impl Stream<Item = String> + Send + 'static {
41//!         let _ = (command, auth_token);
42//!         stream! { yield "ok".into(); }
43//!     }
44//! }
45//! ```
46//!
47//! # Macros at a glance
48//!
49//! | Macro | Purpose |
50//! |---|---|
51//! | `#[plexus_macros::activation]` | Turn an `impl` block into a Plexus RPC activation — and, with `client`, emit its typed client. |
52//! | `#[plexus_macros::method]` | Mark a method as an RPC endpoint. |
53//! | `#[plexus_macros::child]` | Register a child activation for `ChildRouter` dispatch. |
54//! | `#[plexus_macros::removed_in]` | Companion to `#[deprecated]` carrying the removal version. |
55//! | `#[derive(PlexusRequest)]` | Typed extraction from `RawRequestContext`. |
56//! | `#[derive(HandleEnum)]` | Type-safe handle enums for an activation. |
57//! | `#[derive(plexus_macros::Deserialize)]` | An internally tagged event's `Deserialize`, its `type` read first (serde's `Deserialize` otherwise). |
58//!
59//! # A method's return type is its contract (0.7)
60//!
61//! | signature | cardinality | schema `returns` / `error` / `progress` |
62//! |---|---|---|
63//! | `-> T` | one | T / — / — |
64//! | `-> Result<T, E>` | one | T / E / — |
65//! | `-> impl Stream<Item = T>` | many | T / — / — |
66//! | `-> impl Stream<Item = Result<T, E>>` | many | T / E / — |
67//! | `-> impl Stream<Item = Progress<T, P>>` | many | T / — / P |
68//! | `-> impl Stream<Item = Result<Progress<T, P>, E>>` | many | T / E / P |
69//!
70//! A Result item travels as data, `{"ok": t}` or `{"err": e}`; a
71//! `Progress::Update(p)` as a progress frame. The namespace is the type's
72//! name — `impl Foo`, or the stem of `impl FooActivation` — or the trait's,
73//! on `impl Foo for Type` (MACRO-13, RETURNS-47; `namespace = "..."`
74//! overrides it).
75//! `#[method(returns(..))]` and `#[derive(StreamEvent)]` are gone, and
76//! `#[method(streaming)]` is a deprecated no-op on a stream form. See the
77//! README's per-macro reference.
78//!
79//! Deprecated surfaces still accepted: `#[hub_methods]`, `#[hub_method]`, the
80//! `hub` and `children = [...]` flags on `#[activation]`. See the migration
81//! section of the README.
82//!
83//! ## Crate version (UMB-2)
84//!
85//! This crate is `proc-macro = true`, which means it can only export macro
86//! attributes — `pub const VERSION` etc. are forbidden by the compiler. The
87//! `plexus-rpc` umbrella reads `plexus-macros`'s version via a build-time
88//! environment variable populated from `Cargo.toml`'s dependency pin
89//! (see `plexus-rpc/build.rs`).
90
91mod codegen;
92mod credential;
93mod handle_enum;
94mod parse;
95mod request;
96mod type_first;
97mod wire;
98
99
100use codegen::generate_all;
101use parse::HubMethodsAttrs;
102use proc_macro::TokenStream;
103use proc_macro2::TokenStream as TokenStream2;
104use quote::{format_ident, quote};
105use syn::{
106    parse::{Parse, ParseStream},
107    parse_macro_input, punctuated::Punctuated, Expr, ExprLit, FnArg, ItemFn, ItemImpl, Lit, Meta,
108    MetaNameValue, Pat, ReturnType, Token, Type,
109};
110
111/// Parsed attributes for hub_method (standalone version)
112struct HubMethodAttrs {
113    name: Option<String>,
114    /// Explicit description from `description = "..."`. When `Some`, this wins over
115    /// `///` doc comments. When `None`, doc comments are used as the default.
116    description: Option<String>,
117    /// Base crate path for imports (default: "crate")
118    crate_path: String,
119}
120
121impl Parse for HubMethodAttrs {
122    fn parse(input: ParseStream) -> syn::Result<Self> {
123        let mut name = None;
124        let mut description: Option<String> = None;
125        let mut crate_path = "crate".to_string();
126
127        if !input.is_empty() {
128            let metas = Punctuated::<Meta, Token![,]>::parse_terminated(input)?;
129
130            for meta in metas {
131                // RETURNS-8: the removed attributes fail here too, not only
132                // inside `#[activation]`.
133                match &meta {
134                    Meta::List(list) if list.path.is_ident("returns") => {
135                        return Err(syn::Error::new_spanned(&list.path, parse::RETURNS_REMOVED));
136                    }
137                    _ => {}
138                }
139                if let Meta::NameValue(MetaNameValue { path, value, .. }) = meta {
140                    if path.is_ident("name") {
141                        if let Expr::Lit(ExprLit {
142                            lit: Lit::Str(s), ..
143                        }) = value
144                        {
145                            name = Some(s.value());
146                        }
147                    } else if path.is_ident("description") {
148                        if let Expr::Lit(ExprLit {
149                            lit: Lit::Str(s), ..
150                        }) = value
151                        {
152                            description = Some(s.value());
153                        }
154                    } else if path.is_ident("crate_path") {
155                        if let Expr::Lit(ExprLit {
156                            lit: Lit::Str(s), ..
157                        }) = value
158                        {
159                            crate_path = s.value();
160                        }
161                    }
162                }
163            }
164        }
165
166        Ok(HubMethodAttrs { name, description, crate_path })
167    }
168}
169
170/// Attribute macro for individual methods within a `#[plexus::activation]` impl block.
171///
172/// # Example
173///
174/// ```ignore
175/// #[plexus::activation]                    // namespace "bash", implicitly
176/// impl Bash {
177///     /// Execute a bash command
178///     #[plexus::method]
179///     async fn execute(&self, command: String) -> impl Stream<Item = BashEvent> {
180///         // ...
181///     }
182/// }
183/// ```
184///
185/// # The return type is the contract (RETURNS-8)
186///
187/// Six forms: `-> T`, `-> Result<T, E>`, `-> impl Stream<Item = T>`,
188/// `-> impl Stream<Item = Result<T, E>>`, `-> impl Stream<Item = Progress<T,
189/// P>>`, `-> impl Stream<Item = Result<Progress<T, P>, E>>`. A plain return
190/// yields one item, `impl Stream` many; `Result` and `Progress` are
191/// recognised by name. Any other return type is a compile error that lists
192/// the six. `returns(..)` is removed (a compile error); `streaming` is a
193/// deprecated no-op on a stream form and an error on a one-item one.
194///
195/// # No in-call question (ASK-1)
196///
197/// `bidirectional` is removed (a compile error): a method never asks its
198/// caller mid-call, and Plexus has no in-call or protocol-wide
199/// confirmation. A method that wants its caller's yes builds it from its
200/// own parameters (a `dry_run`, a plan id).
201///
202/// # Authorization arguments (R-1 / AUTHZ-CORE-2)
203///
204/// - `scope = "..."` — explicit required scope, emitted into the generated
205///   `MethodSchema.requires_credential`. Repeatable: `scope = "x.y",
206///   scope = "x.z"` means the caller must satisfy **ALL** listed scopes
207///   (conjunction — AND, not OR). Literals are validated at compile time
208///   against the AUTHZ-CORE-4 scope grammar (dot-separated `[a-z][a-z0-9_]*`
209///   segments, optional trailing `.*` segment wildcard, or bare `*`).
210/// - `input_window = N` (BIDIR-6) — on a method with an `Input<T>` parameter,
211///   the credit it grants (default 64). `input_max_buffered = N`: the bytes
212///   held past which it grants no credit until drained (default 64 MiB). `input_max_items = N`,
213///   `input_max_bytes = N`: limits over the call's life, none unless given.
214///   An `Input<T>` is at most one, top-level, and not one of the params:
215///   `MethodSchema.input` is `T`'s schema, and the client takes a stream.
216/// - `public` — the method is exempt from the default-deny gate; emitted as
217///   `MethodSchema.public = true`. Mixing `public` with `scope = "..."` is a
218///   compile error (a public method has no required scope to enforce).
219/// - Neither — the implicit `<activation>.<method>` scope rule applies at
220///   registry-build time (AUTHZ-CORE-4); the schema carries no
221///   `requires_credential` for the implicit case.
222#[proc_macro_attribute]
223pub fn method(attr: TokenStream, item: TokenStream) -> TokenStream {
224    let args = parse_macro_input!(attr as HubMethodAttrs);
225    let input_fn = parse_macro_input!(item as ItemFn);
226
227    match hub_method_impl(args, input_fn) {
228        Ok(tokens) => tokens.into(),
229        Err(e) => e.to_compile_error().into(),
230    }
231}
232
233/// Deprecated: use `plexus::method` instead.
234#[deprecated(since = "0.5.0", note = "Use `plexus::method` instead")]
235#[proc_macro_attribute]
236pub fn hub_method(attr: TokenStream, item: TokenStream) -> TokenStream {
237    method(attr, item)
238}
239
240/// Attribute macro for individual **child** methods within a
241/// `#[plexus_macros::activation]` impl block.
242///
243/// Two method shapes are accepted:
244///
245/// | Shape | Role | Example |
246/// |---|---|---|
247/// | `fn NAME(&self) -> Child` (no args) | Static child — routing name is the method name | `fn mercury(&self) -> Mercury` |
248/// | `fn NAME(&self, name: &str) -> Option<Child>` (sync or async) | Dynamic fallback dispatcher | `fn planet(&self, name: &str) -> Option<Planet>` |
249///
250/// The enclosing `#[plexus_macros::activation]` macro collects all `#[child]`
251/// methods and generates a `ChildRouter` impl whose `get_child(name)`
252/// dispatches over them. `#[child]` methods are **not** exposed as Plexus RPC
253/// methods — they contribute only to `ChildRouter` routing.
254///
255/// # Example
256///
257/// ```ignore
258/// #[plexus_macros::activation(namespace = "solar")]
259/// impl Solar {
260///     #[plexus_macros::child]
261///     fn mercury(&self) -> Mercury { self.mercury.clone() }
262///
263///     #[plexus_macros::child]
264///     async fn planet(&self, name: &str) -> Option<Planet> {
265///         self.lookup_planet(name).await
266///     }
267/// }
268/// ```
269///
270/// `list = method` and `search = method` name the sibling methods that
271/// stream a dynamic child's names (`#[plexus_macros::child(list = names)]`).
272/// NEST-17: by path; the string form (`list = "names"`) is accepted for one
273/// release with a deprecation warning.
274///
275/// # How the child inherits its caller (MACRO-20)
276///
277/// `forward = same_service | identity_only | pass_through | anonymous`
278/// picks the policy the emitted `ChildRouter::forward_policy_for` hands
279/// the child. A static child defaults to `same_service`: the same service as
280/// its parent, it keeps the caller whole (principal stamp, session,
281/// ceiling). Write `#[plexus_macros::child(forward = identity_only)]` for a
282/// deputy that must not see the caller's session. A dynamic child keeps the
283/// framework default (`IdentityOnly`) unless it names one.
284///
285/// Used standalone (outside an `#[activation]` block) this attribute is a
286/// no-op that returns the function unchanged.
287/// NEST-7: an activation returned by name — a peer, in this process or
288/// across the network, typed by a contract's peer trait or untyped:
289///
290/// ```ignore
291/// #[plexus_macros::peer(list = integrations)]
292/// async fn integration(&self, name: &str) -> Result<Box<dyn forge::ForgePeer>, PeerError> { … }
293/// #[plexus_macros::peer(list = dendrites, search = find)]
294/// async fn dendrite(&self, name: &str) -> Result<Box<dyn Peer>, PeerError> { … }
295/// ```
296///
297/// Inside `#[plexus_macros::activation]` the slot's role is
298/// `MethodRole::Peer { interface }`, routing calls it (a typed peer checked
299/// against the slot's interface first) and a failure is its typed error
300/// item. Outside it this attribute does nothing.
301#[proc_macro_attribute]
302pub fn peer(_attr: TokenStream, item: TokenStream) -> TokenStream {
303    item
304}
305
306#[proc_macro_attribute]
307pub fn child(_attr: TokenStream, item: TokenStream) -> TokenStream {
308    // Outside of #[plexus_macros::activation] this attribute does nothing;
309    // the activation macro strips it and collects the method into the
310    // generated ChildRouter impl.
311    item
312}
313
314/// Companion attribute to Rust's built-in `#[deprecated]` for carrying a
315/// `removed_in = "VERSION"` hint that rustc doesn't recognize.
316///
317/// Rust's `#[deprecated(since = "X", note = "Y")]` supports only `since` and
318/// `note`. This companion attribute supplies the removal version that the
319/// `plexus-macros` codegen folds into the method's `DeprecationInfo.removed_in`
320/// field on the emitted `MethodSchema`.
321///
322/// # Example
323///
324/// ```ignore
325/// #[deprecated(since = "0.5", note = "use `new_method` instead")]
326/// #[plexus_macros::removed_in("0.6")]
327/// #[plexus_macros::method]
328/// async fn legacy(&self) -> impl Stream<Item = String> + Send + 'static {
329///     // ...
330/// }
331/// ```
332///
333/// # Requirements
334///
335/// `#[plexus_macros::removed_in]` is only meaningful when paired with
336/// `#[deprecated]`. The `#[plexus_macros::activation]` macro emits a compile
337/// error when it encounters `#[removed_in]` on a method that doesn't also
338/// carry `#[deprecated]`.
339///
340/// As a standalone attribute (outside an `#[activation]` block) this is a
341/// no-op that returns the item unchanged — the activation macro parses and
342/// strips it during codegen.
343#[proc_macro_attribute]
344pub fn removed_in(attr: TokenStream, item: TokenStream) -> TokenStream {
345    // When `#[plexus_macros::removed_in("X")]` is placed OUTSIDE
346    // `#[plexus_macros::activation(...)]` on the same impl block, the
347    // `removed_in` proc macro runs BEFORE the activation macro (outer
348    // attrs expand first), so a naive no-op implementation would consume
349    // the attribute before the activation macro ever sees it.
350    //
351    // Workaround: emit a synthetic `#[doc(hidden)]` marker attribute on
352    // the item's attr list that encodes the removed_in value. The
353    // activation / method codegen scans for this marker as an equivalent
354    // signal to the companion attribute and uses it to populate
355    // `DeprecationInfo.removed_in`.
356    //
357    // Stable rustc treats `#[doc(hidden)]` as a regular doc attribute and
358    // the sentinel payload rides along in the same literal string.
359    let attr_str: String = match syn::parse::<syn::LitStr>(attr.clone()) {
360        Ok(s) => s.value(),
361        Err(_) => {
362            // Not a bare string literal — just let the item pass through
363            // and let the activation/method layer produce the proper error.
364            return item;
365        }
366    };
367    let marker = format!("__plexus_removed_in:{}", attr_str);
368    let item_ts: proc_macro2::TokenStream = item.into();
369    let marker_lit = proc_macro2::Literal::string(&marker);
370    let out = quote::quote! {
371        #[doc(hidden)]
372        #[doc = #marker_lit]
373        #item_ts
374    };
375    out.into()
376}
377
378fn hub_method_impl(args: HubMethodAttrs, input_fn: ItemFn) -> syn::Result<TokenStream2> {
379    // Extract method name (from attr or function name)
380    let method_name = args
381        .name
382        .unwrap_or_else(|| input_fn.sig.ident.to_string());
383
384    // Resolve description: explicit `description = "..."` wins over `///` doc
385    // comments; if neither is present, description is the empty string.
386    let description = match args.description {
387        Some(explicit) => explicit,
388        None => extract_doc_comment(&input_fn),
389    };
390
391    // Extract input type from first parameter (if any)
392    let input_type = extract_input_type(&input_fn)?;
393
394    // Extract return type
395    let return_type = extract_return_type(&input_fn)?;
396
397    // Function name for the schema function
398    let fn_name = &input_fn.sig.ident;
399    let schema_fn_name = format_ident!("{}_schema", fn_name);
400
401    // Parse crate path
402    let crate_path: syn::Path = syn::parse_str(&args.crate_path)
403        .map_err(|e| syn::Error::new_spanned(&input_fn.sig, format!("Invalid crate_path: {}", e)))?;
404
405    // Generate the schema function
406    let schema_fn = generate_schema_fn(
407        &schema_fn_name,
408        &method_name,
409        &description,
410        input_type.as_ref(),
411        &return_type,
412        &crate_path,
413    );
414
415    // Return the original function plus the schema function
416    Ok(quote! {
417        #input_fn
418
419        #schema_fn
420    })
421}
422
423fn extract_doc_comment(input_fn: &ItemFn) -> String {
424    // Delegate to the shared helper so the standalone `#[method]` macro path
425    // follows the same doc-comment extraction rule as the in-activation path:
426    // lines joined with '\n', common leading whitespace stripped.
427    parse::extract_doc_description(&input_fn.attrs).unwrap_or_default()
428}
429
430fn extract_input_type(input_fn: &ItemFn) -> syn::Result<Option<Type>> {
431    // Skip self parameter, get first real parameter
432    for arg in &input_fn.sig.inputs {
433        match arg {
434            FnArg::Receiver(_) => continue, // Skip &self
435            FnArg::Typed(pat_type) => {
436                // Skip context-like parameters
437                if let Pat::Ident(ident) = &*pat_type.pat {
438                    let name = ident.ident.to_string();
439                    if name == "ctx" || name == "context" || name == "self_" {
440                        continue;
441                    }
442                }
443                return Ok(Some((*pat_type.ty).clone()));
444            }
445        }
446    }
447
448    Ok(None)
449}
450
451fn extract_return_type(input_fn: &ItemFn) -> syn::Result<Type> {
452    match &input_fn.sig.output {
453        ReturnType::Default => Err(syn::Error::new_spanned(
454            &input_fn.sig,
455            "hub_method requires a return type",
456        )),
457        ReturnType::Type(_, ty) => Ok((*ty.clone()).clone()),
458    }
459}
460
461fn generate_schema_fn(
462    fn_name: &syn::Ident,
463    method_name: &str,
464    description: &str,
465    input_type: Option<&Type>,
466    return_type: &Type,
467    crate_path: &syn::Path,
468) -> TokenStream2 {
469    // Z2H-2: the standalone `#[method]` macro has no activation-level shim
470    // module, so resolve the dep roots absolutely: through the plexus-rpc
471    // umbrella's `__deps` re-exports when the consumer depends on it, or the
472    // extern prelude (today's semantics) otherwise.
473    let (serde_json_root, schemars_root) =
474        match codegen::umbrella_crate(proc_macro2::Span::call_site()) {
475            Some(umbrella) => (
476                quote! { ::#umbrella::__deps::serde_json },
477                quote! { ::#umbrella::__deps::schemars },
478            ),
479            None => (quote! { serde_json }, quote! { schemars }),
480        };
481
482    let input_schema = if let Some(input_ty) = input_type {
483        quote! {
484            Some(#serde_json_root::to_value(#schemars_root::schema_for!(#input_ty)).unwrap())
485        }
486    } else {
487        quote! { None }
488    };
489
490    let _ = return_type; // Will be used for protocol schema in future
491    let _ = crate_path;
492
493    quote! {
494        /// Generated schema function for this hub method
495        #[allow(dead_code)]
496        pub fn #fn_name() -> #serde_json_root::Value {
497            #serde_json_root::json!({
498                "name": #method_name,
499                "description": #description,
500                "input": #input_schema,
501            })
502        }
503    }
504}
505
506/// Attribute macro for impl blocks defining a Plexus activation.
507///
508/// Generates:
509/// - Method enum for schema extraction
510/// - Activation trait implementation
511/// - RPC server trait and implementation
512///
513/// # Attributes
514///
515/// - `namespace = "..."` - The activation namespace (the name rule below
516///   gives it from `impl FooActivation`)
517/// - `version = "..."` (optional, default: "1.0.0") - Version string
518/// - `description = "..."` (optional) - Activation description
519/// - `crate_path = "..."` (optional, default: "crate") - Path to substrate crate
520/// - `client` (optional flag) - also emit the typed client (MACRO-2, below)
521/// - `server_cfg = "<cfg predicate>"` (optional) - compile the server half
522///   only under that `cfg` (MACRO-2, below)
523///
524/// # Example
525///
526/// ```ignore
527/// #[plexus::activation(namespace = "bash", version = "1.0.0", description = "Execute bash commands")]
528/// impl Bash {
529///     /// Execute a bash command and stream output
530///     #[plexus::method]
531///     async fn execute(&self, command: String) -> impl Stream<Item = BashEvent> + Send + 'static {
532///         self.executor.execute(&command).await
533///     }
534/// }
535/// ```
536///
537/// # The typed client (`client`, `server_cfg`) — MACRO-2, 0.7 shapes RETURNS-9
538///
539/// The macro already knows, when it runs, every method's wire name, its
540/// parameters and its precise contract (cardinality, item, error, progress).
541/// With `client` it also emits a **typed client** for the activation, and the
542/// activation's **aggregate** `{Ns}Event` (one variant per method, carrying
543/// that method's item), so a Rust consumer never hand-writes a call site or
544/// hand-mirrors an item type:
545///
546/// ```ignore
547/// #[plexus_macros::activation(client)]                 // namespace "tickets", implicitly
548/// impl Tickets { /* unchanged */ }
549///
550/// // emitted beside the impl: TicketsClient<T>, and TicketsEvent
551/// let client = TicketsClient::new(transport);                      // any plexus_client::Transport
552/// let health = client.health().await?;                             // one item: Health
553/// match client.get("MNG-2".into()).await? { Ok(t) => .., Err(no) => .. }   // one, fallible
554/// let rows: Vec<_> = client.list(None, None).try_collect().await?; // many: MethodStream
555/// let mut s = client.import(src).with_progress();                  // Frame<item, P>
556/// let mut ev = client.watch(None).events();                        // TicketsEvent
557/// ```
558///
559/// `?` is the call failing (`ClientError::Remote(RemoteError)` for the
560/// server's typed error frame); a match on the item is the activation's
561/// answer. The client is generic over the transport, so the emitted code
562/// names none of them; its parameter and item types are the activation's
563/// own, so a change to either is a compile error in every consumer. A crate
564/// that already defines a type named `{Ns}Event` renames it before turning
565/// `client` on.
566///
567/// **Requires** the consuming crate to depend on `plexus-client`. A
568/// proc-macro crate cannot check that for you at expansion time in general,
569/// but the path is resolved through `proc-macro-crate`, so a missing
570/// dependency is reported at the `client` flag rather than as an unresolved
571/// import in code you did not write.
572///
573/// **`server_cfg = "..."`** puts the *server* half of the expansion — the
574/// impl block, the method enum, the `Activation` impl, the jsonrpsee trait —
575/// behind a `cfg`, while the client half stays unconditional. That is what
576/// makes an activation crate reachable from `wasm32-unknown-unknown`:
577///
578/// ```ignore
579/// // Cargo.toml: server deps are optional and behind `feature = "server"`.
580/// // plexus-macros itself stays non-optional — a proc-macro crate is built
581/// // for the host, so it costs a wasm32 build nothing.
582/// #[plexus_macros::activation(
583///     namespace = "tickets",
584///     client,
585///     server_cfg = "feature = \"server\"",
586/// )]
587/// impl Tickets { /* .. */ }
588/// ```
589///
590/// A consumer then says one line — `tickets-api = { version = "..",
591/// default-features = false }` — and gets the types and the client, with no
592/// tokio, jsonrpsee or plexus-core anywhere in its tree. Gating your own
593/// struct definition and server-only imports is still yours to do; the macro
594/// only gates its own output.
595///
596/// Both flags are opt-in: an activation that names neither expands exactly
597/// as it did before.
598///
599/// # `#[activation]` needs nothing — MACRO-13, RETURNS-47
600///
601/// The type names everything, every key is an override, and (NEST-17) the
602/// trait is emitted every time, `{Name}ActivationSchema` unless named:
603///
604/// ```ignore
605/// /// Tickets.                              // the activation's description
606/// #[plexus_macros::activation]
607/// impl Tickets {
608///     /// Every ticket.                     // the method's description
609///     pub async fn list(&self) -> impl Stream<Item = Ticket> + Send + 'static { .. }
610///     #[plexus_macros::method]
611///     pub async fn total(&self) -> u64 { .. }    // one item: marked
612///     pub fn new() -> Self { .. }           // not async: a plain method
613///     async fn helper(&self) -> u32 { .. }  // not pub: a plain method
614/// }
615/// // namespace "tickets"; `TicketsClient<T>`, whose `total()` answers
616/// // `Result<u64, ClientError>` and `list()` a `MethodStream`; the trait
617/// // `TicketsActivationSchema`, implemented by `Tickets` (when `Clone`).
618/// ```
619///
620/// - **The name rule.** `impl Tickets` is named by itself (RETURNS-47: no
621///   suffix forced); `impl TicketsActivation` by its stem, `Tickets`, as
622///   before. The namespace is the name in snake_case (`TicketsApi` →
623///   `tickets_api`), the client `TicketsClient<T>`. `namespace = "…"`
624///   overrides the namespace.
625/// - **The trait every time** (NEST-17, owner 2026-11-09, reversing
626///   RETURNS-47's "only when named"). `impl Shop` and `impl ShopActivation`
627///   emit `trait ShopActivationSchema`; `trait = "Bar"` renames it (and
628///   names the client `BarClient` and, absent `namespace`, the namespace
629///   `bar`); a contract is its trait (`Foo`). Each wire method is in it
630///   under its own return type, boxed, with nothing the server injects. The
631///   activation implements it by cloning itself into each stream (the
632///   default trait only where the type is `Clone`); a method that takes
633///   `auth`, `reach` or a `#[from_auth]` value reads it from the call's
634///   context there (`plexus_core::call::caller()`, as `impl Trait for Type`
635///   does — a missing caller is the method's error: its `E` from a
636///   `PlexusError` or a `PeerError`; `reach` outside a call is
637///   `Reach::nowhere()`). An `#[activation_param]` is in no context, so an
638///   activation with one does not implement its trait. The client's
639///   methods answer `Result<T, ClientError>` (one item) or the
640///   `{Ns}{Method}Stream` alias (many); it implements the trait too when
641///   every method answers one `Result<T, E>` with `E: From<PeerError>`, so
642///   `dyn ShopActivationSchema` is local or remote alike.
643/// - **`impl Trait for Type`.** `#[plexus_macros::activation] impl
644///   forge::Forge for GitHub` serves a trait written by hand: the trait
645///   names the namespace (`forge`) and the client (`ForgeClient<T>`, emitted
646///   here), the type names nothing, and every `async fn` on `&self` is a
647///   wire method, called as `<GitHub as forge::Forge>::m`. Its methods reach
648///   their caller through the call's context, `plexus_core::call::caller()`
649///   (a trait's signature cannot carry `#[from_auth]`). Under `auth =
650///   "required"` the dispatch refuses an anonymous caller (or a call outside
651///   any context) before the body of every method not `public`, out of band
652///   and typed, as `#[from_auth]` does. `#[plexus_macros::from_auth(self.
653///   access.verify)]` on the method is `#[from_auth]`'s form here: the
654///   verifier runs on the signed-in caller before the body, its error the
655///   call's typed refusal by the same route, its value the body's through
656///   `plexus_core::call::verified::<User>()`. It has no direct JSON-RPC
657///   methods, only the service's `{ns}.call`; `#[child]` in it is not served
658///   yet (GRAFT-1).
659/// - **Every public method a wire method.** Every `pub async fn` on `&self`
660///   returning `impl Stream<Item = E>` is on the wire with no `#[method]`
661///   (which stays for its overrides, and marks a one-item method); one
662///   returning anything else unmarked is a compile error; `methods = marked`
663///   restores the `#[method]`-only rule.
664/// - **`served = written`** (KEEL-27, opt-in per block): an unmarked fn is
665///   what its signature says — not `pub`, or not on `&self`, a helper; a
666///   `pub fn x(&self) -> A` a mount, `pub fn x(&self, name: &str) ->
667///   Option<A>` a slot (each checked by the compiler, `A: ChildRouter`, the
668///   refusal naming the fn and what a mount returns); a `pub async fn x(&self,
669///   name: &str) -> Result<Box<dyn I>, PeerError>` a fallible mount (a
670///   `#[peer]`); any other `pub async fn` on `&self` a method (a bare
671///   `#[method]`, one item or a stream). A marked fn is what its marker
672///   says; an option no signature carries (`#[method(name = …)]` and the
673///   rest, `#[child(list = …, search = …, forward = …, opaque)]`, a mount
674///   behind a type alias, a private served fn) keeps its marker. Not with
675///   `methods = marked`, nor on `impl Trait for Type`.
676/// - **The client without a flag**, whenever the crate depends on
677///   `plexus-client`; `client` is accepted with a deprecation warning.
678/// - **The `server` feature default.** A crate whose manifest declares a
679///   `server` feature gets its server half under `#[cfg(feature =
680///   "server")]`; `server_cfg` overrides. The trait and the client are never
681///   gated.
682/// - **A bodiless activation is a contract**, and a contract is its trait:
683///   when every wire method is bodiless (`pub async fn f(&self, ..) ->
684///   impl Stream<..>;`), on `impl FooActivation` (trait `Foo`) or with
685///   `trait = "…"`, the macro emits `pub struct FooActivation<D: Foo>(Arc<D>)`
686///   delegating to `D`, `impl<D: Foo> Foo for FooActivation<D>`, and
687///   `Foo::server(self)`: `service.register(Local::new().server())`.
688///
689/// **Written before MACRO-13.** An activation on a type not named
690/// `…Activation` that says its `namespace` expands exactly as it did (no
691/// trait; the client on the `client` flag; only `#[method]`s on the wire)
692/// with a deprecation warning saying what to change. A later release
693/// refuses it.
694#[proc_macro_attribute]
695pub fn activation(attr: TokenStream, item: TokenStream) -> TokenStream {
696    let args = parse_macro_input!(attr as HubMethodsAttrs);
697    let input_impl = parse_macro_input!(item as ItemImpl);
698
699    match generate_all(args, input_impl) {
700        Ok(tokens) => tokens.into(),
701        Err(e) => e.to_compile_error().into(),
702    }
703}
704
705/// Deprecated: use `plexus::activation` instead.
706#[deprecated(since = "0.5.0", note = "Use `plexus::activation` instead")]
707#[proc_macro_attribute]
708pub fn hub_methods(attr: TokenStream, item: TokenStream) -> TokenStream {
709    activation(attr, item)
710}
711
712/// Derive macro for declaring credential-bearing fields on a return-type
713/// struct or enum (per `AUTHZ-CRED-MACRO-1`).
714///
715/// Apply `#[derive(Credentials)]` to a struct or enum. Within the item,
716/// annotate each credential-bearing field with the helper attribute
717/// `#[credential(kind = "...", attach_as = "...", ...)]` carrying the
718/// per-field metadata. The field's type must be `Credential<T>` (the sealed
719/// wrapper from `plexus_auth_core`); any other type produces a compile
720/// error citing the wrapper requirement.
721///
722/// **Why a derive macro and not a freestanding attribute macro?** Stable Rust
723/// proc-macros cannot intercept attribute macros applied directly to struct
724/// fields; only derive-helper attributes can appear there. See
725/// `plans/AUTHZ/AUTHZ-CRED-MACRO-1-RUN-NOTES.md` for the rationale.
726///
727/// # Example
728///
729/// ```ignore
730/// use plexus_auth_core::{
731///     AttachmentSite, Credential, CredentialKind, CredentialScheme,
732///     HeaderName, MethodPath, Scope,
733/// };
734///
735/// // `CredentialFieldMarker` lands in plexus-auth-core in a follow-up; for
736/// // now the macro emits code that references it by name and consumers
737/// // provide the definition (see run-notes).
738///
739/// #[derive(plexus_macros::Credentials, serde::Serialize)]
740/// pub struct LoginEvent {
741///     pub user_id: String,
742///
743///     #[credential(
744///         kind = "bearer",
745///         attach_as = "header:authorization",
746///         scheme = "Bearer ",
747///     )]
748///     pub session: Credential<String>,
749/// }
750/// ```
751///
752/// # Clauses
753///
754/// | Clause | Required? | Notes |
755/// |---|---|---|
756/// | `kind = "<name>"` | required | Closed enum: `"bearer"`, `"cookie"`, `"oauth_access"`, `"oauth_refresh"`, `"oidc_id"`, `"aws_sts"`, `"macaroon"`. The escape valve `kind(other = "<name>")` carries a backend-specific kind. |
757/// | `attach_as = "<spec>"` | required | One of `"header:<name>"`, `"cookie:<name>"`, `"first_frame:<setup-method>:<param>"`, `"in_rpc_param:<name>"`. |
758/// | `scheme = "<prefix>"` | optional | E.g. `"Bearer "` (trailing space significant). |
759/// | `scopes = ["a.b", ...]` | optional, default empty | List of scope identifiers. |
760/// | `refresh_via = "<method-path>"` | optional | E.g. `"auth.refresh"`. |
761/// | `revoke_via = "<method-path>"` | optional | E.g. `"auth.logout"`. |
762/// | `sensitive` | optional flag | Accepted for clarity; credentials are always sensitive. |
763///
764/// # Emitted artifacts
765///
766/// The macro emits two free functions in the same module:
767///
768/// - `fn __plexus_credential_marker_for_<TypeIdent>() -> Vec<CredentialFieldMarker>`
769/// - `fn __plexus_sensitive_fields_for_<TypeIdent>() -> Vec<(Option<&'static str>, &'static str)>`
770///
771/// The consumer (per `AUTHZ-CRED-CORE-3`) calls the first function during
772/// schema build; the second mirrors the implicit `#[sensitive]` rule for the
773/// redaction pipeline (per `AUTHZ-PRIVACY-2`).
774///
775/// The emitted code requires `CredentialFieldMarker`, `CredentialKind`,
776/// `AttachmentSite`, `CredentialScheme`, `Scope`, `MethodPath`, `HeaderName`,
777/// `CookieName`, `ParamName`, and `CredentialKindName` to be in scope at the
778/// emission site. Importing `plexus_auth_core::*` (or the equivalent named
779/// imports) at the top of the consuming module satisfies all but
780/// `CredentialFieldMarker`, which lands in `plexus_auth_core` in a follow-up.
781#[proc_macro_derive(Credentials, attributes(credential))]
782pub fn credentials_derive(input: TokenStream) -> TokenStream {
783    credential::expand_credentials_derive(input)
784}
785
786/// Derive macro for type-safe handle creation and parsing.
787///
788/// Generates:
789/// - `to_handle(&self) -> Handle` - converts enum variant to Handle
790/// - `impl TryFrom<&Handle>` - parses Handle back to enum variant
791/// - `impl From<EnumName> for Handle` - convenience conversion
792///
793/// # Attributes
794///
795/// Enum-level (required):
796/// - `plugin_id = "CONSTANT_NAME"` - Name of the constant holding the plugin UUID
797/// - `version = "1.0.0"` - Semantic version for handles
798/// - `crate_path = "..."` (optional, default: "plexus_core") - Path to plexus_core crate
799/// - `plugin_id_type = "Type<Args>"` (optional) - Concrete type whose associated
800///   constant `plugin_id` names. Use this when the owning activation is generic
801///   (e.g. `Cone<P: HubContext = NoParent>`) to pin the instantiation and avoid
802///   E0283 "cannot infer type" errors. Pairs with `plugin_id` — e.g.
803///   `plugin_id = "Cone::PLUGIN_ID", plugin_id_type = "Cone<NoParent>"` emits
804///   `<Cone<NoParent>>::PLUGIN_ID`.
805///
806/// Variant-level:
807/// - `method = "..."` (required) - The handle.method value
808/// - `table = "..."` (optional) - SQLite table name (for future resolution)
809/// - `key = "..."` (optional) - Primary key column (for future resolution)
810///
811/// # Example
812///
813/// ```ignore
814/// use hub_macro::HandleEnum;
815/// use uuid::Uuid;
816///
817/// pub const MY_PLUGIN_ID: Uuid = uuid::uuid!("550e8400-e29b-41d4-a716-446655440000");
818///
819/// #[derive(HandleEnum)]
820/// #[handle(plugin_id = "MY_PLUGIN_ID", version = "1.0.0")]
821/// pub enum MyPluginHandle {
822///     #[handle(method = "event", table = "events", key = "id")]
823///     Event { event_id: String },
824///
825///     #[handle(method = "message")]
826///     Message { message_id: String, role: String },
827/// }
828///
829/// // Usage:
830/// let handle_enum = MyPluginHandle::Event { event_id: "evt-123".into() };
831/// let handle: Handle = handle_enum.to_handle();
832/// // handle.method == "event"
833/// // handle.meta == ["evt-123"]
834///
835/// // Parsing back:
836/// let parsed = MyPluginHandle::try_from(&handle)?;
837/// ```
838#[proc_macro_derive(HandleEnum, attributes(handle))]
839pub fn handle_enum_derive(input: TokenStream) -> TokenStream {
840    handle_enum::derive(input)
841}
842
843/// PERF.115-43 · an internally tagged enum's `Deserialize`, its tag read
844/// first: in place of serde's, on a house event.
845///
846/// serde reads an internally tagged enum (`#[serde(tag = "type")]`, every
847/// event the house writes) whole into a private buffer before it reads the
848/// tag, then reads the variant out of the buffer. Written in serde's place,
849/// this derive reads the first key: when it is the tag, the variant is chosen
850/// by the tag's value and its fields are read straight from the rest of the
851/// object; when it is not, serde reads the object, buffer and all, as it
852/// always has. plexus-core writes `type` first, so a client, a hop or a
853/// service reading another's events reads them without the buffer.
854///
855/// ```ignore
856/// #[derive(Debug, Clone, serde::Serialize, plexus_macros::Deserialize, schemars::JsonSchema)]
857/// #[serde(tag = "type", rename_all = "snake_case")]
858/// pub enum TicketsEvent {
859///     Health { version: String, count: u64 },
860///     Ready,
861///     Error { message: String },
862/// }
863/// ```
864///
865/// Everything else about the enum is serde's: the derive has serde derive
866/// it twice more beside it (`#[serde(remote = …)]`), once as written and
867/// once without its tag, so every `#[serde]` attribute (`rename_all`,
868/// `rename`, `alias`, `other`, `default`, `skip`, `with`, `flatten`,
869/// `deny_unknown_fields`, `expecting`) is read by serde's own code. A struct
870/// variant and a unit variant are read straight; a newtype variant, a struct
871/// variant with a flattened field and a variant read `with` a function are
872/// read by serde's buffered read. What serde refuses is refused in serde's
873/// words. A value inside a variant is read by the deserializer itself, so a
874/// value only the input can carry (a `RawValue`, a map keyed by numbers)
875/// reaches a variant whose tag comes first.
876///
877/// It is for an internally tagged enum that is not generic, with no
878/// untagged variant (one is tried on the whole object once the tagged ones
879/// fail, which needs the buffer); anything else is a compile error that says
880/// to derive serde's `Deserialize`. The runtime is plexus-client's
881/// (`plexus_client::__rt::type_first`), so the deriving crate depends on
882/// plexus-client, as every crate with a generated client does.
883#[proc_macro_derive(Deserialize, attributes(serde))]
884pub fn deserialize_derive(input: TokenStream) -> TokenStream {
885    type_first::derive(input)
886}
887
888/// PLEXUS-59 · `#[derive(PlexusWire)]` — a type that crosses the wire.
889///
890/// A method's parameter, its answer or a stream's item is a type that serde
891/// reads and writes and schemars describes. `PlexusWire` is the three at
892/// once — serde's `Serialize` and `Deserialize`, schemars' `JsonSchema` —
893/// named through plexus-rpc when the crate depends on it, so an app lists
894/// neither serde nor schemars for its wire types. An enum is tagged the way
895/// every Plexus event is, `tag = "type", rename_all = "snake_case"`, unless
896/// it says its own `tag` or `untagged`.
897///
898/// ```ignore
899/// use plexus_rpc::prelude::*;
900///
901/// #[derive(Debug, Clone, PlexusWire)]
902/// pub struct Tick {
903///     n: u32,
904/// }
905/// ```
906///
907/// `#[serde(…)]` and `#[schemars(…)]` on the type, its fields and its
908/// variants are read as ever. It is for a type with no generics; one that
909/// has them derives serde's and schemars' traits itself.
910#[proc_macro_derive(PlexusWire, attributes(serde, schemars))]
911pub fn plexus_wire_derive(input: TokenStream) -> TokenStream {
912    let input = parse_macro_input!(input as syn::DeriveInput);
913    wire::derive(input).unwrap_or_else(|e| e.to_compile_error()).into()
914}
915
916/// Derive macro for typed HTTP/WebSocket request extraction.
917///
918/// Generates `impl PlexusRequest` (extraction) and `impl schemars::JsonSchema`
919/// (with `x-plexus-source` extensions) for the annotated struct.
920///
921/// # Field annotations
922///
923/// - `#[from_cookie("name")]` — extract from named cookie
924/// - `#[from_header("name")]` — extract from named HTTP header
925/// - `#[from_query("name")]` — extract from named URI query parameter
926/// - `#[from_peer]` — copy `ctx.peer` (peer socket address)
927/// - `#[from_auth_context]` — copy `ctx.auth` (auth context)
928/// - (no annotation) — `Default::default()`
929///
930/// # Example
931///
932/// ```ignore
933/// use plexus_macros::PlexusRequest;
934///
935/// #[derive(PlexusRequest)]
936/// struct MyRequest {
937///     #[from_cookie("access_token")]
938///     auth_token: String,
939///
940///     #[from_header("origin")]
941///     origin: Option<String>,
942///
943///     #[from_peer]
944///     peer_addr: Option<std::net::SocketAddr>,
945/// }
946/// ```
947#[proc_macro_derive(
948    PlexusRequest,
949    attributes(from_cookie, from_header, from_query, from_peer, from_auth_context)
950)]
951pub fn plexus_request_derive(input: TokenStream) -> TokenStream {
952    request::derive(input)
953}
954
955/// No-op `JsonSchema` derive — used when plexus-macros is aliased as `schemars`
956/// in dev-dependencies to prevent duplicate `impl JsonSchema` conflicts with
957/// `#[derive(PlexusRequest)]` (which generates its own `impl JsonSchema`).
958///
959/// When plexus-macros is aliased as schemars in dev-deps:
960/// ```toml
961/// [dev-dependencies]
962/// schemars = { path = "../plexus-macros", package = "plexus-macros", features = ["schemars-compat"] }
963/// ```
964/// then `#[derive(schemars::JsonSchema)]` invokes THIS derive instead of the real schemars derive,
965/// producing no output, so only `PlexusRequest`'s `impl JsonSchema` exists.
966#[cfg(feature = "schemars-compat")]
967#[proc_macro_derive(JsonSchema, attributes(schemars, serde))]
968pub fn json_schema_noop_derive(_input: TokenStream) -> TokenStream {
969    // Intentionally produces no output.
970    // PlexusRequest already generates impl JsonSchema with x-plexus-source extensions.
971    TokenStream::new()
972}