1pub mod applied;
14pub mod catalogs;
15pub mod clients;
16pub mod ids;
17pub mod machine;
18pub mod project;
19pub mod secrets;
20pub mod server;
21pub mod settings;
22pub mod skill_meta;
23pub mod sources;
24pub mod validate;
25
26use std::ops::Range;
27use std::path::Path;
28
29use schemars::JsonSchema;
30use serde::Serialize;
31use serde::de::DeserializeOwned;
32use toml_edit::{ArrayOfTables, DocumentMut, Item, TableLike, Value};
33
34use crate::error::{CoreError, ErrorCode};
35use crate::fs::Fs;
36pub use validate::{
37 Diagnostic, Diagnostics, Severity, StoreDocument, StoreFile, validate_store_file,
38};
39
40pub const SCHEMA_VERSION: i64 = 1;
42
43const BOM: char = '\u{feff}';
44
45pub trait StoreModel: Serialize + DeserializeOwned + JsonSchema {
47 const SCHEMA_NAME: &'static str;
49}
50
51pub fn json_schema<T: StoreModel>() -> String {
54 let generator = schemars::generate::SchemaSettings::draft2020_12()
55 .with_transform(drop_null)
56 .into_generator();
57 let schema = generator.into_root_schema_for::<T>();
58 let mut text = serde_json::to_string_pretty(&schema).expect("JSON Schema serializes");
59 text.push('\n');
60 text
61}
62
63fn drop_null(schema: &mut schemars::Schema) {
65 use serde_json::Value as Json;
66 if let Some(object) = schema.as_object_mut() {
67 if let Some(Json::Array(types)) = object.get_mut("type") {
68 types.retain(|ty| ty != "null");
69 if types.len() == 1 {
70 let only = types.remove(0);
71 object.insert("type".to_owned(), only);
72 }
73 }
74 if let Some(Json::Array(options)) = object.get_mut("anyOf") {
75 options.retain(|option| option.get("type").is_none_or(|ty| ty != "null"));
76 if let [Json::Object(_)] = options.as_slice() {
77 let Some(Json::Object(only)) = options.pop() else {
78 unreachable!("checked above");
79 };
80 object.remove("anyOf");
81 for (key, value) in only {
82 object.entry(key).or_insert(value);
83 }
84 }
85 }
86 }
87 schemars::transform::transform_subschemas(&mut drop_null, schema);
88}
89
90#[derive(Debug, Clone)]
92pub struct TomlDocument<T> {
93 doc: DocumentMut,
94 value: T,
95 bom: bool,
96 crlf: bool,
97}
98
99impl<T: StoreModel> TomlDocument<T> {
100 pub fn new(value: T) -> Self {
102 Self {
103 doc: DocumentMut::new(),
104 value,
105 bom: false,
106 crlf: false,
107 }
108 }
109
110 pub fn parse(text: &str) -> Result<Self, Diagnostic> {
114 let bom = text.starts_with(BOM);
115 let text = text.strip_prefix(BOM).unwrap_or(text);
116 let crlf = text.find('\n').is_some_and(|i| text[..i].ends_with('\r'));
117
118 let spanned = toml_edit::Document::parse(text).map_err(|err| {
119 Diagnostic::error(
120 ErrorCode::ParseError,
121 "",
122 located(text, err.span(), err.message()),
123 )
124 })?;
125 check_schema_version(spanned.as_table())?;
126 let value =
127 toml::from_str::<T>(text).map_err(|err| serde_diagnostic(text, &spanned, &err))?;
128 Ok(Self {
129 doc: spanned.into_mut(),
130 value,
131 bom,
132 crlf,
133 })
134 }
135
136 pub fn load(fs: &dyn Fs, path: &Path) -> Result<Self, CoreError> {
138 let text = fs.read_to_string(path).map_err(|err| {
139 CoreError::new(ErrorCode::IoError, format!("cannot read file: {err}")).with_path(path)
140 })?;
141 Self::parse(&text).map_err(|diagnostic| diagnostic.to_core_error(Some(path)))
142 }
143
144 pub fn save(&self, fs: &dyn Fs, path: &Path) -> Result<(), CoreError> {
146 let text = self.to_text().map_err(|err| err.with_path(path))?;
147 fs.write(path, text.as_bytes()).map_err(|err| {
148 CoreError::new(ErrorCode::IoError, format!("cannot write file: {err}")).with_path(path)
149 })
150 }
151
152 pub fn value(&self) -> &T {
153 &self.value
154 }
155
156 pub fn value_mut(&mut self) -> &mut T {
157 &mut self.value
158 }
159
160 pub fn into_value(self) -> T {
161 self.value
162 }
163
164 pub fn to_text(&self) -> Result<String, CoreError> {
168 let rendered = toml::to_string(&self.value).map_err(|err| {
169 CoreError::new(ErrorCode::InvalidValue, format!("cannot serialize: {err}"))
170 })?;
171 let fresh: DocumentMut = rendered.parse().map_err(|err: toml_edit::TomlError| {
172 CoreError::new(
173 ErrorCode::ParseError,
174 format!("serialized TOML does not parse: {}", err.message()),
175 )
176 })?;
177 let mut doc = self.doc.clone();
178 merge_table(doc.as_table_mut(), fresh.as_table());
179 let mut text = doc.to_string();
180 if self.crlf {
181 text = text.replace('\n', "\r\n");
182 }
183 if self.bom {
184 text.insert(0, BOM);
185 }
186 Ok(text)
187 }
188}
189
190fn check_schema_version(root: &toml_edit::Table) -> Result<(), Diagnostic> {
193 match root.get("schema") {
194 None => Err(Diagnostic::error(
195 ErrorCode::MissingField,
196 "schema",
197 format!("missing `schema = {SCHEMA_VERSION}`"),
198 )),
199 Some(item) => match item.as_integer() {
200 Some(SCHEMA_VERSION) => Ok(()),
201 Some(other) => Err(Diagnostic::error(
202 ErrorCode::UnsupportedSchema,
203 "schema",
204 format!(
205 "schema {other} is not supported; this build reads schema {SCHEMA_VERSION}"
206 ),
207 )),
208 None => Err(Diagnostic::error(
209 ErrorCode::InvalidValue,
210 "schema",
211 "`schema` must be an integer",
212 )),
213 },
214 }
215}
216
217fn serde_diagnostic(
218 text: &str,
219 spanned: &toml_edit::Document<&str>,
220 err: &toml::de::Error,
221) -> Diagnostic {
222 let root = spanned.as_table();
223 let message = err.message();
224 let mut span = err.span().filter(|span| !span.is_empty());
225 let mut path = span
226 .as_ref()
227 .and_then(|span| path_at(root, span.start, ""))
228 .unwrap_or_default();
229 if let Some(field) = message
231 .strip_prefix("missing field `")
232 .and_then(|rest| rest.strip_suffix('`'))
233 {
234 path = validate::join(&path, field);
235 return Diagnostic::error(ErrorCode::MissingField, path, message);
236 }
237 if path.is_empty()
240 && let Some(needle) = offending_value(message)
241 {
242 let mut hits = Vec::new();
243 find_scalars(root, &needle, "", &mut hits);
244 if let [(found, found_span)] = hits.as_slice() {
245 path = found.clone();
246 span = found_span.clone();
247 }
248 }
249 let span = span.filter(|_| !path.is_empty());
250 Diagnostic::error(ErrorCode::InvalidValue, path, located(text, span, message))
251}
252
253fn offending_value(message: &str) -> Option<String> {
256 let quoted = |rest: &str, open: char, close: char| {
257 let rest = &rest[rest.find(open)? + open.len_utf8()..];
258 rest.find(close).map(|end| rest[..end].to_owned())
259 };
260 if let Some(rest) = message.strip_prefix("unknown variant ") {
261 return quoted(rest, '`', '`');
262 }
263 let rest = message.strip_prefix("invalid type: ")?;
264 let rest = &rest[..rest.find(", expected").unwrap_or(rest.len())];
265 match rest.strip_prefix("string ") {
266 Some(string) => quoted(string, '"', '"'),
267 None => quoted(rest, '`', '`'),
268 }
269}
270
271fn find_scalars(
273 table: &dyn TableLike,
274 needle: &str,
275 prefix: &str,
276 hits: &mut Vec<(String, Option<Range<usize>>)>,
277) {
278 fn visit_value(
279 value: &Value,
280 needle: &str,
281 path: String,
282 hits: &mut Vec<(String, Option<Range<usize>>)>,
283 ) {
284 let text = match value {
285 Value::String(v) => v.value().clone(),
286 Value::Integer(v) => v.value().to_string(),
287 Value::Float(v) => v.value().to_string(),
288 Value::Boolean(v) => v.value().to_string(),
289 Value::Datetime(v) => v.value().to_string(),
290 Value::Array(array) => {
291 for (index, value) in array.iter().enumerate() {
292 visit_value(value, needle, validate::at(&path, index), hits);
293 }
294 return;
295 }
296 Value::InlineTable(table) => return find_scalars(table, needle, &path, hits),
297 };
298 if text == needle {
299 hits.push((path, value.span()));
300 }
301 }
302 for (key, item) in table.iter() {
303 let path = validate::join(prefix, key);
304 match item {
305 Item::Value(value) => visit_value(value, needle, path, hits),
306 Item::Table(table) => find_scalars(table, needle, &path, hits),
307 Item::ArrayOfTables(array) => {
308 for (index, table) in array.iter().enumerate() {
309 find_scalars(table, needle, &validate::at(&path, index), hits);
310 }
311 }
312 Item::None => {}
313 }
314 }
315}
316
317fn path_at(table: &dyn TableLike, offset: usize, prefix: &str) -> Option<String> {
319 for (key, item) in table.iter() {
320 let path = validate::join(prefix, key);
321 if let Some(inner) = item_path_at(item, offset, &path) {
322 return Some(inner);
323 }
324 let key_span = table.key(key).and_then(|key| key.span());
325 if contains(item.span(), offset) || contains(key_span, offset) {
326 return Some(path);
327 }
328 }
329 None
330}
331
332fn item_path_at(item: &Item, offset: usize, path: &str) -> Option<String> {
333 match item {
334 Item::Table(table) => path_at(table, offset, path),
335 Item::ArrayOfTables(array) => array.iter().enumerate().find_map(|(index, table)| {
336 path_at(table, offset, &validate::at(path, index))
337 .or_else(|| contains(table.span(), offset).then(|| validate::at(path, index)))
338 }),
339 Item::Value(Value::InlineTable(table)) => path_at(table, offset, path),
340 Item::Value(Value::Array(array)) => array.iter().enumerate().find_map(|(index, value)| {
341 contains(value.span(), offset).then(|| validate::at(path, index))
342 }),
343 Item::Value(_) | Item::None => None,
344 }
345}
346
347fn contains(span: Option<Range<usize>>, offset: usize) -> bool {
348 span.is_some_and(|span| span.contains(&offset))
349}
350
351fn located(text: &str, span: Option<Range<usize>>, message: &str) -> String {
353 let Some(span) = span else {
354 return message.to_owned();
355 };
356 let before = &text[..span.start.min(text.len())];
357 let line = before.matches('\n').count() + 1;
358 let column = before.len() - before.rfind('\n').map_or(0, |i| i + 1) + 1;
359 format!("line {line}, column {column}: {message}")
360}
361
362fn merge_table(old: &mut dyn TableLike, new: &dyn TableLike) {
365 let stale: Vec<String> = old
366 .iter()
367 .filter(|(key, _)| !new.contains_key(key))
368 .map(|(key, _)| key.to_owned())
369 .collect();
370 for key in stale {
371 old.remove(&key);
372 }
373 for (key, new_item) in new.iter() {
374 match old.get_mut(key) {
375 Some(old_item) => merge_item(old_item, new_item),
376 None => {
377 old.insert(key, detached(new_item));
378 }
379 }
380 }
381}
382
383fn merge_item(old: &mut Item, new: &Item) {
384 if plain(old) == plain(new) {
385 return;
386 }
387 if let (Some(old), Some(new)) = (old.as_table_like_mut(), new.as_table_like()) {
388 return merge_table(old, new);
389 }
390 if let (Item::ArrayOfTables(old), Item::ArrayOfTables(new)) = (&mut *old, new) {
391 return merge_array_of_tables(old, new);
392 }
393 let replacement = detached(new);
394 if let Item::Value(old_value) = old {
395 if let Ok(mut value) = replacement.clone().into_value() {
398 *value.decor_mut() = old_value.decor().clone();
399 *old_value = value;
400 return;
401 }
402 }
403 *old = replacement;
404}
405
406fn merge_array_of_tables(old: &mut ArrayOfTables, new: &ArrayOfTables) {
407 while old.len() > new.len() {
408 old.remove(old.len() - 1);
409 }
410 for (index, new_table) in new.iter().enumerate() {
411 match old.get_mut(index) {
412 Some(old_table) => merge_table(old_table, new_table),
413 None => {
414 let mut table = new_table.clone();
415 clear_positions(&mut table);
416 old.push(table);
417 }
418 }
419 }
420}
421
422fn detached(item: &Item) -> Item {
425 let mut item = item.clone();
426 match &mut item {
427 Item::Table(table) => clear_positions(table),
428 Item::ArrayOfTables(array) => array.iter_mut().for_each(clear_positions),
429 Item::Value(_) | Item::None => {}
430 }
431 item
432}
433
434fn clear_positions(table: &mut toml_edit::Table) {
435 table.set_position(None);
436 for (_, item) in table.iter_mut() {
437 match item {
438 Item::Table(table) => clear_positions(table),
439 Item::ArrayOfTables(array) => array.iter_mut().for_each(clear_positions),
440 Item::Value(_) | Item::None => {}
441 }
442 }
443}
444
445fn plain(item: &Item) -> Option<toml::Value> {
447 match item {
448 Item::None => None,
449 Item::Value(value) => Some(plain_value(value)),
450 Item::Table(table) => Some(plain_table(table)),
451 Item::ArrayOfTables(array) => Some(toml::Value::Array(
452 array.iter().map(|table| plain_table(table)).collect(),
453 )),
454 }
455}
456
457fn plain_table(table: &dyn TableLike) -> toml::Value {
458 toml::Value::Table(
459 table
460 .iter()
461 .filter_map(|(key, item)| plain(item).map(|value| (key.to_owned(), value)))
462 .collect(),
463 )
464}
465
466fn plain_value(value: &Value) -> toml::Value {
467 match value {
468 Value::String(v) => toml::Value::String(v.value().clone()),
469 Value::Integer(v) => toml::Value::Integer(*v.value()),
470 Value::Float(v) => toml::Value::Float(*v.value()),
471 Value::Boolean(v) => toml::Value::Boolean(*v.value()),
472 Value::Datetime(v) => toml::Value::Datetime(*v.value()),
473 Value::Array(array) => toml::Value::Array(array.iter().map(plain_value).collect()),
474 Value::InlineTable(table) => plain_table(table),
475 }
476}