Keyboard shortcuts

Press ← or β†’ to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

url2ref generates formatted citations from URLs by extracting metadata from web pages.

Metadata Sources

  • Open Graph
  • Schema.org
  • HTML Meta Tags
  • DOI Resolution
  • Zotero/Citoid (optional)
  • AI Extraction (optional)

Citation Formats

FormatUse Case
MediaWikiWikipedia editing
BibTeXLaTeX/academic papers
HarvardAcademic writing

Example

url2ref-cli --url "https://www.bbc.com/news/technology-12345678"

Output:

{{cite web
  | title = Example News Article
  | author = John Smith
  | date = 2024-01-15
  | website = BBC News
  | url = https://www.bbc.com/news/technology-12345678
  | access-date = 2024-01-20
}}

Next

See Installation to get started.

Installation

Prerequisites

  • Rust 1.70+ (rustup.rs)
  • libcurl and OpenSSL dev headers (Linux)
  • Node.js 16+ (for web interface)

Quick Start

git clone https://github.com/url2ref/url2ref.git
cd url2ref

# CLI
cargo run --bin url2ref-cli -- --url "https://example.com"

# Web interface
cd url2ref-web/npm && ./build.sh && cd ../..
cargo run --bin url2ref-web

System Dependencies

Ubuntu/Debian:

sudo apt install build-essential libcurl4-openssl-dev libssl-dev pkg-config

Fedora/RHEL:

sudo dnf install gcc libcurl-devel openssl-devel

macOS:

xcode-select --install

Next

Building from Source

Clone

git clone https://github.com/url2ref/url2ref.git
cd url2ref

Build CLI

cargo build --release --bin url2ref-cli

Binary: target/release/url2ref-cli

Install globally:

cargo install --path url2ref-cli

Build Web Interface

cd url2ref-web/npm
npm install
./build.sh
cd ../..
cargo build --release --bin url2ref-web

Run:

cargo run --bin url2ref-web
# Server at http://localhost:8000

Build Library Only

cargo build -p url2ref

Or as a dependency:

[dependencies]
url2ref = { git = "https://github.com/url2ref/url2ref" }

Tests & Docs

cargo test
cargo doc --no-deps --open
cargo build --target x86_64-unknown-linux-musl --release

Troubleshooting

libcurl not found

Linux:

sudo apt install libcurl4-openssl-dev  # Debian/Ubuntu
sudo dnf install libcurl-devel          # Fedora

macOS:

brew install curl
export PKG_CONFIG_PATH="/usr/local/opt/curl/lib/pkgconfig"

OpenSSL errors

Linux:

sudo apt install libssl-dev pkg-config  # Debian/Ubuntu

macOS:

brew install openssl
export OPENSSL_DIR=$(brew --prefix openssl)

SCSS compilation fails

Ensure you have the latest npm packages:

cd url2ref-web/npm
rm -rf node_modules
npm install
./build.sh

Next Steps

Docker

Quick Start

git clone https://github.com/url2ref/url2ref.git
cd url2ref
docker-compose up

Web interface at http://localhost:8000.

Manual Build

docker build -t url2ref .
docker run -p 8000:8000 url2ref

CLI via Docker

docker run --rm url2ref url2ref-cli --url "https://example.com"
docker run --rm url2ref url2ref-cli --url "https://example.com" --format bibtex

Environment Variables

docker run -p 8000:8000 \
  -e DEEPL_API_KEY="your-key" \
  -e ROCKET_ADDRESS="0.0.0.0" \
  url2ref

Docker Compose with API Keys

# docker-compose.override.yml
services:
  url2ref-web:
    environment:
      - DEEPL_API_KEY=your-key
      - OPENAI_API_KEY=your-key

CLI

Usage

url2ref-cli [OPTIONS] --url <URL>

Options:
  -u, --url <URL>                    URL to cite
  -f, --format <FORMAT>              wiki, bibtex, harvard [default: wiki]
  -m, --metadata-priority <TYPE>     opengraph, schemaorg, htmlmeta, doi, zotero
  -t, --target-lang <LANG>           Translate title (ISO 639)
      --translation-provider <PROV>  deepl, google [default: deepl]
      --ai-extraction                Enable AI extraction
      --ai-provider <PROVIDER>       openai, anthropic [default: openai]
  -h, --help                         Print help

Examples

# MediaWiki (default)
url2ref-cli -u "https://www.bbc.com/news/technology-12345"

# BibTeX
url2ref-cli -u "https://arxiv.org/abs/2301.00001" -f bibtex

# With translation
url2ref-cli -u "https://www.lemonde.fr/article" -t EN

# With AI extraction
url2ref-cli -u "https://example.com" --ai-extraction

In This Section

Basic Usage

Generate a Citation

url2ref-cli --url "https://www.example.com/article"
# or
url2ref-cli -u "https://www.example.com/article"

Choose Format

url2ref-cli -u "https://example.com" -f wiki    # MediaWiki (default)
url2ref-cli -u "https://example.com" -f bibtex  # BibTeX
url2ref-cli -u "https://example.com" -f harvard # Harvard

Copy to Clipboard

Linux:

url2ref-cli -u "https://example.com" | xclip -selection clipboard

macOS:

url2ref-cli -u "https://example.com" | pbcopy

Shell Alias

# ~/.bashrc or ~/.zshrc
alias cite='url2ref-cli -f wiki -u'

Usage:

cite "https://example.com"

Citation Formats

MediaWiki (wiki)

url2ref-cli -u "https://example.com" -f wiki
{{cite web
  | title = Article Title
  | author = Jane Smith
  | date = 2024-01-15
  | website = Example News
  | url = https://example.com/article
  | access-date = 2024-01-20
}}

Fields: title, trans-title, author, date, website, publisher, url, archive-url, archive-date, access-date, language

BibTeX (bibtex)

url2ref-cli -u "https://example.com" -f bibtex
@misc{example2024,
  author = {Smith, Jane},
  title = {Article Title},
  year = {2024},
  month = {jan},
  url = {https://example.com/article},
  urldate = {2024-01-20}
}

Harvard (harvard)

url2ref-cli -u "https://example.com" -f harvard
Smith, J. (2024) 'Article Title', Example News. 
Available at: https://example.com/article (Accessed: 20 January 2024).

Variations:

  • Without author: 'Title' (2024) Website. Available at: URL (Accessed: Date).
  • Without date: Author (n.d.) 'Title', Website. Available at: URL (Accessed: Date).

Metadata Priority

Sources

SourceFlagBest For
Open GraphopengraphNews, blogs, social content
Schema.orgschemaorgNews orgs with structured data
HTML MetahtmlmetaOlder/simple websites
DOIdoiAcademic papers
ZoterozoteroAcademic databases, complex pages

Usage

url2ref-cli -u "https://example.com" -m schemaorg
url2ref-cli -u "https://doi.org/10.1038/nature12373" -m doi
url2ref-cli -u "https://www.jstor.org/stable/12345" -m zotero

Recommendations

  • News articles: Default priority works well (Open Graph first)
  • Academic papers with DOI: Use -m doi
  • JSTOR/PubMed: Use -m zotero
  • Sites with rich snippets: Try -m schemaorg

Translation

Translate article titles using DeepL or Google Translate.

Usage

# Translate to English (auto-detect source)
url2ref-cli -u "https://www.lemonde.fr/article" --target-lang EN

# Specify source language
url2ref-cli -u "https://www.spiegel.de/article" --source-lang DE --target-lang EN

# Use Google instead of DeepL
url2ref-cli -u "https://example.fr" --target-lang EN --translation-provider google

API Keys

export DEEPL_API_KEY="your-key"        # deepl.com/pro-api
export GOOGLE_TRANSLATE_API_KEY="your-key"  # console.cloud.google.com

Output

MediaWiki includes trans-title:

{{cite web
  | title = L'intelligence artificielle transforme l'industrie
  | trans-title = Artificial intelligence transforms industry
  | language = fr
  ...
}}

Language Codes

Use ISO 639-1: EN, DE, FR, ES, IT, JA, ZH, RU, PT, NL

DeepL variants: EN-US, EN-GB, PT-BR, PT-PT

Shell Configuration

Add to your shell profile for convenience:

# ~/.bashrc or ~/.zshrc
export DEEPL_API_KEY="your-key"

# Alias for common translation tasks
alias cite-translate='url2ref-cli --target-lang EN'

Next Steps

AI Extraction

Use AI to extract metadata when traditional parsing fails.

Usage

url2ref-cli -u "https://example.com" --ai-extraction

# Specify provider and model
url2ref-cli -u "https://example.com" \
  --ai-extraction \
  --ai-provider openai \
  --ai-model gpt-4o-mini

API Keys

export OPENAI_API_KEY="sk-..."
export ANTHROPIC_API_KEY="sk-ant-..."

Providers & Models

ProviderModels
OpenAIgpt-4o, gpt-4o-mini
Anthropicclaude-3-haiku-20240307, claude-3-sonnet-20240229

Recommended: gpt-4o-mini or claude-3-haiku for cost-effective extraction.

When to Use

  • Pages without metadata markup
  • Old websites or blogs
  • When traditional extraction returns incomplete data

Combined with Translation

url2ref-cli -u "https://foreign-site.com/article" \
  --ai-extraction \
  --target-lang EN

Poor Extraction Quality

  • Try a more capable model (gpt-4o instead of gpt-4o-mini)
  • The page content might be JavaScript-rendered (AI can only see the initial HTML)

Slow Response

  • AI extraction adds 1-5 seconds depending on the model
  • Use faster models for better performance

Shell Configuration

# ~/.bashrc or ~/.zshrc
export OPENAI_API_KEY="your-key"
export ANTHROPIC_API_KEY="your-key"

# Alias for AI-assisted citations
alias cite-ai='url2ref-cli --ai-extraction --ai-provider openai --ai-model gpt-4o-mini'

Security Notes

  • API keys are read from environment variables only
  • Keys are never logged or stored
  • In the web interface, AI keys can be entered per-request (not stored server-side)

Next Steps

Web Interface

Browser-based citation generation at http://localhost:8000.

Start

cargo run --bin url2ref-web

Features

  • Multiple formats (Wiki, BibTeX, Harvard)
  • Compare metadata from all sources
  • One-click copy to clipboard
  • Title translation (DeepL/Google)
  • AI extraction (OpenAI/Anthropic)
  • Wayback Machine archive integration

In This Section

Getting Started

Setup

# Build frontend
cd url2ref-web/npm
npm install
./build.sh
cd ../..

# Start server
cargo run --bin url2ref-web

Open http://localhost:8000.

Usage

  1. Enter a URL
  2. Click β€œGenerate” (or press Enter)
  3. Switch formats using Wiki/BibTeX/Harvard tabs
  4. Click πŸ“‹ to copy

Options

Expand the Options panel for:

  • Translation: Select target language, requires DEEPL_API_KEY or GOOGLE_TRANSLATE_API_KEY
  • Zotero/Citoid: Use Wikipedia’s citation service
  • AI Extraction: Fill missing fields (requires OPENAI_API_KEY or ANTHROPIC_API_KEY)

Multi-Source View

Click β€œShow sources” to compare metadata from OpenGraph, Schema.org, HTML Meta, etc. Click a value to use it.

Archive Integration

Automatically checks Wayback Machine. Click β€œCreate archive” to save the page.

Features

Citation Formats

Switch between Wiki, BibTeX, and Harvard using the format tabs. Click πŸ“‹ to copy.

Metadata Source Comparison

Click β€œShow all sources” to see values from OpenGraph, Schema.org, HTML Meta, etc. Click any value to use it in the citation.

Default priority: OpenGraph β†’ Schema.org β†’ HTML Meta β†’ DOI β†’ Zotero β†’ AI

Translation

Enable in Options panel. Requires DEEPL_API_KEY or GOOGLE_TRANSLATE_API_KEY. Output includes both original and translated title.

Zotero/Citoid

Enable in Options panel. Uses Wikipedia’s Citoid API with specialized extractors for academic databases and complex pages.

AI Extraction

Enable in Options panel. Enter API key (OpenAI or Anthropic). Key is used client-side and not stored on server.

Archive Integration

Automatically checks Wayback Machine for existing archives. Shows archive URL/date or offers to create one.

Configuration

Config File

url2ref-web/config.toml:

[default]
address = "127.0.0.1"
port = 8000

[release]
address = "0.0.0.0"
log_level = "critical"

Environment Variables

VariableDescriptionDefault
ROCKET_ADDRESSBind address127.0.0.1
ROCKET_PORTPort8000
ROCKET_LOG_LEVELoff, critical, normal, debugnormal
DEEPL_API_KEYDeepL translationβ€”
GOOGLE_TRANSLATE_API_KEYGoogle translationβ€”
export ROCKET_ADDRESS="0.0.0.0"
export ROCKET_PORT="3000"
cargo run --bin url2ref-web

TLS

[default.tls]
certs = "/path/to/cert.pem"
key = "/path/to/key.pem"

Or use a reverse proxy (nginx, Caddy) in production.

For production deployments, consider adding rate limiting via a reverse proxy:

# nginx rate limiting
limit_req_zone $binary_remote_addr zone=url2ref:10m rate=10r/s;

server {
    location /api/ {
        limit_req zone=url2ref burst=20 nodelay;
        proxy_pass http://127.0.0.1:8000;
    }
}

Docker Configuration

When running in Docker, use environment variables:

# docker-compose.yml
services:
  url2ref-web:
    build: .
    ports:
      - "8000:8000"
    environment:
      - ROCKET_ADDRESS=0.0.0.0
      - ROCKET_PORT=8000
      - ROCKET_LOG_LEVEL=normal
      - DEEPL_API_KEY=${DEEPL_API_KEY}

Health Checks

The server responds to requests at the root path. For health checks:

curl -f http://localhost:8000/ || exit 1

Or add a dedicated health endpoint (requires code modification).

Monitoring

Logging

Logs are written to stderr. Redirect for persistence:

cargo run --bin url2ref-web 2>&1 | tee -a url2ref.log

Log Levels

LevelDescription
offNo logging
criticalOnly critical errors
normalStandard logging
debugVerbose debugging

Production Checklist

Before deploying to production:

  • Set ROCKET_PROFILE=release
  • Bind to 0.0.0.0 if using containers
  • Configure TLS (directly or via reverse proxy)
  • Set appropriate log level
  • Configure API keys securely (not in code)
  • Set up rate limiting
  • Enable static file caching
  • Configure health checks
  • Set up log rotation

Next Steps

Metadata Sources

Overview

SourceBest For
Open GraphNews, blogs, social content
Schema.orgNews orgs with structured data
HTML MetaOlder/simple websites
DOIAcademic papers
Zotero/CitoidAcademic databases, complex pages
AIFallback for missing data

Open Graph

Extracts og:title, og:site_name, article:author, article:published_time from <meta property="og:*"> tags.

Schema.org

Parses JSON-LD (<script type="application/ld+json">) for Article, NewsArticle, ScholarlyArticle types. Often has multiple authors and publisher info.

HTML Meta

Extracts <title> and <meta name="author">. Universal but limited.

DOI

Resolves DOIs via CrossRef/DataCite. Authoritative metadata for academic papers including all authors, journal, and publication details.

Zotero/Citoid

Uses Wikipedia’s Citoid API with specialized translators for JSTOR, PubMed, Google Scholar, news sites, and hundreds more.

AI Extraction

Sends page content to OpenAI or Anthropic to extract fields when traditional parsing fails. Requires API key.

Default Priority

  1. Open Graph
  2. Schema.org
  3. HTML Meta
  4. DOI (if available)
  5. Zotero (if enabled)
  6. AI (if enabled)

Citation Formats Reference

MediaWiki (wiki)

{{cite web
  | url = https://example.com/article
  | title = Article Title
  | trans-title = Translated Title
  | author = Jane Smith
  | date = 2024-01-15
  | website = Example News
  | publisher = Example Media Inc.
  | language = en
  | access-date = 2024-01-20
  | archive-url = https://web.archive.org/...
  | archive-date = 2024-01-15
}}

Multiple authors: author1, author2, author3

BibTeX (bibtex)

@misc{example2024,
  author = {Smith, Jane},
  title = {Article Title},
  year = {2024},
  month = {jan},
  url = {https://example.com/article},
  urldate = {2024-01-20}
}

Entry types: @misc (web pages), @article (journals)

Citation key format: {domain}{year}

Special characters (& % $ # _ { } ~ ^) are auto-escaped.

Harvard (harvard)

Smith, J. (2024) 'Article Title', Example News. 
Available at: https://example.com/article (Accessed: 20 January 2024).

Variations:

  • No author: 'Title' (2024) Website. Available at: URL (Accessed: Date).
  • No date: Author (n.d.) 'Title', Website. Available at: URL (Accessed: Date).

Without date:

Smith, J. (n.d.) 'Understanding Modern Web Development', Tech Blog. 
Available at: https://example.com/article (Accessed: 20 January 2024).

Without author or date:

'Understanding Modern Web Development' (n.d.) Tech Blog. 
Available at: https://example.com/article (Accessed: 20 January 2024).

Author Name Formatting

Full NameHarvard Format
Jane SmithSmith, J.
John A. DoeDoe, J.A.
Organization NameOrganization Name

Multiple Authors

Two authors:

Smith, J. and Doe, J. (2024) 'Title'...

Three or more:

Smith, J., Doe, J. and Johnson, A. (2024) 'Title'...

Many authors (in-text):

Smith, J. et al. (2024) 'Title'...

Date Formatting

FormatAccess Date Display
Day Month Year20 January 2024

Example Output

Smith, J. (2024) 'Understanding Modern Web Development', Tech Blog. 
Available at: https://www.example.com/article (Accessed: 20 January 2024).

Format Comparison

Same Source

URL: https://www.bbc.com/news/technology-12345

MediaWiki:

{{cite web
  | url = https://www.bbc.com/news/technology-12345
  | title = AI Revolution: What's Next?
  | author = Tech Correspondent
  | date = 2024-01-15
  | website = BBC News
  | access-date = 2024-01-20
}}

BibTeX:

@misc{bbc2024,
  author = {Tech Correspondent},
  title = {AI Revolution: What's Next?},
  year = {2024},
  month = {jan},
  howpublished = {BBC News},
  url = {https://www.bbc.com/news/technology-12345},
  urldate = {2024-01-20}
}

Harvard:

Tech Correspondent (2024) 'AI Revolution: What's Next?', BBC News. 
Available at: https://www.bbc.com/news/technology-12345 (Accessed: 20 January 2024).

Field Availability

FieldWikiBibTeXHarvard
URLβœ“βœ“βœ“
Titleβœ“βœ“βœ“
Trans-Titleβœ“notenote
Authorβœ“βœ“βœ“
Dateβœ“βœ“βœ“
Websiteβœ“howpublishedβœ“
Publisherβœ“βœ“βœ“
Languageβœ“βœ“β€”
Access Dateβœ“βœ“βœ“
Archive URLβœ“noteβ€”
Archive Dateβœ“noteβ€”
Journalβ€”βœ“βœ“
Volumeβ€”βœ“βœ“
DOIβ€”βœ“βœ“

Next Steps

API

Rust library for programmatic citation generation.

Installation

[dependencies]
url2ref = { git = "https://github.com/url2ref/url2ref" }

Quick Start

#![allow(unused)]
fn main() {
use url2ref::{generate, GenerationOptions};

let options = GenerationOptions::default();
let reference = generate("https://example.com/article", &options)?;

println!("{}", reference.wiki());
println!("{}", reference.bibtex());
println!("{}", reference.harvard());
}

Configuration

#![allow(unused)]
fn main() {
use url2ref::{GenerationOptions, GenerationOptionsBuilder};
use url2ref::generator::{TranslationOptions, TranslationProvider, ArchiveOptions, AiExtractionOptions};

let options = GenerationOptions {
    attribute_config: AttributeConfig::default(),
    translation_options: TranslationOptions {
        provider: TranslationProvider::DeepL,
        target: Some("EN".to_string()),
        deepl_key: std::env::var("DEEPL_API_KEY").ok(),
        ..Default::default()
    },
    archive_options: ArchiveOptions {
        include_archived: true,
        perform_archival: false,
    },
    ai_options: AiExtractionOptions::default(),
};
}

Functions

FunctionDescription
generate(url, options)Generate reference from URL
generate_from_file(path, options)Generate from local HTML
parse_all_metadata(url)Extract all metadata without generating
fetch_parse_info(url, options)Fetch and parse for reuse

Types

TypeDescription
ReferenceEnum with NewsArticle, ScholarlyArticle, GenericReference
AttributeEnum for Title, Authors, Date, Url, etc.
GenerationOptionsConfiguration for generation

Error Handling

#![allow(unused)]
fn main() {
match generate(url, &options) {
    Ok(reference) => println!("{}", reference.wiki()),
    Err(ReferenceGenerationError::CurlError(e)) => eprintln!("Network: {}", e),
    Err(ReferenceGenerationError::ParseFailure) => eprintln!("No metadata found"),
    Err(e) => eprintln!("Error: {}", e),
}
}

Generate Docs

cargo doc --no-deps --open

Environment Variables

Translation

VariableDescription
DEEPL_API_KEYDeepL API key
GOOGLE_TRANSLATE_API_KEYGoogle Cloud Translation API key

AI Extraction

VariableDescription
OPENAI_API_KEYOpenAI API key
ANTHROPIC_API_KEYAnthropic API key

Web Server

VariableDescriptionDefault
ROCKET_ADDRESSIP address to bind127.0.0.1
ROCKET_PORTPort to listen on8000
ROCKET_WORKERSWorker threadsCPU count
ROCKET_LOG_LEVELoff, critical, normal, debugnormal
ROCKET_TLS_CERTSPath to TLS certificateβ€”
ROCKET_TLS_KEYPath to TLS private keyβ€”

Examples

With translation:

export DEEPL_API_KEY="your-key"
url2ref-cli --url "https://example.com" --target-lang EN

With AI extraction:

export OPENAI_API_KEY="your-key"
url2ref-cli --url "https://example.com" --ai-extraction

Web server on all interfaces:

export ROCKET_ADDRESS="0.0.0.0"
export ROCKET_PORT="3000"

Docker:

docker run -e DEEPL_API_KEY="your-key" -e ROCKET_ADDRESS="0.0.0.0" url2ref

Contributing

Setup

git clone https://github.com/YOUR_USERNAME/url2ref.git
cd url2ref
cargo build
cargo test

For web interface:

cd url2ref-web/npm && npm install && ./build.sh

Workflow

  1. Create branch: git checkout -b feature/your-feature
  2. Make changes
  3. Run cargo fmt and cargo clippy
  4. Run cargo test
  5. Commit with clear message
  6. Open PR

Commit Format

type(scope): description

feat(parser): add Dublin Core support
fix(cli): handle URLs with special characters
docs: update installation guide

Project Structure

url2ref/           # Core library
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ lib.rs          # Public API
β”‚   β”œβ”€β”€ generator.rs    # Reference generation
β”‚   β”œβ”€β”€ parser.rs       # Metadata parsing
β”‚   β”œβ”€β”€ opengraph.rs    # Open Graph parser
β”‚   β”œβ”€β”€ schema_org.rs   # Schema.org parser
β”‚   β”œβ”€β”€ doi.rs          # DOI resolution
β”‚   β”œβ”€β”€ zotero.rs       # Zotero/Citoid
β”‚   β”œβ”€β”€ ai_extractor.rs # AI extraction
β”‚   └── citation.rs     # Citation formatters
url2ref-cli/       # CLI application
url2ref-web/       # Web interface
docs/              # This documentation

Adding a Metadata Source

  1. Create parser in url2ref/src/
  2. Add to MetadataType enum
  3. Add tests
  4. Update docs

Adding a Citation Format

  1. Add formatter in citation.rs
  2. Add method to Reference
  3. Update CLI and web interface
  4. Add tests

Architecture

Overview

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              url2ref-cli / url2ref-web              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                          β”‚
                          β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                 url2ref (Core Library)              β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  Generator β†’ Parser β†’ Citation Formatters           β”‚
β”‚       β”‚         β”‚                                   β”‚
β”‚       β–Ό         β–Ό                                   β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚ OpenGraphβ”‚Schema.orgβ”‚HTML Metaβ”‚DOIβ”‚Zoteroβ”‚AIβ”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Data Flow

URL β†’ HTTP Fetch β†’ HTML Parse β†’ Metadata Extract β†’ Merge β†’ Reference β†’ Citation

Core Modules

ModulePurpose
generator.rsOrchestrates generation
parser.rsCoordinates extraction
attribute.rsMetadata types
reference.rsReference enum
citation.rsFormat builders

Parsers

Each source has a dedicated parser:

  • opengraph.rs - <meta property="og:*">
  • schema_org.rs - JSON-LD and microdata
  • html_meta.rs - <title>, <meta name="*">
  • doi.rs - CrossRef/DataCite resolution
  • zotero.rs - Wikipedia Citoid API
  • ai_extractor.rs - LLM extraction

Attribute System

#![allow(unused)]
fn main() {
// Per-source collection
type AttributeCollection = HashMap<AttributeType, Attribute>;

// Multi-source for comparison
type MultiSourceAttributeCollection = 
    HashMap<AttributeType, HashMap<MetadataType, Attribute>>;
}

Priority determines which source’s value is used when merging.

Citation Builders

#![allow(unused)]
fn main() {
trait CitationBuilder {
    fn try_add(self, attr: &Option<Attribute>) -> Self;
    fn build(self) -> String;
}
}

Implementations: WikiCitation, BibTeXCitation, HarvardCitation

Web Interface

Browser β†’ Rocket Route β†’ Handler β†’ url2ref β†’ JSON β†’ Browser
EndpointPurpose
GET /Home page
POST /generateGenerate citation
POST /archiveCreate archive
bibtex: Option,
wiki: Option,
harvard: Option,
fields: Option,
multi_source: Option,
error: Option,
}

## CLI Architecture

### Argument Parsing

Uses `clap` derive macros:

```rust
#[derive(Parser)]
struct CommandLineArgs {
    #[clap(short, long)]
    url: String,
    
    #[clap(short, long, value_enum)]
    format: CitationFormat,
    // ...
}

Flow

Args β†’ Parse β†’ Build Options β†’ generate() β†’ Format Output β†’ Print

Error Handling

Error Types

#![allow(unused)]
fn main() {
pub enum ReferenceGenerationError {
    CurlError(CurlError),
    ParseFailure,
    ParseSkip,
    HTMLParseError(std::io::Error),
    DeepLError(DeepLError),
    TranslationError,
    DoiError(DoiError),
    ArchiveError(ArchiveError),
    AiExtractionError(AiExtractionError),
}
}

Error Propagation

Uses thiserror for error definitions and ? operator for propagation.

Dependencies

Key Crates

CratePurpose
scraperHTML parsing
serde_jsonJSON handling
curlHTTP requests
chronoDate handling
clapCLI argument parsing
rocketWeb framework
teraTemplating
deepl-apiTranslation

Performance Considerations

HTTP Caching

ParseInfo allows caching fetched HTML:

#![allow(unused)]
fn main() {
// Fetch once
let parse_info = fetch_parse_info(url, None)?;

// Reuse multiple times
let reference = generate_from_parse_info(&parse_info, &opts)?;
let metadata = parse_all_metadata_from_parse_info(&parse_info);
}

Parser Initialization

Parsers are only initialized for configured sources:

#![allow(unused)]
fn main() {
let parsers = options
    .attribute_config
    .parsers_used();  // Only active parsers
}

Extension Points

Adding a Metadata Source

  1. Create parser module implementing extraction
  2. Add variant to MetadataType
  3. Update parser.rs initialization
  4. Add to priority options

Adding a Citation Format

  1. Implement CitationBuilder trait
  2. Add method to Reference enum
  3. Update CLI and web interfaces

Adding an Attribute

  1. Add to AttributeType enum
  2. Add to Attribute enum
  3. Update parsers to extract it
  4. Update citation formatters

Testing Strategy

Unit Tests

Test individual parsers with known HTML:

#![allow(unused)]
fn main() {
#[test]
fn test_opengraph_title() {
    let html = r#"<meta property="og:title" content="Test">"#;
    // ...
}
}

Integration Tests

Test full generation with real/mock URLs:

#![allow(unused)]
fn main() {
#[test]
fn test_full_generation() {
    let reference = generate("file://test.html", &opts)?;
    assert!(reference.wiki().contains("title"));
}
}

Test Data

Located in url2ref/tests/data/ - HTML fixtures for various scenarios.