pub mod external;
pub mod hoist;
pub mod manifest;
pub mod operation_def;
pub mod plugin;
pub mod session;
pub use manifest::Manifest;
use tsurara_sem::{Model, Options, Warning};
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct OutputFile {
pub path: String,
pub contents: String,
}
#[derive(Debug, Clone)]
pub struct Output {
pub files: Vec<OutputFile>,
pub warnings: Vec<Warning>,
pub manifest: Option<Manifest>,
}
#[derive(Debug, Clone, Copy)]
pub struct ExampleInput<'a> {
pub model: &'a Model,
pub opts: &'a Options,
pub manifest: &'a Manifest,
pub operation: &'a tsurara_sem::operation::Operation,
pub samples: &'a tsurara_sample::OperationSamples,
}
pub fn example_base_url(model: &Model) -> String {
let Some(server) = model.servers.first() else {
return "https://api.example.com".into();
};
let mut url = server.url.clone();
for v in &server.variables {
url = url.replace(&format!("{{{}}}", v.name), &v.default);
}
if url.contains(['{', '"', '\\', '\'', '`']) || tsurara_sem::text::has_control(&url) {
return "https://api.example.com".into();
}
if url.starts_with("https://") || url.starts_with("http://") {
url
} else {
format!(
"https://api.example.com{}",
if url.starts_with('/') {
url
} else {
String::new()
}
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Example {
pub file: String,
pub code: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
}
#[derive(Debug, Clone)]
pub struct Emitted {
pub files: Vec<OutputFile>,
pub warnings: Vec<Warning>,
pub manifest: Option<Manifest>,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
pub struct Markers {
pub generated: String,
#[serde(default)]
pub version: Option<VersionMarker>,
#[serde(default)]
pub sidecars: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct VersionMarker {
pub file: String,
pub prefix: String,
}
impl Markers {
pub fn recorded_version(&self, files: &[OutputFile]) -> Option<String> {
let marker = self.version.as_ref()?;
let file = files.iter().find(|f| f.path == marker.file)?;
file.contents
.lines()
.find_map(|l| l.strip_prefix(marker.prefix.as_str()))
.map(|r| r.trim().to_owned())
}
}
pub trait Backend {
fn id(&self) -> &'static str;
fn markers(&self) -> Markers;
fn emit(&self, model: &Model, opts: &Options) -> Result<Emitted, Error>;
fn example(&self, _input: &ExampleInput) -> Option<Example> {
None
}
fn options_json(&self) -> serde_json::Value {
serde_json::Value::Null
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
Sem(#[from] tsurara_sem::Error),
#[error("{0}")]
External(String),
#[error("{0}")]
Options(String),
#[error("plugin `{name}`: {source}")]
Plugin {
name: String,
#[source]
source: plugin::PluginError,
},
}
pub fn generate_from_model(
backend: &dyn Backend,
model: &Model,
opts: &Options,
) -> Result<Output, Error> {
let Emitted {
files,
warnings: backend_warnings,
manifest,
} = backend.emit(model, opts)?;
let mut warnings = model.warnings.clone();
warnings.extend(backend_warnings.into_iter().map(|w| Warning {
language: Some(backend.id().to_owned()),
..w
}));
warnings.sort();
warnings.dedup();
Ok(Output {
files,
warnings,
manifest,
})
}
pub fn generate(
backend: &dyn Backend,
set: &tsurara_loader::DocumentSet,
opts: &Options,
) -> Result<Output, Error> {
let model = tsurara_sem::build_model(set, opts)?;
generate_from_model(backend, &model, opts)
}
pub use plugin::generate_with_plugins;
#[cfg(feature = "schema")]
pub fn json_schemas() -> Vec<(&'static str, String)> {
use schemars::generate::SchemaSettings;
let render = |schema: schemars::Schema| {
let mut text = serde_json::to_string_pretty(&schema).expect("schemas serialize");
text.push('\n');
text
};
let settings = || SchemaSettings::draft2020_12();
let model = settings()
.into_generator()
.into_root_schema_for::<tsurara_sem::Model>();
let manifest = settings()
.into_generator()
.into_root_schema_for::<Manifest>();
let mut generator = settings().into_generator();
let messages = [
("Describe", generator.subschema_for::<external::Describe>()),
(
"GenerateRequest",
generator.subschema_for::<external::GenerateRequest>(),
),
(
"GenerateResponse",
generator.subschema_for::<external::GenerateResponse>(),
),
(
"ExtendInput",
generator.subschema_for::<plugin::ExtendInput>(),
),
("Files", generator.subschema_for::<Vec<OutputFile>>()),
(
"SessionRequest",
generator.subschema_for::<session::SessionRequest>(),
),
(
"SessionResponse",
generator.subschema_for::<session::SessionResponse>(),
),
];
let mut defs = generator.take_definitions(true);
let refs: Vec<serde_json::Value> = messages
.into_iter()
.map(|(name, schema)| {
let value = schema.to_value();
if value.get("$ref").is_some() {
value
} else {
defs.insert(name.into(), value);
serde_json::json!({ "$ref": format!("#/$defs/{name}") })
}
})
.collect();
let protocol = serde_json::json!({
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "tsurara plugin and external backend protocol",
"description": "`describe` answers with Describe; `generate` receives GenerateRequest and answers with GenerateResponse; the extend hook receives ExtendInput and answers with Files; transformFiles receives and answers with Files; transformModel receives and answers with the model (sem-model.schema.json). Plugin modules exchange SessionRequest and SessionResponse, one per line.",
"anyOf": refs,
"$defs": defs,
});
vec![
("sem-model.schema.json", render(model)),
("manifest.schema.json", render(manifest)),
(
"plugin-protocol.schema.json",
format!(
"{}\n",
serde_json::to_string_pretty(&protocol).expect("serializes")
),
),
]
}