Skip to main content

ask/registry/
api.rs

1//! Registry HTTP surface — `RegistrySource`, the flattened API response, and the
2//! `fetch_registry_entry` / `resolve_from_registry` lookups. Rust port of the
3//! network half of `registry.ts` (plus the `RegistrySource` type from
4//! `packages/schema/src/registry.ts`).
5
6use serde::{Deserialize, Serialize};
7
8use super::{detect_ecosystem, parse_ecosystem, REGISTRY_BASE_URL};
9use crate::http::{encode_uri_component, HttpClient};
10
11/// A way to fetch one package's docs (discriminated on `type`). Mirrors the
12/// `sourceSchema` discriminated union: `npm | github | web | llms-txt`.
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14#[serde(
15    tag = "type",
16    rename_all = "kebab-case",
17    rename_all_fields = "camelCase"
18)]
19pub enum RegistrySource {
20    Npm {
21        package: String,
22        #[serde(default, skip_serializing_if = "Option::is_none")]
23        path: Option<String>,
24    },
25    Github {
26        repo: String,
27        #[serde(default, skip_serializing_if = "Option::is_none")]
28        branch: Option<String>,
29        #[serde(default, skip_serializing_if = "Option::is_none")]
30        tag: Option<String>,
31        #[serde(default, skip_serializing_if = "Option::is_none")]
32        path: Option<String>,
33    },
34    Web {
35        urls: Vec<String>,
36        #[serde(default, skip_serializing_if = "Option::is_none")]
37        max_depth: Option<u32>,
38        #[serde(default, skip_serializing_if = "Option::is_none")]
39        allowed_path_prefix: Option<String>,
40    },
41    LlmsTxt {
42        url: String,
43    },
44}
45
46impl RegistrySource {
47    /// The `type` discriminant as it appears on the wire.
48    pub fn type_name(&self) -> &'static str {
49        match self {
50            RegistrySource::Npm { .. } => "npm",
51            RegistrySource::Github { .. } => "github",
52            RegistrySource::Web { .. } => "web",
53            RegistrySource::LlmsTxt { .. } => "llms-txt",
54        }
55    }
56}
57
58/// The single package block in a flattened registry API response.
59#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
60pub struct RegistryApiPackage {
61    pub name: String,
62    #[serde(default)]
63    pub description: Option<String>,
64}
65
66/// Flattened registry API response — one registry entry focused on a single
67/// package. `resolved_name` is the CLI-facing slug (`@mastra/core` →
68/// `mastra-core`); `sources` is in the author's declared priority order.
69#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
70#[serde(rename_all = "camelCase")]
71pub struct RegistryApiResponse {
72    pub name: String,
73    pub description: String,
74    pub repo: String,
75    #[serde(default)]
76    pub homepage: Option<String>,
77    #[serde(default)]
78    pub license: Option<String>,
79    #[serde(default)]
80    pub tags: Option<Vec<String>>,
81    pub resolved_name: String,
82    pub package: RegistryApiPackage,
83    pub sources: Vec<RegistrySource>,
84}
85
86/// The result of resolving a spec against the registry.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct RegistryResolution {
89    pub ecosystem: String,
90    pub name: String,
91    pub version: String,
92    pub source: RegistrySource,
93}
94
95#[derive(Deserialize)]
96struct StatusBody {
97    #[serde(rename = "statusMessage")]
98    status_message: Option<String>,
99}
100
101/// Fetch a registry entry from the registry API. Accepts either `(owner, repo)`
102/// for a direct lookup or `(ecosystem, name)` for an alias lookup — the API
103/// handles both via a catch-all slug.
104///
105/// Returns `None` on 404, on any non-2xx (after warning with the server's
106/// `statusMessage` — e.g. the 409 monorepo-disambiguation guidance), on a
107/// transport failure/timeout, or on a body that does not parse. Parity with
108/// `fetchRegistryEntry`.
109pub fn fetch_registry_entry(
110    client: &dyn HttpClient,
111    first: &str,
112    second: &str,
113) -> Option<RegistryApiResponse> {
114    // `second` may contain `/` for scoped npm packages — encode it so the server
115    // sees a single catch-all segment.
116    let url = format!(
117        "{REGISTRY_BASE_URL}/api/registry/{}/{}",
118        encode_uri_component(first),
119        encode_uri_component(second),
120    );
121
122    let response = match client.get(&url) {
123        Ok(r) => r,
124        // Transport failure / timeout — treat as a miss, let downstream
125        // resolvers take over.
126        Err(_) => return None,
127    };
128
129    if response.status == 404 {
130        return None;
131    }
132    if !response.ok() {
133        let message = serde_json::from_str::<StatusBody>(&response.body)
134            .ok()
135            .and_then(|b| b.status_message)
136            .unwrap_or_else(|| format!("HTTP {}", response.status));
137        eprintln!(
138            "Registry lookup for {first}/{second} returned {}: {message}",
139            response.status
140        );
141        return None;
142    }
143
144    serde_json::from_str::<RegistryApiResponse>(&response.body).ok()
145}
146
147/// Resolve a spec against the registry: split the ecosystem/name/version, look
148/// up the entry, and return its primary (first) source. Parity with
149/// `resolveFromRegistry`.
150pub fn resolve_from_registry(
151    client: &dyn HttpClient,
152    input: &str,
153    project_dir: &std::path::Path,
154) -> Option<RegistryResolution> {
155    let (explicit_ecosystem, spec) = parse_ecosystem(input);
156
157    // Split a trailing `@version` (last `@`, but not a leading scope marker).
158    let (name, version) = match spec.rfind('@') {
159        Some(idx) if idx > 0 => (&spec[..idx], &spec[idx + 1..]),
160        _ => (spec, "latest"),
161    };
162
163    let ecosystem = explicit_ecosystem
164        .map(str::to_string)
165        .unwrap_or_else(|| detect_ecosystem(project_dir).to_string());
166
167    let entry = fetch_registry_entry(client, &ecosystem, name)?;
168
169    let Some(primary) = entry.sources.first() else {
170        eprintln!("Registry entry for {name} has no sources");
171        return None;
172    };
173
174    Some(RegistryResolution {
175        ecosystem,
176        name: entry.resolved_name.clone(),
177        version: version.to_string(),
178        source: primary.clone(),
179    })
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185    use crate::http::mock::MockClient;
186
187    const BASE: &str = "https://ask-registry.pages.dev";
188
189    fn entry_json() -> &'static str {
190        r#"{
191            "name": "next.js",
192            "description": "The React Framework",
193            "repo": "vercel/next.js",
194            "resolvedName": "next",
195            "package": { "name": "next" },
196            "sources": [
197                { "type": "npm", "package": "next", "path": "dist/docs" },
198                { "type": "github", "repo": "vercel/next.js", "path": "docs" }
199            ]
200        }"#
201    }
202
203    #[test]
204    fn source_discriminated_union_roundtrips() {
205        let src: RegistrySource =
206            serde_json::from_str(r#"{"type":"llms-txt","url":"https://x/llms.txt"}"#).unwrap();
207        assert_eq!(
208            src,
209            RegistrySource::LlmsTxt {
210                url: "https://x/llms.txt".into()
211            }
212        );
213        assert_eq!(src.type_name(), "llms-txt");
214        // camelCase field on a web source.
215        let web: RegistrySource = serde_json::from_str(
216            r#"{"type":"web","urls":["https://x"],"maxDepth":2,"allowedPathPrefix":"/docs"}"#,
217        )
218        .unwrap();
219        assert!(matches!(
220            web,
221            RegistrySource::Web {
222                max_depth: Some(2),
223                ..
224            }
225        ));
226    }
227
228    #[test]
229    fn fetch_entry_ok() {
230        let client =
231            MockClient::new().with(&format!("{BASE}/api/registry/npm/next"), 200, entry_json());
232        let entry = fetch_registry_entry(&client, "npm", "next").unwrap();
233        assert_eq!(entry.resolved_name, "next");
234        assert_eq!(entry.sources.len(), 2);
235        assert_eq!(entry.sources[0].type_name(), "npm");
236    }
237
238    #[test]
239    fn fetch_entry_scoped_name_is_url_encoded() {
240        // `@mastra/client-js` → catch-all segment `%40mastra%2Fclient-js`.
241        let url = format!("{BASE}/api/registry/npm/%40mastra%2Fclient-js");
242        let client = MockClient::new().with(&url, 200, entry_json());
243        assert!(fetch_registry_entry(&client, "npm", "@mastra/client-js").is_some());
244    }
245
246    #[test]
247    fn fetch_entry_404_and_transport_error_are_none() {
248        let client = MockClient::new().with(&format!("{BASE}/api/registry/npm/missing"), 404, "");
249        assert!(fetch_registry_entry(&client, "npm", "missing").is_none());
250        // Unregistered URL → MockClient errors (transport failure) → None.
251        assert!(fetch_registry_entry(&client, "npm", "never").is_none());
252    }
253
254    #[test]
255    fn fetch_entry_non_ok_warns_and_returns_none() {
256        let client = MockClient::new().with(
257            &format!("{BASE}/api/registry/mastra-ai/mastra"),
258            409,
259            r#"{"statusMessage":"Monorepo entry — use npm:@mastra/core"}"#,
260        );
261        assert!(fetch_registry_entry(&client, "mastra-ai", "mastra").is_none());
262    }
263
264    #[test]
265    fn resolve_splits_version_and_returns_primary_source() {
266        let client =
267            MockClient::new().with(&format!("{BASE}/api/registry/npm/next"), 200, entry_json());
268        let dir = tempfile::tempdir().unwrap();
269        // Explicit ecosystem prefix + version.
270        let res = resolve_from_registry(&client, "npm:next@14.2.3", dir.path()).unwrap();
271        assert_eq!(res.ecosystem, "npm");
272        assert_eq!(res.name, "next");
273        assert_eq!(res.version, "14.2.3");
274        assert_eq!(res.source.type_name(), "npm");
275    }
276
277    #[test]
278    fn resolve_detects_ecosystem_from_project_when_prefix_absent() {
279        let client =
280            MockClient::new().with(&format!("{BASE}/api/registry/npm/next"), 200, entry_json());
281        let dir = tempfile::tempdir().unwrap();
282        std::fs::write(dir.path().join("package.json"), "{}").unwrap();
283        // No prefix, no version → ecosystem from package.json, version "latest".
284        let res = resolve_from_registry(&client, "next", dir.path()).unwrap();
285        assert_eq!(res.ecosystem, "npm");
286        assert_eq!(res.version, "latest");
287    }
288}