Skip to main content

ask/
ask_json.rs

1//! `ask.json` schema — Rust port of `packages/schema/src/ask-json.ts`.
2//!
3//! `ask.json` is the single declarative input in the lazy-first architecture: a
4//! list of library entries. Each entry is either a bare **spec string** (the
5//! canonical, diff-clean form) or an **object** carrying a non-empty `docsPaths`
6//! override selected by the user at `ask add` time.
7//!
8//! Spec strings carry the ecosystem in the prefix (`npm:next`,
9//! `npm:@scope/pkg`, `github:owner/repo@v1.2.3`).
10
11use serde::{Deserialize, Serialize};
12
13/// Object form of a library entry — used ONLY when the user selected a subset of
14/// candidate documentation paths. `docs_paths` is required and non-empty; an
15/// empty override is indistinguishable from the default, so the canonical
16/// "no override" form is the bare string. Unknown fields are rejected (parity
17/// with the zod `.strict()`).
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(deny_unknown_fields)]
20pub struct LibraryEntryObject {
21    pub spec: String,
22    #[serde(rename = "docsPaths")]
23    pub docs_paths: Vec<String>,
24}
25
26/// A library entry: a bare spec string, or an object with a `docsPaths`
27/// override. Serialized untagged so the string form stays a plain JSON string on
28/// disk (existing `ask.json` files render unchanged).
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(untagged)]
31pub enum LibraryEntry {
32    Spec(String),
33    WithDocs(LibraryEntryObject),
34}
35
36/// Lazy-first `ask.json` — a list of library entries. Unknown top-level fields
37/// are rejected (parity with `.strict()`).
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(deny_unknown_fields)]
40pub struct AskJson {
41    pub libraries: Vec<LibraryEntry>,
42}
43
44/// Materialization mode for the eager `--fetch` path.
45#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
46#[serde(rename_all = "lowercase")]
47pub enum StoreMode {
48    #[default]
49    Copy,
50    Link,
51    Ref,
52}
53
54/// Validation failure for an `ask.json` document, mirroring the zod refinements
55/// that plain serde structural parsing does not enforce.
56#[derive(Debug, thiserror::Error, PartialEq, Eq)]
57pub enum AskJsonError {
58    #[error("spec must start with an ecosystem prefix (e.g. \"npm:next\", \"github:owner/repo@v1.2.3\"): {0:?}")]
59    InvalidSpec(String),
60    #[error(
61        "docsPaths override must be non-empty (use a bare spec string for no override): {0:?}"
62    )]
63    EmptyDocsPaths(String),
64    #[error("docsPaths entries must be non-empty strings: {0:?}")]
65    EmptyDocsPathItem(String),
66}
67
68impl AskJson {
69    /// Parse and validate an `ask.json` document from a JSON string.
70    ///
71    /// Deserialization enforces structure + strictness (`deny_unknown_fields`);
72    /// [`AskJson::validate`] then enforces the zod refinements (spec-string
73    /// shape, non-empty `docsPaths`).
74    pub fn parse(json: &str) -> anyhow::Result<Self> {
75        let parsed: AskJson = serde_json::from_str(json)?;
76        parsed.validate()?;
77        Ok(parsed)
78    }
79
80    /// Run the content refinements the serde layer cannot express.
81    pub fn validate(&self) -> Result<(), AskJsonError> {
82        for entry in &self.libraries {
83            let spec = entry.spec();
84            if !is_valid_spec_string(spec) {
85                return Err(AskJsonError::InvalidSpec(spec.to_string()));
86            }
87            if let LibraryEntry::WithDocs(obj) = entry {
88                if obj.docs_paths.is_empty() {
89                    return Err(AskJsonError::EmptyDocsPaths(spec.to_string()));
90                }
91                if obj.docs_paths.iter().any(|p| p.is_empty()) {
92                    return Err(AskJsonError::EmptyDocsPathItem(spec.to_string()));
93                }
94            }
95        }
96        Ok(())
97    }
98}
99
100impl LibraryEntry {
101    /// Extract the spec string from either form (parity with `specFromEntry`).
102    pub fn spec(&self) -> &str {
103        match self {
104            LibraryEntry::Spec(s) => s,
105            LibraryEntry::WithDocs(o) => &o.spec,
106        }
107    }
108
109    /// The docs-path override, or `None` for the bare-string form
110    /// (parity with `docsPathsFromEntry`).
111    pub fn docs_paths(&self) -> Option<&[String]> {
112        match self {
113            LibraryEntry::Spec(_) => None,
114            LibraryEntry::WithDocs(o) => Some(&o.docs_paths),
115        }
116    }
117}
118
119/// Build a library entry from a spec and optional docs paths. Canonical-form
120/// rule: an empty or absent `docs_paths` collapses to a bare string so
121/// `ask.json` stays diff-clean (parity with `entryFromSpec`).
122pub fn entry_from_spec(spec: impl Into<String>, docs_paths: &[String]) -> LibraryEntry {
123    let spec = spec.into();
124    if docs_paths.is_empty() {
125        LibraryEntry::Spec(spec)
126    } else {
127        LibraryEntry::WithDocs(LibraryEntryObject {
128            spec,
129            docs_paths: docs_paths.to_vec(),
130        })
131    }
132}
133
134/// Equivalent of the zod `SpecString` regex `^[a-z][a-z0-9+-]*:.+$`: a lowercase
135/// ecosystem prefix, then `:`, then at least one payload char.
136fn is_valid_spec_string(spec: &str) -> bool {
137    let Some((prefix, payload)) = spec.split_once(':') else {
138        return false;
139    };
140    if payload.is_empty() {
141        return false;
142    }
143    // The zod regex `^...:.+$` has no `s`/`m` flags: `.` never matches a JS line
144    // terminator and `$` is strict end-of-string, so a payload containing any JS
145    // line terminator (LF, CR, U+2028, U+2029) is rejected. Mirror that so Rust
146    // does not accept multiline specs the TS schema rejects. (The prefix charset
147    // already excludes these.)
148    if payload.contains(['\n', '\r', '\u{2028}', '\u{2029}']) {
149        return false;
150    }
151    let mut chars = prefix.chars();
152    match chars.next() {
153        Some(c) if c.is_ascii_lowercase() => {}
154        _ => return false,
155    }
156    chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '+' || c == '-')
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[test]
164    fn parses_mixed_string_and_object_entries() {
165        let json = r#"{
166            "libraries": [
167                "npm:next",
168                { "spec": "npm:zod", "docsPaths": ["docs/API.md"] },
169                "github:vercel/ai@v5.0.0"
170            ]
171        }"#;
172        let ask = AskJson::parse(json).unwrap();
173        assert_eq!(ask.libraries.len(), 3);
174        assert_eq!(ask.libraries[0], LibraryEntry::Spec("npm:next".into()));
175        assert_eq!(ask.libraries[1].spec(), "npm:zod");
176        assert_eq!(
177            ask.libraries[1].docs_paths(),
178            Some(&["docs/API.md".to_string()][..])
179        );
180        assert_eq!(ask.libraries[2].docs_paths(), None);
181    }
182
183    #[test]
184    fn string_entry_roundtrips_as_plain_string() {
185        // The canonical no-override form must serialize back to a bare string,
186        // not an object — otherwise every ask.json would churn on write.
187        let entry = LibraryEntry::Spec("npm:next".into());
188        assert_eq!(serde_json::to_string(&entry).unwrap(), "\"npm:next\"");
189    }
190
191    #[test]
192    fn object_entry_uses_camelcase_docs_paths() {
193        let entry = entry_from_spec("npm:zod", &["docs/API.md".to_string()]);
194        assert_eq!(
195            serde_json::to_string(&entry).unwrap(),
196            r#"{"spec":"npm:zod","docsPaths":["docs/API.md"]}"#
197        );
198    }
199
200    #[test]
201    fn entry_from_spec_collapses_empty_docs_paths_to_string() {
202        assert_eq!(
203            entry_from_spec("npm:next", &[]),
204            LibraryEntry::Spec("npm:next".into())
205        );
206        assert!(matches!(
207            entry_from_spec("npm:next", &["d".to_string()]),
208            LibraryEntry::WithDocs(_)
209        ));
210    }
211
212    #[test]
213    fn rejects_spec_without_ecosystem_prefix() {
214        let err = AskJson::parse(r#"{"libraries":["next"]}"#).unwrap_err();
215        assert!(err.to_string().contains("ecosystem prefix"));
216    }
217
218    #[test]
219    fn rejects_spec_with_embedded_line_terminator() {
220        // The `\n` here is a JSON escape → the parsed spec string contains a real
221        // newline. TS's `.+$` regex rejects it; Rust must too.
222        let err = AskJson::parse(r#"{"libraries":["npm:next\nmalicious"]}"#).unwrap_err();
223        assert!(err.to_string().contains("ecosystem prefix"));
224    }
225
226    #[test]
227    fn rejects_object_with_empty_docs_paths() {
228        // Structurally valid but violates the non-empty refinement.
229        let err =
230            AskJson::parse(r#"{"libraries":[{"spec":"npm:zod","docsPaths":[]}]}"#).unwrap_err();
231        assert!(err.to_string().contains("non-empty"));
232    }
233
234    #[test]
235    fn rejects_unknown_top_level_field() {
236        assert!(AskJson::parse(r#"{"libraries":[],"extra":1}"#).is_err());
237    }
238
239    #[test]
240    fn rejects_unknown_object_entry_field() {
241        assert!(AskJson::parse(
242            r#"{"libraries":[{"spec":"npm:zod","docsPaths":["d"],"ref":"v1"}]}"#
243        )
244        .is_err());
245    }
246
247    #[test]
248    fn spec_string_shape_matches_regex() {
249        assert!(is_valid_spec_string("npm:next"));
250        assert!(is_valid_spec_string("github:owner/repo@v1.2.3"));
251        assert!(is_valid_spec_string("llms-txt:x"));
252        assert!(!is_valid_spec_string("Next:x")); // uppercase prefix start
253        assert!(!is_valid_spec_string("npm:")); // empty payload
254        assert!(!is_valid_spec_string("noprefix"));
255        assert!(!is_valid_spec_string(":x")); // empty prefix
256    }
257
258    #[test]
259    fn store_mode_serializes_lowercase() {
260        assert_eq!(serde_json::to_string(&StoreMode::Ref).unwrap(), "\"ref\"");
261        assert_eq!(
262            serde_json::from_str::<StoreMode>("\"link\"").unwrap(),
263            StoreMode::Link
264        );
265    }
266}