1use std::collections::BTreeMap;
8use std::path::PathBuf;
9
10use indexmap::IndexMap;
11use serde::{Deserialize, Serialize};
12
13use crate::diagnostic::{SchemaDiagnostic, Severity, child_path};
14use crate::dialect::Dialect;
15use crate::filter::{FilterConfig, FilterError};
16use crate::names::SourceSubpath;
17
18#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum Source {
21 Git { url: String },
22 Path { path: PathBuf },
23}
24
25#[derive(Debug, Clone, PartialEq)]
29pub struct Entry {
30 pub source: Source,
31 pub version: Option<String>,
32 pub subpath: Option<SourceSubpath>,
33 pub dialect: Option<Dialect>,
35 pub plugin: Option<String>,
37 pub filter: FilterConfig,
38 pub unknown: BTreeMap<String, toml::Value>,
40}
41
42#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
46pub struct RawEntry {
47 #[serde(default, skip_serializing_if = "Option::is_none")]
48 pub url: Option<String>,
49 #[serde(default, skip_serializing_if = "Option::is_none", with = "path_serde")]
50 pub path: Option<PathBuf>,
51 #[serde(default, skip_serializing_if = "Option::is_none")]
52 pub subpath: Option<SourceSubpath>,
53 #[serde(default, skip_serializing_if = "Option::is_none")]
54 pub version: Option<String>,
55 #[serde(default, skip_serializing_if = "Option::is_none")]
56 pub dialect: Option<Dialect>,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub plugin: Option<String>,
59 #[serde(flatten)]
60 pub filter: FilterConfig,
61 #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")]
62 pub unknown: BTreeMap<String, toml::Value>,
63}
64
65mod path_serde {
67 use std::path::PathBuf;
68
69 use serde::{Deserialize, Deserializer, Serializer};
70
71 pub fn serialize<S: Serializer>(
72 path: &Option<PathBuf>,
73 serializer: S,
74 ) -> Result<S::Ok, S::Error> {
75 match path {
76 Some(path) => serializer.serialize_some(&path.to_string_lossy().replace('\\', "/")),
77 None => serializer.serialize_none(),
78 }
79 }
80
81 pub fn deserialize<'de, D: Deserializer<'de>>(
82 deserializer: D,
83 ) -> Result<Option<PathBuf>, D::Error> {
84 Ok(Option::<String>::deserialize(deserializer)?.map(PathBuf::from))
85 }
86}
87
88#[derive(Debug, thiserror::Error, PartialEq, Eq)]
90pub enum EntryError {
91 #[error("source `{name}` has both `url` and `path` — pick one")]
92 BothSources { name: String },
93 #[error("source `{name}` has neither `url` nor `path` — one is required")]
94 NoSource { name: String },
95 #[error(transparent)]
96 PluginSelector(#[from] PluginSelectorError),
97 #[error(transparent)]
99 Filter(#[from] FilterError),
100 #[error(
101 "dependency name `{name}` is reserved: names starting `{prefix}` are what Mars records the user level's and a host's content under in a project"
102 )]
103 Reserved { name: String, prefix: &'static str },
104}
105
106pub const USER_PREFIX: &str = "_user-";
108pub const HOST_PREFIX: &str = "_provided-";
110pub const RESERVED_PREFIXES: [&str; 2] = [USER_PREFIX, HOST_PREFIX];
113
114impl EntryError {
115 pub fn code(&self) -> &'static str {
117 match self {
118 Self::BothSources { .. } | Self::NoSource { .. } => "dependency.source",
119 Self::PluginSelector(_) => "dependency.plugin-selector",
120 Self::Filter(_) => "dependency.filter-conflict",
121 Self::Reserved { .. } => "dependency.reserved-name",
122 }
123 }
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum Strictness {
129 Consumer,
131 Package,
135}
136
137#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct EntryWarning {
140 pub code: &'static str,
141 pub message: String,
142}
143
144impl Entry {
145 pub fn git(url: impl Into<String>) -> Self {
147 Self::from_source(Source::Git { url: url.into() })
148 }
149
150 pub fn at_path(path: impl Into<PathBuf>) -> Self {
152 Self::from_source(Source::Path { path: path.into() })
153 }
154
155 pub fn from_source(source: Source) -> Self {
157 Self {
158 source,
159 version: None,
160 subpath: None,
161 dialect: None,
162 plugin: None,
163 filter: FilterConfig::default(),
164 unknown: BTreeMap::new(),
165 }
166 }
167
168 pub fn url(&self) -> Option<&str> {
170 match &self.source {
171 Source::Git { url } => Some(url),
172 Source::Path { .. } => None,
173 }
174 }
175
176 pub fn path(&self) -> Option<&std::path::Path> {
178 match &self.source {
179 Source::Path { path } => Some(path),
180 Source::Git { .. } => None,
181 }
182 }
183
184 pub fn read(
191 name: &str,
192 mut raw: RawEntry,
193 strictness: Strictness,
194 ) -> Result<(Self, Vec<EntryWarning>), EntryError> {
195 if let Some(prefix) = RESERVED_PREFIXES
196 .into_iter()
197 .find(|prefix| name.starts_with(prefix))
198 {
199 return Err(EntryError::Reserved {
200 name: name.into(),
201 prefix,
202 });
203 }
204 let mut warnings = Vec::new();
205 if strictness == Strictness::Package && raw.plugin.is_some() && raw.dialect.take().is_some()
206 {
207 warnings.push(EntryWarning {
208 code: "dependency.dialect-ignored",
209 message: format!(
210 "source `{name}` has both `plugin` and `dialect`; the dialect is ignored"
211 ),
212 });
213 }
214 let source = match (raw.url, raw.path) {
215 (Some(url), None) => Source::Git {
216 url: crate::git_url::with_default_scheme(&url),
217 },
218 (None, Some(path)) => Source::Path { path },
219 (Some(_), Some(_)) => return Err(EntryError::BothSources { name: name.into() }),
220 (None, None) => return Err(EntryError::NoSource { name: name.into() }),
221 };
222 validate_plugin_selector(
223 name,
224 raw.plugin.as_deref(),
225 raw.subpath.as_ref(),
226 raw.dialect,
227 )?;
228 match (raw.filter.validate(name), strictness) {
229 (Err(conflict), Strictness::Consumer) => return Err(conflict.into()),
230 (Err(conflict), Strictness::Package) => warnings.push(EntryWarning {
231 code: "dependency.filter-conflict",
232 message: conflict.to_string(),
233 }),
234 (Ok(()), _) => {}
235 }
236 let entry = Self {
237 source,
238 version: raw.version,
239 subpath: raw.subpath,
240 dialect: raw.dialect,
241 plugin: raw.plugin,
242 filter: raw.filter,
243 unknown: raw.unknown,
244 };
245 Ok((entry, warnings))
246 }
247}
248
249impl From<&Entry> for RawEntry {
250 fn from(entry: &Entry) -> Self {
251 let (url, path) = match &entry.source {
252 Source::Git { url } => (Some(url.clone()), None),
253 Source::Path { path } => (None, Some(path.clone())),
254 };
255 Self {
256 url,
257 path,
258 subpath: entry.subpath.clone(),
259 version: entry.version.clone(),
260 dialect: entry.dialect,
261 plugin: entry.plugin.clone(),
262 filter: entry.filter.clone(),
263 unknown: entry.unknown.clone(),
264 }
265 }
266}
267
268impl From<Entry> for RawEntry {
269 fn from(entry: Entry) -> Self {
270 Self::from(&entry)
271 }
272}
273
274impl Serialize for Entry {
275 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
276 RawEntry::from(self).serialize(serializer)
277 }
278}
279
280#[derive(Debug, Clone, Default, PartialEq, Serialize)]
282pub struct Dependencies {
283 #[serde(skip_serializing_if = "IndexMap::is_empty")]
284 pub dependencies: IndexMap<String, Entry>,
285 #[serde(
286 rename = "local-dependencies",
287 skip_serializing_if = "IndexMap::is_empty"
288 )]
289 pub local_dependencies: IndexMap<String, Entry>,
290}
291
292impl Dependencies {
293 pub fn read(
300 document: &toml_edit::DocumentMut,
301 diagnostics: &mut Vec<SchemaDiagnostic>,
302 ) -> Self {
303 let tables = ["dependencies", "local-dependencies"].map(|key| match document.get(key) {
304 None => Ok(None),
305 Some(item) => item.as_table_like().map(Some).ok_or(key),
306 });
307 let [Ok(dependencies), Ok(local_dependencies)] = tables else {
308 let bad = tables.iter().find_map(|table| table.as_ref().err());
309 diagnostics.push(SchemaDiagnostic::new(
310 "dependency.invalid",
311 Severity::Error,
312 Vec::new(),
313 format!(
314 "`dependencies` and `local-dependencies` must be tables: `{}` is not",
315 bad.copied().unwrap_or_default()
316 ),
317 ));
318 return Self::default();
319 };
320 Self {
321 dependencies: read_table("dependencies", dependencies, Severity::Error, diagnostics),
322 local_dependencies: read_table(
323 "local-dependencies",
324 local_dependencies,
325 Severity::Warning,
326 diagnostics,
327 ),
328 }
329 }
330}
331
332fn read_table(
334 table: &str,
335 items: Option<&dyn toml_edit::TableLike>,
336 refusal: Severity,
337 diagnostics: &mut Vec<SchemaDiagnostic>,
338) -> IndexMap<String, Entry> {
339 let mut entries = IndexMap::new();
340 for (name, item) in items.into_iter().flat_map(|items| items.iter()) {
341 let path = child_path(table, name);
342 if let Err(message) = crate::ordered::reject_unholdable_key(name) {
345 diagnostics.push(SchemaDiagnostic::new(
346 "toml.non-json-value",
347 refusal,
348 path,
349 message,
350 ));
351 continue;
352 }
353 let key_path = format!("{table}.{name}");
354 let raw = match item.clone().into_value() {
355 Ok(value) => RawEntry::deserialize(
356 serde::de::IntoDeserializer::<toml_edit::de::Error>::into_deserializer(value),
357 )
358 .map_err(|error| format!("{key_path}: {}", error.to_string().trim_end())),
359 Err(_) => Err(format!("{key_path}: must be a table")),
360 };
361 let raw = match raw {
362 Ok(raw) => raw,
363 Err(message) => {
364 diagnostics.push(SchemaDiagnostic::new(
365 "dependency.invalid",
366 refusal,
367 path,
368 message,
369 ));
370 continue;
371 }
372 };
373 match Entry::read(name, raw, Strictness::Package) {
374 Ok((mut entry, warnings)) => {
375 let written = item.as_table_like();
378 let unknown = std::mem::take(&mut entry.unknown);
379 for (key, value) in unknown {
380 let holdable = crate::ordered::reject_unholdable_key(&key).and_then(|()| {
381 match written.and_then(|table| table.get(&key)) {
382 Some(item) => crate::manifest::item_json(item).and_then(|json| {
383 toml::Value::try_from(&json).map_err(|error| error.to_string())
384 }),
385 None => Ok(value),
386 }
387 });
388 match holdable {
389 Ok(value) => {
390 entry.unknown.insert(key, value);
391 }
392 Err(message) => {
393 let mut at = path.clone();
394 at.push(crate::diagnostic::PathSegment::Key(key));
395 diagnostics.push(SchemaDiagnostic::new(
396 "toml.non-json-value",
397 Severity::Warning,
398 at,
399 message,
400 ));
401 }
402 }
403 }
404 diagnostics.extend(warnings.into_iter().map(|warning| {
405 SchemaDiagnostic::new(
406 warning.code,
407 Severity::Warning,
408 path.clone(),
409 warning.message,
410 )
411 }));
412 entries.insert(name.to_owned(), entry);
413 }
414 Err(error) => diagnostics.push(SchemaDiagnostic::new(
415 error.code(),
416 refusal,
417 path,
418 error.to_string(),
419 )),
420 }
421 }
422 entries
423}
424
425#[derive(Debug, thiserror::Error, PartialEq, Eq)]
427pub enum PluginSelectorError {
428 #[error("source `{name}` has `plugin = \"{plugin}\"`; a plugin name is {rule}")]
429 BadName {
430 name: String,
431 plugin: String,
432 rule: &'static str,
433 },
434 #[error(
435 "source `{name}` has both `plugin` and `subpath` — a marketplace is read at the root of its source, and the marketplace entry says where the plugin is"
436 )]
437 WithSubpath { name: String },
438 #[error(
439 "source `{name}` has both `plugin` and `dialect` — a marketplace plugin is read as a Claude plugin"
440 )]
441 WithDialect { name: String },
442}
443
444pub fn validate_plugin_selector(
447 name: &str,
448 plugin: Option<&str>,
449 subpath: Option<&SourceSubpath>,
450 dialect: Option<Dialect>,
451) -> Result<(), PluginSelectorError> {
452 let Some(plugin) = plugin else {
453 return Ok(());
454 };
455 let name = name.to_string();
456 if !crate::claude::manifest::is_plugin_name(plugin) {
457 return Err(PluginSelectorError::BadName {
458 name,
459 plugin: plugin.to_string(),
460 rule: crate::claude::manifest::PLUGIN_NAME_RULE,
461 });
462 }
463 if subpath.is_some() {
464 return Err(PluginSelectorError::WithSubpath { name });
465 }
466 if dialect.is_some() {
467 return Err(PluginSelectorError::WithDialect { name });
468 }
469 Ok(())
470}