use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use laravel::http::{Request, Response};
use serde_json::{Map, Value, json};
use crate::errors::{ApiErrorCode, ErrorCode};
#[cfg(feature = "database")]
use crate::query::{ApiQuery, Pagination};
use crate::resources::{Kind, Link, Resource};
use crate::versioning::{self, ApiVersion, VersionChange};
use crate::{State, time};
const JSON_API: &str = "application/vnd.api+json";
#[derive(Clone, Default)]
pub struct Endpoint {
summary: Option<String>,
description: Option<String>,
operation_id: Option<String>,
tags: Vec<String>,
status: Option<u16>,
resource: Option<String>,
collection: bool,
#[cfg(feature = "database")]
query: Option<ApiQuery>,
body: Option<(String, Value, Option<Value>)>,
scopes: Vec<(String, String)>,
hidden: bool,
}
impl Endpoint {
#[must_use]
pub fn new(summary: &str) -> Self {
Self {
summary: Some(summary.to_owned()),
..Self::default()
}
}
#[must_use]
pub fn unnamed() -> Self {
Self::default()
}
#[must_use]
pub fn description(mut self, text: &str) -> Self {
self.description = Some(text.to_owned());
self
}
#[must_use]
pub fn operation_id(mut self, id: &str) -> Self {
self.operation_id = Some(id.to_owned());
self
}
#[must_use]
pub fn tags<I: IntoIterator<Item = S>, S: Into<String>>(mut self, tags: I) -> Self {
self.tags = tags.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub const fn status(mut self, status: u16) -> Self {
self.status = Some(status);
self
}
#[must_use]
pub fn resource(mut self, kind: &str) -> Self {
self.resource = Some(kind.to_owned());
self
}
#[must_use]
pub const fn collection(mut self) -> Self {
self.collection = true;
self
}
#[cfg(feature = "database")]
#[must_use]
pub fn query(mut self, query: &ApiQuery) -> Self {
self.resource = Some(query.kind.clone());
self.query = Some(query.clone());
self
}
#[must_use]
pub fn json_api_body(mut self, schema: Value, example: Value) -> Self {
self.body = Some((JSON_API.to_owned(), schema, Some(example)));
self
}
#[must_use]
pub fn body(mut self, schema: Value, example: Value) -> Self {
self.body = Some(("application/json".to_owned(), schema, Some(example)));
self
}
#[must_use]
pub fn scope(mut self, scope: &str, description: &str) -> Self {
self.scopes.push((scope.to_owned(), description.to_owned()));
self
}
#[must_use]
pub const fn hidden(mut self) -> Self {
self.hidden = true;
self
}
}
#[derive(Clone)]
pub(crate) struct Settings {
pub(crate) title: Option<String>,
pub(crate) description: Option<String>,
pub(crate) servers: Option<Vec<String>>,
pub(crate) version: String,
pub(crate) error_codes: Vec<Arc<dyn ErrorCode>>,
pub(crate) endpoints: Vec<(String, Endpoint)>,
}
impl Default for Settings {
fn default() -> Self {
Self {
title: None,
description: None,
servers: None,
version: "1.0.0".to_owned(),
error_codes: Vec::new(),
endpoints: Vec::new(),
}
}
}
struct ApiRoute {
methods: Vec<String>,
uri: String,
}
fn routes(settings: &Settings) -> Vec<ApiRoute> {
let mut routes: Vec<ApiRoute> = Vec::new();
for (key, _) in &settings.endpoints {
let Some((method, uri)) = key.split_once(' ') else {
continue;
};
let uri = format!("/{}", uri.trim_start_matches('/'));
match routes.iter_mut().find(|route| route.uri == uri) {
Some(route) => route.methods.push(method.to_uppercase()),
None => routes.push(ApiRoute {
methods: vec![method.to_uppercase()],
uri,
}),
}
}
routes
}
#[must_use]
pub fn undeclared(routes: &laravel::routing::RouteTable) -> Vec<String> {
let declared: Vec<String> = crate::STATE
.get()
.map(|state| {
state
.config
.openapi
.endpoints
.iter()
.map(|(key, _)| key.clone())
.collect()
})
.unwrap_or_default();
routes
.iter()
.filter(|route| {
route
.middleware
.iter()
.any(|name| name == "fusion_stack::FusionStack")
})
.flat_map(|route| {
let uri = format!("/{}", route.uri.trim_start_matches('/'));
route
.methods
.iter()
.filter(|method| *method != "HEAD")
.map(move |method| format!("{method} {uri}"))
.collect::<Vec<_>>()
})
.filter(|key| !declared.contains(key))
.collect()
}
pub fn generate(version: Option<&str>) -> Result<Value, String> {
let state = crate::STATE
.get()
.ok_or_else(|| "Fusion Stack is not registered as a service provider.".to_owned())?;
let version = match (&state.registry, version) {
(None, _) => None,
(Some(registry), None) => Some(registry.latest.clone()),
(Some(registry), Some(name)) => Some(
registry
.named(name)
.ok_or_else(|| format!("[{name}] is not a version of this API."))?,
),
};
Ok(Generator::new(state, version).document(&routes(&state.config.openapi)))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Gap {
pub kind: String,
pub item: String,
pub location: String,
}
pub fn undocumented() -> Result<Vec<Gap>, String> {
let state = crate::STATE
.get()
.ok_or_else(|| "Fusion Stack is not registered as a service provider.".to_owned())?;
let version = state
.registry
.as_ref()
.map(|registry| registry.latest.clone());
let mut generator = Generator::new(state, version);
generator.document(&routes(&state.config.openapi));
Ok(generator
.gaps
.into_inner()
.into_iter()
.map(|(kind, item, location)| Gap {
kind,
item,
location,
})
.collect())
}
#[must_use]
pub fn pretty(document: &Value) -> String {
let mut body = Vec::new();
let formatter = serde_json::ser::PrettyFormatter::with_indent(b" ");
let mut serializer = serde_json::Serializer::with_formatter(&mut body, formatter);
let _ = serde::Serialize::serialize(document, &mut serializer);
String::from_utf8(body).unwrap_or_default()
}
pub async fn serve(request: Request) -> Response {
let query = crate::query_string::parse(request.uri().query().unwrap_or_default());
let version = query
.get("version")
.and_then(Value::as_str)
.filter(|v| !v.is_empty());
match generate(version) {
Ok(document) => {
let body = pretty(&document);
let mut http =
laravel::axum::http::Response::new(laravel::axum::body::Body::from(body));
http.headers_mut().insert(
laravel::http::header::CONTENT_TYPE,
laravel::http::HeaderValue::from_static("application/json"),
);
Response::from_http(http)
}
Err(_) => Response::new((
laravel::http::StatusCode::NOT_FOUND,
laravel::http::Json(
json!({ "message": "Unknown version. Run api:version:list to see the versions." }),
),
)),
}
}
struct Generator<'a> {
state: &'a State,
version: Option<ApiVersion>,
changes: Vec<Arc<dyn VersionChange>>,
schemas: BTreeMap<String, Value>,
operation_ids: Vec<String>,
scopes: BTreeMap<String, String>,
gaps: RefCell<BTreeSet<(String, String, String)>>,
}
impl<'a> Generator<'a> {
fn new(state: &'a State, version: Option<ApiVersion>) -> Self {
let changes = match (&state.registry, &version) {
(Some(registry), Some(version)) => registry.changes_after(version, None),
_ => Vec::new(),
};
Self {
state,
version,
changes,
schemas: BTreeMap::new(),
operation_ids: Vec::new(),
scopes: BTreeMap::new(),
gaps: RefCell::new(BTreeSet::new()),
}
}
fn missing(&self, kind: &str, item: String, location: String) {
self.gaps
.borrow_mut()
.insert((kind.to_owned(), item, location));
}
fn settings(&self) -> &Settings {
&self.state.config.openapi
}
fn document(&mut self, routes: &[ApiRoute]) -> Value {
let mut paths: BTreeMap<String, Map<String, Value>> = BTreeMap::new();
for route in routes {
for method in &route.methods {
let key = format!("{method} {}", route.uri);
if let (Some(registry), Some(version)) = (&self.state.registry, &self.version)
&& registry
.assert_route_available(
&key,
method,
route.uri.trim_start_matches('/'),
version,
)
.is_err()
{
continue;
}
let endpoint = self
.settings()
.endpoints
.iter()
.find(|(known, _)| *known == key)
.map(|(_, endpoint)| endpoint.clone())
.unwrap_or_default();
if endpoint.hidden {
continue;
}
let operation = self.operation(method, &route.uri, &endpoint);
paths
.entry(route.uri.clone())
.or_default()
.insert(method.to_lowercase(), operation);
}
}
for (scope, description) in &self.scopes {
if description.is_empty() {
self.missing("scope", scope.clone(), "RequiresScope::describe".to_owned());
}
}
let own: Vec<String> = self
.settings()
.error_codes
.iter()
.filter(|code| code.description().is_empty())
.map(|code| code.code().to_owned())
.collect();
for code in own {
self.missing("error code", code, "ErrorCode::description".to_owned());
}
let mut schemas = self.error_schemas();
schemas.extend(std::mem::take(&mut self.schemas));
let mut components = Map::new();
components.insert("schemas".into(), Value::Object(schemas));
components.insert(
"responses".into(),
json!({ "Error": {
"description": "An error, in the JSON:API error format.",
"content": { JSON_API: { "schema": { "$ref": "#/components/schemas/ErrorDocument" } } },
}}),
);
if self.state.config.auth {
components.insert(
"securitySchemes".into(),
json!({ "bearer": {
"type": "http",
"scheme": "bearer",
"description": format!("An API key (`fs_live_…`) or a token from another configured guard.{}", self.scope_list()),
}}),
);
}
let servers = self.settings().servers.clone().unwrap_or_else(|| {
vec![std::env::var("APP_URL").unwrap_or_else(|_| "http://localhost".to_owned())]
});
let mut document = Map::new();
document.insert("openapi".into(), json!("3.1.0"));
document.insert("info".into(), self.info());
document.insert(
"servers".into(),
Value::Array(
servers
.into_iter()
.map(|url| json!({ "url": url }))
.collect(),
),
);
document.insert(
"paths".into(),
Value::Object(
paths
.into_iter()
.map(|(path, ops)| (path, Value::Object(ops)))
.collect(),
),
);
document.insert("components".into(), Value::Object(components));
Value::Object(document)
}
fn info(&self) -> Value {
let settings = self.settings();
let mut info = Map::new();
let title = settings
.title
.clone()
.or_else(|| std::env::var("APP_NAME").ok())
.unwrap_or_else(|| "API".to_owned());
info.insert("title".into(), json!(title));
if let Some(description) = &settings.description {
info.insert("description".into(), json!(description));
}
let version = self
.version
.as_ref()
.map_or_else(|| settings.version.clone(), ToString::to_string);
info.insert("version".into(), json!(version));
if let (Some(registry), Some(version)) = (&self.state.registry, &self.version)
&& let Some(deprecation) = registry.deprecation(version)
{
info.insert("x-deprecated".into(), json!(true));
if let Some(sunset) = deprecation.sunset {
info.insert("x-sunset".into(), json!(time::date(sunset)));
}
}
Value::Object(info)
}
fn operation(&mut self, method: &str, uri: &str, endpoint: &Endpoint) -> Value {
let route = format!("{method} {uri}");
let path_parameters: Vec<String> = uri
.split('/')
.filter_map(|segment| segment.strip_prefix('{')?.strip_suffix('}'))
.map(|name| name.trim_end_matches('?').to_owned())
.collect();
let resource = endpoint.resource.clone();
let collection = endpoint.collection;
let status = endpoint.status.unwrap_or(
if method == "POST" && resource.is_some() && !collection && path_parameters.is_empty() {
201
} else {
200
},
);
for (scope, description) in &endpoint.scopes {
let known = self.scopes.entry(scope.clone()).or_default();
if known.is_empty() {
known.clone_from(description);
}
}
let scopes: Vec<String> = endpoint
.scopes
.iter()
.map(|(scope, _)| scope.clone())
.collect();
let notes = endpoint.scopes.iter().map(|(scope, description)| {
if description.is_empty() {
format!("Requires the `{scope}` scope.")
} else {
format!("Requires the `{scope}` scope: {description}")
}
});
let description: Vec<String> = endpoint
.description
.clone()
.into_iter()
.chain(notes)
.collect();
let mut parameters: Vec<Value> = path_parameters
.iter()
.map(|name| json!({ "name": name, "in": "path", "required": true, "schema": { "type": "string" } }))
.collect();
#[cfg(feature = "database")]
let has_query = endpoint.query.is_some();
#[cfg(not(feature = "database"))]
let has_query = false;
#[cfg(feature = "database")]
if let Some(query) = &endpoint.query {
parameters.extend(self.query_parameters(query, collection, &route));
}
parameters.extend(self.header_parameters(method));
let mut responses = Map::new();
responses.insert(
status.to_string(),
self.success(status, resource.as_deref(), collection),
);
let config = &self.state.config;
let idempotent =
config.idempotency.enabled && config.idempotency.methods.iter().any(|m| m == method);
for (error, applies) in [
(400, has_query || self.version.is_some()),
(401, !scopes.is_empty()),
(403, !scopes.is_empty()),
(404, !path_parameters.is_empty()),
(409, idempotent),
(410, self.version.is_some()),
(422, endpoint.body.is_some()),
(429, config.rate_limit.enabled),
] {
if applies {
responses.insert(
error.to_string(),
json!({ "$ref": "#/components/responses/Error" }),
);
}
}
if endpoint.summary.is_none() {
self.missing(
"endpoint",
format!("{method} {uri}"),
format!("Config::endpoint(\"{method} {uri}\")"),
);
}
if let Some((media, schema, _)) = &endpoint.body {
self.body_gaps(
media,
schema,
endpoint.resource.as_deref(),
&format!("{method} {uri}"),
&route,
);
}
let mut operation = Map::new();
operation.insert(
"operationId".into(),
json!(self.operation_id(endpoint, method, uri)),
);
operation.insert(
"summary".into(),
json!(
endpoint
.summary
.clone()
.unwrap_or_else(|| format!("{method} {uri}"))
),
);
if !description.is_empty() {
operation.insert("description".into(), json!(description.join("\n\n")));
}
operation.insert(
"tags".into(),
json!(if endpoint.tags.is_empty() {
tags(uri)
} else {
endpoint.tags.clone()
}),
);
if !parameters.is_empty() {
operation.insert("parameters".into(), Value::Array(parameters));
}
if let Some((media, schema, example)) = &endpoint.body {
let mut content = Map::new();
content.insert(
"schema".into(),
self.downgrade_body_schema(schema.clone(), &route),
);
if let Some(example) = example {
content.insert(
"example".into(),
self.downgrade_document(example.clone(), &route),
);
}
operation.insert(
"requestBody".into(),
json!({ "required": true, "content": { media.clone(): content } }),
);
}
operation.insert("responses".into(), Value::Object(responses));
if config.auth {
let security = if scopes.is_empty() {
json!([{}, { "bearer": [] }])
} else {
json!([{ "bearer": dedup(&scopes) }])
};
operation.insert("security".into(), security);
}
if !scopes.is_empty() {
operation.insert("x-required-scopes".into(), json!(dedup(&scopes)));
}
Value::Object(operation)
}
fn operation_id(&mut self, endpoint: &Endpoint, method: &str, uri: &str) -> String {
let base = endpoint
.operation_id
.clone()
.unwrap_or_else(|| camel(&format!("{} {uri}", method.to_lowercase())));
let mut id = base.clone();
let mut index = 2;
while self.operation_ids.contains(&id) {
id = camel(&format!("{} {base}", method.to_lowercase()));
if self.operation_ids.contains(&id) {
id = format!("{base}{index}");
}
index += 1;
}
self.operation_ids.push(id.clone());
id
}
fn client_name(&self, kind: &str, field: Option<&str>, route: &str) -> String {
let (kind, field) = versioning::downgrade_name(&self.changes, route, kind, field);
field.unwrap_or(kind)
}
fn resource(&self, kind: &str) -> Option<&Resource> {
self.state.config.resource_named(kind)
}
#[cfg(feature = "database")]
fn query_parameters(&self, query: &ApiQuery, collection: bool, route: &str) -> Vec<Value> {
let kind = &query.kind;
let mut parameters = Vec::new();
if !query.includes.is_empty() {
let includes: Vec<String> = query
.includes
.iter()
.map(|path| self.client_path(kind, path, route))
.collect();
parameters.push(query_parameter(
"include",
&format!(
"Related resources to include, comma-separated. Allowed: {}. Nested paths include their parents.",
includes.join(", ")
),
Some(with_parents(&includes)),
));
}
for (fields_kind, fields) in &query.fields {
let client_kind = self.client_name(fields_kind, None, route);
let names: Vec<String> = fields
.iter()
.map(|field| self.client_name(fields_kind, Some(field), route))
.collect();
parameters.push(query_parameter(
&format!("fields[{client_kind}]"),
&format!(
"Only these fields of {client_kind}, comma-separated: {}.",
names.join(", ")
),
Some(names),
));
}
if !collection {
return parameters;
}
for filter in &query.filters {
let name = self.client_name(kind, Some(&filter.name), route);
let described = query
.descriptions
.iter()
.find(|(known, _)| *known == filter.name)
.map(|(_, text)| format!(" {text}"))
.unwrap_or_default();
if described.is_empty() {
self.missing(
"filter",
format!("{}.{name}", self.client_name(kind, None, route)),
"ApiQuery::describe".to_owned(),
);
}
for operator in &filter.operators {
let (parameter, text) = match operator.as_str() {
"eq" => (
format!("filter[{name}]"),
format!("Only results whose {name} matches."),
),
"in" => (
format!("filter[{name}][in]"),
format!(
"Only results whose {name} is one of these comma-separated values."
),
),
other => (
format!("filter[{name}][{other}]"),
format!("Only results whose {name} is {other} the value."),
),
};
parameters.push(query_parameter(
¶meter,
&format!("{text}{described}"),
(operator == "in").then(Vec::new),
));
}
}
if !query.sorts.is_empty() {
let sorts: Vec<String> = query
.sorts
.iter()
.map(|sort| self.client_name(kind, Some(sort), route))
.collect();
let default = if query.default_sort.is_empty() {
"by ID".to_owned()
} else {
format!("by {}", query.default_sort)
};
let values = sorts
.iter()
.cloned()
.chain(sorts.iter().map(|sort| format!("-{sort}")))
.collect();
parameters.push(query_parameter(
"sort",
&format!(
"Comma-separated fields, `-` for descending. Allowed: {}. Defaults to {default}.",
sorts.join(", ")
),
Some(values),
));
}
let config = &self.state.config;
parameters.push(json!({ "name": "page[size]", "in": "query", "description": "Results per page.", "schema": {
"type": "integer", "minimum": 1, "maximum": config.max_page_size, "default": config.page_size,
}}));
match query.pagination {
Pagination::Offset { .. } => parameters.push(json!({
"name": "page[number]", "in": "query", "description": "The page, from 1.",
"schema": { "type": "integer", "minimum": 1, "default": 1 },
})),
Pagination::Cursor => {
parameters.push(query_parameter(
"page[after]",
"A cursor from `links.next`.",
None,
));
parameters.push(query_parameter(
"page[before]",
"A cursor from `links.prev`.",
None,
));
}
}
parameters
}
#[cfg(feature = "database")]
fn client_path(&self, kind: &str, path: &str, route: &str) -> String {
let mut kind = kind.to_owned();
let mut names = Vec::new();
for segment in path.split('.') {
names.push(self.client_name(&kind, Some(segment), route));
match self
.resource(&kind)
.and_then(|resource| resource.relationships.iter().find(|r| r.name == segment))
{
Some(relationship) => kind.clone_from(&relationship.related),
None => break,
}
}
names.join(".")
}
fn header_parameters(&self, method: &str) -> Vec<Value> {
let mut parameters = Vec::new();
if let Some(version) = &self.version {
parameters.push(json!({
"name": "Api-Version", "in": "header",
"description": "The API version. Without it, requests get the version the API key is pinned to, or the default version.",
"schema": { "type": "string", "example": version.to_string() },
}));
}
let idempotency = &self.state.config.idempotency;
if idempotency.enabled && idempotency.methods.iter().any(|known| known == method) {
parameters.push(json!({
"name": "Idempotency-Key", "in": "header",
"description": "A unique value, such as a UUID, to retry the request safely.",
"schema": { "type": "string", "maxLength": 255 },
}));
}
parameters
}
fn success(&mut self, status: u16, resource: Option<&str>, collection: bool) -> Value {
if status == 204 {
return json!({ "description": "No content." });
}
let Some(kind) = resource else {
return json!({ "description": "Success.", "content": { "application/json": { "schema": { "type": "object" } } } });
};
let reference = self.resource_schema(kind);
let mut seen = Vec::new();
let mut included = self.included_refs(kind, &mut seen);
included.sort();
included.dedup();
let mut properties = Map::new();
properties.insert(
"data".into(),
if collection {
json!({ "type": "array", "items": { "$ref": reference } })
} else {
json!({ "$ref": reference })
},
);
if !included.is_empty() {
let items = if included.len() == 1 {
json!({ "$ref": included[0] })
} else {
json!({ "oneOf": included.iter().map(|r| json!({ "$ref": r })).collect::<Vec<_>>() })
};
properties.insert(
"included".into(),
json!({ "type": "array", "items": items }),
);
}
if collection {
let link = json!({ "type": ["string", "null"], "format": "uri" });
properties.insert(
"links".into(),
json!({ "type": "object", "properties": { "first": link, "prev": link, "next": link, "last": link } }),
);
properties.insert(
"meta".into(),
json!({ "type": "object", "properties": { "page": { "type": "object", "properties": {
"size": { "type": "integer" }, "number": { "type": "integer" }, "total": { "type": "integer" },
}}}}),
);
}
json!({
"description": if collection { "A page of resources." } else { "The resource." },
"content": { JSON_API: { "schema": { "type": "object", "required": ["data"], "properties": properties } } },
})
}
fn resource_schema(&mut self, kind: &str) -> String {
let client_kind = self.client_name(kind, None, "");
let name = format!("{}Resource", studly(&client_kind));
let reference = format!("#/components/schemas/{name}");
if self.schemas.contains_key(&name) {
return reference;
}
self.schemas.insert(name.clone(), json!({}));
let Some(resource) = self.resource(kind).cloned() else {
self.schemas.insert(
name,
json!({ "type": "object", "required": ["type", "id"], "properties": {
"type": { "type": "string", "const": client_kind }, "id": { "type": "string" },
"attributes": { "type": "object" }, "relationships": { "type": "object" },
"links": { "type": "object" }, "meta": { "type": "object" },
}}),
);
return reference;
};
let mut attributes = Map::new();
for attribute in &resource.attributes {
let mut schema = match attribute.kind {
Kind::String => json!({ "type": "string" }),
Kind::Integer => json!({ "type": "integer" }),
Kind::Number => json!({ "type": "number" }),
Kind::Boolean => json!({ "type": "boolean" }),
Kind::Timestamp => json!({ "type": "string", "format": "date-time" }),
Kind::Json => json!({}),
};
if attribute.nullable
&& let Some(kind) = schema.get("type").cloned()
{
schema["type"] = json!([kind, "null"]);
}
describe(&resource, &attribute.name, &mut schema);
self.field_gap(&resource, &client_kind, &attribute.name);
attributes.insert(self.client_name(kind, Some(&attribute.name), ""), schema);
}
let mut relationships = Map::new();
for relationship in &resource.relationships {
let identifier = json!({ "type": "object", "required": ["type", "id"], "properties": {
"type": { "type": "string", "const": self.client_name(&relationship.related, None, "") },
"id": { "type": "string" },
}});
let data = match relationship.link {
Link::HasMany { .. } => json!({ "type": "array", "items": identifier }),
Link::BelongsTo { .. } => json!({ "oneOf": [identifier, { "type": "null" }] }),
};
let mut schema = json!({ "type": "object", "properties": { "data": data } });
describe(&resource, &relationship.name, &mut schema);
self.field_gap(&resource, &client_kind, &relationship.name);
relationships.insert(self.client_name(kind, Some(&relationship.name), ""), schema);
}
let mut properties = Map::new();
properties.insert(
"type".into(),
json!({ "type": "string", "const": client_kind }),
);
properties.insert("id".into(), json!({ "type": "string" }));
properties.insert(
"attributes".into(),
json!({ "type": "object", "properties": attributes }),
);
if !relationships.is_empty() {
properties.insert(
"relationships".into(),
json!({ "type": "object", "properties": relationships }),
);
}
properties.insert("links".into(), json!({ "type": "object" }));
properties.insert("meta".into(), json!({ "type": "object" }));
self.schemas.insert(
name,
json!({ "type": "object", "required": ["type", "id"], "properties": properties }),
);
reference
}
fn field_gap(&self, resource: &Resource, client_kind: &str, field: &str) {
let described = resource
.descriptions
.iter()
.any(|(name, description)| name == field && !description.text.is_empty());
if !described {
self.missing(
"field",
format!(
"{client_kind}.{}",
self.client_name(&resource.kind, Some(field), "")
),
format!("Resource \"{}\"", resource.kind),
);
}
}
fn body_gaps(
&self,
media: &str,
schema: &Value,
resource: Option<&str>,
key: &str,
route: &str,
) {
let location = format!("the body of Config::endpoint(\"{key}\")");
if media == JSON_API {
let kind = resource
.map(|kind| format!("{}.", self.client_name(kind, None, route)))
.unwrap_or_default();
for member in ["attributes", "relationships"] {
if let Some(fields) = schema
.pointer(&format!("/properties/data/properties/{member}/properties"))
.and_then(Value::as_object)
{
for (field, field_schema) in fields {
if field_schema.get("description").is_none() {
self.missing("field", format!("{kind}{field}"), location.clone());
}
}
}
}
} else if let Some(fields) = schema.get("properties").and_then(Value::as_object) {
for (field, field_schema) in fields {
if field_schema.get("description").is_none() {
self.missing("field", field.clone(), location.clone());
}
}
}
}
fn included_refs(&mut self, kind: &str, seen: &mut Vec<String>) -> Vec<String> {
if seen.iter().any(|known| known == kind) {
return Vec::new();
}
seen.push(kind.to_owned());
let related: Vec<String> = self
.resource(kind)
.map(|resource| {
resource
.relationships
.iter()
.map(|r| r.related.clone())
.collect()
})
.unwrap_or_default();
let mut refs = Vec::new();
for related in related {
refs.push(self.resource_schema(&related));
refs.extend(self.included_refs(&related, seen));
}
refs
}
fn downgrade_body_schema(&self, mut schema: Value, route: &str) -> Value {
let Some(kind) = schema
.pointer("/properties/data/properties/type/enum/0")
.and_then(Value::as_str)
.map(str::to_owned)
else {
return schema;
};
for member in ["attributes", "relationships"] {
let Some(section) =
schema.pointer_mut(&format!("/properties/data/properties/{member}"))
else {
continue;
};
if let Some(Value::Object(properties)) = section.get_mut("properties") {
let renamed: Map<String, Value> = std::mem::take(properties)
.into_iter()
.map(|(name, value)| (self.client_name(&kind, Some(&name), route), value))
.collect();
*properties = renamed;
}
if let Some(Value::Array(required)) = section.get_mut("required") {
for name in required.iter_mut() {
if let Some(text) = name.as_str() {
*name = json!(self.client_name(&kind, Some(text), route));
}
}
}
}
schema
}
fn downgrade_document(&self, mut document: Value, route: &str) -> Value {
let types = versioning::document::types(&document);
for change in self.changes.iter().rev() {
if versioning::applies_to(change.as_ref(), &types, route) {
change.transform_response(&mut document);
}
}
document
}
fn error_schemas(&self) -> Map<String, Value> {
let mut descriptions: BTreeMap<String, String> = BTreeMap::new();
let package = ApiErrorCode::ALL.iter().map(|code| code as &dyn ErrorCode);
let own = self.settings().error_codes.iter().map(AsRef::as_ref);
for code in package.chain(own) {
let text = if code.description().is_empty() {
format!("{}.", code.title())
} else {
code.description().to_owned()
};
descriptions.insert(code.code().to_owned(), format!("{}: {text}", code.status()));
}
let codes: Vec<&String> = descriptions.keys().collect();
let mut schemas = Map::new();
schemas.insert("Error".into(), json!({ "type": "object", "required": ["status", "code", "title"], "properties": {
"status": { "type": "string", "description": "The HTTP status code." },
"code": { "type": "string", "enum": codes, "description": "A stable, machine-readable error code.", "x-enumDescriptions": descriptions },
"title": { "type": "string" },
"detail": { "type": "string" },
"source": { "type": "object", "properties": {
"pointer": { "type": "string", "description": "A JSON pointer to the request document member at fault." },
"parameter": { "type": "string", "description": "The query parameter at fault." },
"header": { "type": "string", "description": "The request header at fault." },
}},
"links": { "type": "object" },
"meta": { "type": "object", "properties": { "request_id": { "type": "string" } } },
}}));
schemas.insert(
"ErrorDocument".into(),
json!({ "type": "object", "required": ["errors"], "properties": {
"errors": { "type": "array", "items": { "$ref": "#/components/schemas/Error" } },
}}),
);
schemas
}
fn scope_list(&self) -> String {
if self.scopes.is_empty() {
return String::new();
}
let lines: Vec<String> = self
.scopes
.iter()
.map(|(scope, description)| {
if description.is_empty() {
format!("- `{scope}`")
} else {
format!("- `{scope}`: {description}")
}
})
.collect();
format!("\n\nScopes:\n\n{}", lines.join("\n"))
}
}
fn describe(resource: &Resource, field: &str, schema: &mut Value) {
let Some((_, description)) = resource.descriptions.iter().find(|(name, _)| name == field)
else {
return;
};
let Value::Object(schema) = schema else {
return;
};
if !description.text.is_empty() {
schema.insert("description".into(), json!(description.text));
}
if !description.values.is_empty() {
schema.insert(
"enum".into(),
json!(
description
.values
.iter()
.map(|(value, _)| value)
.collect::<Vec<_>>()
),
);
let meanings: Map<String, Value> = description
.values
.iter()
.map(|(value, meaning)| (value.clone(), json!(meaning)))
.collect();
schema.insert("x-enumDescriptions".into(), Value::Object(meanings));
}
}
fn query_parameter(name: &str, description: &str, values: Option<Vec<String>>) -> Value {
match values {
None => {
json!({ "name": name, "in": "query", "description": description, "schema": { "type": "string" } })
}
Some(values) => {
let items = if values.is_empty() {
json!({ "type": "string" })
} else {
json!({ "type": "string", "enum": values })
};
json!({ "name": name, "in": "query", "description": description, "style": "form", "explode": false, "schema": { "type": "array", "items": items } })
}
}
}
fn with_parents(paths: &[String]) -> Vec<String> {
let mut all: Vec<String> = Vec::new();
for path in paths {
let segments: Vec<&str> = path.split('.').collect();
for end in 1..=segments.len() {
let parent = segments[..end].join(".");
if !all.contains(&parent) {
all.push(parent);
}
}
}
all
}
fn dedup(values: &[String]) -> Vec<String> {
let mut unique: Vec<String> = Vec::new();
for value in values {
if !unique.contains(value) {
unique.push(value.clone());
}
}
unique
}
fn tags(path: &str) -> Vec<String> {
path.trim_matches('/')
.split('/')
.find(|segment| {
!segment.is_empty()
&& !segment.starts_with('{')
&& !(segment.len() > 1
&& segment.starts_with('v')
&& segment[1..].bytes().all(|b| b.is_ascii_digit()))
})
.map(|segment| vec![segment.to_owned()])
.unwrap_or_default()
}
fn camel(text: &str) -> String {
let mut out = String::new();
for (index, word) in text
.split(|c: char| !c.is_ascii_alphanumeric())
.filter(|word| !word.is_empty())
.enumerate()
{
let mut chars = word.chars();
if let Some(first) = chars.next() {
if index == 0 {
out.push(first.to_ascii_lowercase());
} else {
out.push(first.to_ascii_uppercase());
}
out.push_str(chars.as_str());
}
}
out
}
fn studly(kind: &str) -> String {
kind.split(['-', '.', '_', ' '])
.filter(|word| !word.is_empty())
.map(|word| {
let mut chars = word.chars();
chars.next().map_or_else(String::new, |first| {
first.to_ascii_uppercase().to_string() + chars.as_str()
})
})
.collect()
}
#[cfg(test)]
mod tests {
use super::{camel, studly, tags, with_parents};
#[test]
fn names_match_laravels_string_helpers() {
assert_eq!(camel("get /v1/orders/{order}"), "getV1OrdersOrder");
assert_eq!(camel("post orders.invoice"), "postOrdersInvoice");
assert_eq!(studly("order-statuses"), "OrderStatuses");
assert_eq!(tags("/v1/orders/{order}/cancel"), ["orders"]);
assert_eq!(tags("/v12/{id}"), Vec::<String>::new());
assert_eq!(
with_parents(&["customer.orders".to_owned(), "customer".to_owned()]),
["customer", "customer.orders"]
);
}
}