Skip to main content

ask/commands/
add.rs

1//! `ask add <spec>` — add a library to `ask.json` and materialize its docs via
2//! `run_install`. Rust port of `commands/add.ts` + the bare-`ask add`
3//! interactive flow in `interactive.ts`.
4//!
5//! The real contract is the persisted `ask.json`, NOT the prompt UI. The
6//! non-interactive path (`--docs-paths`, `--clear-docs-paths`, cold-cache bare
7//! `add`) is what gets byte-parity tested against the TS oracle; the TTY
8//! multiselect / text prompts are seamed out so unit tests never need a
9//! terminal, and the production defaults use `dialoguer`.
10
11use std::collections::HashSet;
12use std::io::IsTerminal;
13use std::path::{Path, PathBuf};
14
15use crate::ask_json::{entry_from_spec, AskJson};
16use crate::commands::ensure_checkout::EnsureCheckoutDeps;
17use crate::discovery::candidates::{
18    gather_docs_candidates, CandidateGatheringError, CandidateGroup,
19};
20use crate::http::HttpClient;
21use crate::install::{run_install, RunInstallOptions};
22use crate::io::{read_ask_json, write_ask_json};
23use crate::registry::api::fetch_registry_entry;
24use crate::registry::detect_ecosystem;
25use crate::spec::{parse_spec, ParsedSpec};
26
27/// A single choice presented by a multiselect prompt. `value` is what the
28/// selection resolves to (an absolute path, or a dependency name); `label` and
29/// `hint` are display-only.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct PromptOption {
32    pub label: String,
33    pub value: String,
34    pub hint: String,
35}
36
37/// Normalize a POSIX path the way Node's `path.posix.normalize` does: collapse
38/// `.`/`//`, resolve `..` (leaving leading `..` for relative escapes), and
39/// return `.` for an empty result. Used by [`sanitize_docs_path`].
40fn posix_normalize(input: &str) -> String {
41    let mut stack: Vec<&str> = Vec::new();
42    for seg in input.split('/') {
43        match seg {
44            "" | "." => {}
45            ".." => {
46                if matches!(stack.last(), Some(&top) if top != "..") {
47                    stack.pop();
48                } else {
49                    stack.push("..");
50                }
51            }
52            other => stack.push(other),
53        }
54    }
55    if stack.is_empty() {
56        ".".to_string()
57    } else {
58        stack.join("/")
59    }
60}
61
62/// Validate and canonicalize a user-supplied docs path. Returns the
63/// POSIX-normalized relative path on success, or `None` when the input is
64/// unsafe / empty. Rejects empty/whitespace, absolute paths, and `..` escapes.
65/// Parity with `sanitizeDocsPath`.
66pub fn sanitize_docs_path(input: &str) -> Option<String> {
67    let trimmed = input.trim();
68    if trimmed.is_empty() {
69        return None;
70    }
71    // `Path::is_absolute` matches `path.isAbsolute` on POSIX (leading `/`).
72    if Path::new(trimmed).is_absolute() {
73        return None;
74    }
75    let normalized = posix_normalize(&trimmed.replace('\\', "/"));
76    if normalized.is_empty() {
77        return None;
78    }
79    if normalized == ".." || normalized.starts_with("../") {
80        return None;
81    }
82    Some(normalized)
83}
84
85const AMBIGUOUS_SPEC_HINT: &str = "Ambiguous spec '{}'. Use:\n\
86     \u{20} • npm:<name>           (e.g. npm:next, npm:@mastra/client-js)\n\
87     \u{20} • github:<owner>/<repo>@<ref>  (e.g. github:vercel/next.js@v14.2.3)";
88
89/// True when `input` is an `owner/repo` pair (exactly one slash, both sides
90/// non-empty). Equivalent to the `^[^/]+/[^/]+$` regex without a regex.
91fn is_owner_repo(input: &str) -> bool {
92    let parts: Vec<&str> = input.split('/').collect();
93    parts.len() == 2 && !parts[0].is_empty() && !parts[1].is_empty()
94}
95
96/// `ask add <spec>` spec normalization: a bare `owner/repo` becomes
97/// `github:owner/repo`; anything else without a `:` is ambiguous and errors.
98/// Parity with `add.ts`'s `normalizeAddSpec`.
99pub fn normalize_add_spec(input: &str) -> anyhow::Result<String> {
100    if !input.contains(':') {
101        if is_owner_repo(input) {
102            return Ok(format!("github:{input}"));
103        }
104        return Err(anyhow::anyhow!(AMBIGUOUS_SPEC_HINT.replacen("{}", input, 1)));
105    }
106    Ok(input.to_string())
107}
108
109/// Interactive-mode spec normalization: assumes npm for bare names, treats
110/// `@scope/pkg` as npm (not github), never errors. Parity with
111/// `interactive.ts`'s `normalizeAddSpec`.
112pub fn normalize_add_spec_interactive(input: &str) -> String {
113    if !input.contains(':') {
114        if input.starts_with('@') {
115            return format!("npm:{input}");
116        }
117        if is_owner_repo(input) {
118            return format!("github:{input}");
119        }
120        return format!("npm:{input}");
121    }
122    input.to_string()
123}
124
125/// Options for [`run_add`].
126#[derive(Debug, Clone)]
127pub struct RunAddOptions {
128    pub project_dir: PathBuf,
129    pub spec: String,
130    /// Raw CSV from `--docs-paths`. When `Some`, skips the interactive prompt.
131    pub docs_paths_arg: Option<String>,
132    /// `--clear-docs-paths` — drop any existing `docsPaths` override.
133    pub clear_docs_paths: bool,
134}
135
136/// What [`run_add`] produced: user-facing messages, collected so the CLI can
137/// print them (routing is not parity-critical — the harness checks `ask.json`).
138#[derive(Debug, Default, PartialEq, Eq)]
139pub struct AddReport {
140    pub stdout: Vec<String>,
141    pub stderr: Vec<String>,
142}
143
144type GatherFn<'a> =
145    dyn Fn(&str, &Path) -> Result<Vec<CandidateGroup>, CandidateGatheringError> + 'a;
146type PromptFn<'a> = dyn Fn(&str, &[PromptOption]) -> Vec<String> + 'a;
147type InstallerFn<'a> = dyn Fn(&Path, &[String]) -> anyhow::Result<()> + 'a;
148
149/// Test/production seams for [`run_add`]. All `None` → real defaults.
150#[derive(Default)]
151pub struct RunAddDeps<'a> {
152    pub gather: Option<&'a GatherFn<'a>>,
153    pub prompt: Option<&'a PromptFn<'a>>,
154    pub is_tty: Option<&'a (dyn Fn() -> bool + 'a)>,
155    pub installer: Option<&'a InstallerFn<'a>>,
156}
157
158/// `ask add <spec>` implementation. Persists the entry (bare string or object
159/// with a `docsPaths` override per the three policies below) then runs the
160/// lazy-first installer for the single spec.
161pub fn run_add(
162    client: &dyn HttpClient,
163    options: &RunAddOptions,
164    deps: &RunAddDeps,
165) -> anyhow::Result<AddReport> {
166    let default_gather = |spec: &str, dir: &Path| {
167        gather_docs_candidates(client, spec, dir, &EnsureCheckoutDeps::default())
168    };
169    let gather: &GatherFn = deps.gather.unwrap_or(&default_gather);
170
171    let default_prompt: &PromptFn = &default_multiselect;
172    let prompt: &PromptFn = deps.prompt.unwrap_or(default_prompt);
173
174    let default_is_tty = || std::io::stdout().is_terminal();
175    let is_tty: &dyn Fn() -> bool = deps.is_tty.unwrap_or(&default_is_tty);
176
177    let default_installer = |dir: &Path, specs: &[String]| -> anyhow::Result<()> {
178        run_install(
179            dir,
180            &RunInstallOptions {
181                only_specs: Some(specs.to_vec()),
182            },
183        )?;
184        Ok(())
185    };
186    let installer: &InstallerFn = deps.installer.unwrap_or(&default_installer);
187
188    let spec = normalize_add_spec(&options.spec)?;
189
190    if let ParsedSpec::Unknown { .. } = parse_spec(&spec) {
191        anyhow::bail!("Invalid spec: {spec}");
192    }
193
194    let mut ask_json = read_ask_json(&options.project_dir)?.unwrap_or(AskJson {
195        libraries: Vec::new(),
196    });
197    let existing_idx = ask_json.libraries.iter().position(|e| e.spec() == spec);
198
199    let mut report = AddReport::default();
200    let selected = resolve_selected_paths(&spec, options, gather, prompt, is_tty, &mut report);
201
202    let entry = entry_from_spec(spec.clone(), selected.as_deref().unwrap_or(&[]));
203    if let Some(idx) = existing_idx {
204        ask_json.libraries[idx] = entry;
205        report.stdout.push(format!("Updated {spec} in ask.json"));
206    } else {
207        ask_json.libraries.push(entry);
208        report.stdout.push(format!("Added {spec} to ask.json"));
209    }
210    write_ask_json(&options.project_dir, &ask_json)?;
211
212    installer(&options.project_dir, &[spec])?;
213    Ok(report)
214}
215
216/// Strip `root` from `abs`, yielding the relative POSIX-ish tail (empty when
217/// equal). Candidates are always descendants of their group root.
218fn relative(root: &Path, abs: &Path) -> String {
219    abs.strip_prefix(root)
220        .map(|p| p.to_string_lossy().into_owned())
221        .unwrap_or_else(|_| abs.to_string_lossy().into_owned())
222}
223
224fn basename(root: &Path) -> String {
225    root.file_name()
226        .map(|s| s.to_string_lossy().into_owned())
227        .unwrap_or_default()
228}
229
230/// Resolve which docs paths (if any) to persist. Returns `None` for the
231/// canonical bare-string form; `Some(paths)` for an object override.
232fn resolve_selected_paths(
233    spec: &str,
234    options: &RunAddOptions,
235    gather: &GatherFn,
236    prompt: &PromptFn,
237    is_tty: &dyn Fn() -> bool,
238    report: &mut AddReport,
239) -> Option<Vec<String>> {
240    // 1. `--clear-docs-paths` → force canonical string form (downgrade).
241    if options.clear_docs_paths {
242        return None;
243    }
244
245    // 2. `--docs-paths a,b,c` → store the supplied CSV, no prompt.
246    if let Some(csv) = &options.docs_paths_arg {
247        let mut parsed = Vec::new();
248        for raw in csv.split(',') {
249            match sanitize_docs_path(raw) {
250                Some(safe) => parsed.push(safe),
251                None => {
252                    let trimmed = raw.trim();
253                    if !trimmed.is_empty() {
254                        report.stderr.push(format!(
255                            "Ignoring unsafe docs-path entry {trimmed:?} (must be a relative path that stays inside its root)."
256                        ));
257                    }
258                }
259            }
260        }
261        return if parsed.is_empty() {
262            None
263        } else {
264            Some(parsed)
265        };
266    }
267
268    // 3. Probe candidates offline; prompt only on a TTY with a real choice.
269    let groups = match gather(spec, &options.project_dir) {
270        Ok(g) => g,
271        Err(err) => {
272            report.stderr.push(format!(
273                "Could not probe docs candidates for {spec}: {}. Recording the spec without a docs-path override.",
274                err.cause
275            ));
276            return None;
277        }
278    };
279
280    let all_candidates: Vec<(&CandidateGroup, &PathBuf)> = groups
281        .iter()
282        .flat_map(|g| g.paths.iter().map(move |p| (g, p)))
283        .collect();
284    let all_are_root_only = groups
285        .iter()
286        .all(|g| g.paths.len() == 1 && g.paths[0] == g.root);
287
288    if !is_tty() || all_candidates.len() <= 1 || all_are_root_only {
289        return None;
290    }
291
292    let prompt_options: Vec<PromptOption> = all_candidates
293        .iter()
294        .map(|(g, abs)| {
295            let rel = relative(&g.root, abs);
296            PromptOption {
297                label: if rel.is_empty() { ".".to_string() } else { rel },
298                value: abs.to_string_lossy().into_owned(),
299                hint: basename(&g.root),
300            }
301        })
302        .collect();
303
304    let picked = prompt(
305        &format!("Select docs paths to keep for {spec} (space to toggle, enter to confirm):"),
306        &prompt_options,
307    );
308    if picked.is_empty() {
309        return None;
310    }
311
312    let mut selected = Vec::new();
313    for abs in &picked {
314        if let Some((g, abs_path)) = all_candidates
315            .iter()
316            .find(|(_, p)| p.to_string_lossy() == *abs)
317        {
318            // Root selection resolves to `.` so the min(1) override schema
319            // still accepts it and the read side re-resolves to the root.
320            let rel = relative(&g.root, abs_path);
321            let rel = if rel.is_empty() { ".".to_string() } else { rel };
322            if let Some(safe) = sanitize_docs_path(&rel) {
323                selected.push(safe);
324            }
325        }
326    }
327    if selected.is_empty() {
328        None
329    } else {
330        Some(selected)
331    }
332}
333
334// ---------------------------------------------------------------------------
335// Interactive flow (bare `ask add`) — TTY-only, not byte-parity tested.
336// ---------------------------------------------------------------------------
337
338/// Dependency names (from `package.json` deps + devDeps) not already declared
339/// in `ask.json`, sorted. Parity with `readProjectDeps`.
340pub fn read_project_deps(
341    package_json: &serde_json::Value,
342    existing_specs: &[String],
343) -> Vec<String> {
344    let mut names: Vec<String> = Vec::new();
345    let mut seen: HashSet<String> = HashSet::new();
346    for key in ["dependencies", "devDependencies"] {
347        if let Some(obj) = package_json.get(key).and_then(|v| v.as_object()) {
348            for k in obj.keys() {
349                if seen.insert(k.clone()) {
350                    names.push(k.clone());
351                }
352            }
353        }
354    }
355    if names.is_empty() {
356        return Vec::new();
357    }
358    let registered: HashSet<String> = existing_specs
359        .iter()
360        .filter_map(|s| match parse_spec(s) {
361            ParsedSpec::Npm { pkg, .. } => Some(pkg),
362            _ => None,
363        })
364        .collect();
365    let mut out: Vec<String> = names
366        .into_iter()
367        .filter(|n| !registered.contains(n))
368        .collect();
369    out.sort();
370    out
371}
372
373/// Which of `deps` have a registry entry. Parity with `checkRegistryBatch`
374/// (sequential here — result set, not concurrency, is the contract).
375#[derive(Debug, Default, PartialEq, Eq)]
376pub struct RegistryCheckResult {
377    pub registered: Vec<String>,
378    pub unregistered: Vec<String>,
379}
380
381pub fn check_registry_batch(
382    client: &dyn HttpClient,
383    ecosystem: &str,
384    deps: &[String],
385) -> RegistryCheckResult {
386    let mut result = RegistryCheckResult::default();
387    for name in deps {
388        if fetch_registry_entry(client, ecosystem, name).is_some() {
389            result.registered.push(name.clone());
390        } else {
391            result.unregistered.push(name.clone());
392        }
393    }
394    result
395}
396
397/// Report for the interactive flow, including an exit code (TTY-required guard
398/// exits 1, mirroring `process.exit(1)`).
399#[derive(Debug, Default, PartialEq, Eq)]
400pub struct InteractiveReport {
401    pub stdout: Vec<String>,
402    pub stderr: Vec<String>,
403    pub exit_code: i32,
404}
405
406type TextFn<'a> = dyn Fn(&str, &str) -> String + 'a;
407
408/// Seams for [`run_interactive_add`].
409#[derive(Default)]
410pub struct RunInteractiveDeps<'a> {
411    pub is_tty: Option<&'a (dyn Fn() -> bool + 'a)>,
412    pub multiselect: Option<&'a PromptFn<'a>>,
413    pub text: Option<&'a TextFn<'a>>,
414    pub installer: Option<&'a InstallerFn<'a>>,
415}
416
417/// Interactive add — scans `package.json` deps, checks them against the ASK
418/// registry, and lets the user multiselect + free-type specs to add.
419pub fn run_interactive_add(
420    client: &dyn HttpClient,
421    project_dir: &Path,
422    deps: &RunInteractiveDeps,
423) -> anyhow::Result<InteractiveReport> {
424    let default_is_tty = || std::io::stdout().is_terminal();
425    let is_tty: &dyn Fn() -> bool = deps.is_tty.unwrap_or(&default_is_tty);
426    let default_multi: &PromptFn = &default_multiselect;
427    let multiselect: &PromptFn = deps.multiselect.unwrap_or(default_multi);
428    let default_text_fn: &TextFn = &default_text;
429    let text: &TextFn = deps.text.unwrap_or(default_text_fn);
430    let default_installer = |dir: &Path, specs: &[String]| -> anyhow::Result<()> {
431        run_install(
432            dir,
433            &RunInstallOptions {
434                only_specs: Some(specs.to_vec()),
435            },
436        )?;
437        Ok(())
438    };
439    let installer: &InstallerFn = deps.installer.unwrap_or(&default_installer);
440
441    let mut report = InteractiveReport::default();
442
443    if !is_tty() {
444        report.stderr.push(
445            "Interactive mode requires a TTY. Use `ask add <spec>` to add a library non-interactively."
446                .to_string(),
447        );
448        report.exit_code = 1;
449        return Ok(report);
450    }
451
452    let ecosystem = detect_ecosystem(project_dir);
453    report
454        .stdout
455        .push(format!("Detected ecosystem: {ecosystem}"));
456
457    let pkg_path = project_dir.join("package.json");
458    if !pkg_path.exists() {
459        report
460            .stderr
461            .push("No package.json found. Cannot scan dependencies.".to_string());
462        report
463            .stdout
464            .push("Use `ask add <spec>` to add a library directly.".to_string());
465        return Ok(report);
466    }
467
468    let package_json: serde_json::Value = match std::fs::read_to_string(&pkg_path)
469        .ok()
470        .and_then(|s| serde_json::from_str(&s).ok())
471    {
472        Some(v) => v,
473        None => {
474            report
475                .stderr
476                .push("Failed to parse package.json. Check for syntax errors.".to_string());
477            return Ok(report);
478        }
479    };
480
481    let mut ask_json = read_ask_json(project_dir)?.unwrap_or(AskJson {
482        libraries: Vec::new(),
483    });
484    let existing_specs: Vec<String> = ask_json
485        .libraries
486        .iter()
487        .map(|e| e.spec().to_string())
488        .collect();
489    let dep_names = read_project_deps(&package_json, &existing_specs);
490
491    if dep_names.is_empty() {
492        report
493            .stdout
494            .push("All project dependencies are already registered in ask.json.".to_string());
495        return Ok(report);
496    }
497
498    report.stdout.push(format!(
499        "Checking {} dependencies against ASK registry...",
500        dep_names.len()
501    ));
502    let RegistryCheckResult {
503        registered,
504        unregistered,
505    } = check_registry_batch(client, ecosystem, &dep_names);
506
507    let mut choices: Vec<PromptOption> = Vec::new();
508    for name in &registered {
509        choices.push(PromptOption {
510            label: name.clone(),
511            value: name.clone(),
512            hint: "registry".to_string(),
513        });
514    }
515    for name in &unregistered {
516        choices.push(PromptOption {
517            label: name.clone(),
518            value: name.clone(),
519            hint: "not in registry".to_string(),
520        });
521    }
522
523    if choices.is_empty() {
524        report
525            .stdout
526            .push("No new dependencies to add.".to_string());
527        return Ok(report);
528    }
529
530    report.stdout.push(format!(
531        "Found {} registered, {} unregistered in ASK registry.",
532        registered.len(),
533        unregistered.len()
534    ));
535
536    let selected = multiselect(
537        "Select libraries to add (space to toggle, enter to confirm):",
538        &choices,
539    );
540
541    let placeholder = "npm:lodash, github:owner/repo@v1";
542    let specs: Vec<String> = if selected.is_empty() {
543        let manual = text(
544            "Enter a spec manually (or press enter to skip):",
545            placeholder,
546        );
547        if manual.trim().is_empty() {
548            report.stdout.push("No libraries selected.".to_string());
549            return Ok(report);
550        }
551        manual
552            .split(',')
553            .map(|s| normalize_add_spec_interactive(s.trim()))
554            .filter(|s| !s.is_empty())
555            .collect()
556    } else {
557        // Selected names always come from package.json → npm ecosystem.
558        let mut specs: Vec<String> = selected.iter().map(|n| format!("npm:{n}")).collect();
559        let manual = text(
560            "Any additional specs to add manually? (press enter to skip):",
561            placeholder,
562        );
563        if !manual.trim().is_empty() {
564            specs.extend(
565                manual
566                    .split(',')
567                    .map(|s| normalize_add_spec_interactive(s.trim()))
568                    .filter(|s| !s.is_empty()),
569            );
570        }
571        specs
572    };
573
574    add_specs(project_dir, &mut ask_json, &specs, installer, &mut report)?;
575    Ok(report)
576}
577
578fn add_specs(
579    project_dir: &Path,
580    ask_json: &mut AskJson,
581    specs: &[String],
582    installer: &InstallerFn,
583    report: &mut InteractiveReport,
584) -> anyhow::Result<()> {
585    let mut added: Vec<String> = Vec::new();
586    for spec in specs {
587        if let ParsedSpec::Unknown { .. } = parse_spec(spec) {
588            report.stderr.push(format!("Skipping invalid spec: {spec}"));
589            continue;
590        }
591        if ask_json.libraries.iter().any(|e| e.spec() == spec) {
592            report.stdout.push(format!("{spec} already in ask.json"));
593            continue;
594        }
595        ask_json.libraries.push(entry_from_spec(spec.clone(), &[]));
596        added.push(spec.clone());
597    }
598
599    if added.is_empty() {
600        report.stdout.push("No new libraries to add.".to_string());
601        return Ok(());
602    }
603
604    write_ask_json(project_dir, ask_json)?;
605    let plural = if added.len() == 1 { "y" } else { "ies" };
606    report.stdout.push(format!(
607        "Added {} librar{plural} to ask.json: {}",
608        added.len(),
609        added.join(", ")
610    ));
611
612    installer(project_dir, &added)?;
613    Ok(())
614}
615
616/// Production multiselect: `dialoguer::MultiSelect`. On any I/O error (no TTY,
617/// interrupted) returns an empty selection, matching the "nothing picked" path.
618fn default_multiselect(msg: &str, opts: &[PromptOption]) -> Vec<String> {
619    use dialoguer::MultiSelect;
620    let items: Vec<String> = opts
621        .iter()
622        .map(|o| {
623            if o.hint.is_empty() {
624                o.label.clone()
625            } else {
626                format!("{}  ({})", o.label, o.hint)
627            }
628        })
629        .collect();
630    match MultiSelect::new().with_prompt(msg).items(&items).interact() {
631        Ok(idxs) => idxs
632            .into_iter()
633            .filter_map(|i| opts.get(i).map(|o| o.value.clone()))
634            .collect(),
635        Err(_) => Vec::new(),
636    }
637}
638
639/// Production text input: `dialoguer::Input`, empty allowed (enter to skip).
640fn default_text(msg: &str, _placeholder: &str) -> String {
641    use dialoguer::Input;
642    Input::<String>::new()
643        .with_prompt(msg)
644        .allow_empty(true)
645        .interact_text()
646        .unwrap_or_default()
647}
648
649#[cfg(test)]
650mod tests {
651    use super::*;
652    use crate::http::mock::MockClient;
653
654    #[test]
655    fn posix_normalize_matches_node() {
656        assert_eq!(posix_normalize("docs/./api"), "docs/api");
657        assert_eq!(posix_normalize("docs//api"), "docs/api");
658        assert_eq!(posix_normalize("a/b/.."), "a");
659        assert_eq!(posix_normalize("a/../.."), "..");
660        assert_eq!(posix_normalize("."), ".");
661        assert_eq!(posix_normalize("./docs"), "docs");
662    }
663
664    #[test]
665    fn sanitize_rejects_unsafe_accepts_relative() {
666        assert_eq!(sanitize_docs_path("docs"), Some("docs".to_string()));
667        assert_eq!(
668            sanitize_docs_path("  docs/api "),
669            Some("docs/api".to_string())
670        );
671        assert_eq!(
672            sanitize_docs_path("docs\\api"),
673            Some("docs/api".to_string())
674        );
675        assert_eq!(sanitize_docs_path("."), Some(".".to_string()));
676        assert_eq!(sanitize_docs_path(""), None);
677        assert_eq!(sanitize_docs_path("   "), None);
678        assert_eq!(sanitize_docs_path("/abs"), None);
679        assert_eq!(sanitize_docs_path(".."), None);
680        assert_eq!(sanitize_docs_path("../escape"), None);
681        assert_eq!(sanitize_docs_path("a/../../b"), None);
682    }
683
684    #[test]
685    fn normalize_add_spec_owner_repo_and_ambiguous() {
686        assert_eq!(
687            normalize_add_spec("vercel/next.js").unwrap(),
688            "github:vercel/next.js"
689        );
690        assert_eq!(normalize_add_spec("npm:next").unwrap(), "npm:next");
691        assert!(normalize_add_spec("lodash").is_err());
692    }
693
694    #[test]
695    fn normalize_interactive_assumes_npm() {
696        assert_eq!(normalize_add_spec_interactive("lodash"), "npm:lodash");
697        assert_eq!(
698            normalize_add_spec_interactive("@mastra/client-js"),
699            "npm:@mastra/client-js"
700        );
701        assert_eq!(
702            normalize_add_spec_interactive("vercel/next.js"),
703            "github:vercel/next.js"
704        );
705        assert_eq!(
706            normalize_add_spec_interactive("github:o/r@v1"),
707            "github:o/r@v1"
708        );
709    }
710
711    #[test]
712    fn read_project_deps_dedups_sorts_excludes_registered() {
713        let pkg = serde_json::json!({
714            "dependencies": { "react": "18", "zod": "3" },
715            "devDependencies": { "vite": "5", "react": "18" }
716        });
717        let existing = vec!["npm:react".to_string()];
718        assert_eq!(read_project_deps(&pkg, &existing), vec!["vite", "zod"]);
719    }
720
721    #[test]
722    fn read_project_deps_empty() {
723        let pkg = serde_json::json!({});
724        assert!(read_project_deps(&pkg, &[]).is_empty());
725    }
726
727    fn write_ask_json_raw(dir: &Path, body: &str) {
728        std::fs::write(dir.join("ask.json"), body).unwrap();
729    }
730
731    #[test]
732    fn run_add_clear_docs_paths_writes_bare_string() {
733        let proj = tempfile::tempdir().unwrap();
734        write_ask_json_raw(
735            proj.path(),
736            r#"{"libraries":[{"spec":"npm:react","docsPaths":["docs"]}]}"#,
737        );
738        let no_install = |_: &Path, _: &[String]| -> anyhow::Result<()> { Ok(()) };
739        let deps = RunAddDeps {
740            installer: Some(&no_install),
741            ..Default::default()
742        };
743        let opts = RunAddOptions {
744            project_dir: proj.path().to_path_buf(),
745            spec: "npm:react".into(),
746            docs_paths_arg: None,
747            clear_docs_paths: true,
748        };
749        run_add(&MockClient::new(), &opts, &deps).unwrap();
750        let written = std::fs::read_to_string(proj.path().join("ask.json")).unwrap();
751        assert!(written.contains("\"npm:react\""));
752        assert!(!written.contains("docsPaths"));
753    }
754
755    #[test]
756    fn run_add_docs_paths_csv_persists_object_and_warns_unsafe() {
757        let proj = tempfile::tempdir().unwrap();
758        let no_install = |_: &Path, _: &[String]| -> anyhow::Result<()> { Ok(()) };
759        let deps = RunAddDeps {
760            installer: Some(&no_install),
761            ..Default::default()
762        };
763        let opts = RunAddOptions {
764            project_dir: proj.path().to_path_buf(),
765            spec: "npm:react".into(),
766            docs_paths_arg: Some("docs, ../evil ,api".into()),
767            clear_docs_paths: false,
768        };
769        let report = run_add(&MockClient::new(), &opts, &deps).unwrap();
770        let written = std::fs::read_to_string(proj.path().join("ask.json")).unwrap();
771        assert!(written.contains("docsPaths"));
772        assert!(written.contains("\"docs\""));
773        assert!(written.contains("\"api\""));
774        assert!(!written.contains("evil"));
775        assert!(report.stderr.iter().any(|m| m.contains("unsafe docs-path")));
776    }
777
778    #[test]
779    fn run_add_bare_owner_repo_normalizes_to_github() {
780        let proj = tempfile::tempdir().unwrap();
781        let captured = std::cell::RefCell::new(Vec::new());
782        let capture = |_: &Path, specs: &[String]| -> anyhow::Result<()> {
783            captured.borrow_mut().extend_from_slice(specs);
784            Ok(())
785        };
786        let deps = RunAddDeps {
787            installer: Some(&capture),
788            ..Default::default()
789        };
790        let opts = RunAddOptions {
791            project_dir: proj.path().to_path_buf(),
792            spec: "vercel/next.js".into(),
793            docs_paths_arg: None,
794            clear_docs_paths: false,
795        };
796        run_add(&MockClient::new(), &opts, &deps).unwrap();
797        assert_eq!(captured.borrow().as_slice(), ["github:vercel/next.js"]);
798        let written = std::fs::read_to_string(proj.path().join("ask.json")).unwrap();
799        assert!(written.contains("github:vercel/next.js"));
800    }
801
802    #[test]
803    fn interactive_requires_tty() {
804        let proj = tempfile::tempdir().unwrap();
805        let no_tty = || false;
806        let deps = RunInteractiveDeps {
807            is_tty: Some(&no_tty),
808            ..Default::default()
809        };
810        let report = run_interactive_add(&MockClient::new(), proj.path(), &deps).unwrap();
811        assert_eq!(report.exit_code, 1);
812        assert!(report.stderr[0].contains("requires a TTY"));
813    }
814
815    #[test]
816    fn interactive_no_package_json() {
817        let proj = tempfile::tempdir().unwrap();
818        let tty = || true;
819        let deps = RunInteractiveDeps {
820            is_tty: Some(&tty),
821            ..Default::default()
822        };
823        let report = run_interactive_add(&MockClient::new(), proj.path(), &deps).unwrap();
824        assert_eq!(report.exit_code, 0);
825        assert!(report.stderr.iter().any(|m| m.contains("No package.json")));
826    }
827
828    #[test]
829    fn interactive_selects_and_installs_npm_specs() {
830        let proj = tempfile::tempdir().unwrap();
831        std::fs::write(
832            proj.path().join("package.json"),
833            r#"{"dependencies":{"lodash":"4"}}"#,
834        )
835        .unwrap();
836        let tty = || true;
837        // MockClient returns nothing → registry lookups miss → all unregistered.
838        let pick = |_: &str, opts: &[PromptOption]| -> Vec<String> {
839            opts.iter().map(|o| o.value.clone()).collect()
840        };
841        let no_text = |_: &str, _: &str| -> String { String::new() };
842        let captured = std::cell::RefCell::new(Vec::new());
843        let capture = |_: &Path, specs: &[String]| -> anyhow::Result<()> {
844            captured.borrow_mut().extend_from_slice(specs);
845            Ok(())
846        };
847        let deps = RunInteractiveDeps {
848            is_tty: Some(&tty),
849            multiselect: Some(&pick),
850            text: Some(&no_text),
851            installer: Some(&capture),
852        };
853        let report = run_interactive_add(&MockClient::new(), proj.path(), &deps).unwrap();
854        assert_eq!(report.exit_code, 0);
855        assert_eq!(captured.borrow().as_slice(), ["npm:lodash"]);
856        let written = std::fs::read_to_string(proj.path().join("ask.json")).unwrap();
857        assert!(written.contains("npm:lodash"));
858    }
859}