1pub mod external;
10pub mod hoist;
11pub mod manifest;
12pub mod operation_def;
13pub mod plugin;
14pub mod session;
15
16pub use manifest::Manifest;
17use tsurara_sem::{Model, Options, Warning};
18
19#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
20#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
21pub struct OutputFile {
22 pub path: String,
24 pub contents: String,
25}
26
27#[derive(Debug, Clone)]
29pub struct Output {
30 pub files: Vec<OutputFile>,
32 pub warnings: Vec<Warning>,
33 pub manifest: Option<Manifest>,
35}
36
37#[derive(Debug, Clone, Copy)]
40pub struct ExampleInput<'a> {
41 pub model: &'a Model,
42 pub opts: &'a Options,
43 pub manifest: &'a Manifest,
44 pub operation: &'a tsurara_sem::operation::Operation,
45 pub samples: &'a tsurara_sample::OperationSamples,
46}
47
48pub fn example_base_url(model: &Model) -> String {
52 let Some(server) = model.servers.first() else {
53 return "https://api.example.com".into();
54 };
55 let mut url = server.url.clone();
56 for v in &server.variables {
57 url = url.replace(&format!("{{{}}}", v.name), &v.default);
58 }
59 if url.contains(['{', '"', '\\', '\'', '`']) || tsurara_sem::text::has_control(&url) {
60 return "https://api.example.com".into();
61 }
62 if url.starts_with("https://") || url.starts_with("http://") {
63 url
64 } else {
65 format!(
66 "https://api.example.com{}",
67 if url.starts_with('/') {
68 url
69 } else {
70 String::new()
71 }
72 )
73 }
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
79#[serde(rename_all = "camelCase")]
80pub struct Example {
81 pub file: String,
82 pub code: String,
83 #[serde(skip_serializing_if = "Option::is_none")]
85 pub note: Option<String>,
86}
87
88#[derive(Debug, Clone)]
90pub struct Emitted {
91 pub files: Vec<OutputFile>,
92 pub warnings: Vec<Warning>,
94 pub manifest: Option<Manifest>,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
99#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
100#[serde(rename_all = "camelCase")]
101pub struct Markers {
102 pub generated: String,
105 #[serde(default)]
107 pub version: Option<VersionMarker>,
108 #[serde(default)]
111 pub sidecars: Vec<String>,
112}
113
114#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
115#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
116pub struct VersionMarker {
117 pub file: String,
119 pub prefix: String,
121}
122
123impl Markers {
124 pub fn recorded_version(&self, files: &[OutputFile]) -> Option<String> {
126 let marker = self.version.as_ref()?;
127 let file = files.iter().find(|f| f.path == marker.file)?;
128 file.contents
129 .lines()
130 .find_map(|l| l.strip_prefix(marker.prefix.as_str()))
131 .map(|r| r.trim().to_owned())
132 }
133}
134
135pub trait Backend {
137 fn id(&self) -> &'static str;
139
140 fn markers(&self) -> Markers;
142
143 fn emit(&self, model: &Model, opts: &Options) -> Result<Emitted, Error>;
146
147 fn example(&self, _input: &ExampleInput) -> Option<Example> {
151 None
152 }
153
154 fn options_json(&self) -> serde_json::Value {
158 serde_json::Value::Null
159 }
160}
161
162#[derive(Debug, thiserror::Error)]
163pub enum Error {
164 #[error(transparent)]
165 Sem(#[from] tsurara_sem::Error),
166 #[error("{0}")]
168 External(String),
169 #[error("{0}")]
171 Options(String),
172 #[error("plugin `{name}`: {source}")]
173 Plugin {
174 name: String,
175 #[source]
176 source: plugin::PluginError,
177 },
178}
179
180pub fn generate_from_model(
182 backend: &dyn Backend,
183 model: &Model,
184 opts: &Options,
185) -> Result<Output, Error> {
186 let Emitted {
187 files,
188 warnings: backend_warnings,
189 manifest,
190 } = backend.emit(model, opts)?;
191 let mut warnings = model.warnings.clone();
192 warnings.extend(backend_warnings.into_iter().map(|w| Warning {
194 language: Some(backend.id().to_owned()),
195 ..w
196 }));
197 warnings.sort();
198 warnings.dedup();
199 Ok(Output {
200 files,
201 warnings,
202 manifest,
203 })
204}
205
206pub fn generate(
208 backend: &dyn Backend,
209 set: &tsurara_loader::DocumentSet,
210 opts: &Options,
211) -> Result<Output, Error> {
212 let model = tsurara_sem::build_model(set, opts)?;
213 generate_from_model(backend, &model, opts)
214}
215
216pub use plugin::generate_with_plugins;
217
218#[cfg(feature = "schema")]
222pub fn json_schemas() -> Vec<(&'static str, String)> {
223 use schemars::generate::SchemaSettings;
224 let render = |schema: schemars::Schema| {
225 let mut text = serde_json::to_string_pretty(&schema).expect("schemas serialize");
226 text.push('\n');
227 text
228 };
229 let settings = || SchemaSettings::draft2020_12();
230 let model = settings()
231 .into_generator()
232 .into_root_schema_for::<tsurara_sem::Model>();
233 let manifest = settings()
234 .into_generator()
235 .into_root_schema_for::<Manifest>();
236
237 let mut generator = settings().into_generator();
239 let messages = [
240 ("Describe", generator.subschema_for::<external::Describe>()),
241 (
242 "GenerateRequest",
243 generator.subschema_for::<external::GenerateRequest>(),
244 ),
245 (
246 "GenerateResponse",
247 generator.subschema_for::<external::GenerateResponse>(),
248 ),
249 (
250 "ExtendInput",
251 generator.subschema_for::<plugin::ExtendInput>(),
252 ),
253 ("Files", generator.subschema_for::<Vec<OutputFile>>()),
254 (
255 "SessionRequest",
256 generator.subschema_for::<session::SessionRequest>(),
257 ),
258 (
259 "SessionResponse",
260 generator.subschema_for::<session::SessionResponse>(),
261 ),
262 ];
263 let mut defs = generator.take_definitions(true);
264 let refs: Vec<serde_json::Value> = messages
266 .into_iter()
267 .map(|(name, schema)| {
268 let value = schema.to_value();
269 if value.get("$ref").is_some() {
270 value
271 } else {
272 defs.insert(name.into(), value);
273 serde_json::json!({ "$ref": format!("#/$defs/{name}") })
274 }
275 })
276 .collect();
277 let protocol = serde_json::json!({
278 "$schema": "https://json-schema.org/draft/2020-12/schema",
279 "title": "tsurara plugin and external backend protocol",
280 "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.",
281 "anyOf": refs,
282 "$defs": defs,
283 });
284 vec![
285 ("sem-model.schema.json", render(model)),
286 ("manifest.schema.json", render(manifest)),
287 (
288 "plugin-protocol.schema.json",
289 format!(
290 "{}\n",
291 serde_json::to_string_pretty(&protocol).expect("serializes")
292 ),
293 ),
294 ]
295}