1use std::collections::BTreeMap;
12
13use serde::{Deserialize, Serialize};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "kebab-case")]
19pub enum Materialization {
20 Copy,
21 Link,
22 Ref,
23 InPlace,
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "kebab-case")]
29pub enum EntryFormat {
30 Docs,
31 IntentSkills,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(deny_unknown_fields, rename_all = "camelCase")]
39pub struct ResolvedEntry {
40 pub spec: String,
42 pub resolved_version: String,
44 pub content_hash: String,
46 pub fetched_at: String,
48 pub file_count: u64,
50 #[serde(skip_serializing_if = "Option::is_none")]
51 pub format: Option<EntryFormat>,
52 #[serde(skip_serializing_if = "Option::is_none")]
53 pub store_path: Option<String>,
54 #[serde(skip_serializing_if = "Option::is_none")]
55 pub materialization: Option<Materialization>,
56 #[serde(skip_serializing_if = "Option::is_none")]
58 pub in_place_path: Option<String>,
59 #[serde(skip_serializing_if = "Option::is_none")]
61 pub commit: Option<String>,
62 #[serde(skip_serializing_if = "Option::is_none")]
64 pub store_subpath: Option<String>,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69#[serde(deny_unknown_fields, rename_all = "camelCase")]
70pub struct ResolvedJson {
71 pub schema_version: u32,
72 pub generated_at: String,
73 pub entries: BTreeMap<String, ResolvedEntry>,
76}
77
78#[derive(Debug, thiserror::Error, PartialEq, Eq)]
80pub enum ResolvedError {
81 #[error("contentHash must be sha256-<64 hex chars>: {0:?}")]
82 ContentHash(String),
83 #[error("commit must be a 40-char lowercase hex SHA: {0:?}")]
84 Commit(String),
85 #[error("{field} must be an ISO-8601 datetime with offset: {value:?}")]
86 DateTime { field: &'static str, value: String },
87 #[error("inPlacePath is required when materialization is 'in-place' (entry {0:?})")]
88 MissingInPlacePath(String),
89 #[error("schemaVersion must be 1, got {0}")]
90 SchemaVersion(u32),
91 #[error("{0} must be a non-empty string")]
92 EmptyField(&'static str),
93}
94
95impl ResolvedEntry {
96 pub fn validate(&self) -> Result<(), ResolvedError> {
98 if self.spec.is_empty() {
101 return Err(ResolvedError::EmptyField("spec"));
102 }
103 if self.resolved_version.is_empty() {
104 return Err(ResolvedError::EmptyField("resolvedVersion"));
105 }
106 if !is_content_hash(&self.content_hash) {
107 return Err(ResolvedError::ContentHash(self.content_hash.clone()));
108 }
109 if !is_iso_datetime_offset(&self.fetched_at) {
110 return Err(ResolvedError::DateTime {
111 field: "fetchedAt",
112 value: self.fetched_at.clone(),
113 });
114 }
115 if let Some(commit) = &self.commit {
116 if !is_git_sha(commit) {
117 return Err(ResolvedError::Commit(commit.clone()));
118 }
119 }
120 if self.materialization == Some(Materialization::InPlace) && self.in_place_path.is_none() {
121 return Err(ResolvedError::MissingInPlacePath(self.spec.clone()));
122 }
123 Ok(())
124 }
125}
126
127impl ResolvedJson {
128 pub fn parse(json: &str) -> anyhow::Result<Self> {
130 let parsed: ResolvedJson = serde_json::from_str(json)?;
131 parsed.validate()?;
132 Ok(parsed)
133 }
134
135 pub fn validate(&self) -> Result<(), ResolvedError> {
137 if self.schema_version != 1 {
138 return Err(ResolvedError::SchemaVersion(self.schema_version));
139 }
140 if !is_iso_datetime_offset(&self.generated_at) {
141 return Err(ResolvedError::DateTime {
142 field: "generatedAt",
143 value: self.generated_at.clone(),
144 });
145 }
146 for entry in self.entries.values() {
147 entry.validate()?;
148 }
149 Ok(())
150 }
151}
152
153fn is_content_hash(s: &str) -> bool {
155 match s.strip_prefix("sha256-") {
156 Some(hex) => {
157 hex.len() == 64
158 && hex
159 .bytes()
160 .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
161 }
162 None => false,
163 }
164}
165
166fn is_git_sha(s: &str) -> bool {
168 s.len() == 40
169 && s.bytes()
170 .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
171}
172
173fn is_iso_datetime_offset(s: &str) -> bool {
178 let Some((date, rest)) = s.split_once('T') else {
179 return false;
180 };
181 let d: Vec<&str> = date.split('-').collect();
183 if d.len() != 3 || d[0].len() != 4 || d[1].len() != 2 || d[2].len() != 2 {
184 return false;
185 }
186 if !d.iter().all(|p| p.bytes().all(|b| b.is_ascii_digit())) {
187 return false;
188 }
189 let (time, offset) = if let Some(stripped) = rest.strip_suffix('Z') {
191 (stripped, true)
192 } else if let Some(idx) = rest.rfind(['+', '-']) {
193 let off = &rest[idx + 1..];
195 let ok = off.len() == 5
196 && off.as_bytes()[2] == b':'
197 && off[..2]
198 .bytes()
199 .chain(off[3..].bytes())
200 .all(|b| b.is_ascii_digit());
201 (&rest[..idx], ok)
202 } else {
203 (rest, false)
204 };
205 if !offset {
206 return false;
207 }
208 let core = time.split('.').next().unwrap_or(time);
210 let t: Vec<&str> = core.split(':').collect();
211 t.len() == 3
212 && t[0].len() == 2
213 && t[1].len() == 2
214 && t[2].len() == 2
215 && t.iter().all(|p| p.bytes().all(|b| b.is_ascii_digit()))
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221
222 const HASH: &str = "sha256-0000000000000000000000000000000000000000000000000000000000000000";
223 const SHA: &str = "0123456789abcdef0123456789abcdef01234567";
224
225 fn base_entry_json(extra: &str) -> String {
226 format!(
227 r#"{{"spec":"npm:next","resolvedVersion":"15.0.0","contentHash":"{HASH}","fetchedAt":"2026-07-04T00:00:00Z","fileCount":3{extra}}}"#
228 )
229 }
230
231 fn doc(entry_json: &str) -> String {
232 format!(
233 r#"{{"schemaVersion":1,"generatedAt":"2026-07-04T00:00:00Z","entries":{{"next":{entry_json}}}}}"#
234 )
235 }
236
237 #[test]
238 fn parses_minimal_entry() {
239 let ask = ResolvedJson::parse(&doc(&base_entry_json(""))).unwrap();
240 let e = &ask.entries["next"];
241 assert_eq!(e.spec, "npm:next");
242 assert_eq!(e.file_count, 3);
243 assert_eq!(e.commit, None);
244 }
245
246 #[test]
247 fn optional_fields_omitted_when_none() {
248 let e = ResolvedJson::parse(&doc(&base_entry_json("")))
249 .unwrap()
250 .entries
251 .remove("next")
252 .unwrap();
253 let json = serde_json::to_string(&e).unwrap();
254 assert!(!json.contains("commit"));
255 assert!(!json.contains("storePath"));
256 assert!(!json.contains("format"));
257 }
258
259 #[test]
260 fn kebab_case_enums_roundtrip() {
261 let json = base_entry_json(
262 r#","materialization":"in-place","inPlacePath":"node_modules/next/dist/docs","format":"intent-skills""#,
263 );
264 let e: ResolvedEntry = serde_json::from_str(&json).unwrap();
265 assert_eq!(e.materialization, Some(Materialization::InPlace));
266 assert_eq!(e.format, Some(EntryFormat::IntentSkills));
267 let out = serde_json::to_string(&e).unwrap();
269 assert!(out.contains(r#""materialization":"in-place""#));
270 assert!(out.contains(r#""format":"intent-skills""#));
271 }
272
273 #[test]
274 fn in_place_requires_in_place_path() {
275 let json = base_entry_json(r#","materialization":"in-place""#);
276 let err = ResolvedJson::parse(&doc(&json)).unwrap_err();
277 assert!(err.to_string().contains("inPlacePath is required"));
278 }
279
280 #[test]
281 fn rejects_bad_content_hash() {
282 let json = base_entry_json("").replace(HASH, "sha256-xyz");
283 assert!(ResolvedJson::parse(&doc(&json)).is_err());
284 }
285
286 #[test]
287 fn rejects_empty_spec_or_version() {
288 let empty_spec = base_entry_json("").replace(r#""spec":"npm:next""#, r#""spec":"""#);
290 assert!(ResolvedJson::parse(&doc(&empty_spec)).is_err());
291 let empty_ver =
292 base_entry_json("").replace(r#""resolvedVersion":"15.0.0""#, r#""resolvedVersion":"""#);
293 assert!(ResolvedJson::parse(&doc(&empty_ver)).is_err());
294 }
295
296 #[test]
297 fn rejects_bad_commit_sha() {
298 let json = base_entry_json(r#","commit":"NOTASHA""#);
299 assert!(ResolvedJson::parse(&doc(&json)).is_err());
300 }
301
302 #[test]
303 fn accepts_valid_commit_sha() {
304 let json = base_entry_json(&format!(r#","commit":"{SHA}""#));
305 let ask = ResolvedJson::parse(&doc(&json)).unwrap();
306 assert_eq!(ask.entries["next"].commit.as_deref(), Some(SHA));
307 }
308
309 #[test]
310 fn rejects_wrong_schema_version() {
311 let doc = doc(&base_entry_json("")).replace("\"schemaVersion\":1", "\"schemaVersion\":2");
312 assert!(ResolvedJson::parse(&doc).is_err());
313 }
314
315 #[test]
316 fn rejects_unknown_entry_field() {
317 let json = base_entry_json(r#","bogus":1"#);
318 assert!(ResolvedJson::parse(&doc(&json)).is_err());
319 }
320
321 #[test]
322 fn datetime_offset_shapes() {
323 assert!(is_iso_datetime_offset("2026-07-04T00:00:00Z"));
324 assert!(is_iso_datetime_offset("2026-07-04T12:30:59.123+09:00"));
325 assert!(is_iso_datetime_offset("2026-07-04T12:30:59-05:00"));
326 assert!(!is_iso_datetime_offset("2026-07-04T00:00:00")); assert!(!is_iso_datetime_offset("2026-07-04 00:00:00Z")); assert!(!is_iso_datetime_offset("not-a-date"));
329 }
330}