beet_router 0.0.8

ECS router and server utilities
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
//! Help handler for displaying endpoint documentation.
//!
//! # Kebab-case Parameter Convention
//!
//! This module demonstrates the kebab-case parameter system used throughout beet,
//! the conversion happens automatically:
//! - `ParamMeta::from_field()` converts snake_case field names to kebab-case for display
//! - `MultiMap::parse_reflect()` normalizes kebab-case keys to snake_case before reflection lookup
use crate::prelude::*;
use beet_core::prelude::*;
use beet_flow::prelude::*;


/// Parameters for configuring the help handler behavior
#[derive(Debug, Clone)]
pub struct HelpHandlerConfig {
	/// Text inserted at the beginning of the formatted output
	pub introduction: String,
	/// The default format to use when rendering help
	pub default_format: HelpFormat,
	/// If true, handler runs when path segments are empty OR --help param is present
	/// If false, handler only runs when --help param is present
	pub match_root: bool,
	/// If true, disable colored output
	pub no_color: bool,
}

impl Default for HelpHandlerConfig {
	fn default() -> Self {
		Self {
			introduction: String::from("Cli Help"),
			default_format: default(),
			match_root: false,
			no_color: false,
		}
	}
}

#[derive(
	Debug,
	Clone,
	PartialEq,
	Eq,
	PartialOrd,
	Ord,
	Hash,
	Deref,
	Reflect,
	Component,
	Default,
)]
#[reflect(Default)]
pub struct HelpParams {
	#[deref]
	#[reflect(@ParamOptions::desc("Get help"))]
	help: bool,
	#[reflect(@ParamOptions::desc("Help format: cli, http"))]
	help_format: Option<String>,
}


/// Creates a help handler middleware that responds to help parameters.
///
/// This handler checks for `HelpParams` (--help, --help-format) and when found,
/// renders documentation for all endpoints that partially match the current path.
///
/// The handler should be added early in the request flow, typically in a Fallback
/// so it can exit early when help is requested.
///
/// # Arguments
/// * `params` - Configuration parameters for the help handler
///
/// # Example
/// ```
/// # use beet_router::prelude::*;
/// # use beet_core::prelude::*;
/// # use beet_flow::prelude::*;
/// # use beet_net::prelude::*;
/// # async {
/// RouterPlugin::world()
///     .spawn(ExchangeSpawner::new_flow(|| {
///         (Fallback, children![
///             help_handler(HelpHandlerConfig {
///                 introduction: String::from("Welcome to my CLI"),
///                 default_format: HelpFormat::Cli,
///                 match_root: false,
///                 no_color: false,
///             }),
///             EndpointBuilder::get()
///                 .with_path("foo")
///                 .with_handler(|| "foo"),
///         ])
///     }))
///     .oneshot_str(Request::get("/?help=true"))
///     .await;
/// # };
/// ```
pub fn help_handler(handler_config: HelpHandlerConfig) -> impl Bundle {
	(
		Name::new("Help Handler"),
		OnSpawn::observe(
			move |ev: On<GetOutcome>,
			      mut route_query: RouteQuery,
			      endpoints_query: Query<&Endpoint>,
			      mut commands: Commands|
			      -> Result {
				let action = ev.target();

				// parse help params
				let req_params = route_query
					.request_meta(action)?
					.params()
					.parse_reflect::<HelpParams>()?;

				// get current path for checking
				let current_path = route_query.path(action)?.clone();
				let is_root = current_path.is_empty();

				// check if help should run:
				// - if match_root is true: run if help param OR path is empty
				// - if match_root is false: run only if help param is present
				let should_run = if handler_config.match_root {
					req_params.help || is_root
				} else {
					req_params.help
				};

				if !should_run {
					// no help requested, pass through
					commands.entity(action).trigger_target(Outcome::Fail);
					return Ok(());
				}



				// get endpoint tree and filter by partial path match
				let tree = route_query.endpoint_tree(action)?;

				// collect all endpoints that match
				let mut matching_endpoints = Vec::new();
				collect_endpoints_from_tree(
					&tree,
					&current_path,
					&mut matching_endpoints,
					&endpoints_query,
				);

				// determine format
				let format = match req_params.help_format.as_deref() {
					Some("http") => HelpFormat::Http,
					Some("cli") => HelpFormat::Cli,
					Some(other) => {
						bevybail!("Unrecognized help-format '{}'", other);
					}
					_ => handler_config.default_format,
				};
				let formatter: Box<dyn EndpointHelpFormatter> = match format {
					HelpFormat::Cli => Box::new(CliFormatter),
					HelpFormat::Http => Box::new(HttpFormatter),
				};


				// render help for all matching endpoints
				let help_text = formatter.format(
					&handler_config,
					&matching_endpoints,
					&current_path,
				);

				let agent = route_query.agents.entity(action);
				commands.entity(agent).insert(
					Response::new(default(), help_text.into())
						.with_content_type("text/plain"),
				);

				// pass to exit fallback early
				commands.entity(action).trigger_target(Outcome::Pass);

				Ok(())
			},
		),
	)
}


// recursively collect all endpoints from the tree
fn collect_endpoints_from_tree(
	node: &EndpointTree,
	current_path: &Vec<String>,
	endpoints: &mut Vec<Endpoint>,
	endpoints_query: &Query<&Endpoint>,
) {
	let node_depth = node.pattern.iter().count();
	let current_depth = current_path.len();

	// determine if we should include this node and/or recurse
	if current_path.is_empty() {
		// show all endpoints when no filter specified
		if let Some(entity) = node.endpoint {
			if let Ok(endpoint) = endpoints_query.get(entity) {
				endpoints.push(endpoint.clone());
			}
		}
		// always recurse when no filter
		for child in &node.children {
			collect_endpoints_from_tree(
				child,
				current_path,
				endpoints,
				endpoints_query,
			);
		}
	} else if node_depth <= current_depth {
		// node is at or above current depth - check if it's on the path
		match node.pattern.parse_path(current_path) {
			Ok(path_match) => {
				// pattern matches current path
				if path_match.exact_match() {
					// exact match - show this endpoint and all children
					if let Some(entity) = node.endpoint {
						if let Ok(endpoint) = endpoints_query.get(entity) {
							endpoints.push(endpoint.clone());
						}
					}
				}
				// recurse to children since we're on the right path
				for child in &node.children {
					collect_endpoints_from_tree(
						child,
						current_path,
						endpoints,
						endpoints_query,
					);
				}
			}
			Err(_) => {
				// pattern doesn't match - don't include or recurse
			}
		}
	}
	// if node_depth > current_depth, we've gone too deep, don't include
}

/// Trait for formatting endpoint help documentation
pub trait EndpointHelpFormatter {
	/// Format the complete help output for multiple endpoints
	fn format(
		&self,
		params: &HelpHandlerConfig,
		endpoints: &[Endpoint],
		path: &Vec<String>,
	) -> String {
		let _enabled = paint_ext::SetPaintEnabledTemp::new(!params.no_color);

		if endpoints.is_empty() {
			return self.format_none_found(path);
		}

		let mut output = String::new();
		output.push_str("\n");
		output.push_str(&params.introduction);
		output.push_str("\n\n");
		output.push_str(&self.format_header());
		output.push_str("\n\n");

		for endpoint in endpoints {
			output.push_str(&self.format_endpoint(endpoint));
			output.push_str("\n");
		}

		output
	}

	fn format_none_found(&self, path: &Vec<String>) -> String;

	/// Format the header section
	fn format_header(&self) -> String;

	/// Format a single endpoint
	fn format_endpoint(&self, endpoint: &Endpoint) -> String;

	/// Format the path
	fn format_path(&self, path: &PathPattern) -> String;

	/// Format the parameters/flags
	fn format_params(&self, endpoint: &Endpoint) -> String;

	/// Format cache strategy (if applicable)
	fn format_cache_strategy(&self, cache: &CacheStrategy) -> String {
		format!("Cache: {:?}", cache)
	}

	/// Format content type (if applicable)
	fn format_content_type(&self, content_type: &ContentType) -> String {
		format!("Content-Type: {:?}", content_type)
	}
}

/// CLI-style formatter with colored output
struct CliFormatter;

impl EndpointHelpFormatter for CliFormatter {
	fn format_header(&self) -> String {
		format!("\n{}", paint_ext::bold("Available commands:"))
	}

	fn format_endpoint(&self, endpoint: &Endpoint) -> String {
		let mut output = String::new();

		// command path (CLI-style: space-separated, no slashes)
		let path_str = self.format_path(endpoint.path());
		output.push_str(&format!("  {}", paint_ext::green(&path_str)));

		// description
		if let Some(desc) = endpoint.description() {
			output.push_str(&format!("\n    {}", desc));
		}

		// params
		output.push_str(&self.format_params(endpoint));

		output
	}

	fn format_path(&self, path: &PathPattern) -> String {
		path.iter()
			.map(|seg| {
				if seg.is_static() {
					seg.to_string()
				} else if seg.is_greedy() {
					format!("[*{}]", seg.name())
				} else {
					format!("[{}]", seg.name())
				}
			})
			.collect::<Vec<_>>()
			.join(" ")
	}



	fn format_params(&self, endpoint: &Endpoint) -> String {
		if endpoint.params().is_empty() {
			return String::new();
		}

		let mut output = String::new();
		output.push_str(&format!("\n    {}", paint_ext::dimmed("Flags:")));

		for param in endpoint.params().iter() {
			output.push_str("\n      ");

			// name with short flag if present
			let mut param_display = format!("--{}", param.name());
			if let Some(short) = param.short() {
				param_display.push_str(&format!(", -{}", short));
			}
			output.push_str(&paint_ext::yellow(format!("{}\t", param_display)));

			// value type
			match param.value() {
				ParamValue::Flag => {
					output.push_str(&paint_ext::dimmed("(flag)     "))
				}
				ParamValue::Single => {
					output.push_str(&paint_ext::dimmed("(value)    "))
				}
				ParamValue::Multiple => {
					output.push_str(&paint_ext::dimmed("(multiple) "))
				}
			}

			// required/optional
			if param.is_required() {
				output.push_str(&paint_ext::red("required"));
			} else {
				output.push_str(&paint_ext::green("optional"));
			}

			// description
			if let Some(desc) = param.description() {
				output.push_str(&format!(" - {}", desc));
			}
		}

		output
	}

	fn format_none_found(&self, path: &Vec<String>) -> String {
		let path_str = if path.is_empty() {
			"<empty>".to_string()
		} else {
			path.join(" ")
		};
		paint_ext::red_bold(format!(
			"No matching endpoints found for path: {}",
			path_str
		))
		.to_string()
	}
}

/// HTTP-style formatter with colored output
struct HttpFormatter;

impl EndpointHelpFormatter for HttpFormatter {
	fn format_header(&self) -> String {
		paint_ext::bold("Available endpoints:").to_string()
	}

	fn format_endpoint(&self, endpoint: &Endpoint) -> String {
		let mut output = String::new();

		// method and path
		let method = endpoint
			.method()
			.map(|m| format!("{:?}", m).to_uppercase())
			.unwrap_or_else(|| "ANY".to_string());
		let path = endpoint.path().annotated_route_path();

		output.push_str(&format!(
			"  {} {}",
			paint_ext::cyan(&method),
			paint_ext::green(&path.to_string())
		));

		// description
		if let Some(desc) = endpoint.description() {
			output.push_str(&format!("\n    {}", desc));
		}

		// query params
		output.push_str(&self.format_params(endpoint));

		// content type
		if let Some(content_type) = endpoint.content_type() {
			output.push_str(&format!(
				"\n    {}",
				paint_ext::dimmed(&self.format_content_type(&content_type))
			));
		}

		// cache strategy
		if let Some(cache) = endpoint.cache_strategy() {
			output.push_str(&format!(
				"\n    {}",
				paint_ext::dimmed(&self.format_cache_strategy(&cache))
			));
		}

		output
	}

	fn format_path(&self, path: &PathPattern) -> String {
		path.annotated_route_path().to_string()
	}



	fn format_params(&self, endpoint: &Endpoint) -> String {
		if endpoint.params().is_empty() {
			return String::new();
		}

		let mut output = String::new();
		output.push_str(&format!(
			"\n    {}",
			paint_ext::bold("Query Parameters:")
		));

		for param in endpoint.params().iter() {
			output.push_str(&format!(
				"\n      {}",
				paint_ext::yellow(param.name())
			));
			if param.is_required() {
				output.push_str(&paint_ext::red(" (required)"));
			} else {
				output.push_str(&paint_ext::green(" (optional)"));
			}
			output.push_str(&format!(
				" - {}",
				paint_ext::dimmed(&param.value().to_string())
			));
			if let Some(desc) = param.description() {
				output.push_str(&format!(": {}", desc));
			}
		}

		output
	}

	fn format_none_found(&self, path: &Vec<String>) -> String {
		let path_str = if path.is_empty() {
			default()
		} else {
			path.join("/")
		};
		paint_ext::red_bold(format!(
			"No matching endpoints found for path: /{}",
			path_str
		))
		.to_string()
	}
}

/// Format for rendering endpoint help
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum HelpFormat {
	#[default]
	/// CLI format with commands and flags
	Cli,
	/// HTTP format with methods and query params
	Http,
}

#[cfg(test)]
mod test {
	use super::*;
	use beet_net::prelude::*;

	#[beet_core::test]
	async fn help_shows_matching_endpoints() {
		let mut world = RouterPlugin::world();
		let mut entity = world.spawn(ExchangeSpawner::new_flow(|| {
			(Fallback, children![
				help_handler(HelpHandlerConfig::default()),
				EndpointBuilder::get()
					.with_path("foo")
					.with_description("The foo command")
					.with_handler(|| "foo"),
				EndpointBuilder::get()
					.with_path("bar")
					.with_description("The bar command")
					.with_handler(|| "bar"),
			])
		}));

		let response = entity.oneshot_str(Request::get("/?help=true")).await;

		response.clone().xpect_contains("foo");
		response.clone().xpect_contains("The foo command");
		response.clone().xpect_contains("bar");
		response.xpect_contains("The bar command");
	}

	#[beet_core::test]
	async fn help_format_http() {
		let mut world = RouterPlugin::world();
		let mut entity = world.spawn(ExchangeSpawner::new_flow(|| {
			(Fallback, children![
				help_handler(HelpHandlerConfig::default()),
				EndpointBuilder::post()
					.with_path("api/users")
					.with_description("Create user")
					.with_handler(|| "create"),
			])
		}));

		let response = entity
			.oneshot_str(Request::get("/?help=true&help-format=http"))
			.await;

		response.clone().xpect_contains("POST");
		response.clone().xpect_contains("api/users");
		response.xpect_contains("Create user");
	}

	#[beet_core::test]
	async fn help_with_params() {
		#[derive(Reflect)]
		struct TestParams {
			#[reflect(@ParamOptions::desc("Enable verbose output"))]
			verbose: bool,
			#[reflect(@ParamOptions::desc_and_short("Output format", 'f'))]
			format: Option<String>,
		}

		let mut world = RouterPlugin::world();
		let mut entity = world.spawn(ExchangeSpawner::new_flow(|| {
			(Fallback, children![
				help_handler(HelpHandlerConfig::default()),
				EndpointBuilder::get()
					.with_path("test")
					.with_params::<TestParams>()
					.with_description("Test command")
					.with_handler(|| "test"),
			])
		}));

		let response = entity.oneshot_str(Request::get("/?help=true")).await;

		response.clone().xpect_contains("verbose");
		response.clone().xpect_contains("Enable verbose output");
		response.clone().xpect_contains("format");
		response.xpect_contains(", -f");
	}

	#[beet_core::test]
	async fn no_help_passes_through() {
		let mut world = RouterPlugin::world();
		let mut entity = world.spawn(ExchangeSpawner::new_flow(|| {
			(Fallback, children![
				help_handler(HelpHandlerConfig::default()),
				EndpointBuilder::get()
					.with_path("foo")
					.with_handler(|| "foo response"),
			])
		}));

		let response = entity.oneshot_str(Request::get("/foo")).await;

		response.xpect_eq("foo response");
	}

	#[beet_core::test]
	async fn kebab_case_params_work() {
		let mut world = RouterPlugin::world();
		let mut entity = world.spawn(ExchangeSpawner::new_flow(|| {
			(Fallback, children![
				help_handler(HelpHandlerConfig::default()),
				EndpointBuilder::get()
					.with_path("test")
					.with_handler(|| "test"),
			])
		}));

		// test both kebab-case and underscore variants
		let response1 = entity
			.oneshot_str(Request::get("/?help=true&help-format=http"))
			.await;
		response1.clone().xpect_contains("GET");

		let response2 = entity
			.oneshot_str(Request::get("/?help=true&help_format=http"))
			.await;
		response2.xpect_contains("GET");
	}

	#[beet_core::test]
	async fn full_kebab_case_flow_integration() {
		// demonstrates the complete kebab-case parameter system:
		// 1. struct fields use snake_case
		// 2. ParamMeta displays them as kebab-case
		// 3. query params accept both formats
		// 4. MultiMap normalizes to snake_case for reflection

		#[derive(Reflect)]
		struct TestParams {
			#[reflect(@ParamOptions::desc("Maximum retry attempts"))]
			max_retry_count: u32,
			#[reflect(@ParamOptions::desc("Enable verbose logging"))]
			enable_verbose_mode: bool,
		}

		let mut world = RouterPlugin::world();
		let mut entity = world.spawn(ExchangeSpawner::new_flow(|| {
			(Fallback, children![
				help_handler(HelpHandlerConfig::default()),
				EndpointBuilder::get()
					.with_path("deploy")
					.with_params::<TestParams>()
					.with_description("Deploy application")
					.with_handler(|| "deployed"),
			])
		}));

		// CLI help shows kebab-case params
		let help_response =
			entity.oneshot_str(Request::get("/?help=true")).await;

		help_response.clone().xpect_contains("--max-retry-count");
		help_response
			.clone()
			.xpect_contains("--enable-verbose-mode");
		help_response
			.clone()
			.xpect_contains("Maximum retry attempts");
		help_response.xpect_contains("Enable verbose logging");

		// HTTP help also shows kebab-case
		let http_help = entity
			.oneshot_str(Request::get("/?help=true&help-format=http"))
			.await;

		http_help.clone().xpect_contains("max-retry-count");
		http_help.xpect_contains("enable-verbose-mode");
	}
}