1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! # plexus-macros
//!
//! Procedural macros for **Plexus RPC** activations. Your Rust function
//! signature IS the schema — the macros extract method names, parameter
//! types, return types, doc comments, deprecation metadata, child routing,
//! and typed request extraction from the source.
//!
//! See the crate-level [`README`](https://github.com/hypermemetic/plexus-macros/blob/main/README.md)
//! for a comprehensive example covering every option, a deep-dive on
//! request forwarding (`PlexusRequest` + `request = ...`), and a
//! per-macro reference.
//!
//! # Quick example
//!
//! ```ignore
//! use futures::Stream;
//! use async_stream::stream;
//! use plexus_macros::PlexusRequest;
//!
//! #[derive(PlexusRequest)]
//! pub struct BashRequest {
//! #[from_cookie("access_token")]
//! auth_token: String,
//! }
//!
//! pub struct Bash;
//!
//! #[plexus_macros::activation(
//! namespace = "bash",
//! version = "1.0.0",
//! description = "Execute bash commands and stream output",
//! request = BashRequest,
//! )]
//! impl Bash {
//! /// Execute a bash command and stream output.
//! #[plexus_macros::method(streaming)]
//! async fn execute(
//! &self,
//! command: String,
//! #[activation_param] auth_token: String,
//! ) -> impl Stream<Item = String> + Send + 'static {
//! let _ = (command, auth_token);
//! stream! { yield "ok".into(); }
//! }
//! }
//! ```
//!
//! # Macros at a glance
//!
//! | Macro | Purpose |
//! |---|---|
//! | `#[plexus_macros::activation]` | Turn an `impl` block into a Plexus RPC activation — and, with `client`, emit its typed client. |
//! | `#[plexus_macros::method]` | Mark a method as an RPC endpoint. |
//! | `#[plexus_macros::child]` | Register a child activation for `ChildRouter` dispatch. |
//! | `#[plexus_macros::removed_in]` | Companion to `#[deprecated]` carrying the removal version. |
//! | `#[derive(PlexusRequest)]` | Typed extraction from `RawRequestContext`. |
//! | `#[derive(HandleEnum)]` | Type-safe handle enums for an activation. |
//!
//! Deprecated surfaces kept through 0.5.x (removed in 0.6): `#[hub_methods]`,
//! `#[hub_method]`, `#[derive(StreamEvent)]`, the `hub` and `children = [...]`
//! flags on `#[activation]`. See the migration section of the README.
//!
//! ## Crate version (UMB-2)
//!
//! This crate is `proc-macro = true`, which means it can only export macro
//! attributes — `pub const VERSION` etc. are forbidden by the compiler. The
//! `plexus-rpc` umbrella reads `plexus-macros`'s version via a build-time
//! environment variable populated from `Cargo.toml`'s dependency pin
//! (see `plexus-rpc/build.rs`).
use generate_all;
use HubMethodsAttrs;
use TokenStream;
use TokenStream as TokenStream2;
use ;
use ;
/// Parsed attributes for hub_method (standalone version)
/// Attribute macro for individual methods within a `#[plexus::activation]` impl block.
///
/// # Example
///
/// ```ignore
/// #[plexus::activation(namespace = "bash")]
/// impl Bash {
/// /// Execute a bash command
/// #[plexus::method]
/// async fn execute(&self, command: String) -> impl Stream<Item = BashEvent> {
/// // ...
/// }
/// }
/// ```
///
/// # Authorization arguments (R-1 / AUTHZ-CORE-2)
///
/// - `scope = "..."` — explicit required scope, emitted into the generated
/// `MethodSchema.requires_credential`. Repeatable: `scope = "x.y",
/// scope = "x.z"` means the caller must satisfy **ALL** listed scopes
/// (conjunction — AND, not OR). Literals are validated at compile time
/// against the AUTHZ-CORE-4 scope grammar (dot-separated `[a-z][a-z0-9_]*`
/// segments, optional trailing `.*` segment wildcard, or bare `*`).
/// - `public` — the method is exempt from the default-deny gate; emitted as
/// `MethodSchema.public = true`. Mixing `public` with `scope = "..."` is a
/// compile error (a public method has no required scope to enforce).
/// - Neither — the implicit `<activation>.<method>` scope rule applies at
/// registry-build time (AUTHZ-CORE-4); the schema carries no
/// `requires_credential` for the implicit case.
/// Deprecated: use `plexus::method` instead.
/// Attribute macro for individual **child** methods within a
/// `#[plexus_macros::activation]` impl block.
///
/// Two method shapes are accepted:
///
/// | Shape | Role | Example |
/// |---|---|---|
/// | `fn NAME(&self) -> Child` (no args) | Static child — routing name is the method name | `fn mercury(&self) -> Mercury` |
/// | `fn NAME(&self, name: &str) -> Option<Child>` (sync or async) | Dynamic fallback dispatcher | `fn planet(&self, name: &str) -> Option<Planet>` |
///
/// The enclosing `#[plexus_macros::activation]` macro collects all `#[child]`
/// methods and generates a `ChildRouter` impl whose `get_child(name)`
/// dispatches over them. `#[child]` methods are **not** exposed as Plexus RPC
/// methods — they contribute only to `ChildRouter` routing.
///
/// # Example
///
/// ```ignore
/// #[plexus_macros::activation(namespace = "solar")]
/// impl Solar {
/// #[plexus_macros::child]
/// fn mercury(&self) -> Mercury { self.mercury.clone() }
///
/// #[plexus_macros::child]
/// async fn planet(&self, name: &str) -> Option<Planet> {
/// self.lookup_planet(name).await
/// }
/// }
/// ```
///
/// Used standalone (outside an `#[activation]` block) this attribute is a
/// no-op that returns the function unchanged.
/// Companion attribute to Rust's built-in `#[deprecated]` for carrying a
/// `removed_in = "VERSION"` hint that rustc doesn't recognize.
///
/// Rust's `#[deprecated(since = "X", note = "Y")]` supports only `since` and
/// `note`. This companion attribute supplies the removal version that the
/// `plexus-macros` codegen folds into the method's `DeprecationInfo.removed_in`
/// field on the emitted `MethodSchema`.
///
/// # Example
///
/// ```ignore
/// #[deprecated(since = "0.5", note = "use `new_method` instead")]
/// #[plexus_macros::removed_in("0.6")]
/// #[plexus_macros::method]
/// async fn legacy(&self) -> impl Stream<Item = String> + Send + 'static {
/// // ...
/// }
/// ```
///
/// # Requirements
///
/// `#[plexus_macros::removed_in]` is only meaningful when paired with
/// `#[deprecated]`. The `#[plexus_macros::activation]` macro emits a compile
/// error when it encounters `#[removed_in]` on a method that doesn't also
/// carry `#[deprecated]`.
///
/// As a standalone attribute (outside an `#[activation]` block) this is a
/// no-op that returns the item unchanged — the activation macro parses and
/// strips it during codegen.
/// Attribute macro for impl blocks defining a Plexus activation.
///
/// Generates:
/// - Method enum for schema extraction
/// - Activation trait implementation
/// - RPC server trait and implementation
///
/// # Attributes
///
/// - `namespace = "..."` (required) - The activation namespace
/// - `version = "..."` (optional, default: "1.0.0") - Version string
/// - `description = "..."` (optional) - Activation description
/// - `crate_path = "..."` (optional, default: "crate") - Path to substrate crate
/// - `client` (optional flag) - also emit the typed client (MACRO-2, below)
/// - `server_cfg = "<cfg predicate>"` (optional) - compile the server half
/// only under that `cfg` (MACRO-2, below)
///
/// # Example
///
/// ```ignore
/// #[plexus::activation(namespace = "bash", version = "1.0.0", description = "Execute bash commands")]
/// impl Bash {
/// /// Execute a bash command and stream output
/// #[plexus::method]
/// async fn execute(&self, command: String) -> impl Stream<Item = BashEvent> + Send + 'static {
/// self.executor.execute(&command).await
/// }
/// }
/// ```
///
/// # The typed client (`client`, `server_cfg`) — MACRO-2
///
/// The macro already knows, when it runs, every method's wire name, its
/// parameters and its `Stream<Item = E>` event type. With `client` it also
/// emits a **typed client** for the activation, so a Rust consumer never
/// hand-writes a call site or hand-mirrors an event type:
///
/// ```ignore
/// #[plexus_macros::activation(namespace = "tickets", client)]
/// impl Tickets { /* unchanged */ }
///
/// // emitted beside the impl:
/// let client = TicketsClient::new(transport); // any plexus_client::Transport
/// let mut watch = client.watch(Some("MACRO".into())); // EventStream<'_, TicketsEvent>
/// let all = client.list_all(None, None, None).await?; // Vec<TicketsEvent>
/// ```
///
/// The client is generic over the transport, so the emitted code names none
/// of them; its parameter and event types are the activation's own, so a
/// change to either is a compile error in every consumer.
///
/// **Requires** the consuming crate to depend on `plexus-client`. A
/// proc-macro crate cannot check that for you at expansion time in general,
/// but the path is resolved through `proc-macro-crate`, so a missing
/// dependency is reported at the `client` flag rather than as an unresolved
/// import in code you did not write.
///
/// **`server_cfg = "..."`** puts the *server* half of the expansion — the
/// impl block, the method enum, the `Activation` impl, the jsonrpsee trait —
/// behind a `cfg`, while the client half stays unconditional. That is what
/// makes an activation crate reachable from `wasm32-unknown-unknown`:
///
/// ```ignore
/// // Cargo.toml: server deps are optional and behind `feature = "server"`.
/// // plexus-macros itself stays non-optional — a proc-macro crate is built
/// // for the host, so it costs a wasm32 build nothing.
/// #[plexus_macros::activation(
/// namespace = "tickets",
/// client,
/// server_cfg = "feature = \"server\"",
/// )]
/// impl Tickets { /* .. */ }
/// ```
///
/// A consumer then says one line — `tickets-api = { version = "..",
/// default-features = false }` — and gets the types and the client, with no
/// tokio, jsonrpsee or plexus-core anywhere in its tree. Gating your own
/// struct definition and server-only imports is still yours to do; the macro
/// only gates its own output.
///
/// Both flags are opt-in: an activation that names neither expands exactly
/// as it did before.
/// Deprecated: use `plexus::activation` instead.
/// Derive macro for declaring credential-bearing fields on a return-type
/// struct or enum (per `AUTHZ-CRED-MACRO-1`).
///
/// Apply `#[derive(Credentials)]` to a struct or enum. Within the item,
/// annotate each credential-bearing field with the helper attribute
/// `#[credential(kind = "...", attach_as = "...", ...)]` carrying the
/// per-field metadata. The field's type must be `Credential<T>` (the sealed
/// wrapper from `plexus_auth_core`); any other type produces a compile
/// error citing the wrapper requirement.
///
/// **Why a derive macro and not a freestanding attribute macro?** Stable Rust
/// proc-macros cannot intercept attribute macros applied directly to struct
/// fields; only derive-helper attributes can appear there. See
/// `plans/AUTHZ/AUTHZ-CRED-MACRO-1-RUN-NOTES.md` for the rationale.
///
/// # Example
///
/// ```ignore
/// use plexus_auth_core::{
/// AttachmentSite, Credential, CredentialKind, CredentialScheme,
/// HeaderName, MethodPath, Scope,
/// };
///
/// // `CredentialFieldMarker` lands in plexus-auth-core in a follow-up; for
/// // now the macro emits code that references it by name and consumers
/// // provide the definition (see run-notes).
///
/// #[derive(plexus_macros::Credentials, serde::Serialize)]
/// pub struct LoginEvent {
/// pub user_id: String,
///
/// #[credential(
/// kind = "bearer",
/// attach_as = "header:authorization",
/// scheme = "Bearer ",
/// )]
/// pub session: Credential<String>,
/// }
/// ```
///
/// # Clauses
///
/// | Clause | Required? | Notes |
/// |---|---|---|
/// | `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. |
/// | `attach_as = "<spec>"` | required | One of `"header:<name>"`, `"cookie:<name>"`, `"first_frame:<setup-method>:<param>"`, `"in_rpc_param:<name>"`. |
/// | `scheme = "<prefix>"` | optional | E.g. `"Bearer "` (trailing space significant). |
/// | `scopes = ["a.b", ...]` | optional, default empty | List of scope identifiers. |
/// | `refresh_via = "<method-path>"` | optional | E.g. `"auth.refresh"`. |
/// | `revoke_via = "<method-path>"` | optional | E.g. `"auth.logout"`. |
/// | `sensitive` | optional flag | Accepted for clarity; credentials are always sensitive. |
///
/// # Emitted artifacts
///
/// The macro emits two free functions in the same module:
///
/// - `fn __plexus_credential_marker_for_<TypeIdent>() -> Vec<CredentialFieldMarker>`
/// - `fn __plexus_sensitive_fields_for_<TypeIdent>() -> Vec<(Option<&'static str>, &'static str)>`
///
/// The consumer (per `AUTHZ-CRED-CORE-3`) calls the first function during
/// schema build; the second mirrors the implicit `#[sensitive]` rule for the
/// redaction pipeline (per `AUTHZ-PRIVACY-2`).
///
/// The emitted code requires `CredentialFieldMarker`, `CredentialKind`,
/// `AttachmentSite`, `CredentialScheme`, `Scope`, `MethodPath`, `HeaderName`,
/// `CookieName`, `ParamName`, and `CredentialKindName` to be in scope at the
/// emission site. Importing `plexus_auth_core::*` (or the equivalent named
/// imports) at the top of the consuming module satisfies all but
/// `CredentialFieldMarker`, which lands in `plexus_auth_core` in a follow-up.
/// **DEPRECATED**: This derive macro is no longer needed.
///
/// With the caller-wraps streaming architecture, event types no longer need to
/// implement `ActivationStreamItem`. Just use plain domain types with standard
/// derives:
///
/// ```ignore
/// #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
/// #[serde(tag = "event", rename_all = "snake_case")]
/// pub enum MyEvent {
/// Data { value: String },
/// Complete { result: i32 },
/// }
/// ```
///
/// The wrapping happens at the call site via `wrap_stream()`.
/// Derive macro for type-safe handle creation and parsing.
///
/// Generates:
/// - `to_handle(&self) -> Handle` - converts enum variant to Handle
/// - `impl TryFrom<&Handle>` - parses Handle back to enum variant
/// - `impl From<EnumName> for Handle` - convenience conversion
///
/// # Attributes
///
/// Enum-level (required):
/// - `plugin_id = "CONSTANT_NAME"` - Name of the constant holding the plugin UUID
/// - `version = "1.0.0"` - Semantic version for handles
/// - `crate_path = "..."` (optional, default: "plexus_core") - Path to plexus_core crate
/// - `plugin_id_type = "Type<Args>"` (optional) - Concrete type whose associated
/// constant `plugin_id` names. Use this when the owning activation is generic
/// (e.g. `Cone<P: HubContext = NoParent>`) to pin the instantiation and avoid
/// E0283 "cannot infer type" errors. Pairs with `plugin_id` — e.g.
/// `plugin_id = "Cone::PLUGIN_ID", plugin_id_type = "Cone<NoParent>"` emits
/// `<Cone<NoParent>>::PLUGIN_ID`.
///
/// Variant-level:
/// - `method = "..."` (required) - The handle.method value
/// - `table = "..."` (optional) - SQLite table name (for future resolution)
/// - `key = "..."` (optional) - Primary key column (for future resolution)
///
/// # Example
///
/// ```ignore
/// use hub_macro::HandleEnum;
/// use uuid::Uuid;
///
/// pub const MY_PLUGIN_ID: Uuid = uuid::uuid!("550e8400-e29b-41d4-a716-446655440000");
///
/// #[derive(HandleEnum)]
/// #[handle(plugin_id = "MY_PLUGIN_ID", version = "1.0.0")]
/// pub enum MyPluginHandle {
/// #[handle(method = "event", table = "events", key = "id")]
/// Event { event_id: String },
///
/// #[handle(method = "message")]
/// Message { message_id: String, role: String },
/// }
///
/// // Usage:
/// let handle_enum = MyPluginHandle::Event { event_id: "evt-123".into() };
/// let handle: Handle = handle_enum.to_handle();
/// // handle.method == "event"
/// // handle.meta == ["evt-123"]
///
/// // Parsing back:
/// let parsed = MyPluginHandle::try_from(&handle)?;
/// ```
/// Derive macro for typed HTTP/WebSocket request extraction.
///
/// Generates `impl PlexusRequest` (extraction) and `impl schemars::JsonSchema`
/// (with `x-plexus-source` extensions) for the annotated struct.
///
/// # Field annotations
///
/// - `#[from_cookie("name")]` — extract from named cookie
/// - `#[from_header("name")]` — extract from named HTTP header
/// - `#[from_query("name")]` — extract from named URI query parameter
/// - `#[from_peer]` — copy `ctx.peer` (peer socket address)
/// - `#[from_auth_context]` — copy `ctx.auth` (auth context)
/// - (no annotation) — `Default::default()`
///
/// # Example
///
/// ```ignore
/// use plexus_macros::PlexusRequest;
///
/// #[derive(PlexusRequest)]
/// struct MyRequest {
/// #[from_cookie("access_token")]
/// auth_token: String,
///
/// #[from_header("origin")]
/// origin: Option<String>,
///
/// #[from_peer]
/// peer_addr: Option<std::net::SocketAddr>,
/// }
/// ```
/// No-op `JsonSchema` derive — used when plexus-macros is aliased as `schemars`
/// in dev-dependencies to prevent duplicate `impl JsonSchema` conflicts with
/// `#[derive(PlexusRequest)]` (which generates its own `impl JsonSchema`).
///
/// When plexus-macros is aliased as schemars in dev-deps:
/// ```toml
/// [dev-dependencies]
/// schemars = { path = "../plexus-macros", package = "plexus-macros", features = ["schemars-compat"] }
/// ```
/// then `#[derive(schemars::JsonSchema)]` invokes THIS derive instead of the real schemars derive,
/// producing no output, so only `PlexusRequest`'s `impl JsonSchema` exists.