lariv-rs 0.1.0

Compile-time plugin web application framework built on Axum, SeaORM, Maud, and HTMX
Documentation
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
//! Uniform capability shape: hooks + items, infallible [`Capability::mount`] → [`Tagged`].
//!
//! Every Lariv capability follows the same builder pattern: a [`CapStore`] holds deferred
//! plugin hooks and initial items; at mount time hooks fold over items and the result is
//! wrapped in a [`Tagged`] value on the app's capability HList.
//!
//! # Core types
//!
//! - [`HasCapTag`] — tag identity for builder-phase stores
//! - [`Capability`] — mount contract (`hooks` + `items` → [`Tagged`])
//! - [`CapStore`] — shared hooks/items container keyed by phantom `Tag`
//! - [`ApplyHooks`] — fold hook HList over items (tail first = install order)
//! - [`CapHookExt`] — prepend plugin hooks on custom builder capabilities (`cap_hook` install step)
//! - [`FoldMount`] — fold a builder HList of capabilities into mounted outputs
//!
//! # Registrar capabilities
//!
//! Item-list capabilities (templates, slots, migrations, commands) use [`RegistrarItems`],
//! [`FoldRegistrarHooks`], and the `apply_registrar_hook!` macro. Opaque capabilities
//! ([`crate::apps::AppsCapability`], [`crate::llm_tools::LlmToolsCapability`], …) implement
//! dedicated [`ApplyHooks`] impls instead. Deployment-local capabilities use a local struct
//! with [`Capability`] + [`CapHookExt`] and register via `cap_attach` / `cap_hook` in
//! [`define_plugin_install!`](crate::plugin_install::define_plugin_install).
//!
//! # Plugin macros
//!
//! - [`define_register_items!`] — declare item tags + `Register*` hook impl
//! - [`define_replace_templates!`] — replace tagged templates at compile-time indices
//! - [`define_passthrough_cap!`] — mount items as plain [`Tagged::new`](Tagged::new)(items)
//!
//! # Examples
//!
//! ```rust ignore
//! // Passthrough state capability (no hooks):
//! define_passthrough_cap!(UsersStateCap, UsersTag, UsersState);
//!
//! // Template items + register hook:
//! define_register_items! {
//!     plugin: UsersTag;
//!     capability: TemplateCapability;
//!     trait: RegisterTemplates;
//!     method: register_templates;
//!     wrapper: TemplateOf;
//!     bounds: [Clone, ProvideRequestCaps, Send, Sync];
//!     hook: RegisterTemplatesHook;
//!     items: [LoginIdx: UsersLoginPageTag => LoginPage]
//! }
//! ```

use std::marker::PhantomData;

use frunk::{HCons, HNil};

use crate::tag::Tagged;

/// Tag identity for builder-phase capability stores (independent of [`Capability`]).
///
/// Lookup/`add_hook` work on stores that do not yet implement [`Capability`] (e.g. Http
/// with pending mount-route hooks).
pub trait HasCapTag {
    type Tag;
}

/// Prepend a plugin hook onto a builder-phase capability (for
/// [`define_plugin_install!`](crate::plugin_install::define_plugin_install) `cap_hook`).
pub trait CapHookExt<Plugin, Hook>: HasCapTag + Sized {
    type Hooked: HasCapTag<Tag = Self::Tag>;
    fn prepend_cap_hook(self, hook: Hook) -> Self::Hooked;
}

impl<Tag, Hooks, Items, Plugin, Hook> CapHookExt<Plugin, Hook> for CapStore<Tag, Hooks, Items> {
    type Hooked = CapStore<Tag, HCons<Tagged<Plugin, Hook>, Hooks>, Items>;

    fn prepend_cap_hook(self, hook: Hook) -> Self::Hooked {
        self.add_hook::<Plugin, Hook>(hook)
    }
}

impl<Tag, Hooks, Items> HasCapTag for CapStore<Tag, Hooks, Items> {
    type Tag = Tag;
}

/// Builder-phase capability: deferred hooks applied to items, then folded to [`Tagged`].
pub trait Capability: HasCapTag + Sized {
    /// Always `Tagged<Self::Tag, Self::Value>`.
    type Output;
    type Value;
    type Hooks;
    type Items;

    fn mount(self) -> Self::Output;
}

/// Shared hooks + items store keyed by `Tag`.
#[derive(Clone, Debug)]
pub struct CapStore<Tag, Hooks, Items> {
    pub hooks: Hooks,
    pub items: Items,
    _tag: PhantomData<fn() -> Tag>,
}

impl<Tag, Hooks, Items> CapStore<Tag, Hooks, Items> {
    /// Construct a store with explicit hooks and items.
    ///
    /// Use when a capability starts with a non-empty hook HList (e.g. after
    /// [`add_hook`](Self::add_hook) in a plugin install chain).
    ///
    /// # Examples
    ///
    /// ```rust ignore
    /// let cap = CapStore::<MyTag, _, _>::new(my_hooks, my_items);
    /// ```
    pub fn new(hooks: Hooks, items: Items) -> Self {
        Self {
            hooks,
            items,
            _tag: PhantomData,
        }
    }

    /// Construct a store with default (empty) hooks and the given items.
    ///
    /// Typical for capabilities whose hooks start as [`HNil`] and are prepended during
    /// plugin install via [`add_hook`](Self::add_hook).
    pub fn empty_hooks(items: Items) -> Self
    where
        Hooks: Default,
    {
        Self::new(Hooks::default(), items)
    }
}

impl<Tag, Items> CapStore<Tag, HNil, Items> {
    /// Construct a hook-free store (common entry point for [`with_*`](crate::db::with_db) helpers).
    ///
    /// Equivalent to `CapStore::new(HNil, items)`.
    ///
    /// # Examples
    ///
    /// ```rust ignore
    /// app.add_capability(CapStore::with_items(DbState { conn }))
    /// ```
    pub fn with_items(items: Items) -> Self {
        Self::new(HNil, items)
    }
}

/// Marker for plugin tags whose [`CapStore`] with [`HNil`] hooks mounts as plain [`Tagged::new`](Tagged::new)(items).
pub trait PassthroughCapTag {}

impl<Tag, Items> Capability for CapStore<Tag, HNil, Items>
where
    Tag: PassthroughCapTag,
{
    type Value = Items;
    type Output = Tagged<Tag, Items>;
    type Hooks = HNil;
    type Items = Items;

    fn mount(self) -> Self::Output {
        Tagged::new(self.items)
    }
}

impl<Tag, Hooks, Items> CapStore<Tag, Hooks, Items> {
    /// Prepend a tagged hook.
    pub fn add_hook<HTag, H>(self, hook: H) -> CapStore<Tag, HCons<Tagged<HTag, H>, Hooks>, Items> {
        CapStore {
            hooks: HCons {
                head: Tagged::new(hook),
                tail: self.hooks,
            },
            items: self.items,
            _tag: PhantomData,
        }
    }

    /// Prepend a tagged item.
    pub fn add_item<ITag, I>(self, item: I) -> CapStore<Tag, Hooks, HCons<Tagged<ITag, I>, Items>> {
        CapStore {
            hooks: self.hooks,
            items: HCons {
                head: Tagged::new(item),
                tail: self.items,
            },
            _tag: PhantomData,
        }
    }

    /// Transform items in place, preserving hooks (e.g. prepend default commands before mount).
    ///
    /// # Examples
    ///
    /// ```rust ignore
    /// cap.map_items(|items| items.prepend::<MyCmdTag, _>(MyCommand))
    /// ```
    pub fn map_items<F, NewItems>(self, f: F) -> CapStore<Tag, Hooks, NewItems>
    where
        F: FnOnce(Items) -> NewItems,
    {
        CapStore {
            hooks: self.hooks,
            items: f(self.items),
            _tag: PhantomData,
        }
    }

    /// Transform hooks in place, preserving items.
    pub fn map_hooks<F, NewHooks>(self, f: F) -> CapStore<Tag, NewHooks, Items>
    where
        F: FnOnce(Hooks) -> NewHooks,
    {
        CapStore {
            hooks: f(self.hooks),
            items: self.items,
            _tag: PhantomData,
        }
    }
}

/// Fold hooks over items (tail first = registration / install order).
///
/// `Proof` carries frunk indices (and nested proofs from earlier hooks), matching
/// [`crate::http::FoldMountRoutes`]. Default `()` is for [`HNil`] / no-index hooks.
pub trait ApplyHooks<Items, Proof = ()>: Sized {
    type Output;
    fn apply_hooks(self, items: Items) -> Self::Output;
}

impl<Items> ApplyHooks<Items, ()> for HNil {
    type Output = Items;

    fn apply_hooks(self, items: Items) -> Self::Output {
        items
    }
}

/// Marks item types folded by [`apply_registrar_hook!`] (frunk HLists). Opaque
/// capabilities ([`crate::apps::AppsCapability`], [`crate::llm_tools::LlmToolsCapability`], …)
/// use dedicated [`ApplyHooks`] impls instead.
mod registrar_items {
    pub trait Sealed {}
    impl Sealed for ::frunk::HNil {}
    impl<Head, Tail> Sealed for ::frunk::HCons<Head, Tail> where Tail: Sealed {}
}

pub trait RegistrarItems: registrar_items::Sealed {}

impl<T> RegistrarItems for T where T: registrar_items::Sealed {}

/// Proof token for [`crate::template::TemplateRegistrar`] hook folding.
pub struct TemplateHookProof;

/// Proof token for [`crate::components::SlotRegistrar`] hook folding.
pub struct SlotHookProof;

/// Proof token for [`crate::migration::MigrationRegistrar`] hook folding.
pub struct MigrationHookProof;

/// Proof token for [`crate::command::CommandRegistrar`] hook folding.
pub struct CommandHookProof;

/// Fold registrar hooks without a proof tuple (used by [`CapStore::resolve_hooks`]).
pub trait FoldRegistrarHooks<Tag, Items> {
    type Output;
    fn fold_registrar_hooks(self, items: Items) -> Self::Output;
}

impl<Tag, Items> FoldRegistrarHooks<Tag, Items> for HNil {
    type Output = Items;

    fn fold_registrar_hooks(self, items: Items) -> Self::Output {
        items
    }
}

/// `ApplyHooks` for a local hook type that implements a registrar trait.
macro_rules! apply_registrar_hook {
    (
        capability: $cap:ident;
        trait: $trait:ident;
        method: $method:ident;
        field: $field:ident;
        proof: $proof:ty;
        tag: $tag:ty;
    ) => {
        impl<Plugin, H, Tail, Items, TailOut, Out, TailProof>
            $crate::capability::ApplyHooks<Items, (TailProof, $proof)>
            for ::frunk::HCons<$crate::tag::Tagged<Plugin, H>, Tail>
        where
            Items: $crate::capability::RegistrarItems,
            Tail: $crate::capability::ApplyHooks<Items, TailProof, Output = TailOut>,
            H: $trait<TailOut, Output = Out>,
        {
            type Output = Out;

            fn apply_hooks(self, items: Items) -> Self::Output {
                let items = self.tail.apply_hooks(items);
                H::$method(self.head.value, $cap { $field: items }).$field
            }
        }

        impl<Plugin, H, Tail, Items, TailOut, Out>
            $crate::capability::FoldRegistrarHooks<$tag, Items>
            for ::frunk::HCons<$crate::tag::Tagged<Plugin, H>, Tail>
        where
            Items: $crate::capability::RegistrarItems,
            Tail: $crate::capability::FoldRegistrarHooks<$tag, Items, Output = TailOut>,
            H: $trait<TailOut, Output = Out>,
        {
            type Output = Out;

            fn fold_registrar_hooks(self, items: Items) -> Self::Output {
                let items = self.tail.fold_registrar_hooks(items);
                H::$method(self.head.value, $cap { $field: items }).$field
            }
        }
    };
}

pub(crate) use apply_registrar_hook;

/// Declare item tags and a `Register*` impl for a marker-style capability.
///
/// Two item shapes are supported (add-order; last entry is HList head):
///
/// - `Tag => Value` — `add::<Tag, Value>()` → `Tagged<Tag, Wrapper<Value>>`
///   (templates)
/// - `Tag, Kind => Value` — `add::<Tag, Kind, Value>()` →
///   `Tagged<Tag, Wrapper<Kind, Value>>` (slots)
/// - empty `items: []` — identity `Register*` (hook queued, nothing added)
///
/// `$idx` names are call-site documentation matching index generics in
/// [`crate::plugin_routes::define_plugin_routes`]; frunk indices are inferred
/// from the concrete [`frunk::HList!`] `Output`.
///
/// ```ignore
/// define_register_items! {
///     plugin: UsersTag;
///     capability: TemplateCapability;
///     trait: RegisterTemplates;
///     method: register_templates;
///     wrapper: TemplateOf;
///     bounds: [Clone, ProvideRequestCaps, Send, Sync];
///     items: [
///         LoginIdx: UsersLoginPageTag => LoginPage,
///     ]
/// }
///
/// define_register_items! {
///     plugin: UsersTag;
///     capability: SlotCapability;
///     trait: RegisterSlots;
///     method: register_slots;
///     bounds: [];
///     items: [];
/// }
/// ```
#[macro_export]
macro_rules! define_register_items {
    // --- identity (no items) ---
    (
        plugin: $plugin:ty;
        capability: $cap:ident;
        trait: $trait:ident;
        method: $method:ident;
        bounds: [$($bound:path),* $(,)?];
        items: [];
        hook: $hook:ident;
    ) => {
        #[derive(Clone, Copy, Default)]
        pub struct $hook;

        impl<T: ::frunk::hlist::HList $(+ $bound)*> $trait<T> for $hook {
            type Output = T;

            fn $method(self, cap: $cap<T>) -> $cap<Self::Output> {
                cap
            }
        }
    };

    // --- two-param add (`Tag => Value`) ---
    (
        plugin: $plugin:ty;
        capability: $cap:ident;
        trait: $trait:ident;
        method: $method:ident;
        wrapper: $wrapper:ident;
        bounds: [$($bound:path),* $(,)?];
        hook: $hook:ident;
        items: [
            $($idx:ident : $tag:ident => $value:ty),+ $(,)?
        ]
    ) => {
        $(
            pub struct $tag;
        )+

        $crate::capability::define_register_items!(
            @impl2 $plugin;
            $cap;
            $trait;
            $method;
            $wrapper;
            $hook;
            [$($bound),*];
            [];
            [];
            $($tag => $value),+
        );
    };

    (
        @impl2 $plugin:ty;
        $cap:ident;
        $trait:ident;
        $method:ident;
        $wrapper:ident;
        $hook:ident;
        [$($bound:path),*];
        [$($rev_tag:ident => $rev_value:ty),*];
        [$($fwd_tag:ident => $fwd_value:ty),*];
        $tag:ident => $value:ty
        $(, $rest_tag:ident => $rest_value:ty)*
    ) => {
        $crate::capability::define_register_items!(
            @impl2 $plugin;
            $cap;
            $trait;
            $method;
            $wrapper;
            $hook;
            [$($bound),*];
            [$tag => $value $(, $rev_tag => $rev_value)*];
            [$($fwd_tag => $fwd_value,)* $tag => $value];
            $($rest_tag => $rest_value),*
        );
    };
    (
        @impl2 $plugin:ty;
        $cap:ident;
        $trait:ident;
        $method:ident;
        $wrapper:ident;
        $hook:ident;
        [$($bound:path),*];
        [$($rev_tag:ident => $rev_value:ty),+];
        [$($fwd_tag:ident => $fwd_value:ty),+];
    ) => {
        #[derive(Clone, Copy, Default)]
        pub struct $hook;

        #[allow(
            clippy::type_complexity,
            reason = "HList![…] of registered items plus prior plugins' T"
        )]
        impl<T: ::frunk::hlist::HList $(+ $bound)*> $trait<T> for $hook {
            type Output = ::frunk::HList![
                $($crate::tag::Tagged<$rev_tag, $wrapper<$rev_value>>),+,
                ...T
            ];

            fn $method(self, cap: $cap<T>) -> $cap<Self::Output> {
                cap
                    $(.add::<$fwd_tag, $fwd_value>())+
            }
        }
    };

    // --- three-param add (`Tag, Kind => Value`) ---
    (
        plugin: $plugin:ty;
        capability: $cap:ident;
        trait: $trait:ident;
        method: $method:ident;
        wrapper: $wrapper:ident;
        bounds: [$($bound:path),* $(,)?];
        hook: $hook:ident;
        items: [
            $($idx:ident : $tag:ident, $kind:ty => $value:ty),+ $(,)?
        ]
    ) => {
        $(
            pub struct $tag;
        )+

        $crate::capability::define_register_items!(
            @impl3 $plugin;
            $cap;
            $trait;
            $method;
            $wrapper;
            $hook;
            [$($bound),*];
            [];
            [];
            $($tag, $kind => $value),+
        );
    };

    (
        @impl3 $plugin:ty;
        $cap:ident;
        $trait:ident;
        $method:ident;
        $wrapper:ident;
        $hook:ident;
        [$($bound:path),*];
        [$($rev_tag:ident, $rev_kind:ty => $rev_value:ty),*];
        [$($fwd_tag:ident, $fwd_kind:ty => $fwd_value:ty),*];
        $tag:ident, $kind:ty => $value:ty
        $(, $rest_tag:ident, $rest_kind:ty => $rest_value:ty)*
    ) => {
        $crate::capability::define_register_items!(
            @impl3 $plugin;
            $cap;
            $trait;
            $method;
            $wrapper;
            $hook;
            [$($bound),*];
            [$tag, $kind => $value $(, $rev_tag, $rev_kind => $rev_value)*];
            [$($fwd_tag, $fwd_kind => $fwd_value,)* $tag, $kind => $value];
            $($rest_tag, $rest_kind => $rest_value),*
        );
    };
    (
        @impl3 $plugin:ty;
        $cap:ident;
        $trait:ident;
        $method:ident;
        $wrapper:ident;
        $hook:ident;
        [$($bound:path),*];
        [$($rev_tag:ident, $rev_kind:ty => $rev_value:ty),+];
        [$($fwd_tag:ident, $fwd_kind:ty => $fwd_value:ty),+];
    ) => {
        #[derive(Clone, Copy, Default)]
        pub struct $hook;

        #[allow(
            clippy::type_complexity,
            reason = "HList![…] of registered items plus prior plugins' T"
        )]
        impl<T: ::frunk::hlist::HList $(+ $bound)*> $trait<T> for $hook {
            type Output = ::frunk::HList![
                $($crate::tag::Tagged<$rev_tag, $wrapper<$rev_kind, $rev_value>>),+,
                ...T
            ];

            fn $method(self, cap: $cap<T>) -> $cap<Self::Output> {
                cap
                    $(.add::<$fwd_tag, $fwd_kind, $fwd_value>())+
            }
        }
    };
}

pub use crate::define_register_items;

/// Register a template hook that replaces tagged pages (and optionally prepends new ones).
#[macro_export]
macro_rules! define_replace_templates {
    (
        hook: $hook:ident;
        bounds: [$($bound:path),* $(,)?];
        replaces: [$($idx:ident : $rep_tag:ident => $rep_value:ty),* $(,)?];
        adds: [$($add_tag:ident => $add_value:ty),* $(,)?];
    ) => {
        $crate::define_replace_templates!(
            @go $hook;
            [$($bound),*];
            T;
            [];
            [];
            [];
            $($idx, $rep_tag, $rep_value),*;
            $($add_tag, $add_value),*
        );
    };

    (
        @go $hook:ident;
        [$($bound:path),*];
        $acc:ty;
        [$($where_acc:ty => $where_idx:ident, $where_tag:ident, $where_value:ty);*];
        [$($done_idx:ident),*];
        [$($done_rep_tag:ident, $done_rep_value:ty),*];
        $idx:ident, $rep_tag:ident, $rep_value:ty
        $(, $rest_idx:ident, $rest_tag:ident, $rest_value:ty)*;
        $($add_tag:ident, $add_value:ty),*
    ) => {
        $crate::define_replace_templates!(
            @go $hook;
            [$($bound),*];
            $crate::traits::get::ReplaceTemplateAtTag<
                $acc,
                $rep_tag,
                $crate::template::TemplateOf<$rep_value>,
                $idx
            >;
            [$($where_acc => $where_idx, $where_tag, $where_value;)* $acc => $idx, $rep_tag, $rep_value];
            [$($done_idx,)* $idx];
            [$($done_rep_tag, $done_rep_value,)* $rep_tag, $rep_value];
            $($rest_idx, $rest_tag, $rest_value),*;
            $($add_tag, $add_value),*
        );
    };

    (
        @go $hook:ident;
        [$($bound:path),*];
        $acc:ty;
        [$($where_acc:ty => $where_idx:ident, $where_tag:ident, $where_value:ty);*];
        [$($idx:ident),*];
        [$($rep_tag:ident, $rep_value:ty),*];
        ;
        $($add_tag:ident, $add_value:ty),*
    ) => {
        $crate::define_replace_templates!(
            @finish $hook;
            [$($bound),*];
            $acc;
            [$($where_acc => $where_idx, $where_tag, $where_value);*];
            [$($idx),*];
            [$($rep_tag, $rep_value),*];
            $($add_tag, $add_value),*
        );
    };

    (
        @finish $hook:ident;
        [$($bound:path),*];
        $acc:ty;
        [$($where_acc:ty => $where_idx:ident, $where_tag:ident, $where_value:ty);*];
        [$($idx:ident),*];
        [$($rep_tag:ident, $rep_value:ty),*];
    ) => {
        #[derive(Clone, Copy, Default)]
        pub struct $hook;

        impl<T: ::frunk::hlist::HList $(+ $bound)* $(, $idx)*> $crate::template::TemplateRegistrar<T> for $hook
        where
            $acc: ::frunk::hlist::HList,
            $( $where_acc:
                $crate::traits::get::IndexOfTemplateTag<
                    $where_tag,
                    $where_idx
                >, )*
            $( $where_acc:
                $crate::traits::replace::MapByTag<
                    $where_tag,
                    $crate::template::TemplateOf<$where_value>,
                    $where_idx
                >, )*
        {
            type Output = $acc;

            fn register_templates(
                self,
                cap: $crate::template::TemplateCapability<T>,
            ) -> $crate::template::TemplateCapability<Self::Output> {
                cap
                    $(.replace_template_tag::<
                        $rep_tag,
                        $crate::template::TemplateOf<$rep_value>,
                        _,
                    >(|_| $crate::template::TemplateOf::new()))*
            }
        }
    };

    (
        @finish $hook:ident;
        [$($bound:path),*];
        $acc:ty;
        [$($where_acc:ty => $where_idx:ident, $where_tag:ident, $where_value:ty);*];
        [$($idx:ident),*];
        [$($rep_tag:ident, $rep_value:ty),*];
        $($add_tag:ident, $add_value:ty),+
    ) => {
        $crate::define_replace_templates!(
            @collect_adds $hook;
            [$($bound),*];
            $acc;
            [$($where_acc => $where_idx, $where_tag, $where_value);*];
            [$($idx),*];
            [$($rep_tag, $rep_value),*];
            [];
            [];
            $($add_tag, $add_value),+
        );
    };

    (
        @collect_adds $hook:ident;
        [$($bound:path),*];
        $acc:ty;
        [$($where_acc:ty => $where_idx:ident, $where_tag:ident, $where_value:ty);*];
        [$($idx:ident),*];
        [$($rep_tag:ident, $rep_value:ty),*];
        [$($rev_tag:ident, $rev_value:ty),*];
        [$($fwd_tag:ident, $fwd_value:ty),*];
        $add_tag:ident, $add_value:ty
        $(, $rest_tag:ident, $rest_value:ty)*
    ) => {
        $crate::define_replace_templates!(
            @collect_adds $hook;
            [$($bound),*];
            $acc;
            [$($where_acc => $where_idx, $where_tag, $where_value);*];
            [$($idx),*];
            [$($rep_tag, $rep_value),*];
            [$add_tag, $add_value $(, $rev_tag, $rev_value)*];
            [$($fwd_tag, $fwd_value,)* $add_tag, $add_value];
            $($rest_tag, $rest_value),*
        );
    };

    (
        @collect_adds $hook:ident;
        [$($bound:path),*];
        $acc:ty;
        [$($where_acc:ty => $where_idx:ident, $where_tag:ident, $where_value:ty);*];
        [$($idx:ident),*];
        [$($rep_tag:ident, $rep_value:ty),*];
        [$($rev_tag:ident, $rev_value:ty),+];
        [$($fwd_tag:ident, $fwd_value:ty),+];
    ) => {
        #[derive(Clone, Copy, Default)]
        pub struct $hook;

        #[allow(
            clippy::type_complexity,
            reason = "HList of prepended templates plus replaced chain"
        )]
        impl<T: ::frunk::hlist::HList $(+ $bound)* $(, $idx)*> $crate::template::TemplateRegistrar<T> for $hook
        where
            $acc: ::frunk::hlist::HList,
            $( $where_acc:
                $crate::traits::get::IndexOfTemplateTag<
                    $where_tag,
                    $where_idx
                >, )*
            $( $where_acc:
                $crate::traits::replace::MapByTag<
                    $where_tag,
                    $crate::template::TemplateOf<$where_value>,
                    $where_idx
                >, )*
        {
            type Output = ::frunk::HList![
                $($crate::tag::Tagged<
                    $rev_tag,
                    $crate::template::TemplateOf<$rev_value>
                >),+,
                ...$acc
            ];

            fn register_templates(
                self,
                cap: $crate::template::TemplateCapability<T>,
            ) -> $crate::template::TemplateCapability<Self::Output> {
                cap
                    $(.replace_template_tag::<
                        $rep_tag,
                        $crate::template::TemplateOf<$rep_value>,
                        _,
                    >(|_| $crate::template::TemplateOf::new()))*
                    $(.add::<$fwd_tag, $fwd_value>())+
            }
        }
    };
}

pub use crate::define_replace_templates;

/// `CapStore<Tag, HNil, Value>` that mounts as [`Tagged::new`](crate::tag::Tagged::new)(`items`).
///
/// ```ignore
/// define_passthrough_cap!(UsersStateCap, UsersTag, UsersState);
/// ```
#[macro_export]
macro_rules! define_passthrough_cap_impl {
    ($cap:ident, $tag:ty, $value:ty) => {
        pub type $cap = $crate::capability::CapStore<$tag, ::frunk::HNil, $value>;

        impl $crate::capability::PassthroughCapTag for $tag {}
    };
}

#[macro_export]
macro_rules! define_passthrough_cap {
    ($($tt:tt)*) => {
        $crate::define_passthrough_cap_impl! { $($tt)* }
    };
}

pub use crate::define_passthrough_cap;

/// Fold a builder HList of [`Capability`] values into mounted [`Tagged`] outputs.
pub trait FoldMount: Sized {
    type Output;
    fn fold_mount(self) -> Self::Output;
}

impl FoldMount for HNil {
    type Output = HNil;

    fn fold_mount(self) -> Self::Output {
        HNil
    }
}

impl<Head, Tail> FoldMount for HCons<Head, Tail>
where
    Head: Capability,
    Tail: FoldMount,
{
    type Output = HCons<Head::Output, Tail::Output>;

    fn fold_mount(self) -> Self::Output {
        HCons {
            head: self.head.mount(),
            tail: self.tail.fold_mount(),
        }
    }
}

/// Helper: apply hooks then wrap items as the mounted [`Tagged`] value.
pub fn mount_with_hooks<Tag, Hooks, Items, Value, F>(
    store: CapStore<Tag, Hooks, Items>,
    wrap: F,
) -> Tagged<Tag, Value>
where
    Hooks: ApplyHooks<Items>,
    F: FnOnce(Hooks::Output) -> Value,
{
    let items = store.hooks.apply_hooks(store.items);
    Tagged::new(wrap(items))
}