bibby 0.2.0

The official Rust SDK for Bytebury — typed clients, smart .env initialization, and ergonomic macros for Geo, Images, PDF, Mailer, Uploader, Cron, Forms, Webhooks, Monitors, and Vault.
Documentation
# `bibby` — The Official Rust SDK for Bytebury

[![Crates.io](https://img.shields.io/crates/v/bibby.svg)](https://crates.io/crates/bibby)
[![Docs.rs](https://docs.rs/bibby/badge.svg)](https://docs.rs/bibby)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

`bibby` is the official Rust SDK for [Bytebury](https://bytebury.com) — strongly-typed async clients, smart `.env` initialization, constant-time webhook signature verification, and ergonomic macros for every Bytebury developer tool.

## Supported Products

| Product | Client | Capabilities |
|---|---|---|
| **Geo** | `client.geo()` | IPv4/IPv6 geolocation, SVG maps, random IPs, corrections |
| **Images** | `client.images()` | Resize, crop, transform, vectorize, analyze, favicons, diff, QR codes |
| **PDF** | `client.pdf()` | HTML/CSS (MiniJinja templates) & URL-to-PDF rendering, Uploader saving |
| **Mailer** | `client.mailer()` | Transactional email (with idempotency & attachments) and email validation |
| **Uploader** | `client.uploader()` | Raw binary uploads, signed download URLs, share links, one-time upload links, storage stats |
| **Cron** | `client.cron()` | Scheduled UTC HTTP jobs, manual runs, run history, schedule previews |
| **Forms** | `client.forms()` | Form endpoints, submissions, CSV export |
| **Webhooks** | `client.webhooks()` | Endpoints, secret rotation, event publishing, replay, HMAC-SHA256 signature verification |
| **Monitors** | `client.monitors()` | Uptime monitors, on-demand checks, 90-day status summaries, incidents, heartbeats |
| **Vault** | `client.vault()` | Encrypted project secrets, `.env` import/export, versions, burn-after-reading shares |

## Installation

```sh
cargo add bibby
```

## Quick Start (Smart `.env` Initialization)

Put your Bytebury API key in `.env` (or export it in your environment):

```env
BYTEBURY_API_TOKEN=bb_live_...
```

Then initialize the client with `Bibby::init()`:

```rust
use bibby::prelude::*;

#[tokio::main]
async fn main() -> Result<()> {
    // Loads `.env` (if present) and reads `BYTEBURY_API_TOKEN`.
    // Also honors optional `BYTEBURY_API_URL` for staging/local gateways.
    let client = Bibby::init()?;

    // 1. Bytebury Geo
    let loc = client.geo().lookup("8.8.8.8").await?;
    println!("{} is in {} ({})", loc.ip, loc.country.name, loc.country.code);

    // 2. Bytebury Mailer (with the `email!` macro)
    let mail = email! {
        to: "ada@example.com",
        subject: "Welcome to Bytebury!",
        html: "<h1>Hello!</h1><p>Glad you're here.</p>",
    };
    client.mailer().send_idempotent(&mail, "welcome-ada-1").await?;

    // 3. Bytebury Images (with the `image_ops!` macro)
    let req = bibby::images::TransformRequest::new(
        bibby::images::ImageSource::from_url("https://example.com/photo.jpg"),
    )
    .operations(image_ops![
        resize(width: 800, height: 600, fit: Cover),
        grayscale,
        blur(1.5),
    ])
    .format(bibby::images::ImageFormat::Webp);
    let image = client.images().transform(&req).await?;
    let _webp_bytes = image.decode_bytes()?;

    // 4. Bytebury PDF (with the `pdf!` macro)
    let pdf = client.pdf().render(&pdf! {
        html: "<h1>Invoice #{{ number }}</h1>",
        data: { "number": 42 },
        page_size: A4,
        margin_mm: 15.0,
        file_name: "invoice-42.pdf",
    }).await?;
    let _pdf_bytes = pdf.decode_bytes()?;

    // 5. Bytebury Webhooks (with the `webhook_event!` macro)
    client.webhooks().publish_event(&webhook_event!(
        "order.created",
        { "order_id": 42, "total_cents": 1999 },
        idempotency_key: "order-42"
    )).await?;

    Ok(())
}
```

## Custom Configuration

Use `Bibby::new(...)`, `Bibby::from_env_var(...)`, or `Bibby::builder()` when you need full control:

```rust
use std::time::Duration;
use bibby::Bibby;

let client = Bibby::builder()
    .from_env()
    .timeout(Duration::from_secs(30))
    .user_agent("my-app/1.0")
    .build()?;
```

`Bibby` is cheaply cloneable (`Arc`-backed) and redacts your API key from `Debug` output.

## Macros

| Macro | Purpose |
|---|---|
| `email! { ... }` | Build a `mailer::SendEmailRequest` with single or multiple recipients |
| `image_ops! [ ... ]` | Compose a `Vec<images::Operation>` transformation pipeline |
| `pdf! { ... }` | Build a `pdf::RenderPdfRequest` with inline JSON template `data` |
| `webhook_event!(...)` | Build a `webhooks::PublishEventRequest` with inline JSON payload |
| `headers! { ... }` | Construct a `BTreeMap<String, String>` of custom HTTP headers |
| `vault_ref!(proj, env, key)` | Format `{{vault:proj/env/key}}` header placeholders for Cron, Webhooks & Monitors |

## Verifying Outgoing Webhooks

Bytebury Webhooks signs every delivery with `X-Bytebury-Signature: t=<unix>,v1=<hex>`. Verify incoming requests in constant time using your endpoint's `whsec_...` secret:

```rust
use bibby::webhooks;

fn handle_webhook(secret: &str, sig_header: &str, raw_body: &[u8]) -> bibby::Result<()> {
    webhooks::verify_signature(secret, sig_header, raw_body)?;
    Ok(())
}
```

## Error Handling

All API errors return `bibby::Error::Api { status, message }` parsed directly from Bytebury's `{ "error": "..." }` JSON responses, with ergonomic predicates:

```rust
match client.geo().lookup("127.0.0.1").await {
    Ok(loc) => println!("{}", loc.country.name),
    Err(err) if err.is_not_found() => eprintln!("Private/unallocated IP"),
    Err(err) if err.is_rate_limited() => eprintln!("Rate limit reached"),
    Err(err) => return Err(err),
}
```

## License

MIT — see [LICENSE](LICENSE).