pageinfo-rs 0.2.1

CLI tool that analyzes web pages and produces structured LLM-friendly output
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
use clap::{Parser, Subcommand};
use std::error::Error;
mod analyzer;
mod cache;
mod client;
mod help;
mod html;
mod http_display;
mod resolve;
mod skills;

/// CLI tool to research web pages
#[derive(Parser, Debug)]
#[command(name = "pginf")]
#[command(author = "oiwn <https://github.org/oiwn>")]
#[command(version = "0.2")]
#[command(about = "CLI tool to research web pages", long_about = None)]
#[command(disable_help_subcommand = true)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
    /// Proxy URL (e.g. socks5://user:pass@host:port)
    #[arg(long, global = true)]
    proxy: Option<String>,
    /// Browser emulation name (e.g. chrome137, firefox, safari)
    #[arg(long, global = true)]
    browser: Option<String>,
    /// Request timeout in seconds
    #[arg(long, global = true)]
    timeout: Option<u64>,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Show built-in help for humans and LLM tools
    Help {
        /// Optional help topic: tool
        topic: Option<String>,
    },
    /// Fetch page, cache it, print HTTP metadata
    Fetch {
        /// URL to fetch
        url: String,
        /// Output as JSON
        #[arg(long)]
        json: bool,
        /// Ignore cache and do not write fetched page to cache
        #[arg(long, conflicts_with = "refresh")]
        no_cache: bool,
        /// Refetch page and overwrite existing cache entry
        #[arg(long)]
        refresh: bool,
    },
    /// Show link grouping and URL structure
    Links {
        /// URL to analyze
        url: String,
        /// Show only internal (inbound) links
        #[arg(long)]
        inbound: bool,
        /// Show only external (outbound) links
        #[arg(long)]
        outbound: bool,
        /// Output as JSON
        #[arg(long)]
        json: bool,
        /// Ignore cache and do not write fetched page to cache
        #[arg(long, conflicts_with = "refresh")]
        no_cache: bool,
        /// Refetch page and overwrite existing cache entry
        #[arg(long)]
        refresh: bool,
    },
    /// Show curated metadata
    Meta {
        /// URL to analyze
        url: String,
        /// Output as JSON
        #[arg(long)]
        json: bool,
        /// Ignore cache and do not write fetched page to cache
        #[arg(long, conflicts_with = "refresh")]
        no_cache: bool,
        /// Refetch page and overwrite existing cache entry
        #[arg(long)]
        refresh: bool,
    },
    /// Show structured data (JSON-LD, Next.js, inline JSON)
    Json {
        /// URL to analyze
        url: String,
        /// Output as JSON
        #[arg(long)]
        json: bool,
        /// Ignore cache and do not write fetched page to cache
        #[arg(long, conflicts_with = "refresh")]
        no_cache: bool,
        /// Refetch page and overwrite existing cache entry
        #[arg(long)]
        refresh: bool,
    },
    /// Extract text content from page
    Text {
        /// URL to analyze
        url: String,
        /// Output format: text (default) or markdown
        #[arg(long, default_value = "text")]
        format: String,
        /// Output as JSON
        #[arg(long)]
        json: bool,
        /// Ignore cache and do not write fetched page to cache
        #[arg(long, conflicts_with = "refresh")]
        no_cache: bool,
        /// Refetch page and overwrite existing cache entry
        #[arg(long)]
        refresh: bool,
    },
    /// Show raw HTTP transaction (request/response debug)
    Http {
        /// URL to load
        #[arg(short, long)]
        url: String,
    },
    /// Show HTML content, optionally filtered by CSS selector
    Html {
        /// URL to fetch
        #[arg(short, long)]
        url: String,
        /// CSS selector to filter elements (e.g. "div.article", "h1, h2", "meta[property]")
        #[arg(short, long)]
        selector: Option<String>,
        /// Ignore cache and do not write fetched page to cache
        #[arg(long, conflicts_with = "refresh")]
        no_cache: bool,
        /// Refetch page and overwrite existing cache entry
        #[arg(long)]
        refresh: bool,
    },
    /// Install pginf skill files for AI coding agents
    Install {
        #[command(subcommand)]
        command: InstallCommand,
    },
}

#[derive(Subcommand, Debug)]
enum InstallCommand {
    /// Install skill files
    Skills {
        #[command(subcommand)]
        target: SkillsTarget,
    },
}

#[derive(Subcommand, Debug)]
enum SkillsTarget {
    /// Install into <project>/.agents/skills/pginf/
    Local,
    /// Install into ~/.agents/skills/pginf/
    Global,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let cli = Cli::parse();

    let mut page_client = client::PageClient::builder();
    if let Some(ref proxy) = cli.proxy {
        page_client = page_client.proxy(proxy)?;
    } else {
        page_client = page_client.proxy_from_env();
    }
    if let Some(ref browser) = cli.browser {
        page_client = page_client.browser(client::parse_browser(browser)?);
    }
    if let Some(secs) = cli.timeout {
        page_client = page_client.timeout(std::time::Duration::from_secs(secs));
    }
    let page_client = page_client.build();

    match &cli.command {
        Commands::Help { topic } => {
            println!("{}", help::render(topic.as_deref()));
        }
        Commands::Fetch {
            url,
            json,
            no_cache,
            refresh,
        } => {
            let resolved =
                resolve::resolve_page(url, &page_client, *no_cache, *refresh)
                    .await?;
            if *json {
                println!("{}", format_fetch_json(&resolved));
            } else {
                println!("{}", format_fetch_markdown(&resolved));
            }
        }
        Commands::Links {
            url,
            inbound,
            outbound,
            json,
            no_cache,
            refresh,
        } => {
            let resolved =
                resolve::resolve_page(url, &page_client, *no_cache, *refresh)
                    .await?;
            let page =
                analyzer::PageInfo::from_fetch_result(&resolved.fetch_result)?;
            if *json {
                println!("{}", page.links_json(*inbound, *outbound));
            } else {
                println!("{}", page.format_links_for_llm());
            }
        }
        Commands::Meta {
            url,
            json,
            no_cache,
            refresh,
        } => {
            let resolved =
                resolve::resolve_page(url, &page_client, *no_cache, *refresh)
                    .await?;
            let page =
                analyzer::PageInfo::from_fetch_result(&resolved.fetch_result)?;
            if *json {
                println!("{}", page.meta_json());
            } else {
                println!("{}", page.format_meta_for_llm());
            }
        }
        Commands::Json {
            url,
            json,
            no_cache,
            refresh,
        } => {
            let resolved =
                resolve::resolve_page(url, &page_client, *no_cache, *refresh)
                    .await?;
            let page =
                analyzer::PageInfo::from_fetch_result(&resolved.fetch_result)?;
            if *json {
                println!("{}", page.json_data_json());
            } else {
                println!("{}", page.format_json_for_llm());
            }
        }
        Commands::Text {
            url,
            format,
            json,
            no_cache,
            refresh,
        } => {
            let resolved =
                resolve::resolve_page(url, &page_client, *no_cache, *refresh)
                    .await?;
            let page =
                analyzer::PageInfo::from_fetch_result(&resolved.fetch_result)?;
            let as_markdown = format == "markdown";
            if *json {
                println!("{}", page.text_json(as_markdown));
            } else {
                println!("{}", page.format_text(as_markdown));
            }
        }
        Commands::Http { url } => {
            let parsed = url::Url::parse(url)?;
            match http_display::retrieve_page(&parsed, &page_client).await {
                Ok(transaction) => {
                    println!("{}", transaction.format_for_llm());

                    let document =
                        dom_content_extraction::scraper::Html::parse_document(
                            &transaction.response.body,
                        );
                    let page_info = html::PageInfo::new(&document);

                    println!("\n=== PAGE INFO ===");
                    println!("{}", page_info);
                    println!("================");
                }
                Err(e) => {
                    eprintln!("Request failed: {}", e);
                }
            }
        }
        Commands::Html {
            url,
            selector,
            no_cache,
            refresh,
        } => {
            let resolved =
                resolve::resolve_page(url, &page_client, *no_cache, *refresh)
                    .await?;
            match selector {
                None => {
                    println!("{}", resolved.fetch_result.body);
                }
                Some(sel) => {
                    let css = dom_content_extraction::scraper::Selector::parse(sel)
                        .map_err(|e| {
                            format!("Invalid CSS selector '{}': {e}", sel)
                        })?;
                    let document =
                        dom_content_extraction::scraper::Html::parse_document(
                            &resolved.fetch_result.body,
                        );
                    let matches: Vec<_> = document.select(&css).collect();
                    if matches.is_empty() {
                        eprintln!("No elements matching '{}'", sel);
                    } else {
                        println!(
                            "{} element(s) matching '{}':\n",
                            matches.len(),
                            sel
                        );
                        for (i, el) in matches.iter().enumerate() {
                            if matches.len() > 1 {
                                println!("--- Element {} ---", i + 1);
                            }
                            println!("{}", el.html());
                        }
                    }
                }
            }
        }
        Commands::Install { command } => match command {
            InstallCommand::Skills { target } => match target {
                SkillsTarget::Local => match skills::install_local() {
                    Ok(msg) => println!("{msg}"),
                    Err(e) => eprintln!("{e}"),
                },
                SkillsTarget::Global => match skills::install_global() {
                    Ok(msg) => println!("{msg}"),
                    Err(e) => eprintln!("{e}"),
                },
            },
        },
    };

    Ok(())
}

fn format_fetch_markdown(resolved: &resolve::ResolveOutput) -> String {
    let r = &resolved.fetch_result;
    let mut out = String::new();
    out.push_str("## Fetch Result\n\n");
    out.push_str(&format!("- **Input URL:** {}\n", r.input_url));
    out.push_str(&format!("- **Final URL:** {}\n", r.final_url));
    out.push_str(&format!("- **Status:** {}\n", r.status));
    out.push_str(&format!("- **Duration:** {}ms\n", r.duration_ms));
    out.push_str(&format!(
        "- **Cached:** {}\n",
        if resolved.from_cache { "yes" } else { "no" }
    ));
    out.push_str(&format!("- **Body size:** {} bytes\n", r.body.len()));
    if !r.headers.is_empty() {
        out.push_str("\n### Response Headers\n\n");
        for (k, v) in &r.headers {
            out.push_str(&format!("- `{}`: {}\n", k, v));
        }
    }
    out
}

fn format_fetch_json(resolved: &resolve::ResolveOutput) -> String {
    let r = &resolved.fetch_result;
    let obj = serde_json::json!({
        "input_url": r.input_url,
        "final_url": r.final_url,
        "status": r.status,
        "duration_ms": r.duration_ms,
        "cached": resolved.from_cache,
        "body_size": r.body.len(),
        "headers": r.headers,
    });
    serde_json::to_string_pretty(&obj).unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::error::ErrorKind;

    #[test]
    fn help_accepts_topic() {
        let cli = Cli::try_parse_from(["pginf", "help", "tool"]).unwrap();
        match cli.command {
            Commands::Help { topic } => {
                assert_eq!(topic.as_deref(), Some("tool"));
            }
            _ => panic!("expected help command"),
        }
    }

    #[test]
    fn fetch_parses_url() {
        let cli =
            Cli::try_parse_from(["pginf", "fetch", "https://example.com"]).unwrap();
        match cli.command {
            Commands::Fetch {
                url,
                json,
                no_cache,
                ..
            } => {
                assert_eq!(url, "https://example.com");
                assert!(!json);
                assert!(!no_cache);
            }
            _ => panic!("expected fetch command"),
        }
    }

    #[test]
    fn fetch_accepts_json_flag() {
        let cli = Cli::try_parse_from([
            "pginf",
            "fetch",
            "https://example.com",
            "--json",
        ])
        .unwrap();
        match cli.command {
            Commands::Fetch { json, .. } => assert!(json),
            _ => panic!("expected fetch command"),
        }
    }

    #[test]
    fn fetch_accepts_no_cache() {
        let cli = Cli::try_parse_from([
            "pginf",
            "fetch",
            "https://example.com",
            "--no-cache",
        ])
        .unwrap();
        match cli.command {
            Commands::Fetch { no_cache, .. } => assert!(no_cache),
            _ => panic!("expected fetch command"),
        }
    }

    #[test]
    fn fetch_rejects_no_cache_with_refresh() {
        let err = Cli::try_parse_from([
            "pginf",
            "fetch",
            "https://example.com",
            "--no-cache",
            "--refresh",
        ])
        .unwrap_err();
        assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
    }

    #[test]
    fn links_parses_url() {
        let cli =
            Cli::try_parse_from(["pginf", "links", "https://example.com"]).unwrap();
        match cli.command {
            Commands::Links {
                url,
                inbound,
                outbound,
                json,
                ..
            } => {
                assert_eq!(url, "https://example.com");
                assert!(!inbound);
                assert!(!outbound);
                assert!(!json);
            }
            _ => panic!("expected links command"),
        }
    }

    #[test]
    fn links_accepts_inbound() {
        let cli = Cli::try_parse_from([
            "pginf",
            "links",
            "https://example.com",
            "--inbound",
        ])
        .unwrap();
        match cli.command {
            Commands::Links { inbound, .. } => assert!(inbound),
            _ => panic!("expected links command"),
        }
    }

    #[test]
    fn links_accepts_outbound() {
        let cli = Cli::try_parse_from([
            "pginf",
            "links",
            "https://example.com",
            "--outbound",
        ])
        .unwrap();
        match cli.command {
            Commands::Links { outbound, .. } => assert!(outbound),
            _ => panic!("expected links command"),
        }
    }

    #[test]
    fn meta_parses_url() {
        let cli =
            Cli::try_parse_from(["pginf", "meta", "https://example.com"]).unwrap();
        match cli.command {
            Commands::Meta { url, json, .. } => {
                assert_eq!(url, "https://example.com");
                assert!(!json);
            }
            _ => panic!("expected meta command"),
        }
    }

    #[test]
    fn json_cmd_parses_url() {
        let cli =
            Cli::try_parse_from(["pginf", "json", "https://example.com"]).unwrap();
        match cli.command {
            Commands::Json { url, json, .. } => {
                assert_eq!(url, "https://example.com");
                assert!(!json);
            }
            _ => panic!("expected json command"),
        }
    }

    #[test]
    fn text_parses_url() {
        let cli =
            Cli::try_parse_from(["pginf", "text", "https://example.com"]).unwrap();
        match cli.command {
            Commands::Text {
                url, format, json, ..
            } => {
                assert_eq!(url, "https://example.com");
                assert_eq!(format, "text");
                assert!(!json);
            }
            _ => panic!("expected text command"),
        }
    }

    #[test]
    fn text_accepts_markdown_format() {
        let cli = Cli::try_parse_from([
            "pginf",
            "text",
            "https://example.com",
            "--format",
            "markdown",
        ])
        .unwrap();
        match cli.command {
            Commands::Text { format, .. } => assert_eq!(format, "markdown"),
            _ => panic!("expected text command"),
        }
    }

    #[test]
    fn html_parses_with_url_only() {
        let cli =
            Cli::try_parse_from(["pginf", "html", "-u", "https://example.com"])
                .unwrap();
        match cli.command {
            Commands::Html {
                url,
                selector,
                no_cache,
                refresh,
            } => {
                assert_eq!(url, "https://example.com");
                assert!(selector.is_none());
                assert!(!no_cache);
                assert!(!refresh);
            }
            _ => panic!("expected html command"),
        }
    }

    #[test]
    fn html_parses_with_selector() {
        let cli = Cli::try_parse_from([
            "pginf",
            "html",
            "-u",
            "https://example.com",
            "-s",
            "div.article",
        ])
        .unwrap();
        match cli.command {
            Commands::Html { selector, .. } => {
                assert_eq!(selector.as_deref(), Some("div.article"));
            }
            _ => panic!("expected html command"),
        }
    }

    #[test]
    fn install_skills_local_parses() {
        let cli =
            Cli::try_parse_from(["pginf", "install", "skills", "local"]).unwrap();
        match cli.command {
            Commands::Install {
                command: InstallCommand::Skills { target },
            } => {
                assert!(matches!(target, SkillsTarget::Local));
            }
            _ => panic!("expected install skills local"),
        }
    }

    #[test]
    fn install_skills_global_parses() {
        let cli =
            Cli::try_parse_from(["pginf", "install", "skills", "global"]).unwrap();
        match cli.command {
            Commands::Install {
                command: InstallCommand::Skills { target },
            } => {
                assert!(matches!(target, SkillsTarget::Global));
            }
            _ => panic!("expected install skills global"),
        }
    }

    #[test]
    fn help_tool_mentions_fetch_as_first_step() {
        let text = help::render(Some("tool"));
        assert!(text.contains("pginf fetch"));
    }

    #[test]
    fn format_fetch_markdown_contains_status() {
        let resolved = resolve::ResolveOutput {
            fetch_result: client::FetchResult {
                input_url: "https://example.com".to_string(),
                final_url: "https://example.com".to_string(),
                status: 200,
                headers: std::collections::HashMap::new(),
                body: "<html></html>".to_string(),
                duration_ms: 42,
            },
            from_cache: false,
        };
        let out = format_fetch_markdown(&resolved);
        assert!(out.contains("200"));
        assert!(out.contains("42ms"));
        assert!(out.contains("example.com"));
    }

    #[test]
    fn format_fetch_json_valid() {
        let resolved = resolve::ResolveOutput {
            fetch_result: client::FetchResult {
                input_url: "https://example.com".to_string(),
                final_url: "https://example.com".to_string(),
                status: 200,
                headers: std::collections::HashMap::new(),
                body: "<html></html>".to_string(),
                duration_ms: 42,
            },
            from_cache: false,
        };
        let out = format_fetch_json(&resolved);
        let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
        assert_eq!(parsed["status"], 200);
        assert_eq!(parsed["duration_ms"], 42);
    }
}