context7-cli 0.4.3

Search library documentation from your terminal — zero runtime, bilingual (EN/PT), multi-key rotation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
/// HTTP client, retry logic, and Context7 API calls.
///
/// This module owns the full lifecycle of API interaction:
/// request building, status handling, and key-rotation retry.
use anyhow::{bail, Context, Result};
use rand::seq::SliceRandom;
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use tokio::time::{sleep, Duration};
use tracing::{error, info, warn};

use crate::errors::ErroContext7;
use crate::i18n::{t, Mensagem};

// ─── CONSTANTE ───────────────────────────────────────────────────────────────

const BASE_URL: &str = "https://context7.com/api";

// ─── MODELOS DE RESPOSTA DA API ───────────────────────────────────────────────

/// Represents a single library entry returned by the search endpoint.
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LibrarySearchResult {
    /// Unique library identifier (e.g. `/facebook/react`).
    pub id: String,
    /// Human-readable library title.
    pub title: String,
    /// Optional short description of the library.
    pub description: Option<String>,
    /// Relevance/trust score returned by the API, if available.
    pub trust_score: Option<f64>,
    /// Number of GitHub stars, if available. The API returns `-1` when unavailable.
    pub stars: Option<i64>,
    /// Total number of documentation snippets indexed.
    pub total_snippets: Option<u64>,
    /// Total number of tokens indexed.
    pub total_tokens: Option<u64>,
    /// Whether the library has been verified by the Context7 team.
    pub verified: Option<bool>,
    /// Git branch used for indexing.
    pub branch: Option<String>,
    /// Indexing state (e.g. "active", "pending").
    pub state: Option<String>,
}

/// A single code block within a documentation snippet.
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct CodeBlock {
    /// Programming language of the code (e.g. `"rust"`, `"bash"`).
    pub language: String,
    /// Source code content.
    pub code: String,
}

/// Represents a single documentation excerpt returned by the docs endpoint (JSON mode).
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DocumentationSnippet {
    /// Page title of the source documentation page, if available.
    pub page_title: Option<String>,
    /// Title of this specific code snippet, if available.
    pub code_title: Option<String>,
    /// Description accompanying the code snippet, if available.
    pub code_description: Option<String>,
    /// Primary programming language of the snippet, if available.
    pub code_language: Option<String>,
    /// Number of tokens in this snippet, if available.
    pub code_tokens: Option<u64>,
    /// Unique identifier or source URL of this snippet, if available.
    pub code_id: Option<String>,
    /// List of code blocks contained in this snippet.
    pub code_list: Option<Vec<CodeBlock>>,
    /// Relevance score for the query, if available.
    pub relevance: Option<f64>,
    /// Model used to generate or rank this snippet, if available.
    pub model: Option<String>,
}

/// Top-level response from the library search endpoint (`GET /api/v1/search`).
#[derive(Debug, Deserialize)]
pub struct RespostaListaBibliotecas {
    /// List of matching libraries.
    pub results: Vec<LibrarySearchResult>,
}

/// Top-level response from the documentation endpoint (`GET /api/v1/{library_id}`).
#[derive(Debug, Deserialize, Serialize)]
pub struct RespostaDocumentacao {
    /// Structured documentation snippets (JSON mode).
    pub snippets: Option<Vec<DocumentationSnippet>>,
}

// ─── CLIENTE HTTP ─────────────────────────────────────────────────────────────

/// Creates a reusable HTTP client with rustls-TLS, 30 s timeout, and HTTP/2.
///
/// The client should be created once per invocation and shared via `Arc`.
pub fn criar_cliente_http() -> Result<reqwest::Client> {
    let cliente = reqwest::Client::builder()
        .use_rustls_tls()
        .timeout(Duration::from_secs(30))
        .user_agent(format!("context7-cli/{}", env!("CARGO_PKG_VERSION")))
        .pool_max_idle_per_host(4)
        .build()
        .with_context(|| t(Mensagem::FalhaCriarClienteHttp))?;

    Ok(cliente)
}

// ─── RETRY COM ROTAÇÃO DE CHAVES ──────────────────────────────────────────────

/// Executes an API call with retry and key rotation.
///
/// Shuffles a local copy of the provided keys (random draw without replacement)
/// and retries up to `min(keys.len(), 5)` times with exponential backoff:
/// 500 ms → 1 s → 2 s.
///
/// Short-circuits immediately on parse errors (status 200 but JSON failed) —
/// retrying with another key would not help in that case.
///
/// The closure receives an owned `String` (clone of the key) to satisfy the
/// `async move` ownership requirement inside the future.
pub async fn executar_com_retry<F, Fut, T>(chaves: &[String], operacao: F) -> Result<T>
where
    F: Fn(String) -> Fut,
    Fut: std::future::Future<Output = Result<T, ErroContext7>>,
{
    let max_tentativas = chaves.len().min(5);

    // Shuffles a local copy — avoids modifying the caller's vec
    let mut chaves_embaralhadas = chaves.to_vec();
    let mut rng = rand::thread_rng();
    chaves_embaralhadas.shuffle(&mut rng);

    let atrasos_ms = [500u64, 1000, 2000];
    let mut chaves_falhas_auth = 0usize;

    for (tentativa, chave) in chaves_embaralhadas
        .into_iter()
        .take(max_tentativas)
        .enumerate()
    {
        info!("Tentativa {}/{}", tentativa + 1, max_tentativas);

        match operacao(chave).await {
            Ok(resultado) => return Ok(resultado),

            Err(ErroContext7::ApiRetornou400 { mensagem }) => {
                // 400 is not transient — abort immediately
                bail!(ErroContext7::ApiRetornou400 { mensagem });
            }

            Err(ErroContext7::BibliotecaNaoEncontrada { library_id }) => {
                // Library doesn't exist — no point trying other keys
                bail!(ErroContext7::BibliotecaNaoEncontrada { library_id });
            }

            Err(ErroContext7::SemChavesApi) => {
                chaves_falhas_auth += 1;
                warn!("Chave de API inválida (401/403), tentando próxima...");
            }

            Err(ErroContext7::RespostaInvalida { status: 200 }) => {
                // Parse failure on HTTP 200 — schema mismatch, not a key issue
                // Short-circuit: no point trying other keys
                bail!(ErroContext7::RespostaInvalida { status: 200 });
            }

            Err(e) => {
                warn!("Falha na tentativa {}: {}", tentativa + 1, e);

                // Backoff before next attempt (not on the last one)
                if tentativa + 1 < max_tentativas && tentativa < atrasos_ms.len() {
                    let atraso = Duration::from_millis(atrasos_ms[tentativa]);
                    info!(
                        "Aguardando {}ms antes de tentar novamente...",
                        atraso.as_millis()
                    );
                    sleep(atraso).await;
                }
            }
        }
    }

    if chaves_falhas_auth >= max_tentativas {
        bail!(ErroContext7::SemChavesApi);
    }

    bail!(ErroContext7::RetryEsgotado {
        tentativas: max_tentativas as u32,
    });
}

// ─── CHAMADAS À API ───────────────────────────────────────────────────────────

/// Searches for libraries matching `nome` with optional relevance `query_contexto`.
///
/// Returns `Err(ErroContext7)` on HTTP errors to enable retry in `executar_com_retry`.
pub async fn buscar_biblioteca(
    cliente: &reqwest::Client,
    chave: &str,
    nome: &str,
    query_contexto: &str,
) -> Result<RespostaListaBibliotecas, ErroContext7> {
    let url = format!("{}/v1/search", BASE_URL);

    let resposta = cliente
        .get(&url)
        .bearer_auth(chave)
        .query(&[("libraryName", nome), ("query", query_contexto)])
        .send()
        .await
        .map_err(|e| {
            error!("Erro de rede ao buscar biblioteca: {}", e);
            ErroContext7::RespostaInvalida { status: 0 }
        })?;

    tratar_status_resposta(resposta).await
}

/// Fetches documentation for `library_id` with an optional `query` filter (JSON mode).
///
/// Always requests `type=json`. Use [`buscar_documentacao_texto`] for plain-text output.
/// Returns `Err(ErroContext7)` on HTTP errors to enable retry in `executar_com_retry`.
pub async fn buscar_documentacao(
    cliente: &reqwest::Client,
    chave: &str,
    library_id: &str,
    query: Option<&str>,
) -> Result<RespostaDocumentacao, ErroContext7> {
    // Normalise library_id: strip leading slash if present
    let id_normalizado = library_id.trim_start_matches('/');
    let url = format!("{}/v1/{}", BASE_URL, id_normalizado);

    let mut construtor = cliente
        .get(&url)
        .bearer_auth(chave)
        .query(&[("type", "json")]);

    if let Some(q) = query {
        construtor = construtor.query(&[("query", q)]);
    }

    let resposta = construtor.send().await.map_err(|e| {
        error!("Erro de rede ao buscar documentação: {}", e);
        ErroContext7::RespostaInvalida { status: 0 }
    })?;

    tratar_status_resposta(resposta).await.map_err(|e| match e {
        ErroContext7::RespostaInvalida { status: 404 } => ErroContext7::BibliotecaNaoEncontrada {
            library_id: library_id.to_string(),
        },
        outro => outro,
    })
}

/// Fetches documentation for `library_id` as raw plain text (markdown).
///
/// Uses `type=txt`. Returns the raw response body as a `String`.
/// Returns `Err(ErroContext7)` on HTTP errors to enable retry in `executar_com_retry`.
pub async fn buscar_documentacao_texto(
    cliente: &reqwest::Client,
    chave: &str,
    library_id: &str,
    query: Option<&str>,
) -> Result<String, ErroContext7> {
    let id_normalizado = library_id.trim_start_matches('/');
    let url = format!("{}/v1/{}", BASE_URL, id_normalizado);

    let mut construtor = cliente
        .get(&url)
        .bearer_auth(chave)
        .query(&[("type", "txt")]);

    if let Some(q) = query {
        construtor = construtor.query(&[("query", q)]);
    }

    let resposta = construtor.send().await.map_err(|e| {
        error!("Erro de rede ao buscar documentação: {}", e);
        ErroContext7::RespostaInvalida { status: 0 }
    })?;

    let status = resposta.status();

    if !status.is_success() {
        match status {
            StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => {
                return Err(ErroContext7::SemChavesApi);
            }
            StatusCode::BAD_REQUEST => {
                let mensagem = resposta
                    .text()
                    .await
                    .unwrap_or_else(|_| "Sem detalhes".to_string());
                return Err(ErroContext7::ApiRetornou400 { mensagem });
            }
            StatusCode::NOT_FOUND => {
                return Err(ErroContext7::BibliotecaNaoEncontrada {
                    library_id: library_id.to_string(),
                });
            }
            _ => {
                return Err(ErroContext7::RespostaInvalida {
                    status: status.as_u16(),
                });
            }
        }
    }

    resposta
        .text()
        .await
        .map_err(|_| ErroContext7::RespostaInvalida {
            status: status.as_u16(),
        })
}

/// Maps HTTP status codes to typed `ErroContext7` variants or deserialises success bodies.
async fn tratar_status_resposta<T: for<'de> Deserialize<'de>>(
    resposta: reqwest::Response,
) -> Result<T, ErroContext7> {
    let status = resposta.status();

    match status {
        s if s.is_success() => resposta.json::<T>().await.map_err(|e| {
            error!("Falha ao desserializar resposta JSON: {}", e);
            ErroContext7::RespostaInvalida {
                status: status.as_u16(),
            }
        }),

        StatusCode::BAD_REQUEST => {
            let mensagem = resposta
                .text()
                .await
                .unwrap_or_else(|_| "Sem detalhes".to_string());
            Err(ErroContext7::ApiRetornou400 { mensagem })
        }

        StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => Err(ErroContext7::SemChavesApi),

        StatusCode::TOO_MANY_REQUESTS => {
            warn!("Rate limit atingido (429), aguardando retry...");
            Err(ErroContext7::RespostaInvalida {
                status: status.as_u16(),
            })
        }

        s if s.is_server_error() => {
            warn!(
                "Erro do servidor ({}), tentando novamente...",
                status.as_u16()
            );
            Err(ErroContext7::RespostaInvalida {
                status: status.as_u16(),
            })
        }

        _ => Err(ErroContext7::RespostaInvalida {
            status: status.as_u16(),
        }),
    }
}

// ─── TESTES ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod testes {
    use super::*;

    // ── Desserialização de structs ────────────────────────────────────────────

    #[test]
    fn testa_deserializacao_library_search_result() {
        let json = r#"{
            "id": "/facebook/react",
            "title": "React",
            "description": "A JavaScript library for building user interfaces",
            "trustScore": 95.0
        }"#;

        let resultado: LibrarySearchResult =
            serde_json::from_str(json).expect("Deve deserializar LibrarySearchResult");

        assert_eq!(resultado.id, "/facebook/react");
        assert_eq!(resultado.title, "React");
        assert_eq!(
            resultado.description.as_deref(),
            Some("A JavaScript library for building user interfaces")
        );
        assert!((resultado.trust_score.unwrap() - 95.0).abs() < f64::EPSILON);
    }

    #[test]
    fn testa_deserializacao_library_search_result_tolerante_campos_faltando() {
        let json = r#"{
            "id": "/minimal/lib",
            "title": "MinimalLib"
        }"#;

        let resultado: LibrarySearchResult =
            serde_json::from_str(json).expect("Deve deserializar mesmo com campos ausentes");

        assert_eq!(resultado.id, "/minimal/lib");
        assert_eq!(resultado.title, "MinimalLib");
        assert!(resultado.description.is_none(), "description deve ser None");
        assert!(resultado.trust_score.is_none(), "trust_score deve ser None");
    }

    #[test]
    fn testa_deserializacao_library_search_result_com_campos_opcionais() {
        let json = r#"{
            "id": "/facebook/react",
            "title": "React",
            "trustScore": 95.0,
            "stars": 228000,
            "totalSnippets": 1500,
            "totalTokens": 250000,
            "verified": true,
            "branch": "main",
            "state": "active"
        }"#;

        let resultado: LibrarySearchResult =
            serde_json::from_str(json).expect("Deve deserializar com campos opcionais");

        assert_eq!(resultado.stars, Some(228_000i64));
        assert_eq!(resultado.total_snippets, Some(1_500));
        assert_eq!(resultado.total_tokens, Some(250_000));
        assert_eq!(resultado.verified, Some(true));
        assert_eq!(resultado.branch.as_deref(), Some("main"));
        assert_eq!(resultado.state.as_deref(), Some("active"));
    }

    #[test]
    fn testa_deserializacao_documentation_snippet() {
        let json = r#"{
            "pageTitle": "React Hooks API",
            "codeTitle": "useEffect example",
            "codeDescription": "The Effect Hook lets you perform side effects.",
            "codeLanguage": "javascript",
            "codeTokens": 68,
            "codeId": "https://github.com/facebook/react/blob/main/packages/react/src/ReactHooks.js",
            "codeList": [
                {"language": "javascript", "code": "useEffect(() => { /* effect */ }, []);"}
            ],
            "relevance": 0.032,
            "model": "gemini-2.5-flash"
        }"#;

        let trecho: DocumentationSnippet =
            serde_json::from_str(json).expect("Deve deserializar DocumentationSnippet");

        assert_eq!(trecho.page_title.as_deref(), Some("React Hooks API"));
        assert_eq!(trecho.code_title.as_deref(), Some("useEffect example"));
        assert_eq!(trecho.code_language.as_deref(), Some("javascript"));
        assert_eq!(trecho.code_tokens, Some(68));
        let lista = trecho.code_list.as_ref().expect("Deve ter code_list");
        assert_eq!(lista.len(), 1);
        assert_eq!(lista[0].language, "javascript");
        assert!((trecho.relevance.unwrap() - 0.032).abs() < f64::EPSILON);
    }

    #[test]
    fn testa_deserializacao_documentation_snippet_sem_campos_opcionais() {
        let json = r#"{}"#;

        let trecho: DocumentationSnippet =
            serde_json::from_str(json).expect("Deve deserializar snippet completamente vazio");

        assert!(trecho.page_title.is_none());
        assert!(trecho.code_title.is_none());
        assert!(trecho.code_list.is_none());
    }

    #[test]
    fn testa_deserializacao_code_block() {
        let json = r#"{"language": "rust", "code": "fn main() {}"}"#;

        let bloco: CodeBlock = serde_json::from_str(json).expect("Deve deserializar CodeBlock");

        assert_eq!(bloco.language, "rust");
        assert_eq!(bloco.code, "fn main() {}");
    }

    // ── Mock HTTP ─────────────────────────────────────────────────────────────

    #[tokio::test]
    async fn testa_buscar_biblioteca_com_mock_servidor_retorna_200() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let servidor_mock = MockServer::start().await;

        let resposta_json = serde_json::json!({
            "results": [
                {
                    "id": "/axum-rs/axum",
                    "title": "axum",
                    "description": "Framework web para Rust",
                    "trustScore": 90.0
                }
            ]
        });

        Mock::given(method("GET"))
            .and(path("/api/v1/search"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&resposta_json))
            .mount(&servidor_mock)
            .await;

        let cliente = reqwest::Client::new();
        let url = format!("{}/api/v1/search", servidor_mock.uri());

        let resposta = cliente
            .get(&url)
            .bearer_auth("ctx7sk-teste-mock")
            .query(&[("libraryName", "axum"), ("query", "axum")])
            .send()
            .await
            .expect("Deve conectar ao mock server");

        assert!(resposta.status().is_success(), "Status deve ser 200");

        let dados: RespostaListaBibliotecas = resposta
            .json()
            .await
            .expect("Deve deserializar resposta do mock");

        assert_eq!(dados.results.len(), 1);
        assert_eq!(dados.results[0].id, "/axum-rs/axum");
        assert_eq!(dados.results[0].title, "axum");
    }

    #[tokio::test]
    async fn testa_buscar_documentacao_com_mock_servidor_retorna_200() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let servidor_mock = MockServer::start().await;

        let resposta_json = serde_json::json!({
            "snippets": [
                {
                    "pageTitle": "axum::Router",
                    "codeTitle": "Basic Router setup",
                    "codeDescription": "O Router do Axum permite definir rotas HTTP de forma declarativa.",
                    "codeLanguage": "rust",
                    "codeList": [
                        {"language": "rust", "code": "let app = Router::new().route(\"/\", get(handler));"}
                    ]
                }
            ]
        });

        Mock::given(method("GET"))
            .and(path("/api/v1/axum-rs/axum"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&resposta_json))
            .mount(&servidor_mock)
            .await;

        let cliente = reqwest::Client::new();
        let url = format!("{}/api/v1/axum-rs/axum", servidor_mock.uri());

        let resposta = cliente
            .get(&url)
            .bearer_auth("ctx7sk-teste-docs-mock")
            .query(&[("type", "json"), ("query", "como criar router")])
            .send()
            .await
            .expect("Deve conectar ao mock server");

        assert!(resposta.status().is_success());

        let dados: RespostaDocumentacao = resposta
            .json()
            .await
            .expect("Deve deserializar resposta do mock");

        let trechos = dados.snippets.as_ref().expect("Deve ter snippets");
        assert_eq!(trechos.len(), 1);
        let lista = trechos[0].code_list.as_ref().expect("Deve ter code_list");
        assert!(lista[0].code.contains("Router::new"));
    }

    // ── Shuffle de chaves ─────────────────────────────────────────────────────

    #[test]
    fn testa_shuffle_chaves_preserva_todos_os_elementos() {
        let chaves_originais: Vec<String> =
            (0..10).map(|i| format!("ctx7sk-chave-{:02}", i)).collect();

        let mut chaves_copia = chaves_originais.clone();
        let mut rng = rand::thread_rng();
        chaves_copia.shuffle(&mut rng);

        assert_eq!(
            chaves_copia.len(),
            chaves_originais.len(),
            "Shuffle deve preservar todos os elementos"
        );

        let mut ordenadas_original = chaves_originais.clone();
        let mut ordenadas_copia = chaves_copia.clone();
        ordenadas_original.sort();
        ordenadas_copia.sort();
        assert_eq!(
            ordenadas_original, ordenadas_copia,
            "Shuffle deve conter os mesmos elementos, apenas em ordem diferente"
        );
    }

    #[test]
    fn testa_max_tentativas_limitado_a_5() {
        // Verifica que chaves.len().min(5) funciona corretamente
        let muitas_chaves: Vec<String> =
            (0..10).map(|i| format!("ctx7sk-chave-{:02}", i)).collect();
        let max = muitas_chaves.len().min(5);
        assert_eq!(
            max, 5,
            "Max tentativas deve ser limitado a 5 mesmo com 10 chaves"
        );

        let poucas_chaves: Vec<String> = vec!["ctx7sk-a".to_string(), "ctx7sk-b".to_string()];
        let max2 = poucas_chaves.len().min(5);
        assert_eq!(max2, 2, "Com 2 chaves, max deve ser 2");
    }
}