1use serde_json::{Map, Value as Json, json};
13
14use crate::router::Router;
15
16#[derive(Debug, Clone)]
18pub struct ActionDoc {
19 pub action: &'static str,
20 pub responses: Vec<ResponseDoc>,
21 pub body: Option<BodyDoc>,
23 pub query: Vec<&'static str>,
24}
25
26#[derive(Debug, Clone)]
28pub struct ResponseDoc {
29 pub status: u16,
30 pub kind: ResponseKind,
31}
32
33#[derive(Debug, Clone)]
34pub enum ResponseKind {
35 Serialized {
38 name: String,
39 schema: fn() -> Json,
40 many: bool,
41 root: Option<String>,
42 },
43 Json,
45 Html,
47 Redirect,
49 Empty,
51}
52
53#[derive(Debug, Clone)]
55pub struct BodyDoc {
56 pub root: &'static str,
57 pub schema: fn() -> Json,
58}
59
60pub trait Documented {
63 fn actions() -> Vec<ActionDoc>;
64}
65
66#[doc(hidden)]
69pub struct DocProbe<T>(std::marker::PhantomData<fn() -> T>);
70
71impl<T> DocProbe<T> {
72 pub fn new() -> Self {
73 Self(std::marker::PhantomData)
74 }
75}
76
77impl<T> Default for DocProbe<T> {
78 fn default() -> Self {
79 Self::new()
80 }
81}
82
83#[doc(hidden)]
84pub trait DocProbeDocumented {
85 fn register(&self, router: &mut Router);
86}
87
88impl<T: Documented> DocProbeDocumented for &DocProbe<T> {
89 fn register(&self, router: &mut Router) {
90 router.document::<T>();
91 }
92}
93
94#[doc(hidden)]
95pub trait DocProbeAny {
96 fn register(&self, router: &mut Router);
97}
98
99impl<T> DocProbeAny for DocProbe<T> {
100 fn register(&self, _router: &mut Router) {}
101}
102
103#[doc(hidden)]
105pub struct ParamsProbe<T>(std::marker::PhantomData<fn() -> T>);
106
107impl<T> ParamsProbe<T> {
108 pub fn new() -> Self {
109 Self(std::marker::PhantomData)
110 }
111}
112
113impl<T> Default for ParamsProbe<T> {
114 fn default() -> Self {
115 Self::new()
116 }
117}
118
119#[doc(hidden)]
120pub trait ParamsProbeModel {
121 fn params_schema(&self) -> Json;
122}
123
124impl<T: crate::Model> ParamsProbeModel for &ParamsProbe<T> {
125 fn params_schema(&self) -> Json {
126 T::params_schema()
127 }
128}
129
130#[doc(hidden)]
131pub trait ParamsProbeAny {
132 fn params_schema(&self) -> Json;
133}
134
135impl<T> ParamsProbeAny for ParamsProbe<T> {
136 fn params_schema(&self) -> Json {
137 json!({"type": "object"})
138 }
139}
140
141pub fn document(router: &Router, title: &str, version: &str, api_version: Option<&str>) -> Json {
145 let mut paths: Map<String, Json> = Map::new();
146 let mut schemas: Map<String, Json> = Map::new();
147 let mut operation_ids: Vec<String> = Vec::new();
148 let mut routes: Vec<_> = router
152 .routes()
153 .iter()
154 .filter(|route| route.answers(api_version))
155 .collect();
156 if api_version.is_some() {
157 routes.sort_by_key(|route| !route.is_versioned());
158 }
159 for route in routes {
160 let method = route.method().as_str().to_ascii_lowercase();
161 if method == "head" || method == "options" {
162 continue;
163 }
164 let (path, params) = openapi_path(route.pattern());
165 let label = route.label();
166 let (controller, action) = label.split_once('#').unwrap_or(("", label));
167 let doc = router
168 .docs_for(controller)
169 .into_iter()
170 .find(|d| d.action == action);
171
172 let constraints = Router::route_constraints(route);
173 let mut parameters: Vec<Json> = params
174 .iter()
175 .map(|name| {
176 let constraint = constraints
177 .iter()
178 .find(|(p, _)| p == name)
179 .map(|(p, pattern)| {
180 let inner = pattern
182 .strip_prefix("^(?:")
183 .and_then(|p| p.strip_suffix(")$"))
184 .unwrap_or(pattern);
185 (*p, inner)
186 });
187 let schema = match constraint {
188 Some((_, pattern)) if is_integer_pattern(pattern) => {
189 json!({"type": "integer"})
190 }
191 Some((_, pattern)) => json!({"type": "string", "pattern": pattern}),
192 None => json!({"type": "string"}),
193 };
194 json!({"name": name, "in": "path", "required": true, "schema": schema})
195 })
196 .collect();
197 let mut operation = Map::new();
198 if !controller.is_empty() {
199 let base = format!("{}_{action}", glacier_inflect::snake_case(controller));
202 let mut id = base.clone();
203 if operation_ids.contains(&id) {
204 let first = path.trim_start_matches('/').split('/').next().unwrap_or("");
205 id = format!("{}_{base}", first.trim_matches(|c| c == '{' || c == '}'));
206 }
207 let mut n = 2;
208 while operation_ids.contains(&id) {
209 id = format!("{base}_{n}");
210 n += 1;
211 }
212 operation_ids.push(id.clone());
213 operation.insert("operationId".into(), json!(id));
214 operation.insert("tags".into(), json!([controller]));
215 }
216 if let (true, Some(api_version)) = (route.is_versioned(), api_version) {
217 parameters.push(json!({
218 "name": "Api-Version",
219 "in": "header",
220 "required": true,
221 "schema": {"type": "string", "enum": [api_version]},
222 }));
223 }
224 let mut responses = Map::new();
225 if let Some(doc) = &doc {
226 for name in &doc.query {
227 parameters.push(json!({
228 "name": name,
229 "in": "query",
230 "required": false,
231 "schema": query_schema(name),
232 }));
233 }
234 if let Some(body) = &doc.body {
235 operation.insert(
236 "requestBody".into(),
237 json!({
238 "required": true,
239 "content": {"application/json": {"schema": {
240 "type": "object",
241 "properties": {body.root: (body.schema)()},
242 "required": [body.root],
243 }}},
244 }),
245 );
246 }
247 for response in &doc.responses {
248 let key = response.status.to_string();
249 if responses.contains_key(&key) {
250 continue;
251 }
252 responses.insert(key, response_json(response, &mut schemas));
253 }
254 }
255 if responses.is_empty() {
256 responses.insert("200".into(), json!({"description": "OK"}));
257 }
258 if !parameters.is_empty() {
259 operation.insert("parameters".into(), Json::Array(parameters));
260 }
261 operation.insert("responses".into(), Json::Object(responses));
262 let entry = paths.entry(path).or_insert_with(|| json!({}));
263 if let Json::Object(entry) = entry {
264 entry.entry(method).or_insert(Json::Object(operation));
265 }
266 }
267 let version = api_version.unwrap_or(version);
268 let mut document = json!({
269 "openapi": "3.1.0",
270 "info": {"title": title, "version": version},
271 "paths": paths,
272 });
273 if !schemas.is_empty() {
274 document["components"] = json!({"schemas": schemas});
275 }
276 document
277}
278
279fn openapi_path(pattern: &str) -> (String, Vec<String>) {
281 let mut params = Vec::new();
282 let path = pattern
283 .split('/')
284 .map(|segment| {
285 match segment
286 .strip_prefix(':')
287 .or_else(|| segment.strip_prefix('*'))
288 {
289 Some(param) => {
290 let (name, rest) = param.split_at(param.find('.').unwrap_or(param.len()));
291 params.push(name.to_owned());
292 format!("{{{name}}}{rest}")
293 }
294 None => segment.to_owned(),
295 }
296 })
297 .collect::<Vec<_>>()
298 .join("/");
299 (if path.is_empty() { "/".into() } else { path }, params)
300}
301
302fn is_integer_pattern(pattern: &str) -> bool {
303 matches!(pattern, r"\d+" | "[0-9]+" | r"^\d+$")
304}
305
306fn query_schema(name: &str) -> Json {
307 match name {
308 "page" | "per_page" => json!({"type": "integer", "minimum": 1}),
309 "sort" => json!({
310 "type": "string",
311 "description": "Columns to sort by, comma-separated; `-` for descending",
312 }),
313 "cursor" => json!({"type": "string", "description": "From a previous page's links"}),
314 _ => json!({"type": "string"}),
315 }
316}
317
318fn description(status: u16) -> String {
319 if status == 404 {
320 return "Not Found: no such record, or not yours (another account's \
322 rows answer 404, never 403)"
323 .to_owned();
324 }
325 http::StatusCode::from_u16(status)
326 .ok()
327 .and_then(|s| s.canonical_reason())
328 .unwrap_or("Response")
329 .to_owned()
330}
331
332fn response_json(response: &ResponseDoc, schemas: &mut Map<String, Json>) -> Json {
333 let description = description(response.status);
334 match &response.kind {
335 ResponseKind::Serialized {
336 name,
337 schema,
338 many,
339 root,
340 } => {
341 schemas.entry(name.clone()).or_insert_with(schema);
342 let one = json!({"$ref": format!("#/components/schemas/{name}")});
343 let body = if *many {
344 json!({"type": "array", "items": one})
345 } else {
346 one
347 };
348 let body = match root {
349 Some(root) => json!({
350 "type": "object",
351 "properties": {root: body},
352 "required": [root],
353 }),
354 None => body,
355 };
356 json!({
357 "description": description,
358 "content": {"application/json": {"schema": body}},
359 })
360 }
361 ResponseKind::Json => json!({
362 "description": description,
363 "content": {"application/json": {"schema": {}}},
364 }),
365 ResponseKind::Html => json!({
366 "description": description,
367 "content": {"text/html": {"schema": {"type": "string"}}},
368 }),
369 ResponseKind::Redirect => json!({
370 "description": description,
371 "headers": {"Location": {"schema": {"type": "string"}}},
372 }),
373 ResponseKind::Empty => json!({"description": description}),
374 }
375}
376
377pub fn typescript(document: &Json) -> String {
381 let mut out =
382 String::from("// Generated by `glacier types` from the app's serializers; don't edit.\n");
383 let Some(schemas) = document
384 .pointer("/components/schemas")
385 .and_then(Json::as_object)
386 else {
387 return out;
388 };
389 for (name, schema) in schemas {
390 out.push('\n');
391 match schema.get("properties") {
392 Some(_) => out.push_str(&format!(
393 "export interface {name} {}\n",
394 ts_object(schema, 0)
395 )),
396 None => out.push_str(&format!("export type {name} = {};\n", ts_type(schema, 0))),
397 }
398 }
399 out
400}
401
402fn ts_type(schema: &Json, depth: usize) -> String {
404 if let Some(reference) = schema.get("$ref").and_then(Json::as_str) {
405 return reference.rsplit('/').next().unwrap_or("unknown").to_owned();
406 }
407 if let Some(values) = schema.get("enum").and_then(Json::as_array) {
408 return values
409 .iter()
410 .map(Json::to_string)
411 .collect::<Vec<_>>()
412 .join(" | ");
413 }
414 let types: Vec<&str> = match schema.get("type") {
415 Some(Json::String(t)) => vec![t.as_str()],
416 Some(Json::Array(ts)) => ts.iter().filter_map(Json::as_str).collect(),
417 _ => return "unknown".to_owned(),
418 };
419 types
420 .iter()
421 .map(|t| match *t {
422 "string" => "string".to_owned(),
423 "integer" | "number" => "number".to_owned(),
424 "boolean" => "boolean".to_owned(),
425 "null" => "null".to_owned(),
426 "array" => {
427 let item = schema
428 .get("items")
429 .map_or("unknown".to_owned(), |i| ts_type(i, depth));
430 if item.contains(" | ") {
431 format!("({item})[]")
432 } else {
433 format!("{item}[]")
434 }
435 }
436 "object" if schema.get("properties").is_some() => ts_object(schema, depth),
437 _ => "Record<string, unknown>".to_owned(),
438 })
439 .collect::<Vec<_>>()
440 .join(" | ")
441}
442
443fn ts_object(schema: &Json, depth: usize) -> String {
446 let required: Vec<&str> = schema
447 .get("required")
448 .and_then(Json::as_array)
449 .map(|r| r.iter().filter_map(Json::as_str).collect())
450 .unwrap_or_default();
451 let indent = " ".repeat(depth + 1);
452 let mut out = String::from("{\n");
453 if let Some(properties) = schema.get("properties").and_then(Json::as_object) {
454 for (field, field_schema) in properties {
455 let optional = if required.contains(&field.as_str()) {
456 ""
457 } else {
458 "?"
459 };
460 out.push_str(&format!(
461 "{indent}{field}{optional}: {};\n",
462 ts_type(field_schema, depth + 1)
463 ));
464 }
465 }
466 out.push_str(&" ".repeat(depth));
467 out.push('}');
468 out
469}
470
471#[doc(hidden)]
473pub fn schema_name<S>() -> String {
474 let name = std::any::type_name::<S>();
475 let name = name.rsplit("::").next().unwrap_or(name);
476 name.strip_suffix("Serializer")
477 .filter(|n| !n.is_empty())
478 .unwrap_or(name)
479 .to_owned()
480}
481
482#[doc(hidden)]
484pub fn status_code(status: impl crate::response::IntoStatus) -> u16 {
485 status.into_status().as_u16()
486}
487
488#[cfg(test)]
489mod tests {
490 use super::*;
491
492 #[test]
493 fn schemas_as_typescript() {
494 let document = json!({"components": {"schemas": {
495 "Book": {"type": "object", "properties": {
496 "id": {"type": "integer"},
497 "title": {"type": "string"},
498 "price": {"type": ["string", "null"]},
499 "tags": {"type": "array", "items": {"type": "string"}},
500 "status": {"type": "string", "enum": ["draft", "published"]},
501 "author": {"$ref": "#/components/schemas/Author"},
502 }, "required": ["id", "title", "price", "tags", "status", "author"]},
503 "Author": {"type": "object", "properties": {
504 "name": {"type": "string"},
505 "books": {"type": ["array", "null"], "items": {"$ref": "#/components/schemas/Book"}},
506 }, "required": ["name"]},
507 }}});
508 assert_eq!(
509 typescript(&document),
510 "// Generated by `glacier types` from the app's serializers; don't edit.\n\n\
511 export interface Book {\n id: number;\n title: string;\n price: string | null;\n \
512 tags: string[];\n status: \"draft\" | \"published\";\n author: Author;\n}\n\n\
513 export interface Author {\n name: string;\n books?: Book[] | null;\n}\n"
514 );
515 }
516
517 #[test]
518 fn paths_use_braces() {
519 assert_eq!(
520 openapi_path("/books/:id/reviews/:review_id"),
521 (
522 "/books/{id}/reviews/{review_id}".to_owned(),
523 vec!["id".to_owned(), "review_id".to_owned()]
524 )
525 );
526 assert_eq!(openapi_path("/files/*path").0, "/files/{path}");
527 assert_eq!(openapi_path("").0, "/");
528 }
529}