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