Skip to main content

ask/registry/
mod.rs

1//! Registry spec parsing, ecosystem detection, and the registry HTTP lookup —
2//! Rust port of `packages/cli/src/registry.ts`.
3//!
4//! The pure parsing/detection helpers live here; the HTTP surface
5//! (`RegistrySource`, `RegistryApiResponse`, [`api::fetch_registry_entry`],
6//! [`api::resolve_from_registry`], bounded by the shared 10s-timeout
7//! [`crate::http::HttpClient`]) lives in the `api` submodule.
8
9pub mod api;
10
11pub use api::{
12    fetch_registry_entry, resolve_from_registry, RegistryApiPackage, RegistryApiResponse,
13    RegistryResolution, RegistrySource,
14};
15
16use std::path::Path;
17
18/// The base URL for the ASK registry API. Kept here so the HTTP port reuses it.
19pub const REGISTRY_BASE_URL: &str = "https://ask-registry.pages.dev";
20
21/// Split an ecosystem prefix off a spec (port of `parseEcosystem`).
22///
23/// `npm:next@canary` → `(Some("npm"), "next@canary")`; `next@canary` →
24/// `(None, "next@canary")`. A prefix is the text before the first `:`, but only
25/// when that colon comes before any `/` — this rules out `owner/repo` shorthand
26/// while still accepting scoped names like `npm:@mastra/client-js`.
27pub fn parse_ecosystem(input: &str) -> (Option<&str>, &str) {
28    let colon = input.find(':');
29    let slash = input.find('/');
30    if let Some(c) = colon {
31        // `colonIdx > 0` in TS: a leading colon does not count as a prefix.
32        if c > 0 && slash.is_none_or(|s| c < s) {
33            return (Some(&input[..c]), &input[c + 1..]);
34        }
35    }
36    (None, input)
37}
38
39/// A parsed `docs add` identifier (port of `ParsedDocSpec`).
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub enum ParsedDocSpec {
42    Github {
43        owner: String,
44        repo: String,
45        ref_: Option<String>,
46    },
47    Ecosystem {
48        ecosystem: String,
49        name: String,
50        version: String,
51    },
52    Name {
53        name: String,
54        version: String,
55    },
56}
57
58/// Error from [`parse_doc_spec`] — mirrors the TS thrown-error messages.
59#[derive(Debug, thiserror::Error, PartialEq, Eq)]
60pub enum DocSpecError {
61    #[error("docs spec is empty — expected `owner/repo`, `ecosystem:name`, or `name`")]
62    Empty,
63    #[error(
64        "invalid docs spec '{0}': github shorthand must contain exactly one slash (owner/repo)"
65    )]
66    NotExactlyOneSlash(String),
67    #[error("invalid docs spec '{0}': owner segment is empty")]
68    EmptyOwner(String),
69    #[error("invalid docs spec '{0}': repo segment is empty")]
70    EmptyRepo(String),
71}
72
73/// Split `name[@version]`, defaulting the version to `latest`. `lastAt > 0`
74/// keeps a leading `@` (bare scoped name) as part of the name.
75fn split_name_version(spec: &str) -> (String, String) {
76    match spec.rfind('@') {
77        Some(idx) if idx > 0 => (spec[..idx].to_string(), spec[idx + 1..].to_string()),
78        _ => (spec.to_string(), "latest".to_string()),
79    }
80}
81
82/// Parse a `docs add` identifier into a [`ParsedDocSpec`] (port of
83/// `parseDocSpec`). Disambiguation, checked in order:
84///
85///   1. Contains `/` and no `:` → github (`owner/repo[@ref]`, exactly one slash).
86///   2. Contains `:` (non-empty prefix) → ecosystem (`prefix:name[@version]`).
87///   3. Otherwise → bare name (`name[@version]`).
88pub fn parse_doc_spec(input: &str) -> Result<ParsedDocSpec, DocSpecError> {
89    if input.is_empty() {
90        return Err(DocSpecError::Empty);
91    }
92
93    // 1. github shape: owner/repo[@ref]. The `:` exclusion keeps scoped
94    //    ecosystem specs (`npm:@scope/pkg@1.0`) out of the github branch.
95    if input.contains('/') && !input.contains(':') {
96        let parts: Vec<&str> = input.split('/').collect();
97        if parts.len() != 2 {
98            return Err(DocSpecError::NotExactlyOneSlash(input.to_string()));
99        }
100        let owner = parts[0];
101        let repo_and_ref = parts[1];
102        if owner.is_empty() {
103            return Err(DocSpecError::EmptyOwner(input.to_string()));
104        }
105        if repo_and_ref.is_empty() {
106            return Err(DocSpecError::EmptyRepo(input.to_string()));
107        }
108        if let Some(at) = repo_and_ref.find('@') {
109            let repo = &repo_and_ref[..at];
110            let ref_ = &repo_and_ref[at + 1..];
111            if repo.is_empty() {
112                return Err(DocSpecError::EmptyRepo(input.to_string()));
113            }
114            return Ok(ParsedDocSpec::Github {
115                owner: owner.to_string(),
116                repo: repo.to_string(),
117                // An empty ref (`owner/repo@`) drops back to no ref.
118                ref_: (!ref_.is_empty()).then(|| ref_.to_string()),
119            });
120        }
121        return Ok(ParsedDocSpec::Github {
122            owner: owner.to_string(),
123            repo: repo_and_ref.to_string(),
124            ref_: None,
125        });
126    }
127
128    // 2. ecosystem shape: prefix:name[@version].
129    if let Some(colon) = input.find(':') {
130        if colon > 0 {
131            let ecosystem = &input[..colon];
132            let (name, version) = split_name_version(&input[colon + 1..]);
133            return Ok(ParsedDocSpec::Ecosystem {
134                ecosystem: ecosystem.to_string(),
135                name,
136                version,
137            });
138        }
139    }
140
141    // 3. bare name: name[@version].
142    let (name, version) = split_name_version(input);
143    Ok(ParsedDocSpec::Name { name, version })
144}
145
146/// Detect the project ecosystem from marker files, defaulting to `npm` (port of
147/// `detectEcosystem`). Checks are ordered; the first existing file wins.
148pub fn detect_ecosystem(project_dir: &Path) -> &'static str {
149    const CHECKS: &[(&str, &str)] = &[
150        ("package.json", "npm"),
151        ("pubspec.yaml", "pub"),
152        ("pyproject.toml", "pypi"),
153        ("requirements.txt", "pypi"),
154        ("go.mod", "go"),
155        ("Cargo.toml", "crates"),
156        ("mix.exs", "hex"),
157        ("pom.xml", "maven"),
158        ("build.gradle", "maven"),
159        ("build.gradle.kts", "maven"),
160    ];
161    for (file, ecosystem) in CHECKS {
162        if project_dir.join(file).exists() {
163            return ecosystem;
164        }
165    }
166    "npm"
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    #[test]
174    fn parse_ecosystem_cases() {
175        assert_eq!(
176            parse_ecosystem("npm:next@canary"),
177            (Some("npm"), "next@canary")
178        );
179        assert_eq!(parse_ecosystem("next@canary"), (None, "next@canary"));
180        // Scoped npm name: colon before slash → still an ecosystem prefix.
181        assert_eq!(
182            parse_ecosystem("npm:@mastra/client-js"),
183            (Some("npm"), "@mastra/client-js")
184        );
185        // owner/repo shorthand: slash before colon (or no colon) → no prefix.
186        assert_eq!(parse_ecosystem("owner/repo"), (None, "owner/repo"));
187        // Leading colon does not count as a prefix.
188        assert_eq!(parse_ecosystem(":x"), (None, ":x"));
189    }
190
191    #[test]
192    fn parse_doc_spec_github_shapes() {
193        assert_eq!(
194            parse_doc_spec("vercel/next.js").unwrap(),
195            ParsedDocSpec::Github {
196                owner: "vercel".into(),
197                repo: "next.js".into(),
198                ref_: None
199            }
200        );
201        assert_eq!(
202            parse_doc_spec("vercel/next.js@v14").unwrap(),
203            ParsedDocSpec::Github {
204                owner: "vercel".into(),
205                repo: "next.js".into(),
206                ref_: Some("v14".into()),
207            }
208        );
209        // Trailing `@` drops back to no ref.
210        assert_eq!(
211            parse_doc_spec("vercel/next.js@").unwrap(),
212            ParsedDocSpec::Github {
213                owner: "vercel".into(),
214                repo: "next.js".into(),
215                ref_: None
216            }
217        );
218    }
219
220    #[test]
221    fn parse_doc_spec_github_errors() {
222        assert_eq!(parse_doc_spec("").unwrap_err(), DocSpecError::Empty);
223        assert_eq!(
224            parse_doc_spec("a/b/c").unwrap_err(),
225            DocSpecError::NotExactlyOneSlash("a/b/c".into())
226        );
227        assert_eq!(
228            parse_doc_spec("/repo").unwrap_err(),
229            DocSpecError::EmptyOwner("/repo".into())
230        );
231        assert_eq!(
232            parse_doc_spec("owner/").unwrap_err(),
233            DocSpecError::EmptyRepo("owner/".into())
234        );
235    }
236
237    #[test]
238    fn parse_doc_spec_ecosystem_and_name() {
239        assert_eq!(
240            parse_doc_spec("npm:next@canary").unwrap(),
241            ParsedDocSpec::Ecosystem {
242                ecosystem: "npm".into(),
243                name: "next".into(),
244                version: "canary".into(),
245            }
246        );
247        assert_eq!(
248            parse_doc_spec("next").unwrap(),
249            ParsedDocSpec::Name {
250                name: "next".into(),
251                version: "latest".into()
252            }
253        );
254        assert_eq!(
255            parse_doc_spec("next@14").unwrap(),
256            ParsedDocSpec::Name {
257                name: "next".into(),
258                version: "14".into()
259            }
260        );
261        // Scoped ecosystem spec with a slash stays in the ecosystem branch (has `:`).
262        assert_eq!(
263            parse_doc_spec("npm:@scope/pkg@1.0").unwrap(),
264            ParsedDocSpec::Ecosystem {
265                ecosystem: "npm".into(),
266                name: "@scope/pkg".into(),
267                version: "1.0".into(),
268            }
269        );
270    }
271
272    #[test]
273    fn detect_ecosystem_from_marker_files() {
274        let dir = tempfile::tempdir().unwrap();
275        // Empty dir → npm default.
276        assert_eq!(detect_ecosystem(dir.path()), "npm");
277        // Cargo.toml → crates (but package.json would win if present first).
278        std::fs::write(dir.path().join("Cargo.toml"), "").unwrap();
279        assert_eq!(detect_ecosystem(dir.path()), "crates");
280        // package.json takes priority (checked first).
281        std::fs::write(dir.path().join("package.json"), "{}").unwrap();
282        assert_eq!(detect_ecosystem(dir.path()), "npm");
283    }
284}