reinhardt-urls 0.2.2

URL routing and proxy utilities for Reinhardt framework
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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
//! Unified Router with closure-based server and client configuration.
//!
//! This module provides [`UnifiedRouter`], a unified entry point for configuring
//! both server-side HTTP routing and client-side SPA routing.
//!
//! # Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────┐
//! │             UnifiedRouter               │
//! │  ┌─────────────┐  ┌─────────────────┐   │
//! │  │ClientRouter │  │  ServerRouter   │   │
//! │  │ (WASM/SPA)  │  │ (HTTP/Backend)  │   │
//! │  └─────────────┘  └─────────────────┘   │
//! └─────────────────────────────────────────┘
//! ```
//!
//! # Example
//!
//! ```rust,ignore
//! use reinhardt_urls::routers::UnifiedRouter;
//! use reinhardt_core::page::Page;
//! use hyper::Method;
//!
//! let router = UnifiedRouter::new()
//!     .server(|s| s
//!         .with_prefix("/api/v1")
//!         .function("/users", Method::GET, list_users)
//!         .function("/users", Method::POST, create_user))
//!     .client(|c| c
//!         .route("home", "/", || home_page())
//!         .route_path("user_detail", "/users/{id}", |Path(id): Path<i64>| user_page(id)));
//! ```
//!
//! # Feature Flags
//!
//! - When `client-router` feature is **enabled**: Full [`UnifiedRouter`] with both
//!   `.server()` and `.client()` methods available.
//! - When `client-router` feature is **disabled**: Server-only [`UnifiedRouter`] with
//!   only `.server()` method available.

#[cfg(native)]
use crate::routers::server_router::ServerRouter;

#[cfg(feature = "client-router")]
use crate::routers::client_router::ClientRouter;

#[cfg(native)]
use hyper::Method;
#[cfg(native)]
use reinhardt_core::exception::Result;
#[cfg(native)]
use reinhardt_di::InjectionContext;
#[cfg(native)]
use reinhardt_http::{Request, Response};
#[cfg(native)]
use reinhardt_middleware::Middleware;
#[cfg(native)]
use std::future::Future;
#[cfg(native)]
use std::sync::Arc;

// ============================================================================
// client-router feature ENABLED
// ============================================================================

/// Unified router combining server and client routing capabilities.
///
/// This struct provides a unified interface for configuring both:
/// - **Server-side routes**: HTTP methods, middleware, DI, ViewSets
/// - **Client-side routes**: SPA navigation, history API, [`Page`] rendering
///
/// # Example
///
/// ```rust,ignore
/// use reinhardt_urls::routers::UnifiedRouter;
/// use reinhardt_core::page::Page;
///
/// let router = UnifiedRouter::new()
///     .server(|s| s.function("/api/health", Method::GET, health_handler))
///     .client(|c| c.route("home", "/", || home_page()));
/// ```
///
/// [`Page`]: reinhardt_core::page::Page
#[cfg(all(feature = "client-router", native))]
pub struct UnifiedRouter {
	server: ServerRouter,
	client: ClientRouter,
	/// WebSocket router for `urls.ws().<app>().<handler>()` URL resolution.
	pub websocket: reinhardt_core::ws::WebSocketRouter,
	di_registrations: reinhardt_di::DiRegistrationList,
	#[cfg(feature = "streaming")]
	streaming_handlers: Vec<reinhardt_streaming::StreamingHandlerRegistration>,
}

#[cfg(all(feature = "client-router", native))]
impl UnifiedRouter {
	/// Creates a new `UnifiedRouter` with default server and client routers.
	pub fn new() -> Self {
		Self {
			server: ServerRouter::new(),
			client: ClientRouter::new(),
			websocket: reinhardt_core::ws::WebSocketRouter::new(),
			di_registrations: reinhardt_di::DiRegistrationList::new(),
			#[cfg(feature = "streaming")]
			streaming_handlers: Vec::new(),
		}
	}

	/// Configure server-side routing with a closure.
	///
	/// The closure receives a [`ServerRouter`] and should return a configured router.
	///
	/// # Example
	///
	/// ```rust,ignore
	/// let router = UnifiedRouter::new()
	///     .server(|s| s
	///         .with_prefix("/api")
	///         .function("/users", Method::GET, list_users));
	/// ```
	pub fn server<F>(mut self, f: F) -> Self
	where
		F: FnOnce(ServerRouter) -> ServerRouter,
	{
		self.server = f(self.server);
		self
	}

	/// Configure client-side routing with a closure.
	///
	/// The closure receives a [`ClientRouter`] and should return a configured router.
	///
	/// # Example
	///
	/// ```rust,ignore
	/// let router = UnifiedRouter::new()
	///     .client(|c| c
	///         .route("home", "/", || home_page())
	///         .route_path("user_detail", "/users/{id}", |Path(id): Path<i64>| user_page(id)));
	/// ```
	pub fn client<F>(mut self, f: F) -> Self
	where
		F: FnOnce(ClientRouter) -> ClientRouter,
	{
		self.client = f(self.client);
		self
	}

	/// Returns a reference to the server router.
	pub fn server_ref(&self) -> &ServerRouter {
		&self.server
	}

	/// Returns a mutable reference to the server router.
	pub fn server_mut(&mut self) -> &mut ServerRouter {
		&mut self.server
	}

	/// Returns a reference to the client router.
	pub fn client_ref(&self) -> &ClientRouter {
		&self.client
	}

	/// Returns a mutable reference to the client router.
	pub fn client_mut(&mut self) -> &mut ClientRouter {
		&mut self.client
	}

	/// Configure WebSocket routing with a closure.
	///
	/// Parallel to `server()` and `client()`. The registered consumers are
	/// available via `UrlReverser::from_global().reverse("websocket:<app>:<handler>")`.
	///
	/// # Example
	///
	/// ```rust,ignore
	/// let router = UnifiedRouter::new()
	///     .websocket(|ws| ws
	///         .consumer(chat_ws)
	///         .consumer(notif_ws));
	/// ```
	pub fn websocket<F>(mut self, f: F) -> Self
	where
		F: FnOnce(reinhardt_core::ws::WebSocketRouter) -> reinhardt_core::ws::WebSocketRouter,
	{
		self.websocket = f(self.websocket);
		self
	}

	/// Returns a reference to the WebSocket router.
	pub fn websocket_ref(&self) -> &reinhardt_core::ws::WebSocketRouter {
		&self.websocket
	}

	/// Apply or stash deferred DI registrations.
	///
	/// If the server router already has a DI context, registrations are applied
	/// directly to its singleton scope. Otherwise they are stashed globally
	/// for later application (e.g., by the `runall` command).
	fn flush_di_registrations(&mut self) {
		if self.di_registrations.is_empty() {
			return;
		}
		let registrations = std::mem::take(&mut self.di_registrations);
		match self
			.server
			.di_context()
			.map(|ctx| Arc::clone(ctx.singleton_scope()))
		{
			Some(scope) => registrations.apply_to(&scope),
			None => crate::routers::register_di_registrations(registrations),
		}
	}

	/// Consumes the router and returns the server router.
	///
	/// If this router has a DI context, deferred DI registrations are applied
	/// directly to its singleton scope. Otherwise they are stashed in the
	/// global registry for later application by the server.
	pub fn into_server(mut self) -> ServerRouter {
		self.flush_di_registrations();
		let errors = self.server.register_all_routes();
		for error in &errors {
			tracing::warn!("{}", error);
		}
		self.server
	}

	/// Consumes the router and returns the client router.
	pub fn into_client(mut self) -> ClientRouter {
		self.flush_di_registrations();
		self.client
	}

	/// Consumes the router and returns both parts.
	pub fn into_parts(mut self) -> (ServerRouter, ClientRouter) {
		self.flush_di_registrations();
		let errors = self.server.register_all_routes();
		for error in &errors {
			tracing::warn!("{}", error);
		}
		(self.server, self.client)
	}

	/// Registers server router globally and returns client router.
	///
	/// This is a convenience method for full-stack applications that need to:
	/// 1. Register the server router globally for HTTP request handling
	/// 2. Keep the client router for SPA navigation
	///
	/// # Example
	///
	/// ```rust,ignore
	/// let client = UnifiedRouter::new()
	///     .server(|s| s.function("/api/data", Method::GET, handler))
	///     .client(|c| c.route("home", "/", || home_page()))
	///     .register_globally();
	///
	/// // Server router is now globally registered
	/// // Client router is returned for SPA use
	/// ```
	pub fn register_globally(self) -> ClientRouter {
		let (server, client) = self.into_parts();
		crate::routers::register_router(server);
		client
	}

	/// Attach deferred DI registrations to this router.
	///
	/// When the router is consumed, these registrations are applied directly
	/// to the DI context's singleton scope if one has been set via
	/// [`with_di_context`](Self::with_di_context). Otherwise they are stashed
	/// globally for later application (e.g., by the `runall` command).
	pub fn with_di_registrations(mut self, list: reinhardt_di::DiRegistrationList) -> Self {
		self.di_registrations.merge(list);
		self
	}

	// ========================================================================
	// Convenience delegations to ServerRouter
	// ========================================================================

	/// Set URL prefix for server router.
	///
	/// This is a convenience method that delegates to [`ServerRouter::with_prefix`].
	pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
		self.server = self.server.with_prefix(prefix);
		self
	}

	/// Set namespace for both server and client routers.
	///
	/// Delegates to [`ServerRouter::with_namespace`] and
	/// [`ClientRouter::with_namespace`] so that server-side URL resolvers
	/// and client-side named route keys are both prefixed consistently
	/// with `"<namespace>:"`. Fixes #3726.
	pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
		let ns: String = namespace.into();
		// Borrow for the client (accepts `&str`) first, then move the owned
		// `String` into the server (accepts `impl Into<String>`) to avoid a
		// redundant `String` allocation.
		self.client = self.client.with_namespace(&ns);
		self.server = self.server.with_namespace(ns);
		self
	}

	/// Set DI context for server router.
	///
	/// This is a convenience method that delegates to [`ServerRouter::with_di_context`].
	pub fn with_di_context(mut self, ctx: Arc<InjectionContext>) -> Self {
		self.server = self.server.with_di_context(ctx);
		self
	}

	/// Add middleware to server router.
	///
	/// This is a convenience method that delegates to [`ServerRouter::with_middleware`].
	///
	/// Any DI singleton registrations contributed by the middleware (via
	/// [`Middleware::di_registrations`]) are merged into this router's
	/// deferred DI registration list so that handlers resolved through
	/// `#[inject]` can see middleware-owned state without a parallel
	/// `with_di_registrations(...)` call. See #4426.
	pub fn with_middleware<M: Middleware + 'static>(mut self, middleware: M) -> Self {
		for (type_id, value) in middleware.di_registrations() {
			self.di_registrations.register_arc_any(type_id, value);
		}
		self.server = self.server.with_middleware(middleware);
		self
	}

	/// Exclude a URL path from the most recently added server middleware.
	///
	/// This is a convenience method that delegates to [`ServerRouter::exclude`].
	pub fn exclude(mut self, pattern: &str) -> Self {
		self.server = self.server.exclude(pattern);
		self
	}

	/// Mount a child server router on this router.
	///
	/// This is a convenience method that delegates to [`ServerRouter::mount`].
	pub fn mount(mut self, prefix: &str, child: ServerRouter) -> Self {
		self.server = self.server.mount(prefix, child);
		self
	}

	/// Mount a child UnifiedRouter on this router.
	///
	/// Mounts the child's server router under `prefix` and merges its client
	/// routes into the parent. Client named routes are preserved with index
	/// offset adjustment so that `url_for("app:route")` resolves on the
	/// project-level unified `UrlReverser`.
	///
	/// The `prefix` argument is applied to server routes only; client routes
	/// keep their patterns as-declared, mirroring the WASM behavior.
	pub fn mount_unified(mut self, prefix: &str, child: UnifiedRouter) -> Self {
		self.client = self.client.merge(child.client);
		self.mount(prefix, child.server)
	}

	/// Mount streaming handlers (producers and consumers) on this router.
	///
	/// Registrations are stored on the router for Phase 3 worker startup.
	/// Consumer worker startup is deferred to a later server startup phase.
	#[cfg(feature = "streaming")]
	pub fn mount_streaming(mut self, router: reinhardt_streaming::StreamingRouter) -> Self {
		self.streaming_handlers.extend(router.into_handlers());
		self
	}

	/// Register an endpoint on server router.
	///
	/// This is a convenience method that delegates to [`ServerRouter::endpoint`].
	pub fn endpoint<F, E>(mut self, f: F) -> Self
	where
		F: FnOnce() -> E,
		E: reinhardt_core::endpoint::EndpointInfo + reinhardt_http::Handler + 'static,
	{
		self.server = self.server.endpoint(f);
		self
	}

	/// Register a function-based route on server router.
	///
	/// This is a convenience method that delegates to [`ServerRouter::function`].
	pub fn function<F, Fut>(mut self, path: &str, method: Method, func: F) -> Self
	where
		F: Fn(Request) -> Fut + Send + Sync + 'static,
		Fut: Future<Output = Result<Response>> + Send + 'static,
	{
		self.server = self.server.function(path, method, func);
		self
	}

	/// Register a named function-based route on server router.
	///
	/// This is a convenience method that delegates to [`ServerRouter::function_named`].
	#[deprecated(
		since = "0.2.0",
		note = "Use `#[get(\"/path\", name = \"name\")]` + `.endpoint()` instead"
	)]
	pub fn function_named<F, Fut>(mut self, path: &str, method: Method, name: &str, func: F) -> Self
	where
		F: Fn(Request) -> Fut + Send + Sync + 'static,
		Fut: Future<Output = Result<Response>> + Send + 'static,
	{
		#[allow(deprecated)]
		{
			self.server = self.server.function_named(path, method, name, func);
		}
		self
	}
}

#[cfg(all(feature = "client-router", native))]
impl std::fmt::Debug for UnifiedRouter {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.debug_struct("UnifiedRouter")
			.field("server", &self.server)
			.field("client", &self.client)
			.field("di_registrations", &self.di_registrations)
			.finish()
	}
}

#[cfg(all(feature = "client-router", native))]
impl Default for UnifiedRouter {
	fn default() -> Self {
		Self::new()
	}
}

// Cross-target signature unification assertion (issue #4569).
//
// Proves that a free function `fn(ServerRouter) -> ServerRouter` is accepted
// by `UnifiedRouter::server` on the native target, mirroring the WASM arm in
// the `#[cfg(all(wasm, feature = "client-router"))]` block. Because the
// closure parameter type is now `ServerRouter` on both targets, the same
// delegate can be passed cross-target without `#[cfg]` at the call site.
#[cfg(all(native, feature = "client-router"))]
#[doc(hidden)]
const _: fn() = || {
	fn delegate(s: ServerRouter) -> ServerRouter {
		s
	}
	let _ = UnifiedRouter::new().server(delegate).client(|c| c);
};

// Note: Handler is not yet implemented for UnifiedRouter when client-router is enabled.
// As of #4065 / #4067, ClientRouter is Send + Sync on native targets (Signal<T> is backed
// by Arc<RwLock<T>>), so the previous Sync blocker no longer applies. A Handler impl can
// be added in a follow-up PR.
// For server-side HTTP handling, use ServerRouter directly or extract it via into_parts().

// ============================================================================
// client-router feature DISABLED
// ============================================================================

/// Unified router for server-side routing only.
///
/// When the `client-router` feature is disabled, this struct provides
/// server-side routing configuration only.
///
/// # Example
///
/// ```rust,ignore
/// use reinhardt_urls::routers::UnifiedRouter;
///
/// let router = UnifiedRouter::new()
///     .server(|s| s.function("/api/health", Method::GET, health_handler));
/// ```
#[cfg(not(feature = "client-router"))]
pub struct UnifiedRouter {
	server: ServerRouter,
	di_registrations: reinhardt_di::DiRegistrationList,
	#[cfg(feature = "streaming")]
	streaming_handlers: Vec<reinhardt_streaming::StreamingHandlerRegistration>,
}

#[cfg(not(feature = "client-router"))]
impl UnifiedRouter {
	/// Creates a new `UnifiedRouter` with default server router.
	pub fn new() -> Self {
		Self {
			server: ServerRouter::new(),
			di_registrations: reinhardt_di::DiRegistrationList::new(),
			#[cfg(feature = "streaming")]
			streaming_handlers: Vec::new(),
		}
	}

	/// Configure server-side routing with a closure.
	pub fn server<F>(mut self, f: F) -> Self
	where
		F: FnOnce(ServerRouter) -> ServerRouter,
	{
		self.server = f(self.server);
		self
	}

	/// Returns a reference to the server router.
	pub fn server_ref(&self) -> &ServerRouter {
		&self.server
	}

	/// Returns a mutable reference to the server router.
	pub fn server_mut(&mut self) -> &mut ServerRouter {
		&mut self.server
	}

	/// Apply or stash deferred DI registrations.
	///
	/// If the server router already has a DI context, registrations are applied
	/// directly to its singleton scope. Otherwise they are stashed globally
	/// for later application (e.g., by the `runall` command).
	fn flush_di_registrations(&mut self) {
		if self.di_registrations.is_empty() {
			return;
		}
		let registrations = std::mem::take(&mut self.di_registrations);
		match self
			.server
			.di_context()
			.map(|ctx| Arc::clone(ctx.singleton_scope()))
		{
			Some(scope) => registrations.apply_to(&scope),
			None => crate::routers::register_di_registrations(registrations),
		}
	}

	/// Consumes the router and returns the server router.
	///
	/// If this router has a DI context, deferred DI registrations are applied
	/// directly to its singleton scope. Otherwise they are stashed in the
	/// global registry for later application by the server.
	pub fn into_server(mut self) -> ServerRouter {
		self.flush_di_registrations();
		let errors = self.server.register_all_routes();
		for error in &errors {
			tracing::warn!("{}", error);
		}
		self.server
	}

	/// Registers server router globally.
	pub fn register_globally(mut self) {
		self.flush_di_registrations();
		crate::routers::register_router(self.server);
	}

	/// Attach deferred DI registrations to this router.
	///
	/// When the router is consumed, these registrations are applied directly
	/// to the DI context's singleton scope if one has been set via
	/// [`with_di_context`](Self::with_di_context). Otherwise they are stashed
	/// globally for later application (e.g., by the `runall` command).
	pub fn with_di_registrations(mut self, list: reinhardt_di::DiRegistrationList) -> Self {
		self.di_registrations.merge(list);
		self
	}

	// ========================================================================
	// Convenience delegations to ServerRouter
	// ========================================================================

	/// Set URL prefix for server router.
	pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
		self.server = self.server.with_prefix(prefix);
		self
	}

	/// Set namespace for server router.
	pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
		self.server = self.server.with_namespace(namespace);
		self
	}

	/// Set DI context for server router.
	pub fn with_di_context(mut self, ctx: Arc<InjectionContext>) -> Self {
		self.server = self.server.with_di_context(ctx);
		self
	}

	/// Add middleware to server router.
	///
	/// Any DI singleton registrations contributed by the middleware (via
	/// [`Middleware::di_registrations`]) are merged into this router's
	/// deferred DI registration list so that handlers resolved through
	/// `#[inject]` can see middleware-owned state without a parallel
	/// `with_di_registrations(...)` call. See #4426.
	pub fn with_middleware<M: Middleware + 'static>(mut self, middleware: M) -> Self {
		for (type_id, value) in middleware.di_registrations() {
			self.di_registrations.register_arc_any(type_id, value);
		}
		self.server = self.server.with_middleware(middleware);
		self
	}

	/// Mount a child server router on this router.
	pub fn mount(mut self, prefix: &str, child: ServerRouter) -> Self {
		self.server = self.server.mount(prefix, child);
		self
	}

	/// Mount a child UnifiedRouter on this router.
	pub fn mount_unified(self, prefix: &str, child: UnifiedRouter) -> Self {
		self.mount(prefix, child.server)
	}

	/// Mount streaming handlers on this router.
	#[cfg(feature = "streaming")]
	pub fn mount_streaming(mut self, router: reinhardt_streaming::StreamingRouter) -> Self {
		self.streaming_handlers.extend(router.into_handlers());
		self
	}

	/// Register an endpoint on server router.
	pub fn endpoint<F, E>(mut self, f: F) -> Self
	where
		F: FnOnce() -> E,
		E: reinhardt_core::endpoint::EndpointInfo + reinhardt_http::Handler + 'static,
	{
		self.server = self.server.endpoint(f);
		self
	}

	/// Register a function-based route on server router.
	pub fn function<F, Fut>(mut self, path: &str, method: Method, func: F) -> Self
	where
		F: Fn(Request) -> Fut + Send + Sync + 'static,
		Fut: Future<Output = Result<Response>> + Send + 'static,
	{
		self.server = self.server.function(path, method, func);
		self
	}

	/// Register a named function-based route on server router.
	#[deprecated(
		since = "0.2.0",
		note = "Use `#[get(\"/path\", name = \"name\")]` + `.endpoint()` instead"
	)]
	pub fn function_named<F, Fut>(mut self, path: &str, method: Method, name: &str, func: F) -> Self
	where
		F: Fn(Request) -> Fut + Send + Sync + 'static,
		Fut: Future<Output = Result<Response>> + Send + 'static,
	{
		#[allow(deprecated)]
		{
			self.server = self.server.function_named(path, method, name, func);
		}
		self
	}
}

#[cfg(not(feature = "client-router"))]
impl std::fmt::Debug for UnifiedRouter {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.debug_struct("UnifiedRouter")
			.field("server", &self.server)
			.field("di_registrations", &self.di_registrations)
			.finish()
	}
}

#[cfg(not(feature = "client-router"))]
impl Default for UnifiedRouter {
	fn default() -> Self {
		Self::new()
	}
}

/// Handler implementation delegates to the inner ServerRouter.
#[cfg(not(feature = "client-router"))]
#[async_trait::async_trait]
impl reinhardt_http::Handler for UnifiedRouter {
	async fn handle(&self, request: Request) -> Result<Response> {
		self.server.handle(request).await
	}
}

// ============================================================================
// WASM target with client-router feature
// ============================================================================

/// No-op `ServerRouter` used on WASM targets.
///
/// On WASM, server-side routing is not available, so this is the WASM
/// counterpart of the native [`ServerRouter`](crate::routers::ServerRouter):
/// it presents the same builder surface, but every method is a no-op that
/// consumes `self`, drops its arguments, and returns `Self`. The result is
/// ultimately discarded by [`UnifiedRouter::server`] on WASM.
///
/// Because the type and its builder methods share their names with the
/// native `ServerRouter`, the same
/// `.server(|s| s.with_prefix(...).endpoint(...).function(...))` closure body
/// compiles uniformly on both native and WASM targets (issue #4569).
///
/// Generic bounds from the native `ServerRouter` are intentionally relaxed
/// here: many upstream bound types (`Handler`, `Middleware`, `ViewSet`,
/// `InjectionContext`, `Method`, …) live behind `#[cfg(native)]` and would
/// not resolve on WASM, so the no-op methods only reproduce the call-site
/// arity.
#[cfg(all(wasm, feature = "client-router"))]
pub struct ServerRouter;

#[cfg(all(wasm, feature = "client-router"))]
impl ServerRouter {
	/// Construct a new no-op `ServerRouter` (WASM).
	pub fn new() -> Self {
		Self
	}

	/// No-op for `ServerRouter::with_prefix`.
	pub fn with_prefix(self, _prefix: impl Into<String>) -> Self {
		self
	}

	/// No-op for `ServerRouter::with_namespace`.
	pub fn with_namespace(self, _namespace: impl Into<String>) -> Self {
		self
	}

	/// No-op for `ServerRouter::with_di_context`.
	pub fn with_di_context<C>(self, _ctx: C) -> Self {
		self
	}

	/// No-op for `ServerRouter::with_middleware`.
	pub fn with_middleware<M>(self, _middleware: M) -> Self {
		self
	}

	/// No-op for `ServerRouter::with_route_middleware`.
	pub fn with_route_middleware<M>(self, _middleware: M) -> Self {
		self
	}

	/// No-op for `ServerRouter::exclude`.
	pub fn exclude(self, _pattern: &str) -> Self {
		self
	}

	/// No-op for `ServerRouter::mount`.
	pub fn mount<R>(self, _prefix: &str, _child: R) -> Self {
		self
	}

	/// No-op for `ServerRouter::group`.
	pub fn group<R>(self, _routers: Vec<R>) -> Self {
		self
	}

	/// No-op for `ServerRouter::function`.
	pub fn function<M, F>(self, _path: &str, _method: M, _func: F) -> Self {
		self
	}

	/// No-op for `ServerRouter::function_named`.
	pub fn function_named<M, F>(self, _path: &str, _method: M, _name: &str, _func: F) -> Self {
		self
	}

	/// No-op for `ServerRouter::route`.
	pub fn route<M, F>(self, _path: &str, _method: M, _func: F) -> Self {
		self
	}

	/// No-op for `ServerRouter::route_named`.
	pub fn route_named<M, F>(self, _path: &str, _method: M, _name: &str, _func: F) -> Self {
		self
	}

	/// No-op for `ServerRouter::handler`.
	pub fn handler<H>(self, _path: &str, _handler: H) -> Self {
		self
	}

	/// No-op for `ServerRouter::handler_arc`.
	pub fn handler_arc<H>(self, _path: &str, _handler: H) -> Self {
		self
	}

	/// No-op for `ServerRouter::handler_with_method`.
	pub fn handler_with_method<M, H>(self, _path: &str, _method: M, _handler: H) -> Self {
		self
	}

	/// No-op for `ServerRouter::handler_with_method_named`.
	pub fn handler_with_method_named<M, H>(
		self,
		_path: &str,
		_method: M,
		_name: &str,
		_handler: H,
	) -> Self {
		self
	}

	/// No-op for `ServerRouter::view`.
	pub fn view<V>(self, _path: &str, _view: V) -> Self {
		self
	}

	/// No-op for `ServerRouter::view_named`.
	pub fn view_named<V>(self, _path: &str, _name: &str, _view: V) -> Self {
		self
	}

	/// No-op for `ServerRouter::viewset`.
	pub fn viewset<V>(self, _prefix: &str, _viewset: V) -> Self {
		self
	}

	/// No-op for `ServerRouter::endpoint`.
	pub fn endpoint<F>(self, _f: F) -> Self {
		self
	}

	/// No-op for `ServerFnRouterExt::server_fn` on the WASM side.
	///
	/// `server_fn` is provided to native `ServerRouter` by the
	/// `ServerFnRouterExt` extension trait in `reinhardt-pages`. That trait
	/// (and its `ServerFnRegistration` bound) is a native-only concern, so
	/// the no-op `ServerRouter` absorbs the call as a free-standing inherent
	/// method without any trait bound. This lets cross-target builder chains
	/// such as `UnifiedRouter::new().server(|s| s.server_fn(marker))` compile
	/// on `wasm32-unknown-unknown` without `#[cfg(native)]` gates at the call
	/// site.
	pub fn server_fn<S>(self, _marker: S) -> Self {
		self
	}
}

#[cfg(all(wasm, feature = "client-router"))]
impl Default for ServerRouter {
	fn default() -> Self {
		Self::new()
	}
}

// Drift detection (Fixes #4185).
//
// Unified/server route declarations re-emit the user-supplied
// `.server(|s| ...)` closure body verbatim on WASM, so every builder
// method called inside that closure must exist on the no-op WASM
// `ServerRouter`. The `const _` below type-checks the canonical builder
// chain on every `cargo check --target wasm32-unknown-unknown`; if a future
// change drops a no-op method while the corresponding native `ServerRouter`
// builder still exists, this assertion fails to compile and CI catches the
// drift.
#[cfg(all(wasm, feature = "client-router"))]
#[doc(hidden)]
const _: fn() = || {
	let _ = UnifiedRouter::new()
		.server(|s| {
			s.with_prefix("/api")
				.with_namespace("api")
				.with_di_context(())
				.with_middleware(())
				.with_route_middleware(())
				.exclude("/internal")
				.mount("/v1/", ServerRouter::new())
				.group(Vec::<ServerRouter>::new())
				.function("/f", (), || ())
				.function_named("/f", (), "f", || ())
				.route("/r", (), || ())
				.route_named("/r", (), "r", || ())
				.handler("/h", ())
				.handler_arc("/h", ())
				.handler_with_method("/h", (), ())
				.handler_with_method_named("/h", (), "h", ())
				.view("/v", ())
				.view_named("/v", "v", ())
				.viewset("/vs/", ())
				.endpoint(|| ())
				.server_fn(())
		})
		.client(|c| c);
};

// Cross-target signature unification assertion (issue #4569).
//
// Proves that a free function `fn(ServerRouter) -> ServerRouter` is accepted
// by `UnifiedRouter::server` on the WASM target, mirroring the native arm in
// the `#[cfg(all(native, feature = "client-router"))]` block. The closure
// parameter type is now uniform across targets, so the same delegate compiles
// on both.
#[cfg(all(wasm, feature = "client-router"))]
#[doc(hidden)]
const _: fn() = || {
	fn delegate(s: ServerRouter) -> ServerRouter {
		s
	}
	let _ = UnifiedRouter::new().server(delegate).client(|c| c);
};

/// Unified router for WASM targets with client-side routing.
///
/// On WASM, only client-side routing is available. The `.server()` method
/// accepts a closure but discards its result, allowing shared route
/// definitions to compile on both server and client.
#[cfg(all(wasm, feature = "client-router"))]
pub struct UnifiedRouter {
	client: ClientRouter,
}

#[cfg(all(wasm, feature = "client-router"))]
impl UnifiedRouter {
	/// Creates a new `UnifiedRouter` with a default client router.
	pub fn new() -> Self {
		Self {
			client: ClientRouter::new(),
		}
	}

	/// Accept and discard server-side routing configuration.
	///
	/// On WASM, server routing is not available. The closure is accepted for
	/// cross-target type-checking — its `ServerRouter` parameter type is unified
	/// with the native arm — and then discarded without being invoked, so the
	/// shared route definitions compile on both targets at zero WASM runtime cost.
	pub fn server<F>(self, _f: F) -> Self
	where
		F: FnOnce(ServerRouter) -> ServerRouter,
	{
		self
	}

	/// Configure client-side routing with a closure.
	pub fn client<F>(mut self, f: F) -> Self
	where
		F: FnOnce(ClientRouter) -> ClientRouter,
	{
		self.client = f(self.client);
		self
	}

	/// Returns a reference to the client router.
	pub fn client_ref(&self) -> &ClientRouter {
		&self.client
	}

	/// Returns a mutable reference to the client router.
	pub fn client_mut(&mut self) -> &mut ClientRouter {
		&mut self.client
	}

	/// Consumes the router and returns the client router.
	pub fn into_client(self) -> ClientRouter {
		self.client
	}

	/// Returns the client router on WASM.
	/// Global registration is caller-managed.
	pub fn register_globally(self) -> ClientRouter {
		self.client
	}

	/// Mount a child UnifiedRouter on this router (client routes only).
	pub fn mount_unified(mut self, _prefix: &str, child: UnifiedRouter) -> Self {
		// Merge child client routes into parent
		self.client = self.client.merge(child.client);
		self
	}

	/// No-op on WASM: streaming is only available on native targets.
	#[cfg(feature = "streaming")]
	pub fn mount_streaming(self, _router: reinhardt_streaming::StreamingRouter) -> Self {
		self
	}

	/// No-op on WASM - server prefix is not applicable.
	pub fn with_prefix(self, _prefix: impl Into<String>) -> Self {
		self
	}

	/// Set namespace for the client router.
	///
	/// On WASM, only the client router is present; server-side namespacing
	/// does not apply. Propagates to [`ClientRouter::with_namespace`] so
	/// that named route keys are prefixed with `"<namespace>:"`. Fixes #3726.
	pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
		let ns: String = namespace.into();
		self.client = self.client.with_namespace(&ns);
		self
	}
}

#[cfg(all(wasm, feature = "client-router"))]
impl std::fmt::Debug for UnifiedRouter {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.debug_struct("UnifiedRouter")
			.field("client", &self.client)
			.finish()
	}
}

#[cfg(all(wasm, feature = "client-router"))]
impl Default for UnifiedRouter {
	fn default() -> Self {
		Self::new()
	}
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
#[allow(deprecated)]
mod tests {
	use super::*;
	#[cfg(feature = "client-router")]
	use reinhardt_core::page::Page;

	#[test]
	fn test_unified_router_new() {
		let router = UnifiedRouter::new();
		// Should have default server router
		assert_eq!(router.server_ref().prefix(), "");
	}

	#[test]
	fn test_unified_router_server_closure() {
		let router = UnifiedRouter::new().server(|s| s.with_prefix("/api").with_namespace("v1"));

		assert_eq!(router.server_ref().prefix(), "/api");
		assert_eq!(router.server_ref().namespace(), Some("v1"));
	}

	#[test]
	fn test_unified_router_convenience_methods() {
		let router = UnifiedRouter::new()
			.with_prefix("/api")
			.with_namespace("v1");

		assert_eq!(router.server_ref().prefix(), "/api");
		assert_eq!(router.server_ref().namespace(), Some("v1"));
	}

	#[cfg(feature = "client-router")]
	#[test]
	fn test_unified_router_client_closure() {
		let router = UnifiedRouter::new().client(|c| c.route("home", "/", || Page::Empty));

		assert_eq!(router.client_ref().route_count(), 1);
	}

	#[cfg(all(feature = "client-router", native))]
	#[test]
	fn unified_with_namespace_propagates_to_client() {
		// Arrange: routes are added first, namespace applied after (matches
		// the call pattern generated by route declarations).
		let router = UnifiedRouter::new()
			.client(|c| c.route("login", "/login/", || Page::Empty))
			.with_namespace("app");

		// Act & Assert
		assert!(
			router.client_ref().has_route("app:login"),
			"client-side named route should be namespaced by UnifiedRouter::with_namespace"
		);
		assert!(
			!router.client_ref().has_route("login"),
			"unprefixed name should no longer resolve after with_namespace"
		);
	}

	#[cfg(all(feature = "client-router", native))]
	#[test]
	fn mount_unified_merges_client_routes_on_native() {
		// Arrange: a child UnifiedRouter that declares a client named route,
		// mirroring what a client route declaration produces on native
		// via `client_url_patterns()`.
		let child =
			UnifiedRouter::new().client(|c| c.route("login_page", "/login/", || Page::Empty));
		let parent = UnifiedRouter::new().client(|c| c.route("home", "/", || Page::Empty));

		// Act
		let merged = parent.mount_unified("/", child);

		// Assert: both parent and child client routes are reachable on the
		// resulting router and can resolve via `ClientRouter::reverse()`.
		assert!(merged.client_ref().has_route("home"));
		assert!(
			merged.client_ref().has_route("login_page"),
			"native mount_unified must merge child client routes (#4076)"
		);
		assert_eq!(merged.client_ref().route_count(), 2);

		assert_eq!(
			merged.client_ref().reverse("login_page", &[]).ok(),
			Some("/login/".to_string()),
			"merged client routes must be resolvable on native"
		);
	}

	#[cfg(all(feature = "client-router", native))]
	#[test]
	fn mount_unified_merges_namespaced_client_routes_on_native() {
		// Arrange: child router applies its own namespace before being mounted,
		// matching the per-app composition pattern `mount_unified("/", auth::routes())`
		// where `auth::routes()` already called `.with_namespace("auth")`.
		let child = UnifiedRouter::new()
			.client(|c| c.route("login_page", "/login/", || Page::Empty))
			.with_namespace("auth");
		let parent = UnifiedRouter::new();

		// Act
		let merged = parent.mount_unified("/", child);

		// Assert
		assert!(
			merged.client_ref().has_route("auth:login_page"),
			"namespaced child client routes must survive native mount_unified"
		);
		assert_eq!(
			merged.client_ref().reverse("auth:login_page", &[]).ok(),
			Some("/login/".to_string())
		);
	}

	#[cfg(all(wasm, feature = "client-router"))]
	#[test]
	fn unified_wasm_with_namespace_propagates_to_client() {
		// Arrange
		let router = UnifiedRouter::new()
			.client(|c| c.route("login", "/login/", || Page::Empty))
			.with_namespace("app");

		// Act & Assert
		assert!(
			router.client_ref().has_route("app:login"),
			"WASM UnifiedRouter::with_namespace must propagate to ClientRouter"
		);
		assert!(
			!router.client_ref().has_route("login"),
			"unprefixed name should no longer resolve after with_namespace on WASM"
		);
	}

	#[cfg(feature = "client-router")]
	#[test]
	fn test_unified_router_into_parts() {
		let router = UnifiedRouter::new()
			.server(|s| s.with_prefix("/api"))
			.client(|c| c.route("home", "/", || Page::Empty));

		let (server, client) = router.into_parts();
		assert_eq!(server.prefix(), "/api");
		assert_eq!(client.route_count(), 1);
	}

	#[cfg(feature = "client-router")]
	#[test]
	fn test_unified_router_into_server() {
		let router = UnifiedRouter::new().server(|s| s.with_prefix("/api"));

		let server = router.into_server();
		assert_eq!(server.prefix(), "/api");
	}

	#[cfg(feature = "client-router")]
	#[test]
	fn test_unified_router_into_client() {
		let router = UnifiedRouter::new().client(|c| c.route("home", "/", || Page::Empty));

		let client = router.into_client();
		assert_eq!(client.route_count(), 1);
	}

	mod flush_di_registrations {
		use super::*;
		use reinhardt_di::{DiRegistrationList, InjectionContext, SingletonScope};
		use rstest::rstest;
		use std::sync::Arc;

		#[rstest]
		fn applies_registrations_to_di_context_singleton_scope() {
			// Arrange
			let singleton_scope = Arc::new(SingletonScope::new());
			let di_ctx = Arc::new(InjectionContext::builder(Arc::clone(&singleton_scope)).build());

			let mut registrations = DiRegistrationList::new();
			registrations.register(42i32);

			// Act
			let _server = UnifiedRouter::new()
				.with_di_registrations(registrations)
				.with_di_context(di_ctx)
				.into_server();

			// Assert
			let value = singleton_scope
				.get::<i32>()
				.expect("i32 should be registered");
			assert_eq!(*value, 42);
		}

		#[rstest]
		fn applies_registrations_regardless_of_builder_order() {
			// Arrange
			let singleton_scope = Arc::new(SingletonScope::new());
			let di_ctx = Arc::new(InjectionContext::builder(Arc::clone(&singleton_scope)).build());

			let mut registrations = DiRegistrationList::new();
			registrations.register(99u64);

			// Act: with_di_context BEFORE with_di_registrations
			let _server = UnifiedRouter::new()
				.with_di_context(di_ctx)
				.with_di_registrations(registrations)
				.into_server();

			// Assert
			let value = singleton_scope
				.get::<u64>()
				.expect("u64 should be registered");
			assert_eq!(*value, 99);
		}

		#[rstest]
		#[serial_test::serial(global_di)]
		fn stashes_globally_when_no_di_context() {
			// Arrange
			let mut registrations = DiRegistrationList::new();
			registrations.register(7u8);

			// Act
			let _server = UnifiedRouter::new()
				.with_di_registrations(registrations)
				.into_server();

			// Assert: registrations stashed globally
			let taken = crate::routers::take_di_registrations();
			assert!(taken.is_some(), "registrations should be stashed globally");
		}
	}

	mod debug_impl {
		use super::*;
		use rstest::rstest;
		use std::sync::Arc;

		#[rstest]
		fn unified_router_implements_debug() {
			let router = UnifiedRouter::new().with_prefix("/api");
			let debug_output = format!("{:?}", router);
			assert!(debug_output.contains("UnifiedRouter"));
			assert!(debug_output.contains("ServerRouter"));
		}

		#[rstest]
		fn arc_try_unwrap_with_expect() {
			// This is the primary use case from #3391:
			// Arc::try_unwrap().expect() requires Debug on the error type
			let router = Arc::new(UnifiedRouter::new());
			let unwrapped = Arc::try_unwrap(router).expect("should have single ref");
			assert_eq!(unwrapped.server_ref().prefix(), "");
		}
	}

	mod route_registration {
		use super::*;
		use hyper::Method;
		use reinhardt_http::{Request, Response, Result};
		use rstest::rstest;

		async fn dummy_handler(_req: Request) -> Result<Response> {
			Ok(Response::ok())
		}

		#[rstest]
		fn into_server_registers_routes_for_reverse() {
			// Arrange
			let router = UnifiedRouter::new().server(|s| {
				s.with_namespace("api").function_named(
					"/health",
					Method::GET,
					"health",
					dummy_handler,
				)
			});

			// Act
			let server = router.into_server();

			// Assert
			let url = server.reverse("api:health", &[]);
			assert_eq!(url, Some("/health".to_string()));
		}

		#[cfg(feature = "client-router")]
		#[rstest]
		fn into_parts_registers_routes_for_reverse() {
			// Arrange
			let router = UnifiedRouter::new().server(|s| {
				s.with_namespace("api").function_named(
					"/health",
					Method::GET,
					"health",
					dummy_handler,
				)
			});

			// Act
			let (server, _client) = router.into_parts();

			// Assert
			let url = server.reverse("api:health", &[]);
			assert_eq!(url, Some("/health".to_string()));
		}
	}
}