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
| Format | Use Case |
|---|---|
| MediaWiki | Wikipedia editing |
| BibTeX | LaTeX/academic papers |
| Harvard | Academic 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
- From Source - Detailed build instructions
- Docker - Container deployment
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
- CLI Usage - Learn to use the command-line tool
- Web Interface - Set up the web interface
- API Documentation - Library API reference
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
| Source | Flag | Best For |
|---|---|---|
| Open Graph | opengraph | News, blogs, social content |
| Schema.org | schemaorg | News orgs with structured data |
| HTML Meta | htmlmeta | Older/simple websites |
| DOI | doi | Academic papers |
| Zotero | zotero | Academic 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 missing metadata
- Environment Variables - All configuration options
- Web Interface - Translate via the browser interface
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
| Provider | Models |
|---|---|
| OpenAI | gpt-4o, gpt-4o-mini |
| Anthropic | claude-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-4oinstead ofgpt-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
- Environment Variables - Complete configuration reference
- Web Interface - Use AI extraction in the browser
- API Documentation - Programmatic access
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
- Enter a URL
- Click βGenerateβ (or press Enter)
- Switch formats using Wiki/BibTeX/Harvard tabs
- Click π to copy
Options
Expand the Options panel for:
- Translation: Select target language, requires
DEEPL_API_KEYorGOOGLE_TRANSLATE_API_KEY - Zotero/Citoid: Use Wikipediaβs citation service
- AI Extraction: Fill missing fields (requires
OPENAI_API_KEYorANTHROPIC_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
| Variable | Description | Default |
|---|---|---|
ROCKET_ADDRESS | Bind address | 127.0.0.1 |
ROCKET_PORT | Port | 8000 |
ROCKET_LOG_LEVEL | off, critical, normal, debug | normal |
DEEPL_API_KEY | DeepL translation | β |
GOOGLE_TRANSLATE_API_KEY | Google 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
| Level | Description |
|---|---|
off | No logging |
critical | Only critical errors |
normal | Standard logging |
debug | Verbose debugging |
Production Checklist
Before deploying to production:
- Set
ROCKET_PROFILE=release - Bind to
0.0.0.0if 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
- Docker Deployment - Container setup
- Environment Variables - Complete reference
- CLI Alternative - Command-line interface
Metadata Sources
Overview
| Source | Best For |
|---|---|
| Open Graph | News, blogs, social content |
| Schema.org | News orgs with structured data |
| HTML Meta | Older/simple websites |
| DOI | Academic papers |
| Zotero/Citoid | Academic databases, complex pages |
| AI | Fallback 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
- Open Graph
- Schema.org
- HTML Meta
- DOI (if available)
- Zotero (if enabled)
- 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 Name | Harvard Format |
|---|---|
| Jane Smith | Smith, J. |
| John A. Doe | Doe, J.A. |
| Organization Name | Organization 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
| Format | Access Date Display |
|---|---|
| Day Month Year | 20 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
| Field | Wiki | BibTeX | Harvard |
|---|---|---|---|
| URL | β | β | β |
| Title | β | β | β |
| Trans-Title | β | note | note |
| Author | β | β | β |
| Date | β | β | β |
| Website | β | howpublished | β |
| Publisher | β | β | β |
| Language | β | β | β |
| Access Date | β | β | β |
| Archive URL | β | note | β |
| Archive Date | β | note | β |
| Journal | β | β | β |
| Volume | β | β | β |
| DOI | β | β | β |
Next Steps
- API Documentation - Programmatic access
- Environment Variables - Configuration
- CLI Citation Formats - Usage guide
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
| Function | Description |
|---|---|
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
| Type | Description |
|---|---|
Reference | Enum with NewsArticle, ScholarlyArticle, GenericReference |
Attribute | Enum for Title, Authors, Date, Url, etc. |
GenerationOptions | Configuration 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
| Variable | Description |
|---|---|
DEEPL_API_KEY | DeepL API key |
GOOGLE_TRANSLATE_API_KEY | Google Cloud Translation API key |
AI Extraction
Web Server
| Variable | Description | Default |
|---|---|---|
ROCKET_ADDRESS | IP address to bind | 127.0.0.1 |
ROCKET_PORT | Port to listen on | 8000 |
ROCKET_WORKERS | Worker threads | CPU count |
ROCKET_LOG_LEVEL | off, critical, normal, debug | normal |
ROCKET_TLS_CERTS | Path to TLS certificate | β |
ROCKET_TLS_KEY | Path 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
- Create branch:
git checkout -b feature/your-feature - Make changes
- Run
cargo fmtandcargo clippy - Run
cargo test - Commit with clear message
- 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
- Create parser in
url2ref/src/ - Add to
MetadataTypeenum - Add tests
- Update docs
Adding a Citation Format
- Add formatter in
citation.rs - Add method to
Reference - Update CLI and web interface
- 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
| Module | Purpose |
|---|---|
generator.rs | Orchestrates generation |
parser.rs | Coordinates extraction |
attribute.rs | Metadata types |
reference.rs | Reference enum |
citation.rs | Format builders |
Parsers
Each source has a dedicated parser:
opengraph.rs-<meta property="og:*">schema_org.rs- JSON-LD and microdatahtml_meta.rs-<title>,<meta name="*">doi.rs- CrossRef/DataCite resolutionzotero.rs- Wikipedia Citoid APIai_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
| Endpoint | Purpose |
|---|---|
GET / | Home page |
POST /generate | Generate citation |
POST /archive | Create 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
| Crate | Purpose |
|---|---|
scraper | HTML parsing |
serde_json | JSON handling |
curl | HTTP requests |
chrono | Date handling |
clap | CLI argument parsing |
rocket | Web framework |
tera | Templating |
deepl-api | Translation |
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
- Create parser module implementing extraction
- Add variant to
MetadataType - Update
parser.rsinitialization - Add to priority options
Adding a Citation Format
- Implement
CitationBuildertrait - Add method to
Referenceenum - Update CLI and web interfaces
Adding an Attribute
- Add to
AttributeTypeenum - Add to
Attributeenum - Update parsers to extract it
- 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.