diff --git a/.github/workflows/update-ytdlp.yml b/.github/workflows/update-ytdlp.yml index 3b9a921..624e566 100644 --- a/.github/workflows/update-ytdlp.yml +++ b/.github/workflows/update-ytdlp.yml @@ -13,39 +13,126 @@ jobs: pull-requests: write steps: - - uses: actions/checkout@v4 + - name: Check out repository + uses: actions/checkout@v4 - - uses: DeterminateSystems/nix-installer-action@main + - name: Install Nix + uses: DeterminateSystems/nix-installer-action@main - - uses: DeterminateSystems/magic-nix-cache-action@main + - name: Enable Nix cache + uses: DeterminateSystems/magic-nix-cache-action@main - - name: Get current yt-dlp version - id: before + - name: Read currently pinned yt-dlp version + id: current run: | - rev=$(jq -r '.nodes.nixpkgs.locked.rev' flake.lock) - version=$(nix eval --raw "github:nixos/nixpkgs/${rev}#yt-dlp.version") - echo "version=${version}" >> "$GITHUB_OUTPUT" + set -euo pipefail + current=$(sed -n '/ytDlp = pkgs.stdenv.mkDerivation/,/^ };$/{ s/^ *version = "\([^"]*\)";/\1/p; }' flake.nix | head -1) + if [ -z "$current" ]; then + echo "::error::Could not read the pinned yt-dlp version from flake.nix. Did the ytDlp derivation move or get renamed?" + exit 1 + fi + echo "Currently pinned yt-dlp: $current" + echo "version=${current}" >> "$GITHUB_OUTPUT" - - name: Update nixpkgs - run: nix flake update nixpkgs - - - name: Get new yt-dlp version - id: after + - name: Query latest yt-dlp release + id: latest + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | - rev=$(jq -r '.nodes.nixpkgs.locked.rev' flake.lock) - version=$(nix eval --raw "github:nixos/nixpkgs/${rev}#yt-dlp.version") - echo "version=${version}" >> "$GITHUB_OUTPUT" + set -euo pipefail + latest=$(curl -sSL \ + -H "Authorization: Bearer $GITHUB_TOKEN" \ + -H "Accept: application/vnd.github+json" \ + https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest | jq -r .tag_name) + if [ -z "$latest" ] || [ "$latest" = "null" ]; then + echo "::error::Could not determine the latest yt-dlp release tag from the GitHub API." + exit 1 + fi + echo "Latest yt-dlp release: $latest" + echo "version=${latest}" >> "$GITHUB_OUTPUT" - - name: Open PR if yt-dlp was updated - if: steps.before.outputs.version != steps.after.outputs.version + - name: Decide whether an update is needed + id: check + env: + CURRENT: ${{ steps.current.outputs.version }} + LATEST: ${{ steps.latest.outputs.version }} + run: | + set -euo pipefail + if [ "$CURRENT" = "$LATEST" ]; then + echo "Already at $CURRENT" + echo "changed=false" >> "$GITHUB_OUTPUT" + else + echo "Update available: $CURRENT -> $LATEST" + echo "changed=true" >> "$GITHUB_OUTPUT" + fi + + - name: Compute SRI hash of the new release + id: hash + if: steps.check.outputs.changed == 'true' + env: + LATEST: ${{ steps.latest.outputs.version }} + run: | + set -euo pipefail + curl -sSL --fail \ + "https://github.com/yt-dlp/yt-dlp/releases/download/${LATEST}/yt-dlp" \ + -o /tmp/yt-dlp + hash=$(nix hash file --sri --type sha256 /tmp/yt-dlp) + case "$hash" in + sha256-*) ;; + *) + echo "::error::Computed hash '${hash}' is not an SRI sha256 hash." + exit 1 + ;; + esac + echo "SRI hash: $hash" + echo "hash=${hash}" >> "$GITHUB_OUTPUT" + + - name: Rewrite the yt-dlp pin in flake.nix + if: steps.check.outputs.changed == 'true' + env: + CURRENT: ${{ steps.current.outputs.version }} + LATEST: ${{ steps.latest.outputs.version }} + HASH: ${{ steps.hash.outputs.hash }} + run: | + set -euo pipefail + sed -i \ + -e "/ytDlp = pkgs.stdenv.mkDerivation/,/^ };\$/{ s|^\( *version = \"\)[^\"]*\(\";\)|\1${LATEST}\2|; }" \ + -e "/ytDlp = pkgs.stdenv.mkDerivation/,/^ };\$/{ s|\(url = \"https://github.com/yt-dlp/yt-dlp/releases/download/\)[^/]*\(/yt-dlp\";\)|\1${LATEST}\2|; }" \ + -e "/ytDlp = pkgs.stdenv.mkDerivation/,/^ };\$/{ s|^\( *hash = \"\)sha256-[^\"]*\(\";\)|\1${HASH}\2|; }" \ + flake.nix + + echo "--- git diff --stat ---" + git diff --stat flake.nix + + changed_files=$(git diff --name-only) + if [ "$changed_files" != "flake.nix" ]; then + echo "::error::Expected only flake.nix to change, got: ${changed_files}" + exit 1 + fi + + occurrences=$(grep -c "$LATEST" flake.nix || true) + if [ "$occurrences" -ne 2 ]; then + echo "::error::Expected the new version ${LATEST} to appear twice in flake.nix (version line + URL), found ${occurrences}." + exit 1 + fi + + if ! grep -q "$HASH" flake.nix; then + echo "::error::New SRI hash was not written into flake.nix." + exit 1 + fi + + echo "Rewrote yt-dlp pin: ${CURRENT} -> ${LATEST}" + + - name: Open pull request + if: steps.check.outputs.changed == 'true' uses: peter-evans/create-pull-request@v6 with: branch: auto/yt-dlp-update delete-branch: true - commit-message: "chore: yt-dlp ${{ steps.before.outputs.version }} → ${{ steps.after.outputs.version }}" - title: "chore: yt-dlp ${{ steps.before.outputs.version }} → ${{ steps.after.outputs.version }}" + commit-message: "chore(nix): yt-dlp ${{ steps.current.outputs.version }} → ${{ steps.latest.outputs.version }}" + title: "chore(nix): yt-dlp ${{ steps.current.outputs.version }} → ${{ steps.latest.outputs.version }}" body: | - Automated `flake.lock` update. yt-dlp bumped from `${{ steps.before.outputs.version }}` to `${{ steps.after.outputs.version }}`. + Automated bump of the pinned yt-dlp release. Old: `${{ steps.current.outputs.version }}`. New: `${{ steps.latest.outputs.version }}`. SRI hash: `${{ steps.hash.outputs.hash }}`. - Triggered by the weekly nixpkgs check. + Upstream release: https://github.com/yt-dlp/yt-dlp/releases/tag/${{ steps.latest.outputs.version }} labels: dependencies diff --git a/AGENTS.md b/AGENTS.md index 10b5963..9dea540 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,6 +18,31 @@ Capture flow: locator → `determine_source()` (`crates/archivr-core/src/capture YouTube playlists and channels produce a **parent container entry** with each video captured as a child entry. `downloader/ytdlp.rs` handles the playlist probe (fetching per-video quality metadata before archiving), the multi-video download loop, and sync mode (skipping already-archived videos when re-archiving a playlist or channel). +Pasted text takes a much shorter path: `perform_text_capture()` (`capture.rs`) skips source detection +and every downloader shell-out — `downloader/text.rs` stages the body under `temp/`, hashes it, and the +blob lands in `raw/` like any other artifact. Entrypoint is +`POST /api/archives/:archive_id/captures/text`. Its body is byte-preserving, its entry has no fabricated +`original_url`, and its normal text preview opens from the entry rail. + +LLM summaries are a post-capture, manual-only subsystem: `crates/archivr-core/src/summarizer.rs` behind +`GET`/`POST /api/archives/:archive_id/entries/:entry_uid/summary`, cached in the `entry_summaries` +table per (entry, provider, model, prompt version, input hash). See `ARCHIVR-MENTAL-MODEL.md` for the +provider set and the status lifecycle. + +The requested provider model is the cache identity; a provider-returned resolved model is display attribution. +At startup, pending/running attempts interrupted by shutdown are failed. A regeneration keeps the previous completed +summary visible until its replacement completes; public readers receive completed content only, never diagnostics. + +`SummaryBuildOptions` keeps summaries text-only unless `include_images` is set. The input digest includes that flag and +the selected blobs' SHA-256, MIME types, and sizes, so a distinct image selection cannot reuse a text-only cache row. +Candidates are `media` artifacts only: `jpg`/`jpeg`, `png`, `webp`, `gif`, and `avif`, capped at four images, 5 MiB each, +and 12 MiB in aggregate. Anthropic HTTP, OpenAI-compatible HTTP, and Codex support images; Claude CLI does not. The core +remains synchronous: the server puts provider work in its blocking boundary rather than introducing async to +`archivr-core`. + +Entry free-text search includes summary text (and generated JSON tags inside it) from the latest completed summary only. +Pending and failed rows do not match, and a newer pending or failed request does not hide an older completed summary. + Per-archive layout (created by `archivr init`): `.archivr/` (name, store_path, `archivr.sqlite`) + sibling `store/` (`raw/`, `raw_tweets/`, `structured/`, `temp/`). Server-level auth lives in a **separate** `archivr-auth.sqlite` (users, sessions, API tokens, role bits GUEST=1/USER=2/ADMIN=4/OWNER=8). The server mounts multiple archives from a TOML registry (`crates/archivr-server/src/registry.rs`); routes are parameterized by `:archive_id`. @@ -32,6 +57,7 @@ The server mounts multiple archives from a TOML registry (`crates/archivr-server | `frontend/src/` | React app: `App.jsx` (root state + custom routing), `api.js` (fetch client), `components/`, `styles.css` | | `docs/` | User docs (`README.md`), `superpowers/plans/` and `superpowers/specs/` (dated design docs — write plans there before large features) | | `modules/nixos/` | NixOS module (`services.archivr-server`) | +| `.github/workflows/` | `update-ytdlp.yml` — weekly cron that PRs a yt-dlp version bump into `flake.nix` | | `vendor/twitter/` | Vendored Twitter scraper (active; the Python the server shells out to). Don't refactor casually. | | `vendor/readability/` | Mozilla `Readability.js`, concatenated into the SingleFile reader-mode browser script by `downloader/singlefile.rs`. | | `testing/` | Legacy scraping scripts + sample data. `testing/creds.txt` holds real tokens — never read, commit, or print it. | @@ -72,7 +98,14 @@ No CI is configured; no rustfmt.toml/clippy.toml — default `cargo fmt`/`clippy - **Auth extraction**: `AuthUser` implements `FromRequestParts` — session cookie (`session`) or `Authorization: Bearer` token (stored SHA3-256-hashed). Passwords are Argon2. - **Logging**: `eprintln!` with `info:`/`warn:` prefixes. No `tracing`/`log` — don't add structured logging piecemeal. - **External tools by env var**: `ARCHIVR_YT_DLP`, `ARCHIVR_CHROME`, `ARCHIVR_SINGLE_FILE`, `ARCHIVR_TWEET_PYTHON`, `ARCHIVR_TWEET_SCRAPER`, `ARCHIVR_STATIC_DIR`, `ARCHIVR_BIND`. Downloaders shell out to subprocesses; resolve binaries through these vars. -- **Frontend**: JSX (no TypeScript), PascalCase components in `frontend/src/components/`, kebab-case CSS classes, plain CSS with custom properties in `styles.css` (no Tailwind/CSS-in-JS). No router — `App.jsx` parses `window.location.pathname` + `history.pushState`. State = `useState` + one `AuthContext`; `sessionStorage` for refresh-resilient dialog state (see `CaptureDialog.jsx` job polling, 500ms). All API calls through `frontend/src/api.js` with relative `/api/*` URLs — add new endpoints there, not inline `fetch`. +- **yt-dlp is resolved, not just read**: `ARCHIVR_YT_DLP` (set by the flake wrappers) is only the + *pinned candidate* handed to `resolve_yt_dlp()` (`downloader/ytdlp.rs`), which compares it against a + self-updated copy in the state dir. `ARCHIVR_YT_DLP_FORCE` (absolute path) bypasses that comparison + entirely; `archivr yt-dlp status` shows and chooses that forced candidate when it applies; `ARCHIVR_STATE_DIR` + relocates the state dir. Never spawn bare `yt-dlp` — call the resolver. +- **LLM summaries by env var**: `ARCHIVR_ANTHROPIC_API_KEY` / `ARCHIVR_ANTHROPIC_URL` / `ARCHIVR_ANTHROPIC_MODEL`, `ARCHIVR_OPENAI_API_KEY` / `ARCHIVR_OPENAI_URL` / `ARCHIVR_OPENAI_MODEL`, `ARCHIVR_CLAUDE_CLI` / `ARCHIVR_CLAUDE_MODEL`, `ARCHIVR_CODEX_CLI` / `ARCHIVR_CODEX_MODEL`, plus `ARCHIVR_SUMMARY_HTTP_TIMEOUT` (default 120s) and `ARCHIVR_SUMMARY_CLI_TIMEOUT` (default 300s). Same convention as above — never TOML, which also keeps API keys out of anything the archive persists. Summaries are manual-only: nothing in `capture.rs` triggers them. The two CLI vars are optional overrides: unset, `resolve_cli()` auto-discovers well-known absolute installs first (`/opt/homebrew/bin/claude`, `/usr/local/bin/claude`; `/Applications/ChatGPT.app/Contents/Resources/codex`, `/opt/homebrew/bin/codex`, `/usr/local/bin/codex`), then `$HOME/.local/bin/`, then the bare name on PATH — the absolute defaults matter because the ChatGPT desktop app ships `codex` off PATH. Frontend static output is generated; never hand-edit `crates/archivr-server/static/`. +- **Frontend**: JSX (no TypeScript), PascalCase components in `frontend/src/components/`, kebab-case CSS classes, plain CSS with custom properties in `styles.css` (no Tailwind/CSS-in-JS). No router — `App.jsx` parses `window.location.pathname` + `history.pushState`. State = `useState` + one `AuthContext`; `sessionStorage` for refresh-resilient dialog state (see `CaptureDialog.jsx` job polling, 500ms). All API calls through `frontend/src/api.js` with relative `/api/*` URLs — add new endpoints there, not inline `fetch`. Summary polling and generate callbacks must remain scoped to the currently selected entry; image-inclusion behavior is unchanged. In-progress captures render through `SkeletonEntryRow.jsx`, which is a compact spinner + locator + "Archiving…" line (with a playlist/channel hint), **not** a grey skeleton block — don't reintroduce placeholder shimmer. Layout comes from semantic classes (e.g. `.capture-text-row` in `styles.css`), never from fallthrough on a generic row class; give a new row shape its own class. +- **CLI providers parse a file, not stdout**: `codex` is invoked as `codex exec --output-last-message -` (prompt on stdin) and the reply is read back from that file — raw stdout carries a runtime header, an echo of the user prompt, and a `tokens used` footer that the JSON extractor will happily mistake for the answer. There is a positional-prompt fallback for older builds that reject `-`. Keep any new CLI provider on the same "give me only the final message" contract. - **Naming (Rust)**: standard snake_case/PascalCase; visibility and roles are bitflag `u32`s, not enums. ## Important Files @@ -80,9 +113,16 @@ No CI is configured; no rustfmt.toml/clippy.toml — default `cargo fmt`/`clippy - `crates/archivr-server/src/main.rs` — server bootstrap: config load, archive mounting, auth DB init, stalled-job recovery (running → failed on startup). - `crates/archivr-server/src/routes.rs` — all HTTP handlers and the router; grep here first for API work. - `crates/archivr-core/src/capture.rs` — `perform_capture()`, `Source` enum, shorthand parsing. -- `crates/archivr-core/src/downloader/ytdlp.rs` — yt-dlp integration; YouTube playlist/channel probe and download, sync mode logic. +- `crates/archivr-core/src/downloader/ytdlp.rs` — every yt-dlp shell-out (playlist/channel probe and download, sync mode) **plus** the binary resolver: `resolve_yt_dlp()`, `state_dir()`, `probe_version()`. +- `crates/archivr-core/src/downloader/text.rs` — pasted-text staging + hashing (`save()` → `StagedText`); accepts only `text/plain` and `text/markdown`. +- `crates/archivr-core/src/summarizer.rs` — the `SummaryProvider` trait and its four implementations (Anthropic HTTP, OpenAI-compatible HTTP, `claude` CLI, `codex` CLI), `PROMPT_VERSION`, `resolve_cli()`, prompt assembly, and `build_summary_input()` (artifact selection + HTML/text/JSON reduction). +- `crates/archivr-cli/src/main.rs` — CLI entry point, including the `archivr yt-dlp update|status` subcommand (staged, atomic zipapp install into the state dir). +- `.github/workflows/update-ytdlp.yml` — weekly (`0 6 * * 1`) + manual auto-bump of the `flake.nix` yt-dlp pin. - `crates/archivr-core/src/database.rs` — single source of truth for all SQLite schema and queries (both archive and auth DBs). - `frontend/src/App.jsx` / `frontend/src/api.js` — frontend root state and API surface. +- `frontend/src/components/CaptureDialog.jsx` — `CaptureRow` (locator input, playlist quality selectors) and `CaptureTextRow` (the "Add text" flow), plus job polling. +- `frontend/src/components/ContextRail.jsx` — the Summary section: provider selector, generate/regenerate, and summary polling. +- `frontend/src/components/TextPreview.jsx` — preview renderer for text/markdown entries. - `docker/config.example.toml` — server config schema: `bind`, `auth_db_path`, repeated `[[archives]]` (`id`, `label`, `archive_path`). - `flake.nix`, `modules/nixos/archivr-server.nix`, `Dockerfile`, `docker-compose.yml` — deployment surfaces; config schema changes must be reflected in all of them plus `docs/README.md`. @@ -93,9 +133,16 @@ No CI is configured; no rustfmt.toml/clippy.toml — default `cargo fmt`/`clippy - Runtime binaries the app expects on PATH or via env vars: `yt-dlp`, Chromium, `single-file` (Node), Python 3 with `twitter-api-client`, `ffmpeg`. `nix develop` provides the dev subset. - `.gitignore` is **default-deny with an allowlist** — new top-level files/dirs are invisible to git until explicitly allowed there. - Frontend build output (`crates/archivr-server/static/`) is generated; never hand-edit it. +- **yt-dlp is pinned to a specific GitHub release** in the `ytDlp` derivation in `flake.nix` (zipapp + fetched from `github.com/yt-dlp/yt-dlp/releases`, wrapped with `python312` + `ffmpeg`) — not taken + from nixpkgs. Both the `archivr` and `archivr-server` wrappers set `ARCHIVR_YT_DLP` from it. Three + ways to bump: the weekly `Update yt-dlp` workflow (automatic PR), `archivr yt-dlp update` + (per-machine, into the state dir), or editing the three fields of the `ytDlp` block by hand. Which + binary actually runs is decided at runtime by `resolve_yt_dlp()` in `downloader/ytdlp.rs`; use + `archivr yt-dlp status` to see the candidates and the winner. ## Testing & QA -- **Rust**: unit tests only, in `#[cfg(test)]` modules inside source files (e.g. `capture.rs`, `database.rs`, `registry.rs`, `routes.rs`, `hash.rs`). No `tests/` integration dir. Patterns: `tempfile` for scratch archives, config round-trip assertions, regex/parser validation. Run `cargo test` or `cargo test -p `. +- **Rust**: unit tests only, in `#[cfg(test)]` modules inside source files (e.g. `capture.rs`, `database.rs`, `registry.rs`, `routes.rs`, `hash.rs`, and newer: `summarizer.rs` — 23 tests over provider construction, CLI/env resolution, output extraction, HTML/text/JSON input reduction and tweet-thread joining; `downloader/ytdlp.rs` — 13 tests, several covering resolver priority and version tie-breaking). No `tests/` integration dir. Patterns: `tempfile` for scratch archives, config round-trip assertions, regex/parser validation. Run `cargo test` or `cargo test -p `. - **Frontend**: no test framework. Storybook (`bun run storybook`) is the component QA surface — stories are colocated `*.stories.jsx` files; add one when adding a nontrivial component. - Manual smoke test for server changes: build frontend, `cargo run -p archivr-server -- `, exercise `/api/*`. diff --git a/ARCHIVR-MENTAL-MODEL.md b/ARCHIVR-MENTAL-MODEL.md index 7f8c3ec..3b4053e 100644 --- a/ARCHIVR-MENTAL-MODEL.md +++ b/ARCHIVR-MENTAL-MODEL.md @@ -81,7 +81,7 @@ There are two user-facing binaries: | Binary | Purpose | |---|---| -| `archivr` | CLI for initializing archives and capturing material into one archive | +| `archivr` | CLI for initializing archives and capturing material into one archive (also `yt-dlp status\|update`) | | `archivr-server` | Web server for browsing one or more existing archives | The CLI writes archive data: @@ -128,6 +128,16 @@ sequenceDiagram CLI->>User: terminal result ``` +**Pasted text short-circuits most of that.** `perform_text_capture` (`capture.rs`) is not a `Source` +route: there is no locator to classify, no URL probe, and no downloader subprocess. It validates the +title (non-empty, ≤ 500 chars), the body (non-empty, ≤ 2 MiB) and the MIME type (`text/plain` or +`text/markdown` only), then calls `downloader/text.rs` to write the bytes into `store/temp//` +and hash them. From there it rejoins the normal path — dedup into `raw/A/B/HASH.EXT`, then run, entry +and artifact rows. The server exposes it as `POST /api/archives/:archive_id/captures/text`, and the UI +drives it from `CaptureTextRow` in `CaptureDialog.jsx`. The body is preserved byte-for-byte, the entry's +`original_url` remains empty (no fabricated `text:` URL), and its normal entry-rail preview renders through +`TextPreview.jsx`. + ## Web Capture Pipeline Web pages (`Source::WebPage`) take a longer path than yt-dlp or tweets: @@ -158,6 +168,82 @@ sequenceDiagram Server-->>Browser: JSON ``` +## LLM Summaries + +Summaries are a **post-capture, manually triggered** subsystem. Nothing in `capture.rs` calls the +summarizer; a summary exists only because someone pressed generate in the Summary section of +`ContextRail.jsx`. + +`crates/archivr-core/src/summarizer.rs` defines one `SummaryProvider` trait with four implementations: +Anthropic HTTP, OpenAI-compatible HTTP, the local `claude` CLI, and the local `codex` CLI. Each is +built purely from environment variables (`provider_from_env`), so no key or model name is ever written +into archive data. `PROMPT_VERSION` in the same file stamps every row, so changing the prompt +invalidates the cache instead of silently mixing generations. + +`entry_summaries` (schema in `database.rs`) is that cache, unique on +(`entry_id`, `provider_kind`, `provider_model`, `prompt_version`, `input_sha256`) — the requested provider +model is the cache identity, so the same entry summarised by two providers, two requested models, or after a +prompt change yields distinct rows, while a repeat request with identical inputs reuses one. When a provider +returns its concrete resolved model, it is stored separately and displayed as attribution without changing that +identity. Rows move `pending` → `running` → `completed` | `failed`, mirroring how capture jobs are tracked; +the frontend polls only for the currently selected entry, and its generate callbacks are scoped to that same +selection. Image-selection behavior remains unchanged. + +On startup the server marks interrupted `pending` or `running` attempts failed. Regeneration is non-destructive: +the prior completed summary stays visible until a replacement completes successfully. Public readers receive only +completed summary content, never pending/failed state or diagnostic error text. + +The summary path is deliberately explicit: UI consent (`Include attached images`) → core selection → input digest and +cache lookup → provider transport → `pending`/`running`/`completed` lifecycle. Text is the default. When consent is +present, `SummaryBuildOptions::include_images` admits only bounded `media` image candidates and the digest includes both +the flag and selected blob identity, MIME type, and size. The core is still synchronous; the server owns the blocking +boundary. Anthropic HTTP, OpenAI-compatible HTTP, and Codex can transport the selected image data; Claude CLI receives +text only. + +```mermaid +flowchart LR + UI["ContextRail Summary"] -->|POST .../summary| Server + Server --> Input["build_summary_input()"] + Input --> Artifacts["entry artifacts on disk"] + Server --> Row["entry_summaries: pending → running"] + Server --> Provider["SummaryProvider (HTTP or CLI)"] + Provider --> Row2["completed / failed"] + UI -->|GET .../summary poll| Row2 +``` + +**X Articles and tweet threads are why the artifact lookup is special.** For most entries `build_summary_input` reads +the single `primary_media` artifact. A `tweet` or `tweet_thread` entry has no `primary_media` — it has +N `raw_tweet_json` artifacts, one per status in the thread. So the summarizer selects on the +`raw_tweet_json` role instead, loads **all** matching artifacts in order, and joins them with +`\n\n---\n\n`; a `---` line reads as a hard paragraph break to every model, keeping individual +statuses from bleeding into one another. For an X Article, the reducer prefers article text over the tweet's body: +`plain_text`, then flattened ordered blocks, then `preview_text`, then `summary_text`; only then does it fall back to +`full_text`/`text`/`content`/`body`. Any change to article reduction or thread status storage must be mirrored here. + +## yt-dlp Lifecycle + +There is no single yt-dlp. Up to three can exist on one machine: + +1. **The flake pin** — the `ytDlp` derivation in `flake.nix` fetches an exact release zipapp from + `github.com/yt-dlp/yt-dlp/releases` and wraps it with `python312` + `ffmpeg`. Both the `archivr` and + `archivr-server` wrappers export it as `ARCHIVR_YT_DLP`. +2. **A state-dir install** — `archivr yt-dlp update` downloads the latest zipapp and installs it + atomically (staged file, then rename) at `/yt-dlp/yt-dlp` with a sibling `.version` + sentinel that lets repeat runs skip the download. +3. **Whatever is on PATH** — the historical behaviour, and the last-resort fallback. + +`resolve_yt_dlp()` in `downloader/ytdlp.rs` picks between them once per process (cached in a +`OnceLock`): `ARCHIVR_YT_DLP_FORCE` wins outright if it points at a real file; otherwise the pinned and +state-dir candidates are probed with `--version` and the newest wins — yt-dlp versions are `YYYY.MM.DD`, +so plain string ordering is chronological — with exact ties going to the state-dir copy the user +deliberately installed. If neither exists, it falls back to bare `yt-dlp`. `archivr yt-dlp status` +prints every candidate, its version, and the winner; when the force variable applies, it includes that +forced candidate and selects it as the winner. + +Three ways to move the version forward: the weekly `.github/workflows/update-ytdlp.yml` cron (reads the +current pin, queries the GitHub releases API, re-hashes with `nix hash file --sri`, rewrites the `ytDlp` +block and opens a PR), `archivr yt-dlp update` for one machine, or editing `flake.nix` by hand. + ## Where To Edit | Feature kind | Edit here | @@ -167,6 +253,10 @@ sequenceDiagram | Archive opening, listing entries, entry detail, runs | `crates/archivr-core/src/archive.rs` | | Download/save behavior | `crates/archivr-core/src/downloader/` | | YouTube playlist/channel download, playlist probe, sync mode | `crates/archivr-core/src/downloader/ytdlp.rs` and `capture.rs` | +| Which yt-dlp binary runs (resolver, state dir, version probe) | `crates/archivr-core/src/downloader/ytdlp.rs` | +| Pasted-text capture (staging, hashing, MIME allowlist) | `crates/archivr-core/src/downloader/text.rs` and `capture.rs` | +| LLM summary providers, prompt, `PROMPT_VERSION`, input building | `crates/archivr-core/src/summarizer.rs` | +| `entry_summaries` schema and summary CRUD | `crates/archivr-core/src/database.rs` | | CLI commands, argument parsing, terminal output | `crates/archivr-cli/src/main.rs` | | Server API routes | `crates/archivr-server/src/routes.rs` | | Auth model (users, sessions, tokens, roles) | `crates/archivr-server/src/auth.rs` | @@ -174,6 +264,9 @@ sequenceDiagram | Frontend root state + routing | `frontend/src/App.jsx` | | Frontend API client | `frontend/src/api.js` | | Frontend components | `frontend/src/components/` | +| Summary UI (provider selector, generate, polling) | `frontend/src/components/ContextRail.jsx` | +| Text/Markdown entry preview | `frontend/src/components/TextPreview.jsx` | +| "Add text" capture row | `frontend/src/components/CaptureDialog.jsx` | | Frontend styling | `frontend/src/styles.css` | ## Practical Feature Rule @@ -196,7 +289,8 @@ The server both reads and writes archive data. Capture jobs are asynchronous: `P **Auth model.** A separate `archivr-auth.sqlite` (path derived from the server config directory) holds users, sessions, and API tokens. Role bits are `u32` flags (`GUEST`, `USER`, `ADMIN`, `OWNER`) so a single bitmask value covers assignment, checks, and visibility. The middleware stack is `setup_guard` → `login_rate_limit` → `security_headers`; route families are classified `READ / ADMIN / WRITE / STATIC` in `routes.rs`. -**Search** is client-side filtering over entries the frontend has already fetched. +**Search** is server-side free-text filtering over entry fields and the latest completed summary. The summary JSON is +searched as text, so generated `tags` participate. Older completed summaries stay searchable while a newer request is +pending or failed; rows with no completed summary contribute no summary-derived match. **Admin view** covers mounted archives, users, sessions, and API tokens. - diff --git a/Cargo.lock b/Cargo.lock index c512560..c6f2510 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,8 +97,10 @@ dependencies = [ "chrono", "clap", "regex", + "reqwest", "rusqlite", "serde_json", + "tempfile", ] [[package]] @@ -1542,6 +1544,7 @@ version = "1.0.150" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" dependencies = [ + "indexmap", "itoa", "memchr", "serde", diff --git a/Cargo.toml b/Cargo.toml index e7229da..433ccbb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ hex = "0.4.3" regex = "1.12.2" rusqlite = { version = "0.32.1", features = ["bundled"] } serde = { version = "1.0.228", features = ["derive"] } -serde_json = "1.0.132" +serde_json = { version = "1.0.132", features = ["preserve_order"] } sha3 = "0.10.8" tempfile = "3.13.0" tokio = { version = "1.41.1", features = ["macros", "rt-multi-thread", "net", "fs", "io-util"] } diff --git a/crates/archivr-cli/Cargo.toml b/crates/archivr-cli/Cargo.toml index 3a190d7..a198852 100644 --- a/crates/archivr-cli/Cargo.toml +++ b/crates/archivr-cli/Cargo.toml @@ -15,3 +15,7 @@ clap.workspace = true regex.workspace = true rusqlite.workspace = true serde_json.workspace = true +reqwest.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/crates/archivr-cli/src/main.rs b/crates/archivr-cli/src/main.rs index ec10543..6c1db54 100644 --- a/crates/archivr-cli/src/main.rs +++ b/crates/archivr-cli/src/main.rs @@ -1,12 +1,27 @@ -use anyhow::{Context, Result}; -use archivr_core::{archive, capture::CaptureConfig}; +use anyhow::{bail, Context, Result}; +use archivr_core::{ + archive, + capture::CaptureConfig, + downloader::ytdlp::{ + forced_yt_dlp, pinned_yt_dlp, probe_version, resolve_yt_dlp, state_dir, state_dir_yt_dlp, + }, +}; use clap::{Parser, Subcommand}; use std::{ env, - path::Path, + path::{Path, PathBuf}, process, + process::Command as ProcCommand, }; +/// GitHub release metadata endpoint for the upstream yt-dlp project. +const YT_DLP_LATEST_RELEASE: &str = + "https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest"; + +/// Every python zipapp starts with this shebang; used as a sanity check that we +/// downloaded the artifact and not an HTML error page or an LFS pointer. +const ZIPAPP_SHEBANG: &[u8] = b"#!/usr/bin/env python3"; + #[derive(Parser, Debug)] #[command(version, about, long_about = None)] struct Args { @@ -48,6 +63,25 @@ enum Command { #[arg(long = "force-with-info-removal")] force_with_info_removal: bool, }, + + /// Inspect or update the yt-dlp binary archivr runs + #[command(name = "yt-dlp")] + YtDlp { + #[command(subcommand)] + subcmd: YtDlpCmd, + }, +} + +#[derive(Subcommand, Debug)] +enum YtDlpCmd { + /// Download the latest yt-dlp zipapp into archivr's state directory + Update { + /// Install this exact release tag instead of the latest (e.g. 2026.09.15) + #[arg(long)] + version: Option, + }, + /// Show every yt-dlp candidate, its version, and which one wins + Status, } fn main() -> Result<()> { @@ -96,7 +130,217 @@ fn main() -> Result<()> { ); Ok(()) - } // _ => eprintln!("Unknown command: {:?}", args.command), + } + + Command::YtDlp { subcmd } => match subcmd { + YtDlpCmd::Update { version } => yt_dlp_update(version.as_deref()), + YtDlpCmd::Status => yt_dlp_status(), + }, } } + +/// Resolves `/yt-dlp/`, erroring out if there is no usable HOME. +fn yt_dlp_state_dir() -> Result { + state_dir() + .map(|d| d.join("yt-dlp")) + .context("could not determine a state directory (is $HOME set?)") +} + +/// Formats one `status` row. Missing candidates show an em dash. +fn format_status_row(role: &str, path: Option<&Path>, chosen: &Path) -> String { + match path { + Some(p) => { + let version = probe_version(p).unwrap_or_else(|| "—".to_string()); + let star = if p == chosen { "*" } else { "" }; + format!("{role}\t{}\t{version}\t{star}", p.display()) + } + None => format!("{role}\t—\t—\t"), + } +} + +/// Prints one `status` row. Missing candidates show an em dash. +fn status_row(role: &str, path: Option<&Path>, chosen: &Path) { + println!("{}", format_status_row(role, path, chosen)); +} + +fn yt_dlp_status() -> Result<()> { + let chosen = resolve_yt_dlp(); + + println!("role\tpath\tversion\tchosen"); + status_row( + "force (ARCHIVR_YT_DLP_FORCE)", + forced_yt_dlp().as_deref(), + &chosen, + ); + status_row("env (ARCHIVR_YT_DLP)", pinned_yt_dlp().as_deref(), &chosen); + + // Show the state-dir slot even when empty, so users can see where an + // `archivr yt-dlp update` would land. + let state_candidate = state_dir_yt_dlp().filter(|p| p.is_file()); + status_row("state-dir", state_candidate.as_deref(), &chosen); + + status_row( + "path-fallback (yt-dlp)", + Some(Path::new("yt-dlp")), + &chosen, + ); + + if let Ok(dir) = yt_dlp_state_dir() { + if state_dir_yt_dlp().is_none_or(|p| !p.is_file()) { + println!("\nNo state-dir install yet; `archivr yt-dlp update` would write to {}", dir.join("yt-dlp").display()); + } + } + + Ok(()) +} + +/// Asks the GitHub API for the newest yt-dlp release tag. +fn latest_yt_dlp_version(client: &reqwest::blocking::Client) -> Result { + let body = client + .get(YT_DLP_LATEST_RELEASE) + .send() + .context("failed to reach the GitHub releases API")? + .error_for_status() + .context("GitHub releases API returned an error")? + .text() + .context("failed to read the GitHub releases API response")?; + + let json: serde_json::Value = + serde_json::from_str(&body).context("GitHub releases API returned invalid JSON")?; + + json.get("tag_name") + .and_then(|t| t.as_str()) + .map(str::to_string) + .context("GitHub releases API response had no tag_name") +} + +fn yt_dlp_update(requested_version: Option<&str>) -> Result<()> { + let dir = yt_dlp_state_dir()?; + let target = dir.join("yt-dlp"); + let staging = dir.join("yt-dlp.new"); + let version_file = dir.join(".version"); + + let client = reqwest::blocking::Client::builder() + .user_agent(concat!("archivr-cli/", env!("CARGO_PKG_VERSION"))) + .build() + .context("failed to build an HTTP client")?; + + let version = match requested_version { + Some(v) => v.to_string(), + None => latest_yt_dlp_version(&client)?, + }; + + // The sibling .version file is what lets us skip a ~3MB download on a + // no-op update; the binary itself is a zipapp with no cheap version probe + // that doesn't cost a python startup. + let installed = std::fs::read_to_string(&version_file).ok(); + if target.is_file() && installed.as_deref().map(str::trim) == Some(version.as_str()) { + println!("yt-dlp {version} is already installed at {}", target.display()); + return Ok(()); + } + + println!("Downloading yt-dlp {version}…"); + let url = format!("https://github.com/yt-dlp/yt-dlp/releases/download/{version}/yt-dlp"); + let bytes = client + .get(&url) + .send() + .with_context(|| format!("failed to download {url}"))? + .error_for_status() + .with_context(|| format!("download failed — is {version} a real release tag?"))? + .bytes() + .context("failed to read the downloaded yt-dlp body")?; + + if !bytes.starts_with(ZIPAPP_SHEBANG) { + bail!( + "downloaded artifact from {url} is not a python zipapp \ + (expected it to start with `{}`) — refusing to install it", + String::from_utf8_lossy(ZIPAPP_SHEBANG) + ); + } + + std::fs::create_dir_all(&dir) + .with_context(|| format!("failed to create {}", dir.display()))?; + std::fs::write(&staging, &bytes) + .with_context(|| format!("failed to write {}", staging.display()))?; + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&staging, std::fs::Permissions::from_mode(0o755)) + .with_context(|| format!("failed to chmod +x {}", staging.display()))?; + } + + // Atomic swap: a concurrently-running archivr sees either the whole old + // binary or the whole new one, never a half-written file. + std::fs::rename(&staging, &target) + .with_context(|| format!("failed to install {}", target.display()))?; + std::fs::write(&version_file, format!("{version}\n")) + .with_context(|| format!("failed to record version in {}", version_file.display()))?; + + // The zipapp is python source, not a native binary — installing it on a + // host without python3 is legal (the server may run under a nix wrapper + // with its own PATH) but worth flagging loudly. + let has_python = ProcCommand::new("python3") + .arg("--version") + .output() + .map(|o| o.status.success()) + .unwrap_or(false); + if !has_python { + eprintln!( + "warning: python3 was not found on PATH — the yt-dlp zipapp just installed \ + at {} will not run until python3 is available", + target.display() + ); + } + + println!("Installed yt-dlp {version} to {}", target.display()); + println!("archivr will now prefer it whenever it is newer than the pinned binary (ARCHIVR_YT_DLP)."); + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::format_status_row; + use archivr_core::downloader::ytdlp::{ + forced_yt_dlp, resolve_yt_dlp_uncached, YT_DLP_FORCE_ENV, + }; + use std::path::Path; + + fn fake_yt_dlp(path: &Path, version: &str) { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, format!("#!/bin/sh\necho {version}\n")).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + } + + #[test] + fn forced_candidate_is_rendered_and_selected() { + let tmp = tempfile::tempdir().unwrap(); + let forced = tmp.path().join("forced/yt-dlp"); + fake_yt_dlp(&forced, "2020.01.01"); + unsafe { std::env::set_var(YT_DLP_FORCE_ENV, &forced) }; + + let candidate = forced_yt_dlp(); + assert_eq!(candidate.as_deref(), Some(forced.as_path())); + let chosen = resolve_yt_dlp_uncached(); + assert_eq!(chosen, forced); + assert_eq!( + format_status_row( + "force (ARCHIVR_YT_DLP_FORCE)", + candidate.as_deref(), + &chosen, + ), + format!( + "force (ARCHIVR_YT_DLP_FORCE)\t{}\t2020.01.01\t*", + forced.display() + ) + ); + + unsafe { std::env::remove_var(YT_DLP_FORCE_ENV) }; + } +} diff --git a/crates/archivr-core/src/archive.rs b/crates/archivr-core/src/archive.rs index e84d4a2..ea63c46 100644 --- a/crates/archivr-core/src/archive.rs +++ b/crates/archivr-core/src/archive.rs @@ -36,6 +36,14 @@ pub struct EntrySummary { pub cacheable_bytes: i64, } +/// One stored LLM summary, as exposed over the API. +/// +/// Aliased rather than redefined: the DB row is already the exact shape the +/// frontend needs, and a second near-identical struct would only add a mapping +/// step to keep in sync. The `View` name exists because `EntrySummary` in this +/// module is the *entry listing* row, an unrelated thing. +pub use crate::database::EntrySummaryRecord as EntrySummaryView; + #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] pub struct EntryDetail { pub summary: EntrySummary, @@ -43,6 +51,12 @@ pub struct EntryDetail { pub source_metadata_json: String, pub display_metadata_json: Option, pub artifacts: Vec, + /// Most recent completed summary for this entry. Always `None` on a fresh + /// capture — summarization is manual. + pub latest_summary: Option, + /// Latest non-completed generation attempt, kept separate so a replacement + /// never displaces readable completed content. + pub summary_attempt: Option, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] @@ -343,12 +357,17 @@ pub fn get_entry_detail( })? .collect::>>()?; + let latest_summary = database::latest_completed_entry_summary(conn, entry_id)?; + let summary_attempt = database::latest_entry_summary_attempt(conn, entry_id)?; + Ok(Some(EntryDetail { summary, structured_root_relpath, source_metadata_json, display_metadata_json, artifacts, + latest_summary, + summary_attempt, })) } @@ -759,7 +778,14 @@ pub fn search_entries( sql.push_str(&format!( " AND (LOWER(e.title) LIKE ?{n} OR LOWER(si.canonical_url) LIKE ?{n} \ OR LOWER(e.entry_uid) LIKE ?{n} OR LOWER(e.source_kind) LIKE ?{n} \ - OR LOWER(e.entity_kind) LIKE ?{n} OR LOWER(e.visibility) LIKE ?{n})" + OR LOWER(e.entity_kind) LIKE ?{n} OR LOWER(e.visibility) LIKE ?{n} \ + OR LOWER(COALESCE((\ + SELECT s.summary_text FROM entry_summaries s \ + WHERE s.entry_id = e.id AND s.status = 'completed' \ + AND s.summary_text IS NOT NULL \ + ORDER BY s.completed_at DESC, s.updated_at DESC, s.id DESC \ + LIMIT 1\ + ), '')) LIKE ?{n})" )); params.push(term); } @@ -1483,6 +1509,192 @@ mod tests { assert_eq!(results.len(), 1); } + fn entry_id_by_title(conn: &rusqlite::Connection, title: &str) -> i64 { + conn.query_row( + "SELECT id FROM archived_entries WHERE title = ?1", + [title], + |row| row.get(0), + ) + .unwrap() + } + + fn complete_summary( + conn: &rusqlite::Connection, + entry_id: i64, + cache_key: &str, + summary_text: &str, + ) -> String { + let uid = database::upsert_pending_entry_summary( + conn, + entry_id, + "test_provider", + None, + "v1", + cache_key, + ) + .unwrap(); + database::update_entry_summary_status(conn, &uid, "completed", Some(summary_text), None) + .unwrap(); + uid + } + + fn set_summary_timestamps( + conn: &rusqlite::Connection, + summary_uid: &str, + timestamp: &str, + ) { + conn.execute( + "UPDATE entry_summaries SET completed_at = ?1, updated_at = ?1 WHERE summary_uid = ?2", + rusqlite::params![timestamp, summary_uid], + ) + .unwrap(); + } + + #[test] + fn search_summary_json_tags_match_and_unrelated_text_is_absent() { + let conn = make_test_db_with_entries(); + let entry_id = entry_id_by_title(&conn, "Resume Templates"); + complete_summary( + &conn, + entry_id, + "tags", + r#"{"tags":["skincare","dermatology"]}"#, + ); + + let matches = search_entries( + &conn, + &SearchEntriesQuery { + q: Some("skincare".to_string()), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(matches.len(), 1); + assert_eq!(matches[0].title.as_deref(), Some("Resume Templates")); + + let unrelated = search_entries( + &conn, + &SearchEntriesQuery { + q: Some("neurology".to_string()), + ..Default::default() + }, + ) + .unwrap(); + assert!(unrelated.is_empty()); + } + + #[test] + fn search_summary_uses_only_the_newest_completed_row() { + let conn = make_test_db_with_entries(); + let entry_id = entry_id_by_title(&conn, "Resume Templates"); + let older = complete_summary(&conn, entry_id, "older", "legacy-skincare-term"); + set_summary_timestamps(&conn, &older, "2026-01-01T00:00:00Z"); + let newer = complete_summary(&conn, entry_id, "newer", "current-dermatology-term"); + set_summary_timestamps(&conn, &newer, "2026-02-01T00:00:00Z"); + + let old_matches = search_entries( + &conn, + &SearchEntriesQuery { + q: Some("legacy-skincare-term".to_string()), + ..Default::default() + }, + ) + .unwrap(); + assert!(old_matches.is_empty()); + + let current_matches = search_entries( + &conn, + &SearchEntriesQuery { + q: Some("current-dermatology-term".to_string()), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(current_matches.len(), 1); + } + + #[test] + fn search_summary_keeps_latest_completed_when_newer_rows_are_pending_or_failed() { + let conn = make_test_db_with_entries(); + let entry_id = entry_id_by_title(&conn, "Resume Templates"); + let completed = complete_summary(&conn, entry_id, "completed", "retained-skincare-term"); + set_summary_timestamps(&conn, &completed, "2026-01-01T00:00:00Z"); + + let pending = database::upsert_pending_entry_summary( + &conn, + entry_id, + "test_provider", + None, + "v1", + "pending", + ) + .unwrap(); + set_summary_timestamps(&conn, &pending, "2026-03-01T00:00:00Z"); + let failed = database::upsert_pending_entry_summary( + &conn, + entry_id, + "test_provider", + None, + "v1", + "failed", + ) + .unwrap(); + database::update_entry_summary_status(&conn, &failed, "failed", None, Some("boom")).unwrap(); + set_summary_timestamps(&conn, &failed, "2026-04-01T00:00:00Z"); + + let matches = search_entries( + &conn, + &SearchEntriesQuery { + q: Some("retained-skincare-term".to_string()), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(matches.len(), 1); + } + + #[test] + fn search_summary_preserves_prefix_collection_and_visibility_scope() { + let conn = make_test_db_with_entries(); + let entry_id = entry_id_by_title(&conn, "Polymarket tweet"); + complete_summary(&conn, entry_id, "scoped", "scoped-skincare-term"); + let tag = create_tag(&conn, "/summary-scope").unwrap(); + database::assign_entry_to_tag( + &conn, + entry_id, + database::get_tag_by_uid(&conn, &tag.tag_uid).unwrap().unwrap().id, + ) + .unwrap(); + let collection = database::create_collection(&conn, "Summary scope", "summary-scope", 2, false) + .unwrap(); + database::add_entry_to_collection(&conn, collection.id, entry_id, 2).unwrap(); + + let query = SearchEntriesQuery { + q: Some("scoped-skincare-term".to_string()), + source_kind: Some("x".to_string()), + entity_kind: Some("tweet".to_string()), + url: Some("x.com".to_string()), + title: Some("polymarket".to_string()), + after: Some("2020-01-01T00:00:00Z".to_string()), + before: Some("9999-01-01T00:00:00Z".to_string()), + tag: Some("/summary-scope".to_string()), + caller_bits: 1, + collection_id: Some(collection.id), + }; + assert!(search_entries(&conn, &query).unwrap().is_empty()); + + let matches = search_entries( + &conn, + &SearchEntriesQuery { + caller_bits: 2, + ..query + }, + ) + .unwrap(); + assert_eq!(matches.len(), 1); + assert_eq!(matches[0].title.as_deref(), Some("Polymarket tweet")); + } + // ---- tag API tests ---- fn make_tag_test_db() -> (rusqlite::Connection, i64, i64) { diff --git a/crates/archivr-core/src/capture.rs b/crates/archivr-core/src/capture.rs index 1b992f1..b52b874 100644 --- a/crates/archivr-core/src/capture.rs +++ b/crates/archivr-core/src/capture.rs @@ -951,7 +951,10 @@ fn register_tweet_artifacts( })?; for (role, raw_relpath) in tweet_raw_artifacts(&json_str)? { let raw_path = PathBuf::from(&raw_relpath); - let blob = blob_record_for_raw_relpath(store_path, &raw_path)?; + let mut blob = blob_record_for_raw_relpath(store_path, &raw_path)?; + if role == "media" { + blob.mime_type = tweet_media_image_mime(blob.extension.as_deref()); + } let blob_id = database::upsert_blob(conn, &blob)?; database::add_entry_artifact( conn, @@ -1030,6 +1033,22 @@ fn record_tweet_entry( Ok(entry) } +/// Trusted image MIME types emitted by the X downloader's media paths. +/// +/// Tweet JSON has no MIME field for ordinary downloaded media. Restricting this +/// inference to the explicit image extensions keeps binary video/audio and +/// unknown extensions out of multimodal summary input. +fn tweet_media_image_mime(extension: Option<&str>) -> Option { + match extension?.to_ascii_lowercase().as_str() { + "jpg" | "jpeg" => Some("image/jpeg".to_string()), + "png" => Some("image/png".to_string()), + "webp" => Some("image/webp".to_string()), + "gif" => Some("image/gif".to_string()), + "avif" => Some("image/avif".to_string()), + _ => None, + } +} + fn tweet_raw_artifacts(tweet_json: &str) -> Result> { let regex = regex::Regex::new(r#""(avatar_local_path|local_path)": "([^"\n]+)""#)?; let mut seen = HashSet::new(); @@ -1562,8 +1581,8 @@ pub fn perform_capture( let (rewritten, fonts) = downloader::font_extractor::extract_and_rewrite(&content, store_path, aid) .unwrap_or_else(|_| (content.clone(), vec![])); // non-fatal - // Extract title after font-stripping so the title tag is not buried - // behind multi-MB embedded font data that would exceed the 256 KiB window. + // Extract title after font-stripping so the title tag is not buried + // behind multi-MB embedded font data that would exceed the 256 KiB window. let title = downloader::singlefile::extract_html_title_str(&rewritten); fs::write(&temp_html, rewritten.as_bytes()) .with_context(|| "failed to write rewritten HTML")?; @@ -1918,6 +1937,171 @@ pub fn perform_capture( }) } +/// Archives user-supplied plain text or Markdown content. +/// +/// # Arguments +/// * `archive_paths` - Path configuration for the archive +/// * `title` - User-supplied title (non-empty, trimmed, capped at 500 chars) +/// * `body` - Text content (non-empty, capped at 2 MiB) +/// * `mime` - MIME type: "text/plain" or "text/markdown" +/// * `archive_id` - Optional archive ID (used for job tracking if provided) +/// +/// # Returns +/// * `CaptureResult` with the run UID and status +/// +/// # Errors +/// * Empty or oversized title/body +/// * Unsupported MIME type +/// * Database or file system errors +pub fn perform_text_capture( + archive_paths: &ArchivePaths, + title: &str, + body: &str, + mime: &str, + _archive_id: Option<&str>, +) -> Result { + // Validate title + let title = title.trim(); + if title.is_empty() { + anyhow::bail!("title must not be empty"); + } + if title.len() > 500 { + anyhow::bail!("title must not exceed 500 characters"); + } + + // Validate body + if body.trim().is_empty() { + anyhow::bail!("body must not be empty"); + } + if body.len() > 2 * 1024 * 1024 { + anyhow::bail!("body must not exceed 2 MiB"); + } + + // Validate MIME type + if mime != "text/plain" && mime != "text/markdown" { + anyhow::bail!("unsupported MIME type: {mime}. Must be 'text/plain' or 'text/markdown'"); + } + + // Generate timestamp + let timestamp = format!( + "{}-{}", + Local::now().format("%Y-%m-%dT%H-%M-%S%.3f"), + Uuid::new_v4().simple(), + ); + let store_path = &archive_paths.store_path; + + // Initialize database + let conn = database::open_or_initialize(&archive_paths.archive_path)?; + let user_id = database::ensure_default_user(&conn)?; + + // Create run and item + let run = database::create_archive_run(&conn, user_id, 1)?; + let source_kind = "text"; + let entity_kind = "document"; + let item = database::create_archive_run_item( + &conn, + run.id, + None, + 0, + &format!("text:{}", title), + None, + source_kind, + entity_kind, + )?; + + // Stage the text content + let staged_text = downloader::text::save(body.as_bytes(), mime, store_path, ×tamp)?; + + // Check if hash already exists + let file_extension = format!(".{}", staged_text.extension); + let hash_exists = hash_exists(&staged_text.hash, &file_extension, store_path)?; + + if !hash_exists { + // Move staged file to raw storage + move_temp_to_raw(&staged_text.staged_path, &staged_text.hash, store_path)?; + } + + // Clean up temp directory + let _ = fs::remove_dir_all(store_path.join("temp").join(×tamp)); + + // Create blob record + let raw_relpath = raw_relative_path_from_hash(&staged_text.hash, &file_extension)?; + let blob = database::BlobRecord { + sha256: staged_text.hash.clone(), + byte_size: staged_text.byte_size as i64, + mime_type: Some(mime.to_string()), + extension: Some(staged_text.extension.clone()), + raw_relpath: path_to_store_string(&raw_relpath), + }; + let blob_id = database::upsert_blob(&conn, &blob)?; + + // Create source identity + let canonical_locator = format!("text:{}", staged_text.hash); + let source_identity_id = database::upsert_source_identity( + &conn, + source_kind, + entity_kind, + None, + None, + &canonical_locator, + )?; + + // Create entry + let entry = database::create_archived_entry( + &conn, + &database::NewEntry { + source_identity_id, + archive_run_id: run.id, + parent_entry_id: None, + root_entry_id: None, + created_by_user_id: user_id, + owned_by_user_id: user_id, + source_kind: source_kind.to_string(), + entity_kind: entity_kind.to_string(), + title: Some(title.to_string()), + visibility: "private".to_string(), + representation_kind: "text".to_string(), + source_metadata_json: json!({ + "requested_locator": format!("text:{}", title), + "canonical_locator": canonical_locator, + "mime_type": mime + }) + .to_string(), + display_metadata_json: None, + }, + )?; + + // Create structured root directory + create_structured_root(store_path, &entry)?; + + // Create primary_media artifact + database::add_entry_artifact( + &conn, + &database::NewArtifact { + entry_id: entry.id, + artifact_role: "primary_media".to_string(), + storage_area: "raw".to_string(), + relpath: blob.raw_relpath, + blob_id: Some(blob_id), + logical_path: None, + metadata_json: None, + }, + )?; + + // Complete the run item + database::complete_archive_run_item(&conn, item.id, entry.id)?; + database::refresh_entry_cached_bytes(&conn, entry.id)?; + database::finish_archive_run(&conn, run.id)?; + + Ok(CaptureResult { + run_uid: run.run_uid.clone(), + status: "completed".to_string(), + completed_child_count: 0, + ublock_skipped: false, + cookie_ext_skipped: false, + }) +} + /// Result of a tweet re-archive operation. #[derive(Debug, serde::Serialize)] pub struct RearchiveResult { @@ -2628,6 +2812,325 @@ mod tests { ); } + #[test] + fn test_text_capture_markdown() { + let base_path = env::temp_dir().join(format!( + "archivr-text-test-{}", + Local::now().format("%Y%m%d%H%M%S%3f") + )); + let _ = fs::remove_dir_all(&base_path); + fs::create_dir_all(&base_path).unwrap(); + + let store_path = base_path.join("store"); + let archive_path = base_path.join(".archivr"); + + // Initialize archive structure + archive::initialize_store_directories(&store_path).unwrap(); + fs::create_dir_all(&archive_path).unwrap(); + fs::write(archive_path.join("name"), "test-archive").unwrap(); + fs::write( + archive_path.join("store_path"), + store_path.to_str().unwrap(), + ) + .unwrap(); + + let archive_paths = ArchivePaths { + archive_path: archive_path.clone(), + store_path: store_path.clone(), + name: "test-archive".to_string(), + }; + + let title = "My Markdown Note"; + let body = "# Heading\n\nSome **bold** text."; + let mime = "text/markdown"; + + let result = perform_text_capture(&archive_paths, title, body, mime, None).unwrap(); + + assert_eq!(result.status, "completed"); + assert_eq!(result.completed_child_count, 0); + assert!(!result.ublock_skipped); + assert!(!result.cookie_ext_skipped); + + // Verify entry was created + let conn = database::open_or_initialize(&archive_path).unwrap(); + let default_coll_id = database::ensure_default_collection(&conn).unwrap(); + let entries = + archive::list_entries_for_collection(&conn, default_coll_id, 0xFFFFFFFF).unwrap(); + assert_eq!(entries.len(), 1); + let entry = &entries[0]; + assert_eq!(entry.title, Some(title.to_string())); + assert_eq!(entry.source_kind, "text"); + assert_eq!(entry.entity_kind, "document"); + + // Clean up + let _ = fs::remove_dir_all(&base_path); + } + + #[test] + fn test_text_capture_plain() { + let base_path = env::temp_dir().join(format!( + "archivr-text-plain-test-{}", + Local::now().format("%Y%m%d%H%M%S%3f") + )); + let _ = fs::remove_dir_all(&base_path); + fs::create_dir_all(&base_path).unwrap(); + + let store_path = base_path.join("store"); + let archive_path = base_path.join(".archivr"); + + // Initialize archive structure + archive::initialize_store_directories(&store_path).unwrap(); + fs::create_dir_all(&archive_path).unwrap(); + fs::write(archive_path.join("name"), "test-archive").unwrap(); + fs::write( + archive_path.join("store_path"), + store_path.to_str().unwrap(), + ) + .unwrap(); + + let archive_paths = ArchivePaths { + archive_path: archive_path.clone(), + store_path: store_path.clone(), + name: "test-archive".to_string(), + }; + + let title = "Plain Text Note"; + let body = "Just plain text content."; + let mime = "text/plain"; + + let result = perform_text_capture(&archive_paths, title, body, mime, None).unwrap(); + + assert_eq!(result.status, "completed"); + + // Verify entry was created + let conn = database::open_or_initialize(&archive_path).unwrap(); + let default_coll_id = database::ensure_default_collection(&conn).unwrap(); + let entries = + archive::list_entries_for_collection(&conn, default_coll_id, 0xFFFFFFFF).unwrap(); + assert_eq!(entries.len(), 1); + let entry = &entries[0]; + assert_eq!(entry.title, Some(title.to_string())); + + // Clean up + let _ = fs::remove_dir_all(&base_path); + } + + #[test] + fn test_text_capture_preserves_intentional_whitespace_in_stored_artifact() { + let base_path = env::temp_dir().join(format!( + "archivr-text-whitespace-test-{}", + Local::now().format("%Y%m%d%H%M%S%3f") + )); + let _ = fs::remove_dir_all(&base_path); + fs::create_dir_all(&base_path).unwrap(); + + let store_path = base_path.join("store"); + let archive_path = base_path.join(".archivr"); + archive::initialize_store_directories(&store_path).unwrap(); + fs::create_dir_all(&archive_path).unwrap(); + fs::write(archive_path.join("name"), "test-archive").unwrap(); + fs::write(archive_path.join("store_path"), store_path.to_str().unwrap()).unwrap(); + + let archive_paths = ArchivePaths { + archive_path: archive_path.clone(), + store_path: store_path.clone(), + name: "test-archive".to_string(), + }; + let body = " \n# Heading\n\nContent with a final newline\n\t \n"; + + perform_text_capture( + &archive_paths, + "Whitespace Note", + body, + "text/markdown", + None, + ) + .unwrap(); + + let conn = database::open_or_initialize(&archive_path).unwrap(); + let raw_relpath: String = conn + .query_row( + "SELECT b.raw_relpath + FROM entry_artifacts ea + JOIN blobs b ON b.id = ea.blob_id + WHERE ea.artifact_role = 'primary_media'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(fs::read(store_path.join(raw_relpath)).unwrap(), body.as_bytes()); + + let _ = fs::remove_dir_all(&base_path); + } + + #[test] + fn test_text_capture_hides_synthetic_url_but_reuses_source_identity() { + let base_path = env::temp_dir().join(format!( + "archivr-text-identity-test-{}", + Local::now().format("%Y%m%d%H%M%S%3f") + )); + let _ = fs::remove_dir_all(&base_path); + fs::create_dir_all(&base_path).unwrap(); + + let store_path = base_path.join("store"); + let archive_path = base_path.join(".archivr"); + archive::initialize_store_directories(&store_path).unwrap(); + fs::create_dir_all(&archive_path).unwrap(); + fs::write(archive_path.join("name"), "test-archive").unwrap(); + fs::write(archive_path.join("store_path"), store_path.to_str().unwrap()).unwrap(); + + let archive_paths = ArchivePaths { + archive_path: archive_path.clone(), + store_path, + name: "test-archive".to_string(), + }; + let body = "Same body, same text identity."; + + perform_text_capture(&archive_paths, "First title", body, "text/plain", None).unwrap(); + perform_text_capture(&archive_paths, "Second title", body, "text/plain", None).unwrap(); + + let conn = database::open_or_initialize(&archive_path).unwrap(); + let default_coll_id = database::ensure_default_collection(&conn).unwrap(); + let entries = archive::list_entries_for_collection(&conn, default_coll_id, 0xFFFFFFFF).unwrap(); + assert_eq!(entries.len(), 2); + assert!(entries.iter().all(|entry| entry.original_url.is_none())); + + let expected_locator = format!("text:{}", crate::hash::hash_bytes(body.as_bytes())); + let (canonical_url, normalized_locator): (Option, String) = conn + .query_row( + "SELECT canonical_url, normalized_locator + FROM source_identities + WHERE source_kind = 'text' AND normalized_locator = ?1", + [&expected_locator], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + assert_eq!(canonical_url, None); + assert_eq!(normalized_locator, expected_locator); + + let source_identity_count: i64 = conn + .query_row( + "SELECT COUNT(*) FROM source_identities WHERE source_kind = 'text'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(source_identity_count, 1); + + let _ = fs::remove_dir_all(&base_path); + } + + #[test] + fn test_text_capture_rejects_empty_title() { + let base_path = env::temp_dir().join(format!( + "archivr-text-empty-title-test-{}", + Local::now().format("%Y%m%d%H%M%S%3f") + )); + let _ = fs::remove_dir_all(&base_path); + fs::create_dir_all(&base_path).unwrap(); + + let store_path = base_path.join("store"); + let archive_path = base_path.join(".archivr"); + archive::initialize_store_directories(&store_path).unwrap(); + fs::create_dir_all(&archive_path).unwrap(); + fs::write(archive_path.join("name"), "test-archive").unwrap(); + fs::write( + archive_path.join("store_path"), + store_path.to_str().unwrap(), + ) + .unwrap(); + + let archive_paths = ArchivePaths { + archive_path, + store_path, + name: "test-archive".to_string(), + }; + + let result = perform_text_capture(&archive_paths, "", "Some body", "text/plain", None); + assert!(result.is_err()); + assert!(result + .unwrap_err() + .to_string() + .contains("title must not be empty")); + + // Clean up + let _ = fs::remove_dir_all(&base_path); + } + + #[test] + fn test_text_capture_rejects_empty_body() { + let base_path = env::temp_dir().join(format!( + "archivr-text-empty-body-test-{}", + Local::now().format("%Y%m%d%H%M%S%3f") + )); + let _ = fs::remove_dir_all(&base_path); + fs::create_dir_all(&base_path).unwrap(); + + let store_path = base_path.join("store"); + let archive_path = base_path.join(".archivr"); + archive::initialize_store_directories(&store_path).unwrap(); + fs::create_dir_all(&archive_path).unwrap(); + fs::write(archive_path.join("name"), "test-archive").unwrap(); + fs::write( + archive_path.join("store_path"), + store_path.to_str().unwrap(), + ) + .unwrap(); + + let archive_paths = ArchivePaths { + archive_path, + store_path, + name: "test-archive".to_string(), + }; + + let result = perform_text_capture(&archive_paths, "Some Title", "", "text/plain", None); + assert!(result.is_err()); + assert!(result + .unwrap_err() + .to_string() + .contains("body must not be empty")); + + // Clean up + let _ = fs::remove_dir_all(&base_path); + } + + #[test] + fn test_text_capture_rejects_bad_mime() { + let base_path = env::temp_dir().join(format!( + "archivr-text-bad-mime-test-{}", + Local::now().format("%Y%m%d%H%M%S%3f") + )); + let _ = fs::remove_dir_all(&base_path); + fs::create_dir_all(&base_path).unwrap(); + + let store_path = base_path.join("store"); + let archive_path = base_path.join(".archivr"); + archive::initialize_store_directories(&store_path).unwrap(); + fs::create_dir_all(&archive_path).unwrap(); + fs::write(archive_path.join("name"), "test-archive").unwrap(); + fs::write( + archive_path.join("store_path"), + store_path.to_str().unwrap(), + ) + .unwrap(); + + let archive_paths = ArchivePaths { + archive_path, + store_path, + name: "test-archive".to_string(), + }; + + let result = perform_text_capture(&archive_paths, "Title", "Body", "text/html", None); + assert!(result.is_err()); + assert!(result + .unwrap_err() + .to_string() + .contains("unsupported MIME type")); + + // Clean up + let _ = fs::remove_dir_all(&base_path); + } + #[test] fn test_initialize_store_directories() { let store_path = env::temp_dir().join(format!( @@ -2648,12 +3151,15 @@ mod tests { #[test] fn test_record_tweet_entry_links_json_and_raw_artifacts() { - let store_path = env::temp_dir().join(format!( - "archivr-tweet-db-test-{}", - Local::now().format("%Y%m%d%H%M%S%3f") - )); - let _ = fs::remove_dir_all(&store_path); - archive::initialize_store_directories(&store_path).unwrap(); + let temp = tempfile::tempdir().unwrap(); + let archive_paths = archive::initialize_archive( + temp.path(), + &temp.path().join("store"), + "Tweet summary test", + false, + ) + .unwrap(); + let store_path = &archive_paths.store_path; fs::create_dir_all(store_path.join("raw").join("a").join("b")).unwrap(); fs::create_dir_all(store_path.join("raw").join("c").join("d")).unwrap(); fs::write( @@ -2670,21 +3176,21 @@ mod tests { .join("raw") .join("c") .join("d") - .join("cdef01.mp4"), + .join("cdef01.jpg"), b"media", ) .unwrap(); fs::write( store_path.join("raw_tweets").join("tweet-123.json"), r#"{ + "full_text": "Tweet body for summary selection.", "author": { "avatar_local_path": "raw/a/b/abcdef.jpg" }, - "entities": { "media": [{ "local_path": "raw/c/d/cdef01.mp4" }] } + "entities": { "media": [{ "local_path": "raw/c/d/cdef01.jpg" }] } }"#, ) .unwrap(); - let conn = rusqlite::Connection::open_in_memory().unwrap(); - database::initialize_schema(&conn).unwrap(); + let conn = database::open_or_initialize(&archive_paths.archive_path).unwrap(); let user_id = database::ensure_default_user(&conn).unwrap(); let run = database::create_archive_run(&conn, user_id, 1).unwrap(); let item = database::create_archive_run_item( @@ -2733,10 +3239,26 @@ mod tests { assert_eq!(artifact_count, 3); assert_eq!(blob_count, 2); + let media_mime: Option = conn + .query_row( + "SELECT b.mime_type FROM entry_artifacts ea JOIN blobs b ON b.id = ea.blob_id WHERE ea.entry_id = ?1 AND ea.artifact_role = 'media'", + [entry.id], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(media_mime.as_deref(), Some("image/jpeg")); + let summary_input = crate::summarizer::build_summary_input( + &archive_paths, + &entry.entry_uid, + crate::summarizer::SummaryBuildOptions { + include_images: true, + }, + ) + .unwrap(); + assert_eq!(summary_input.request.images.len(), 1); + assert_eq!(summary_input.request.images[0].mime_type, "image/jpeg"); assert_eq!(run_status, "completed"); assert!(store_path.join(&entry.structured_root_relpath).is_dir()); - - let _ = fs::remove_dir_all(store_path); } mod title_tests { diff --git a/crates/archivr-core/src/database.rs b/crates/archivr-core/src/database.rs index 95b4f26..31318e0 100644 --- a/crates/archivr-core/src/database.rs +++ b/crates/archivr-core/src/database.rs @@ -110,6 +110,30 @@ pub struct CaptureJobRecord { pub updated_at: String, } +/// One row of `entry_summaries` — a regenerable LLM summary of an entry. +/// +/// `provider_model` is stored as `''` (not NULL) when a provider has no explicit +/// model, because SQLite treats NULLs as distinct inside a UNIQUE index and a +/// NULL model would defeat the `(entry_id, provider_kind, provider_model, +/// prompt_version, input_sha256)` dedupe key. Readers map `''` back to `None`. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub struct EntrySummaryRecord { + pub summary_uid: String, + pub entry_uid: String, + pub provider_kind: String, + /// Model selected by the provider after resolving the requested cache-key alias. + pub resolved_model: Option, + pub provider_model: Option, + pub prompt_version: String, + pub input_sha256: String, + pub status: String, + pub summary_text: Option, + pub error_text: Option, + pub created_at: String, + pub updated_at: String, + pub completed_at: Option, +} + #[derive(Debug, Clone, serde::Serialize)] pub struct UserSummary { pub user_uid: String, @@ -322,6 +346,26 @@ pub fn initialize_schema(conn: &Connection) -> Result<()> { created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); + CREATE TABLE IF NOT EXISTS entry_summaries ( + id INTEGER PRIMARY KEY, + summary_uid TEXT NOT NULL UNIQUE, + entry_id INTEGER NOT NULL REFERENCES archived_entries(id) ON DELETE CASCADE, + provider_kind TEXT NOT NULL, + provider_model TEXT NOT NULL DEFAULT '', + resolved_model TEXT, + prompt_version TEXT NOT NULL, + input_sha256 TEXT NOT NULL, + status TEXT NOT NULL CHECK(status IN ('pending','running','completed','failed')), + summary_text TEXT, + error_text TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + completed_at TEXT + ); + CREATE INDEX IF NOT EXISTS idx_entry_summaries_entry_updated + ON entry_summaries(entry_id, updated_at DESC); + CREATE INDEX IF NOT EXISTS idx_entry_summaries_cache_lookup + ON entry_summaries(entry_id, provider_kind, provider_model, prompt_version, input_sha256, status); CREATE INDEX IF NOT EXISTS idx_capture_jobs_status ON capture_jobs(status); CREATE INDEX IF NOT EXISTS idx_archive_run_items_run_id ON archive_run_items(run_id); CREATE INDEX IF NOT EXISTS idx_archived_entries_source_identity_id ON archived_entries(source_identity_id); @@ -436,6 +480,12 @@ pub fn initialize_schema(conn: &Connection) -> Result<()> { // Migration: add notes_json column to existing capture_jobs tables. // Silently ignored when the column already exists (idempotent). let _ = conn.execute("ALTER TABLE capture_jobs ADD COLUMN notes_json TEXT", []); + // Provider responses may resolve a requested alias to a concrete model. + // Keep that display-only value outside the cache key. + let _ = conn.execute( + "ALTER TABLE entry_summaries ADD COLUMN resolved_model TEXT", + [], + ); // Migration: add requires_auth column to existing collections tables. // Silently ignored when the column already exists (idempotent). let _ = conn.execute( @@ -443,6 +493,54 @@ pub fn initialize_schema(conn: &Connection) -> Result<()> { [], ); + // Summary attempts used to be unique by cache key, which meant forced + // regeneration erased the last completed result. Rebuild that small table + // without the cache-key constraint while retaining all existing rows. + let summary_table_sql: Option = conn + .query_row( + "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'entry_summaries'", + [], + |row| row.get(0), + ) + .optional()?; + if summary_table_sql.as_deref().is_some_and(|sql| { + sql.contains( + "UNIQUE(entry_id, provider_kind, provider_model, prompt_version, input_sha256)", + ) + }) { + conn.execute_batch( + "BEGIN; + CREATE TABLE entry_summaries_rebuilt ( + id INTEGER PRIMARY KEY, + summary_uid TEXT NOT NULL UNIQUE, + entry_id INTEGER NOT NULL REFERENCES archived_entries(id) ON DELETE CASCADE, + provider_kind TEXT NOT NULL, + provider_model TEXT NOT NULL DEFAULT '', + resolved_model TEXT, + prompt_version TEXT NOT NULL, + input_sha256 TEXT NOT NULL, + status TEXT NOT NULL CHECK(status IN ('pending','running','completed','failed')), + summary_text TEXT, + error_text TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + completed_at TEXT + ); + INSERT INTO entry_summaries_rebuilt + SELECT id, summary_uid, entry_id, provider_kind, COALESCE(provider_model, ''), + resolved_model, prompt_version, input_sha256, status, summary_text, error_text, + created_at, updated_at, completed_at + FROM entry_summaries; + DROP TABLE entry_summaries; + ALTER TABLE entry_summaries_rebuilt RENAME TO entry_summaries; + CREATE INDEX idx_entry_summaries_entry_updated + ON entry_summaries(entry_id, updated_at DESC); + CREATE INDEX idx_entry_summaries_cache_lookup + ON entry_summaries(entry_id, provider_kind, provider_model, prompt_version, input_sha256, status); + COMMIT;", + )?; + } + Ok(()) } @@ -1354,6 +1452,265 @@ pub fn fail_stalled_capture_jobs(conn: &Connection) -> Result { Ok(n) } +/// Marks summary attempts left pending or running by a previous process as +/// failed. The message is deliberately stable and does not expose internals. +pub fn fail_stalled_entry_summaries(conn: &Connection) -> Result { + let now = now_timestamp(); + conn.execute( + "UPDATE entry_summaries + SET status = 'failed', + error_text = 'Summary generation was interrupted by a server restart.', + updated_at = ?1 + WHERE status IN ('pending', 'running')", + [now], + ) + .map_err(Into::into) +} + +// ── entry_summaries ──────────────────────────────────────────────────────── +// +// Summaries are a regenerable child record of an entry, never a column on +// `archived_entries`: an entry can carry several (one per provider/model/prompt +// version), and any of them can be thrown away and recomputed. Generation is +// manual-only — nothing in `capture.rs` writes here. + +/// `SELECT` list shared by every `entry_summaries` read, so all readers build +/// an identical `EntrySummaryRecord` from the same column ordering. +const ENTRY_SUMMARY_COLS: &str = + "SELECT s.summary_uid, e.entry_uid, s.provider_kind, s.provider_model, s.resolved_model, + s.prompt_version, s.input_sha256, s.status, s.summary_text, + s.error_text, s.created_at, s.updated_at, s.completed_at + FROM entry_summaries s + JOIN archived_entries e ON e.id = s.entry_id"; + +fn map_entry_summary(row: &rusqlite::Row<'_>) -> rusqlite::Result { + Ok(EntrySummaryRecord { + summary_uid: row.get(0)?, + entry_uid: row.get(1)?, + provider_kind: row.get(2)?, + // '' is the stored stand-in for "this provider has no model"; see the + // doc comment on EntrySummaryRecord for why it is not NULL. + provider_model: row.get::<_, Option>(3)?.filter(|m| !m.is_empty()), + resolved_model: row.get(4)?, + prompt_version: row.get(5)?, + input_sha256: row.get(6)?, + status: row.get(7)?, + summary_text: row.get(8)?, + error_text: row.get(9)?, + created_at: row.get(10)?, + updated_at: row.get(11)?, + completed_at: row.get(12)?, + }) +} + +/// Resolves `entry_uid` to its integer primary key. `Ok(None)` if absent. +pub fn entry_id_for_uid(conn: &Connection, entry_uid: &str) -> Result> { + conn.query_row( + "SELECT id FROM archived_entries WHERE entry_uid = ?1", + [entry_uid], + |row| row.get(0), + ) + .optional() + .map_err(Into::into) +} + +/// Creates a fresh pending summary attempt for one cache key. +/// +/// Attempts are intentionally not unique by cache key: a forced regeneration +/// must leave an older completed result available while the new attempt runs. +pub fn upsert_pending_entry_summary( + conn: &Connection, + entry_id: i64, + provider_kind: &str, + provider_model: Option<&str>, + prompt_version: &str, + input_sha256: &str, +) -> Result { + let summary_uid = format!("sum_{}", &Uuid::new_v4().simple().to_string()[..10]); + let now = now_timestamp(); + let model = provider_model.unwrap_or(""); + conn.execute( + "INSERT INTO entry_summaries + (summary_uid, entry_id, provider_kind, provider_model, prompt_version, + input_sha256, status, summary_text, error_text, created_at, updated_at, completed_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'pending', NULL, NULL, ?7, ?7, NULL)", + rusqlite::params![ + summary_uid, + entry_id, + provider_kind, + model, + prompt_version, + input_sha256, + now + ], + )?; + Ok(summary_uid) +} + +/// Completes a summary while retaining the provider's concrete response model +/// for display. The requested provider model remains the cache-key identity. +pub fn update_entry_summary_completed( + conn: &Connection, + summary_uid: &str, + summary_text: &str, + resolved_model: Option<&str>, +) -> Result<()> { + let now = now_timestamp(); + conn.execute( + "UPDATE entry_summaries + SET status = 'completed', summary_text = ?1, error_text = NULL, + resolved_model = ?2, completed_at = ?3, updated_at = ?3 + WHERE summary_uid = ?4", + rusqlite::params![summary_text, resolved_model, now, summary_uid], + )?; + Ok(()) +} + +/// Moves a summary row through `running` → `completed` / `failed`. +/// `completed_at` is stamped only on the terminal `completed` transition. +pub fn update_entry_summary_status( + conn: &Connection, + summary_uid: &str, + status: &str, + summary_text: Option<&str>, + error_text: Option<&str>, +) -> Result<()> { + let now = now_timestamp(); + let completed_at = if status == "completed" { + Some(now.clone()) + } else { + None + }; + conn.execute( + "UPDATE entry_summaries + SET status = ?1, summary_text = ?2, error_text = ?3, + completed_at = ?4, updated_at = ?5 + WHERE summary_uid = ?6", + rusqlite::params![ + status, + summary_text, + error_text, + completed_at, + now, + summary_uid + ], + )?; + Ok(()) +} + +/// Returns one summary by its public uid. +pub fn get_entry_summary_by_uid( + conn: &Connection, + summary_uid: &str, +) -> Result> { + conn.query_row( + &format!("{ENTRY_SUMMARY_COLS} WHERE s.summary_uid = ?1"), + [summary_uid], + map_entry_summary, + ) + .optional() + .map_err(Into::into) +} + +/// Looks up the row for one exact cache key — used to short-circuit a POST when +/// a completed summary for identical input already exists and `force` is false. +pub fn find_entry_summary( + conn: &Connection, + entry_id: i64, + provider_kind: &str, + provider_model: Option<&str>, + prompt_version: &str, + input_sha256: &str, +) -> Result> { + conn.query_row( + &format!( + "{ENTRY_SUMMARY_COLS} + WHERE s.entry_id = ?1 AND s.provider_kind = ?2 AND s.provider_model = ?3 + AND s.prompt_version = ?4 AND s.input_sha256 = ?5 + ORDER BY CASE WHEN s.status = 'completed' THEN 0 ELSE 1 END, + s.completed_at DESC, s.updated_at DESC, s.id DESC" + ), + rusqlite::params![ + entry_id, + provider_kind, + provider_model.unwrap_or(""), + prompt_version, + input_sha256 + ], + map_entry_summary, + ) + .optional() + .map_err(Into::into) +} + +/// Most recently touched summary for an entry, whatever its status. +/// Used where a caller explicitly needs the most recent attempt regardless of +/// whether it has completed. +pub fn latest_entry_summary( + conn: &Connection, + entry_id: i64, +) -> Result> { + conn.query_row( + &format!( + "{ENTRY_SUMMARY_COLS} WHERE s.entry_id = ?1 + ORDER BY s.updated_at DESC, s.id DESC LIMIT 1" + ), + [entry_id], + map_entry_summary, + ) + .optional() + .map_err(Into::into) +} + +/// The most recent completed summary, excluding in-flight and failed attempts. +/// This is the stable summary shown in entry detail and used by free-text search. +pub fn latest_completed_entry_summary( + conn: &Connection, + entry_id: i64, +) -> Result> { + conn.query_row( + &format!( + "{ENTRY_SUMMARY_COLS} WHERE s.entry_id = ?1 AND s.status = 'completed' + ORDER BY s.completed_at DESC, s.updated_at DESC, s.id DESC LIMIT 1" + ), + [entry_id], + map_entry_summary, + ) + .optional() + .map_err(Into::into) +} + +/// The newest non-completed replacement attempt after the retained completed +/// result. This includes failed rows so authenticated callers can show a recent +/// failure beside readable content, but suppresses historical failures after a +/// newer successful regeneration. +pub fn latest_entry_summary_attempt( + conn: &Connection, + entry_id: i64, +) -> Result> { + conn.query_row( + &format!( + "{ENTRY_SUMMARY_COLS} WHERE s.entry_id = ?1 AND s.status != 'completed' + AND ( + NOT EXISTS ( + SELECT 1 FROM entry_summaries c + WHERE c.entry_id = s.entry_id AND c.status = 'completed' + ) + OR (s.updated_at, s.id) > ( + SELECT c.updated_at, c.id FROM entry_summaries c + WHERE c.entry_id = s.entry_id AND c.status = 'completed' + ORDER BY c.completed_at DESC, c.updated_at DESC, c.id DESC LIMIT 1 + ) + ) + ORDER BY s.updated_at DESC, s.id DESC LIMIT 1" + ), + [entry_id], + map_entry_summary, + ) + .optional() + .map_err(Into::into) +} + pub fn create_archive_run( conn: &Connection, created_by_user_id: i64, @@ -1445,7 +1802,11 @@ pub fn finish_archive_run(conn: &Connection, run_id: i64) -> Result<()> { [run_id], |row| row.get(0), )?; - let status = if failed_count > 0 { "failed" } else { "completed" }; + let status = if failed_count > 0 { + "failed" + } else { + "completed" + }; conn.execute( "UPDATE archive_runs SET status = ?1, finished_at = ?2 WHERE id = ?3", params![status, now_timestamp(), run_id], @@ -1681,9 +2042,8 @@ pub fn delete_entry(conn: &Connection, entry_uid: &str) -> Result { // (no grandchildren), so without `id = ?1` the set would be empty and // cascade_cached_bytes_after_subtree_delete would not recalculate shared-blob totals. let subtree_ids: Vec = { - let mut stmt = conn.prepare( - "SELECT id FROM archived_entries WHERE id = ?1 OR root_entry_id = ?1", - )?; + let mut stmt = + conn.prepare("SELECT id FROM archived_entries WHERE id = ?1 OR root_entry_id = ?1")?; stmt.query_map([entry_id], |row| row.get(0))? .collect::>()? }; @@ -2334,7 +2694,6 @@ pub fn visibility_to_bits(visibility: &str) -> u32 { } } - /// Returns the id of the '_default_' collection, creating it if absent. pub fn ensure_default_collection(conn: &Connection) -> Result { let now = now_timestamp(); @@ -2437,16 +2796,20 @@ pub fn get_collection_by_slug(conn: &Connection, slug: &str) -> Result(4)? as u32, - created_at: row.get(5)?, - requires_auth: row.get::<_, i64>(6)? != 0, - }), - ).optional().map_err(Into::into) + |row| { + Ok(CollectionRecord { + id: row.get(0)?, + collection_uid: row.get(1)?, + name: row.get(2)?, + slug: row.get(3)?, + default_visibility_bits: row.get::<_, i64>(4)? as u32, + created_at: row.get(5)?, + requires_auth: row.get::<_, i64>(6)? != 0, + }) + }, + ) + .optional() + .map_err(Into::into) } /// Adds an entry to a collection with given visibility_bits. Idempotent (INSERT OR IGNORE). @@ -2505,7 +2868,12 @@ pub fn get_entry_collection_memberships( WHERE ce.entry_id = ?1", )?; stmt.query_map([entry_id], |row| { - Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get::<_, i64>(3)? as u32)) + Ok(( + row.get(0)?, + row.get(1)?, + row.get(2)?, + row.get::<_, i64>(3)? as u32, + )) })? .collect::>() .map_err(Into::into) @@ -3063,7 +3431,10 @@ mod tests { |row| row.get::<_, i64>(0).map(|v| v as u32), ) .unwrap(); - assert_eq!(default_bits, 2, "default collection should start USER-visible"); + assert_eq!( + default_bits, 2, + "default collection should start USER-visible" + ); // Create an entry with visibility = "private" (what capture always passes). let entry = create_entry_fixture(&conn, "private", None, None); @@ -3111,7 +3482,10 @@ mod tests { |row| row.get::<_, i64>(0).map(|v| v as u32), ) .unwrap(); - assert_eq!(public_bits, 3, "collection default=public should produce bits=3"); + assert_eq!( + public_bits, 3, + "collection default=public should produce bits=3" + ); // Child entries must NOT use the collection default — they keep // visibility_to_bits(entry.visibility) so parent-child visibility @@ -3124,7 +3498,10 @@ mod tests { |row| row.get::<_, i64>(0).map(|v| v as u32), ) .unwrap(); - assert_eq!(child_bits, 0, "child entries must use visibility_to_bits, not collection default"); + assert_eq!( + child_bits, 0, + "child entries must use visibility_to_bits, not collection default" + ); } #[test] @@ -4153,27 +4530,414 @@ mod tests { // Root item (parent_item_id IS NULL) — mirrors what record_container_entry does. let root_item = create_archive_run_item( - &c, run.id, None, 0, "https://example.com/pl", None, "youtube", "playlist", - ).unwrap(); + &c, + run.id, + None, + 0, + "https://example.com/pl", + None, + "youtube", + "playlist", + ) + .unwrap(); // Child item (parent_item_id IS NOT NULL). let child_item = create_archive_run_item( - &c, run.id, Some(root_item.id), 1, "https://example.com/v1", None, "youtube", "video", - ).unwrap(); + &c, + run.id, + Some(root_item.id), + 1, + "https://example.com/v1", + None, + "youtube", + "video", + ) + .unwrap(); // Complete both — marks archive_runs.completed_count = 2. c.execute( "UPDATE archive_run_items SET status = 'completed' WHERE id IN (?1, ?2)", rusqlite::params![root_item.id, child_item.id], - ).unwrap(); + ) + .unwrap(); refresh_run_counters(&c, run.id).unwrap(); - let total: i64 = c.query_row( - "SELECT completed_count FROM archive_runs WHERE id = ?1", [run.id], |r| r.get(0), - ).unwrap(); + let total: i64 = c + .query_row( + "SELECT completed_count FROM archive_runs WHERE id = ?1", + [run.id], + |r| r.get(0), + ) + .unwrap(); assert_eq!(total, 2, "both items completed: DB counter must be 2"); let child_count = get_run_completed_child_count(&c, run.id).unwrap(); assert_eq!(child_count, 1, "only the child item must be counted"); } + // ── entry_summaries ──────────────────────────────────────────────────── + + #[test] + fn initialize_schema_is_idempotent_for_entry_summaries() { + // initialize_schema runs on *every* open_or_initialize, so re-running it + // against a populated DB must be a no-op, not an error. + let c = conn(); + let entry = create_entry_fixture(&c, "private", None, None); + upsert_pending_entry_summary(&c, entry.id, "claude_cli", None, "v1", "abc").unwrap(); + + initialize_schema(&c).unwrap(); + initialize_schema(&c).unwrap(); + + let exists: i64 = c + .query_row( + "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='entry_summaries'", + [], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(exists, 1); + assert!(latest_entry_summary(&c, entry.id).unwrap().is_some()); + } + + #[test] + fn initialize_schema_migrates_resolved_model_for_existing_summary_table() { + let c = Connection::open_in_memory().unwrap(); + c.execute_batch( + "CREATE TABLE entry_summaries ( + id INTEGER PRIMARY KEY, + summary_uid TEXT NOT NULL UNIQUE, + entry_id INTEGER NOT NULL, + provider_kind TEXT NOT NULL, + provider_model TEXT, + prompt_version TEXT NOT NULL, + input_sha256 TEXT NOT NULL, + status TEXT NOT NULL, + summary_text TEXT, + error_text TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + completed_at TEXT, + UNIQUE(entry_id, provider_kind, provider_model, prompt_version, input_sha256) + );", + ) + .unwrap(); + + initialize_schema(&c).unwrap(); + + let has_resolved_model: i64 = c + .query_row( + "SELECT COUNT(*) FROM pragma_table_info('entry_summaries') WHERE name = 'resolved_model'", + [], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(has_resolved_model, 1); + } + + #[test] + fn entry_summary_lifecycle_pending_running_completed() { + let c = conn(); + let entry = create_entry_fixture(&c, "private", None, None); + let uid = + upsert_pending_entry_summary(&c, entry.id, "anthropic_http", Some("m1"), "v1", "sha1") + .unwrap(); + assert!(uid.starts_with("sum_"), "got {uid}"); + assert_eq!(uid.len(), "sum_".len() + 10); + + let rec = get_entry_summary_by_uid(&c, &uid).unwrap().unwrap(); + assert_eq!(rec.status, "pending"); + assert_eq!(rec.entry_uid, entry.entry_uid); + assert_eq!(rec.provider_model.as_deref(), Some("m1")); + assert!(rec.completed_at.is_none()); + + update_entry_summary_status(&c, &uid, "running", None, None).unwrap(); + assert_eq!( + get_entry_summary_by_uid(&c, &uid).unwrap().unwrap().status, + "running" + ); + + update_entry_summary_status(&c, &uid, "completed", Some("{\"summary\":\"s\"}"), None) + .unwrap(); + let rec = get_entry_summary_by_uid(&c, &uid).unwrap().unwrap(); + assert_eq!(rec.status, "completed"); + assert_eq!(rec.summary_text.as_deref(), Some("{\"summary\":\"s\"}")); + assert!(rec.completed_at.is_some(), "completed rows must be stamped"); + } + + #[test] + fn entry_summary_keeps_requested_model_for_cache_and_resolved_model_for_display() { + let c = conn(); + let entry = create_entry_fixture(&c, "private", None, None); + let uid = upsert_pending_entry_summary( + &c, + entry.id, + "anthropic_http", + Some("claude-3-5-sonnet-latest"), + "v1", + "sha1", + ) + .unwrap(); + + update_entry_summary_completed(&c, &uid, "summary", Some("claude-3-5-sonnet-20241022")) + .unwrap(); + let rec = get_entry_summary_by_uid(&c, &uid).unwrap().unwrap(); + + assert_eq!( + rec.provider_model.as_deref(), + Some("claude-3-5-sonnet-latest") + ); + assert_eq!( + rec.resolved_model.as_deref(), + Some("claude-3-5-sonnet-20241022") + ); + assert_eq!( + find_entry_summary( + &c, + entry.id, + "anthropic_http", + Some("claude-3-5-sonnet-latest"), + "v1", + "sha1", + ) + .unwrap() + .unwrap() + .summary_uid, + uid, + ); + } + + #[test] + fn entry_summary_failure_records_error_and_no_completed_at() { + let c = conn(); + let entry = create_entry_fixture(&c, "private", None, None); + let uid = upsert_pending_entry_summary(&c, entry.id, "codex_cli", None, "v1", "s").unwrap(); + update_entry_summary_status(&c, &uid, "failed", None, Some("boom")).unwrap(); + let rec = get_entry_summary_by_uid(&c, &uid).unwrap().unwrap(); + assert_eq!(rec.status, "failed"); + assert_eq!(rec.error_text.as_deref(), Some("boom")); + assert!(rec.completed_at.is_none()); + } + + #[test] + fn regenerating_a_completed_summary_creates_a_new_attempt_and_preserves_completion() { + let c = conn(); + let entry = create_entry_fixture(&c, "private", None, None); + let first = + upsert_pending_entry_summary(&c, entry.id, "claude_cli", None, "v1", "sha").unwrap(); + update_entry_summary_status(&c, &first, "completed", Some("old"), None).unwrap(); + + // Regeneration must retain the finished result while a new attempt runs. + let second = + upsert_pending_entry_summary(&c, entry.id, "claude_cli", None, "v1", "sha").unwrap(); + assert_ne!(first, second, "regeneration needs a distinct attempt uid"); + + let n: i64 = c + .query_row("SELECT COUNT(*) FROM entry_summaries", [], |r| r.get(0)) + .unwrap(); + assert_eq!(n, 2); + + let completed = get_entry_summary_by_uid(&c, &first).unwrap().unwrap(); + assert_eq!(completed.status, "completed"); + assert_eq!(completed.summary_text.as_deref(), Some("old")); + let rec = get_entry_summary_by_uid(&c, &second).unwrap().unwrap(); + assert_eq!(rec.status, "pending"); + update_entry_summary_status(&c, &second, "failed", None, Some("boom")).unwrap(); + assert_eq!( + latest_completed_entry_summary(&c, entry.id) + .unwrap() + .unwrap() + .summary_uid, + first, + "a failed regeneration must not replace the previous completed result" + ); + } + + #[test] + fn latest_summary_attempt_is_separate_from_the_retained_completed_summary() { + let c = conn(); + let entry = create_entry_fixture(&c, "private", None, None); + let completed = + upsert_pending_entry_summary(&c, entry.id, "claude_cli", None, "v1", "old").unwrap(); + update_entry_summary_status(&c, &completed, "completed", Some("previous"), None).unwrap(); + let pending = + upsert_pending_entry_summary(&c, entry.id, "claude_cli", None, "v1", "new").unwrap(); + + assert_eq!( + latest_completed_entry_summary(&c, entry.id).unwrap().unwrap().summary_uid, + completed + ); + assert_eq!( + latest_entry_summary_attempt(&c, entry.id).unwrap().unwrap().summary_uid, + pending + ); + + update_entry_summary_status(&c, &pending, "failed", None, Some("boom")).unwrap(); + assert_eq!( + latest_completed_entry_summary(&c, entry.id).unwrap().unwrap().summary_text.as_deref(), + Some("previous") + ); + assert_eq!( + latest_entry_summary_attempt(&c, entry.id).unwrap().unwrap().status, + "failed" + ); + + let successful_replacement = + upsert_pending_entry_summary(&c, entry.id, "claude_cli", None, "v1", "newer").unwrap(); + update_entry_summary_status( + &c, + &successful_replacement, + "completed", + Some("replacement"), + None, + ) + .unwrap(); + assert_eq!( + latest_completed_entry_summary(&c, entry.id) + .unwrap() + .unwrap() + .summary_uid, + successful_replacement + ); + assert!( + latest_entry_summary_attempt(&c, entry.id).unwrap().is_none(), + "a failed attempt predating a successful replacement must not remain visible" + ); + } + + #[test] + fn fail_stalled_entry_summaries_marks_pending_and_running_with_restart_message() { + let c = conn(); + let entry = create_entry_fixture(&c, "private", None, None); + let pending = + upsert_pending_entry_summary(&c, entry.id, "claude_cli", None, "v1", "a").unwrap(); + let running = + upsert_pending_entry_summary(&c, entry.id, "codex_cli", None, "v1", "b").unwrap(); + let completed = + upsert_pending_entry_summary(&c, entry.id, "anthropic_http", None, "v1", "c").unwrap(); + update_entry_summary_status(&c, &running, "running", None, None).unwrap(); + update_entry_summary_status(&c, &completed, "completed", Some("done"), None).unwrap(); + + assert_eq!(fail_stalled_entry_summaries(&c).unwrap(), 2); + for uid in [&pending, &running] { + let row = get_entry_summary_by_uid(&c, uid).unwrap().unwrap(); + assert_eq!(row.status, "failed"); + assert_eq!( + row.error_text.as_deref(), + Some("Summary generation was interrupted by a server restart.") + ); + assert!(!row.updated_at.is_empty()); + } + assert_eq!( + get_entry_summary_by_uid(&c, &completed) + .unwrap() + .unwrap() + .status, + "completed" + ); + } + + #[test] + fn entry_summaries_with_no_model_preserve_none_across_attempts() { + // CLI providers have no explicit model, so the stored empty-string + // sentinel must always map back to None even when attempts accumulate. + let c = conn(); + let entry = create_entry_fixture(&c, "private", None, None); + upsert_pending_entry_summary(&c, entry.id, "claude_cli", None, "v1", "sha").unwrap(); + upsert_pending_entry_summary(&c, entry.id, "claude_cli", None, "v1", "sha").unwrap(); + let n: i64 = c + .query_row("SELECT COUNT(*) FROM entry_summaries", [], |r| r.get(0)) + .unwrap(); + assert_eq!(n, 2); + // …and it reads back as None, not as an empty-string model. + let rec = latest_entry_summary(&c, entry.id).unwrap().unwrap(); + assert_eq!(rec.provider_model, None); + } + + #[test] + fn different_cache_keys_produce_separate_summaries() { + let c = conn(); + let entry = create_entry_fixture(&c, "private", None, None); + upsert_pending_entry_summary(&c, entry.id, "claude_cli", None, "v1", "sha").unwrap(); + upsert_pending_entry_summary(&c, entry.id, "codex_cli", None, "v1", "sha").unwrap(); + upsert_pending_entry_summary(&c, entry.id, "claude_cli", None, "v2", "sha").unwrap(); + upsert_pending_entry_summary(&c, entry.id, "claude_cli", None, "v1", "other").unwrap(); + let n: i64 = c + .query_row("SELECT COUNT(*) FROM entry_summaries", [], |r| r.get(0)) + .unwrap(); + assert_eq!(n, 4); + } + + #[test] + fn find_entry_summary_matches_only_the_exact_cache_key() { + let c = conn(); + let entry = create_entry_fixture(&c, "private", None, None); + let uid = + upsert_pending_entry_summary(&c, entry.id, "openai_compatible", Some("gpt"), "v1", "s") + .unwrap(); + let hit = find_entry_summary(&c, entry.id, "openai_compatible", Some("gpt"), "v1", "s") + .unwrap() + .unwrap(); + assert_eq!(hit.summary_uid, uid); + assert!( + find_entry_summary( + &c, + entry.id, + "openai_compatible", + Some("gpt"), + "v1", + "changed" + ) + .unwrap() + .is_none(), + "a changed input digest must miss the cache" + ); + } + + #[test] + fn latest_entry_summary_returns_the_most_recently_updated_row() { + let c = conn(); + let entry = create_entry_fixture(&c, "private", None, None); + let a = upsert_pending_entry_summary(&c, entry.id, "claude_cli", None, "v1", "a").unwrap(); + let b = upsert_pending_entry_summary(&c, entry.id, "codex_cli", None, "v1", "b").unwrap(); + update_entry_summary_status(&c, &a, "completed", Some("first"), None).unwrap(); + update_entry_summary_status(&c, &b, "completed", Some("second"), None).unwrap(); + // Same-timestamp ties break on id DESC, so the later insert wins either way. + assert_eq!( + latest_entry_summary(&c, entry.id) + .unwrap() + .unwrap() + .summary_uid, + b + ); + } + + #[test] + fn latest_entry_summary_is_none_for_an_unsummarized_entry() { + let c = conn(); + let entry = create_entry_fixture(&c, "private", None, None); + assert!(latest_entry_summary(&c, entry.id).unwrap().is_none()); + } + + #[test] + fn deleting_an_entry_cascades_to_its_summaries() { + let c = conn(); + c.pragma_update(None, "foreign_keys", "ON").unwrap(); + let entry = create_entry_fixture(&c, "private", None, None); + upsert_pending_entry_summary(&c, entry.id, "claude_cli", None, "v1", "a").unwrap(); + assert!(delete_entry(&c, &entry.entry_uid).unwrap()); + let n: i64 = c + .query_row("SELECT COUNT(*) FROM entry_summaries", [], |r| r.get(0)) + .unwrap(); + assert_eq!(n, 0); + } + + #[test] + fn entry_id_for_uid_resolves_and_misses() { + let c = conn(); + let entry = create_entry_fixture(&c, "private", None, None); + assert_eq!( + entry_id_for_uid(&c, &entry.entry_uid).unwrap(), + Some(entry.id) + ); + assert_eq!(entry_id_for_uid(&c, "ent_nope").unwrap(), None); + } } diff --git a/crates/archivr-core/src/downloader/mod.rs b/crates/archivr-core/src/downloader/mod.rs index c16474a..c170793 100644 --- a/crates/archivr-core/src/downloader/mod.rs +++ b/crates/archivr-core/src/downloader/mod.rs @@ -7,3 +7,4 @@ pub mod metadata; pub mod http; pub mod singlefile; pub mod font_extractor; +pub mod text; diff --git a/crates/archivr-core/src/downloader/text.rs b/crates/archivr-core/src/downloader/text.rs new file mode 100644 index 0000000..6f24d80 --- /dev/null +++ b/crates/archivr-core/src/downloader/text.rs @@ -0,0 +1,118 @@ +use anyhow::{bail, Result}; +use std::path::{Path, PathBuf}; + +use crate::hash::hash_bytes; + +/// Represents a staged text file ready to be moved into the raw store. +#[derive(Debug)] +pub struct StagedText { + pub staged_path: PathBuf, + pub hash: String, + pub extension: String, + pub byte_size: u64, +} + +/// Stages a text body (plain or Markdown) in the temp directory and computes its hash. +/// +/// # Arguments +/// * `body` - The raw bytes of the text content +/// * `mime` - MIME type, must be "text/plain" or "text/markdown" +/// * `store_path` - Root store path where temp/ subdirectory will be created +/// * `timestamp` - Timestamp string used in the staged file name +/// +/// # Returns +/// * `StagedText` with the staged path, hash, extension, and byte size +/// +/// # Errors +/// * Rejects MIME types other than "text/plain" or "text/markdown" +/// * IO errors during directory creation or file writing +pub fn save(body: &[u8], mime: &str, store_path: &Path, timestamp: &str) -> Result { + // Validate MIME type + let extension = match mime { + "text/markdown" => ".md", + "text/plain" => ".txt", + _ => bail!("unsupported MIME type: {mime}. Must be 'text/plain' or 'text/markdown'"), + }; + + // Create temp directory + let temp_dir = store_path.join("temp").join(timestamp); + std::fs::create_dir_all(&temp_dir)?; + + // Stage under temp// + let staged_path = temp_dir.join(format!("{timestamp}{extension}")); + + // Write the content + std::fs::write(&staged_path, body)?; + + // Compute SHA3 hash + let hash = hash_bytes(body); + let byte_size = body.len() as u64; + let extension_str = extension.trim_start_matches('.').to_string(); + + Ok(StagedText { + staged_path, + hash, + extension: extension_str, + byte_size, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::TempDir; + + #[test] + fn test_save_markdown() { + let temp_dir = TempDir::new().unwrap(); + let store_path = temp_dir.path(); + let content = b"# Hello\n\nThis is markdown."; + let mime = "text/markdown"; + + let result = save(content, mime, store_path, "2024-01-01T12-00-00.000-abc123").unwrap(); + + assert_eq!(result.extension, "md"); + assert_eq!(result.byte_size, content.len() as u64); + assert!(result.staged_path.exists()); + assert_eq!(std::fs::read(&result.staged_path).unwrap(), content); + } + + #[test] + fn test_save_plain_text() { + let temp_dir = TempDir::new().unwrap(); + let store_path = temp_dir.path(); + let content = b"Plain text content"; + let mime = "text/plain"; + + let result = save(content, mime, store_path, "2024-01-01T12-00-00.000-abc123").unwrap(); + + assert_eq!(result.extension, "txt"); + assert_eq!(result.byte_size, content.len() as u64); + assert!(result.staged_path.exists()); + } + + #[test] + fn test_save_rejects_unsupported_mime() { + let temp_dir = TempDir::new().unwrap(); + let store_path = temp_dir.path(); + let content = b"test"; + + let result = save(content, "text/html", store_path, "2024-01-01T12-00-00.000-abc123"); + assert!(result.is_err()); + assert!(result.unwrap_err().to_string().contains("unsupported MIME type")); + } + + #[test] + fn test_save_hash_is_consistent() { + let temp_dir = TempDir::new().unwrap(); + let store_path = temp_dir.path(); + let content = b"archivr text"; + + let result1 = save(content, "text/plain", store_path, "2024-01-01T12-00-00.000-abc123").unwrap(); + + let temp_dir2 = TempDir::new().unwrap(); + let result2 = save(content, "text/plain", temp_dir2.path(), "2024-01-01T12-00-01.000-def456").unwrap(); + + assert_eq!(result1.hash, result2.hash); + } +} diff --git a/crates/archivr-core/src/downloader/ytdlp.rs b/crates/archivr-core/src/downloader/ytdlp.rs index 26c091d..12de8a4 100644 --- a/crates/archivr-core/src/downloader/ytdlp.rs +++ b/crates/archivr-core/src/downloader/ytdlp.rs @@ -4,6 +4,7 @@ use std::{ env, path::{Path, PathBuf}, process::Command, + sync::OnceLock, }; use uuid::Uuid; use serde_json; @@ -11,6 +12,112 @@ use serde_json; use crate::downloader::cookies::{domain_from_url, write_netscape_cookie_file}; use crate::hash::hash_file; +/// Env var that force-pins a specific yt-dlp binary, bypassing version comparison. +pub const YT_DLP_FORCE_ENV: &str = "ARCHIVR_YT_DLP_FORCE"; +/// Env var set by the nix flake wrapper, pointing at the pinned yt-dlp. +pub const YT_DLP_ENV: &str = "ARCHIVR_YT_DLP"; +/// Override for the mutable state directory (used by `archivr yt-dlp` and tests). +pub const STATE_DIR_ENV: &str = "ARCHIVR_STATE_DIR"; + +static RESOLVED_YT_DLP: OnceLock = OnceLock::new(); + +/// Mutable per-user state directory for archivr. +/// +/// `ARCHIVR_STATE_DIR` wins if set. Otherwise this mirrors what `dirs::state_dir()` +/// would give us without taking on the dependency: `~/Library/Application Support` +/// on macOS, `$XDG_STATE_HOME` (default `~/.local/state`) elsewhere. +pub fn state_dir() -> Option { + if let Some(dir) = env::var_os(STATE_DIR_ENV) { + if !dir.is_empty() { + return Some(PathBuf::from(dir)); + } + } + + let home = PathBuf::from(env::var_os("HOME").filter(|h| !h.is_empty())?); + + if cfg!(target_os = "macos") { + Some(home.join("Library").join("Application Support").join("archivr")) + } else { + let base = env::var_os("XDG_STATE_HOME") + .filter(|d| !d.is_empty()) + .map(PathBuf::from) + .unwrap_or_else(|| home.join(".local").join("state")); + Some(base.join("archivr")) + } +} + +/// Path of the user-installed (self-updated) yt-dlp inside the state dir. +pub fn state_dir_yt_dlp() -> Option { + state_dir().map(|d| d.join("yt-dlp").join("yt-dlp")) +} + +/// The explicit yt-dlp override, if it points to a file on disk. +pub fn forced_yt_dlp() -> Option { + let p = PathBuf::from(env::var_os(YT_DLP_FORCE_ENV).filter(|v| !v.is_empty())?); + p.is_file().then_some(p) +} + +/// The nix-pinned yt-dlp advertised via `ARCHIVR_YT_DLP`, if it exists on disk. +pub fn pinned_yt_dlp() -> Option { + let p = PathBuf::from(env::var_os(YT_DLP_ENV).filter(|v| !v.is_empty())?); + p.is_file().then_some(p) +} + +/// Runs ` --version` and returns the trimmed stdout. +/// +/// yt-dlp versions are `YYYY.MM.DD`, so plain string ordering is chronological +/// ordering — no semver parsing needed. +pub fn probe_version(binary: &Path) -> Option { + let out = Command::new(binary).arg("--version").output().ok()?; + if !out.status.success() { + return None; + } + let version = String::from_utf8_lossy(&out.stdout).trim().to_string(); + (!version.is_empty()).then_some(version) +} + +/// The candidate yt-dlp binaries, in priority order for tie-breaking +/// (later entries win ties, so the deliberately-installed state-dir copy is last). +pub fn yt_dlp_candidates() -> Vec<(&'static str, PathBuf)> { + let mut candidates = Vec::new(); + if let Some(p) = pinned_yt_dlp() { + candidates.push(("env (ARCHIVR_YT_DLP)", p)); + } + if let Some(p) = state_dir_yt_dlp() { + if p.is_file() { + candidates.push(("state-dir", p)); + } + } + candidates +} + +/// Picks the yt-dlp binary to run, without consulting the process-wide cache. +/// +/// Priority: `ARCHIVR_YT_DLP_FORCE` > newest of (pinned, state-dir) by version +/// string > bare `yt-dlp` (PATH lookup, the historical behaviour). +pub fn resolve_yt_dlp_uncached() -> PathBuf { + if let Some(forced) = forced_yt_dlp() { + return forced; + } + + yt_dlp_candidates() + .into_iter() + .filter_map(|(_, path)| probe_version(&path).map(|v| (v, path))) + // `max_by` keeps the *last* maximum, and the state-dir candidate is last, + // so an exact version tie resolves in favour of the user's own install. + .max_by(|(a, _), (b, _)| a.cmp(b)) + .map(|(_, path)| path) + .unwrap_or_else(|| PathBuf::from("yt-dlp")) +} + +/// Cached [`resolve_yt_dlp_uncached`] — `--version` is spawned at most once +/// per process no matter how many yt-dlp calls the run makes. +pub fn resolve_yt_dlp() -> PathBuf { + RESOLVED_YT_DLP + .get_or_init(resolve_yt_dlp_uncached) + .clone() +} + /// A single item in a flat playlist listing from `fetch_playlist_info`. #[derive(Debug)] pub struct PlaylistItem { @@ -164,7 +271,7 @@ pub fn download( ) -> Result<(String, String)> { println!("Downloading with yt-dlp: {path}"); - let ytdlp = env::var("ARCHIVR_YT_DLP").unwrap_or_else(|_| "yt-dlp".to_string()); + let ytdlp = resolve_yt_dlp(); let is_audio = quality == Some("audio"); let temp_dir = store_path.join("temp").join(timestamp); @@ -207,7 +314,7 @@ pub fn download( .arg("-o") .arg(&out_template) .output() - .with_context(|| format!("failed to spawn {ytdlp} process")); + .with_context(|| format!("failed to spawn {} process", ytdlp.display())); // Remove cookie file immediately regardless of outcome. if let Some(cf) = &cookie_file { @@ -253,7 +360,7 @@ fn find_downloaded_file(temp_dir: &Path, timestamp: &str) -> Result { /// On failure (non-zero exit or no stdout), prints the captured stderr /// to stderr (for debugging) then returns `None` so callers can proceed. pub fn fetch_metadata(path: &str, cookies: &HashMap) -> Option { - let ytdlp = std::env::var("ARCHIVR_YT_DLP").unwrap_or_else(|_| "yt-dlp".to_string()); + let ytdlp = resolve_yt_dlp(); // Write a temp cookie file if needed; UUID-named to avoid collisions. let cookie_file: Option = if !cookies.is_empty() { @@ -342,7 +449,7 @@ fn normalize_item_url( /// Returns an error if yt-dlp fails, the output is not valid JSON, or /// the root `_type` is not `"playlist"`. pub fn fetch_playlist_info(url: &str, cookies: &HashMap) -> Result { - let ytdlp = std::env::var("ARCHIVR_YT_DLP").unwrap_or_else(|_| "yt-dlp".to_string()); + let ytdlp = resolve_yt_dlp(); let cookie_file: Option = if !cookies.is_empty() { let domain = domain_from_url(url); @@ -366,7 +473,7 @@ pub fn fetch_playlist_info(url: &str, cookies: &HashMap) -> Resu if let Some(cf) = &cookie_file { let _ = std::fs::remove_file(cf); } - let out = out.with_context(|| format!("failed to spawn {ytdlp}"))?; + let out = out.with_context(|| format!("failed to spawn {}", ytdlp.display()))?; if !out.status.success() { let stderr = String::from_utf8_lossy(&out.stderr); bail!("yt-dlp -J --flat-playlist failed for {url}: {stderr}"); @@ -425,7 +532,7 @@ pub fn probe_playlist_qualities( url: &str, cookies: &HashMap, ) -> Result { - let ytdlp = std::env::var("ARCHIVR_YT_DLP").unwrap_or_else(|_| "yt-dlp".to_string()); + let ytdlp = resolve_yt_dlp(); let cookie_file: Option = if !cookies.is_empty() { let domain = domain_from_url(url); @@ -449,7 +556,7 @@ pub fn probe_playlist_qualities( if let Some(cf) = &cookie_file { let _ = std::fs::remove_file(cf); } - let out = out.with_context(|| format!("failed to spawn {ytdlp}"))?; + let out = out.with_context(|| format!("failed to spawn {}", ytdlp.display()))?; if !out.status.success() { let stderr = String::from_utf8_lossy(&out.stderr); bail!("yt-dlp -J failed for {url}: {stderr}"); @@ -501,7 +608,131 @@ pub fn probe_playlist_qualities( #[cfg(test)] mod tests { - use super::{available_video_heights, has_audio_track, quality_format}; + use super::{ + available_video_heights, has_audio_track, quality_format, resolve_yt_dlp_uncached, + state_dir, STATE_DIR_ENV, YT_DLP_ENV, YT_DLP_FORCE_ENV, + }; + use std::path::{Path, PathBuf}; + use std::sync::{Mutex, MutexGuard}; + + /// Env vars are process-global, so resolver tests take turns. + static ENV_LOCK: Mutex<()> = Mutex::new(()); + + /// Clears every env var the resolver reads and hands back the serialising guard. + fn env_guard() -> MutexGuard<'static, ()> { + let guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + for key in [YT_DLP_FORCE_ENV, YT_DLP_ENV, STATE_DIR_ENV] { + unsafe { std::env::remove_var(key) }; + } + guard + } + + /// Writes an executable stub that reports `version` when asked for `--version`. + fn fake_yt_dlp(path: &Path, version: &str) { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, format!("#!/bin/sh\necho {version}\n")).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + } + + #[test] + fn resolve_yt_dlp_prefers_state_dir_when_newer() { + let _guard = env_guard(); + let tmp = tempfile::tempdir().unwrap(); + + let pinned = tmp.path().join("nix/yt-dlp"); + fake_yt_dlp(&pinned, "2026.08.19"); + + let state = tmp.path().join("state"); + fake_yt_dlp(&state.join("yt-dlp/yt-dlp"), "2026.09.01"); + + unsafe { + std::env::set_var(YT_DLP_ENV, &pinned); + std::env::set_var(STATE_DIR_ENV, &state); + } + + assert_eq!(resolve_yt_dlp_uncached(), state.join("yt-dlp/yt-dlp")); + } + + #[test] + fn resolve_yt_dlp_prefers_pinned_when_newer() { + let _guard = env_guard(); + let tmp = tempfile::tempdir().unwrap(); + + let pinned = tmp.path().join("nix/yt-dlp"); + fake_yt_dlp(&pinned, "2026.09.15"); + + let state = tmp.path().join("state"); + fake_yt_dlp(&state.join("yt-dlp/yt-dlp"), "2026.08.19"); + + unsafe { + std::env::set_var(YT_DLP_ENV, &pinned); + std::env::set_var(STATE_DIR_ENV, &state); + } + + assert_eq!(resolve_yt_dlp_uncached(), pinned); + } + + #[test] + fn resolve_yt_dlp_breaks_version_ties_toward_state_dir() { + let _guard = env_guard(); + let tmp = tempfile::tempdir().unwrap(); + + let pinned = tmp.path().join("nix/yt-dlp"); + fake_yt_dlp(&pinned, "2026.09.01"); + + let state = tmp.path().join("state"); + fake_yt_dlp(&state.join("yt-dlp/yt-dlp"), "2026.09.01"); + + unsafe { + std::env::set_var(YT_DLP_ENV, &pinned); + std::env::set_var(STATE_DIR_ENV, &state); + } + + assert_eq!(resolve_yt_dlp_uncached(), state.join("yt-dlp/yt-dlp")); + } + + #[test] + fn resolve_yt_dlp_honours_force_override_regardless_of_version() { + let _guard = env_guard(); + let tmp = tempfile::tempdir().unwrap(); + + let forced = tmp.path().join("forced/yt-dlp"); + fake_yt_dlp(&forced, "2020.01.01"); + + let state = tmp.path().join("state"); + fake_yt_dlp(&state.join("yt-dlp/yt-dlp"), "2026.09.01"); + + unsafe { + std::env::set_var(YT_DLP_FORCE_ENV, &forced); + std::env::set_var(STATE_DIR_ENV, &state); + } + + assert_eq!(resolve_yt_dlp_uncached(), forced); + } + + #[test] + fn resolve_yt_dlp_falls_back_to_bare_when_no_candidate_exists() { + let _guard = env_guard(); + let tmp = tempfile::tempdir().unwrap(); + + unsafe { + std::env::set_var(YT_DLP_ENV, tmp.path().join("missing/yt-dlp")); + std::env::set_var(STATE_DIR_ENV, tmp.path().join("empty-state")); + } + + assert_eq!(resolve_yt_dlp_uncached(), PathBuf::from("yt-dlp")); + } + + #[test] + fn state_dir_override_wins_over_platform_default() { + let _guard = env_guard(); + unsafe { std::env::set_var(STATE_DIR_ENV, "/tmp/archivr-state-override") }; + assert_eq!(state_dir(), Some(PathBuf::from("/tmp/archivr-state-override"))); + } #[test] fn quality_format_audio() { diff --git a/crates/archivr-core/src/lib.rs b/crates/archivr-core/src/lib.rs index cd97ffb..907f9e6 100644 --- a/crates/archivr-core/src/lib.rs +++ b/crates/archivr-core/src/lib.rs @@ -4,3 +4,4 @@ pub mod database; pub mod downloader; pub mod hash; pub mod twitter; +pub mod summarizer; diff --git a/crates/archivr-core/src/summarizer.rs b/crates/archivr-core/src/summarizer.rs new file mode 100644 index 0000000..f405e30 --- /dev/null +++ b/crates/archivr-core/src/summarizer.rs @@ -0,0 +1,2177 @@ +//! Per-entry LLM summaries. +//! +//! A summary is a *regenerable child record* of an entry (`entry_summaries`), +//! not a column on `archived_entries` and not an artifact on disk: an entry can +//! carry several summaries (one per provider / model / prompt version), any of +//! them can be discarded and recomputed, and none of them is part of the +//! preserved capture. Generation is manual-only — nothing in `capture.rs` calls +//! into this module. +//! +//! Four providers sit behind one [`SummaryProvider`] trait: two HTTP APIs and +//! two local CLIs. They are configured by environment variable, never by TOML, +//! matching how the rest of the tree resolves external tools (`ARCHIVR_YT_DLP`, +//! `ARCHIVR_SINGLE_FILE`, `ARCHIVR_TWEET_SCRAPER`, …) and keeping API keys out +//! of any file the archive would otherwise persist. + +use anyhow::{Context, Result, anyhow, bail}; +use base64::Engine; +use std::{ + env, + io::Write, + path::{Path, PathBuf}, + process::{Command, Stdio}, + sync::mpsc, + thread, + time::Duration, +}; + +use crate::{archive::ArchivePaths, database, hash}; + +/// Bump whenever the prompt text below changes in a way that would produce a +/// materially different summary. It is part of the `entry_summaries` cache key, +/// so a bump makes every stored summary regenerate on next request instead of +/// silently mixing outputs from two different prompts. +pub const PROMPT_VERSION: &str = "v1-2026-08-22"; + +/// Maximum number of explicitly opted-in local images supplied to a summary. +pub const MAX_SUMMARY_IMAGES: usize = 4; +/// Maximum byte size for one explicitly opted-in image. +pub const MAX_SUMMARY_IMAGE_BYTES: u64 = 5 * 1024 * 1024; +/// Maximum combined byte size for explicitly opted-in images. +pub const MAX_SUMMARY_IMAGE_TOTAL_BYTES: u64 = 12 * 1024 * 1024; + +/// User-safe copy for entries whose archived artifacts do not contain +/// summarizable text. Keep this separate from provider and archive failures. +pub const UNSUPPORTED_SUMMARY_CONTENT_HEADING: &str = "This entry can’t be summarized yet."; +pub const UNSUPPORTED_SUMMARY_CONTENT_DETAIL: &str = "It doesn’t contain archived text that a summary provider can read. Summaries currently support text notes, web pages, X posts and threads, and X Articles. Video, audio, and image-only entries need a transcript or text source."; +pub const UNSUPPORTED_SUMMARY_CONTENT_MESSAGE: &str = concat!( + "This entry can’t be summarized yet.\n\n", + "It doesn’t contain archived text that a summary provider can read. Summaries currently support text notes, web pages, X posts and threads, and X Articles. Video, audio, and image-only entries need a transcript or text source." +); + +/// Upper bound on characters fed to a model. Archived pages run to hundreds of +/// kilobytes; past this point we are paying for tokens that do not change a +/// five-sentence summary. Truncation happens *before* hashing so the cache key +/// describes exactly what the model saw. +const MAX_INPUT_CHARS: usize = 48_000; + +const DEFAULT_HTTP_TIMEOUT_SECS: u64 = 120; +const DEFAULT_CLI_TIMEOUT_SECS: u64 = 300; + +#[derive(Debug)] +struct UnsupportedSummaryContent; + +impl std::fmt::Display for UnsupportedSummaryContent { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("unsupported summary content") + } +} + +impl std::error::Error for UnsupportedSummaryContent {} + +fn unsupported_summary_content_error() -> anyhow::Error { + anyhow::Error::new(UnsupportedSummaryContent) +} + +/// True only for expected, pre-provider summary-input limitations. +pub fn is_unsupported_summary_content_error(error: &anyhow::Error) -> bool { + error + .chain() + .any(|cause| cause.downcast_ref::().is_some()) +} + +/// The instruction half of the prompt. JSON output is requested because parsing +/// prose out of a free-form answer is the single most fragile part of an LLM +/// integration; a JSON object survives models that like to add pleasantries. +const SYSTEM_PROMPT: &str = "\ +You summarize archived web content for a personal archive index. + +Reply with a single JSON object and nothing else — no markdown fence, no prose +before or after. The object has exactly these keys: + + \"tldr\": one sentence, at most 25 words. + \"summary\": 4 to 6 sentences of plain English describing what the content + says, its claims, and its conclusion. No preamble like + \"This article discusses\". + \"tags\": an array of at most 5 short lowercase topic tags. + +Write in English regardless of the source language. If the content is too +short or empty to summarize, still return the object and say so in \"summary\"."; + +// ── Request / output types ───────────────────────────────────────────────── + +/// Controls optional material included while building a summary request. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct SummaryBuildOptions { + pub include_images: bool, +} + +/// An archived image that was explicitly selected for a summary request. +/// +/// `archive_file` is an absolute local path, kept inside the archive store and +/// never exposed through an API response. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SummaryImage { + pub sha256: String, + pub mime_type: String, + pub byte_size: u64, + pub archive_file: PathBuf, +} + +/// Everything the prompt builder needs about one entry. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SummaryRequest { + pub entry_uid: String, + pub title: Option, + pub source_kind: String, + pub entity_kind: String, + pub content: String, + pub images: Vec, +} + +/// What a provider produced. `model` is echoed back because HTTP providers may +/// resolve an alias (`claude-3-5-sonnet-latest`) to a dated concrete model, and +/// the concrete one is what we want recorded against the summary. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SummaryOutput { + pub text: String, + pub model: Option, +} + +/// One way of turning a [`SummaryRequest`] into text. +/// +/// `Send + Sync` so a boxed provider can cross into the server's +/// `spawn_blocking` worker. +pub trait SummaryProvider: Send + Sync { + /// Stable identifier persisted as `entry_summaries.provider_kind`. + fn kind(&self) -> &'static str; + fn model(&self) -> Option<&str>; + fn summarize(&self, request: &SummaryRequest) -> Result; +} + +// ── Configuration ────────────────────────────────────────────────────────── + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HttpProviderConfig { + /// Full URL, e.g. `https://api.anthropic.com/v1/messages`. + pub endpoint: String, + pub api_key: String, + pub model: String, + pub timeout_secs: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CliProviderConfig { + /// Resolved via `ARCHIVR_CLAUDE_CLI` / `ARCHIVR_CODEX_CLI`; a bare name is + /// left for the OS to resolve on `PATH`, as elsewhere in the tree. + pub executable: PathBuf, + pub model: Option, + pub timeout_secs: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProviderConfig { + AnthropicHttp(HttpProviderConfig), + OpenAiCompatible(HttpProviderConfig), + ClaudeCli(CliProviderConfig), + CodexCli(CliProviderConfig), +} + +pub const PROVIDER_KINDS: [&str; 4] = [ + "anthropic_http", + "openai_compatible", + "claude_cli", + "codex_cli", +]; + +pub fn provider_from_config(cfg: ProviderConfig) -> Box { + match cfg { + ProviderConfig::AnthropicHttp(c) => Box::new(AnthropicHttpProvider(c)), + ProviderConfig::OpenAiCompatible(c) => Box::new(OpenAiCompatibleProvider(c)), + ProviderConfig::ClaudeCli(c) => Box::new(ClaudeCliProvider(c)), + ProviderConfig::CodexCli(c) => Box::new(CodexCliProvider(c)), + } +} + +/// Reads a required env var, failing with the *exact variable name* so the +/// server can hand a caller an actionable 400 rather than "not configured". +fn required_env(name: &str) -> Result { + match env::var(name) { + Ok(v) if !v.trim().is_empty() => Ok(v), + _ => bail!("missing required environment variable: {name}"), + } +} + +fn env_or(name: &str, default: &str) -> String { + env::var(name) + .ok() + .filter(|v| !v.trim().is_empty()) + .unwrap_or_else(|| default.to_string()) +} + +fn optional_env(name: &str) -> Option { + env::var(name).ok().filter(|v| !v.trim().is_empty()) +} + +fn env_timeout(name: &str, default: u64) -> u64 { + env::var(name) + .ok() + .and_then(|v| v.trim().parse::().ok()) + .filter(|v| *v > 0) + .unwrap_or(default) +} + +/// Resolve a CLI executable path. +/// +/// Priority: `env_name` override → first `well_known_absolute` path that +/// exists → `HOME/.local/bin/` if it exists → bare name (relies on the +/// server's PATH). The macOS defaults matter for `codex`, which the ChatGPT +/// desktop app installs at `/Applications/ChatGPT.app/Contents/Resources/codex` +/// and does not add to PATH. +fn resolve_cli(env_name: &str, well_known_absolute: &[&str], bare: &str) -> PathBuf { + if let Some(explicit) = optional_env(env_name) { + return PathBuf::from(explicit); + } + for candidate in well_known_absolute { + let p = Path::new(candidate); + if p.is_file() { + return p.to_path_buf(); + } + } + if let Some(home) = env::var_os("HOME") { + let mut p = PathBuf::from(home); + p.push(".local/bin"); + p.push(bare); + if p.is_file() { + return p; + } + } + PathBuf::from(bare) +} + +/// Builds a provider configuration for `kind` purely from the environment. +pub fn provider_from_env(kind: &str) -> Result { + match kind { + "anthropic_http" => Ok(ProviderConfig::AnthropicHttp(HttpProviderConfig { + endpoint: env_or( + "ARCHIVR_ANTHROPIC_URL", + "https://api.anthropic.com/v1/messages", + ), + api_key: required_env("ARCHIVR_ANTHROPIC_API_KEY")?, + model: env_or("ARCHIVR_ANTHROPIC_MODEL", "claude-3-5-sonnet-latest"), + timeout_secs: env_timeout("ARCHIVR_SUMMARY_HTTP_TIMEOUT", DEFAULT_HTTP_TIMEOUT_SECS), + })), + "openai_compatible" => Ok(ProviderConfig::OpenAiCompatible(HttpProviderConfig { + endpoint: env_or( + "ARCHIVR_OPENAI_URL", + "https://api.openai.com/v1/chat/completions", + ), + api_key: required_env("ARCHIVR_OPENAI_API_KEY")?, + model: env_or("ARCHIVR_OPENAI_MODEL", "gpt-4o-mini"), + timeout_secs: env_timeout("ARCHIVR_SUMMARY_HTTP_TIMEOUT", DEFAULT_HTTP_TIMEOUT_SECS), + })), + "claude_cli" => Ok(ProviderConfig::ClaudeCli(CliProviderConfig { + executable: resolve_cli( + "ARCHIVR_CLAUDE_CLI", + &["/opt/homebrew/bin/claude", "/usr/local/bin/claude"], + "claude", + ), + model: optional_env("ARCHIVR_CLAUDE_MODEL"), + timeout_secs: env_timeout("ARCHIVR_SUMMARY_CLI_TIMEOUT", DEFAULT_CLI_TIMEOUT_SECS), + })), + "codex_cli" => Ok(ProviderConfig::CodexCli(CliProviderConfig { + executable: resolve_cli( + "ARCHIVR_CODEX_CLI", + &[ + "/Applications/ChatGPT.app/Contents/Resources/codex", + "/opt/homebrew/bin/codex", + "/usr/local/bin/codex", + ], + "codex", + ), + model: optional_env("ARCHIVR_CODEX_MODEL"), + timeout_secs: env_timeout("ARCHIVR_SUMMARY_CLI_TIMEOUT", DEFAULT_CLI_TIMEOUT_SECS), + })), + other => bail!( + "unknown summary provider: {other} (expected one of {})", + PROVIDER_KINDS.join(", ") + ), + } +} + +// ── Prompt assembly ──────────────────────────────────────────────────────── + +/// The user half of the prompt: entry metadata as a small header, then content. +pub fn build_user_prompt(request: &SummaryRequest) -> String { + let mut s = String::new(); + if let Some(title) = request.title.as_deref().filter(|t| !t.trim().is_empty()) { + s.push_str(&format!("Title: {title}\n")); + } + s.push_str(&format!( + "Source: {} / {}\n\nContent:\n{}\n", + request.source_kind, request.entity_kind, request.content + )); + s +} + +/// CLIs take a single prompt string on stdin, so the system half is prepended +/// rather than passed as a separate role. +fn build_combined_prompt(request: &SummaryRequest) -> String { + format!("{SYSTEM_PROMPT}\n\n---\n\n{}", build_user_prompt(request)) +} + +// ── HTTP providers ───────────────────────────────────────────────────────── + +fn http_client(timeout_secs: u64) -> Result { + reqwest::blocking::Client::builder() + // reqwest's own timeout covers connect + read, which is all a + // request/response provider needs — no watchdog thread required. + .timeout(Duration::from_secs(timeout_secs)) + .build() + .context("failed to build HTTP client for summary provider") +} + +/// Body builder kept separate from the transport so it can be unit-tested +/// without a network round-trip. +fn read_image_base64(image: &SummaryImage) -> Result { + let bytes = std::fs::read(&image.archive_file).with_context(|| { + format!( + "failed to read summary image {}", + image.archive_file.display() + ) + })?; + Ok(base64::engine::general_purpose::STANDARD.encode(bytes)) +} + +pub fn anthropic_request_body(model: &str, request: &SummaryRequest) -> Result { + if request.images.is_empty() { + return Ok(serde_json::json!({ + "model": model, + "max_tokens": 1024, + "messages": [{ + "role": "user", + "content": build_combined_prompt(request), + }], + })); + } + + let mut content = vec![serde_json::json!({ + "type": "text", + "text": build_combined_prompt(request), + })]; + for image in &request.images { + content.push(serde_json::json!({ + "type": "image", + "source": { + "type": "base64", + "media_type": image.mime_type, + "data": read_image_base64(image)?, + }, + })); + } + Ok(serde_json::json!({ + "model": model, + "max_tokens": 1024, + "messages": [{ "role": "user", "content": content }], + })) +} + +pub fn openai_request_body(model: &str, request: &SummaryRequest) -> Result { + if request.images.is_empty() { + return Ok(serde_json::json!({ + "model": model, + "messages": [ + { "role": "system", "content": SYSTEM_PROMPT }, + { "role": "user", "content": build_user_prompt(request) }, + ], + })); + } + + let mut content = vec![serde_json::json!({ + "type": "text", + "text": build_user_prompt(request), + })]; + for image in &request.images { + content.push(serde_json::json!({ + "type": "image_url", + "image_url": { + "url": format!("data:{};base64,{}", image.mime_type, read_image_base64(image)?), + }, + })); + } + Ok(serde_json::json!({ + "model": model, + "messages": [ + { "role": "system", "content": SYSTEM_PROMPT }, + { "role": "user", "content": content }, + ], + })) +} + +struct AnthropicHttpProvider(HttpProviderConfig); + +impl SummaryProvider for AnthropicHttpProvider { + fn kind(&self) -> &'static str { + "anthropic_http" + } + fn model(&self) -> Option<&str> { + Some(&self.0.model) + } + fn summarize(&self, request: &SummaryRequest) -> Result { + let body = anthropic_request_body(&self.0.model, request)?; + let resp = http_client(self.0.timeout_secs)? + .post(&self.0.endpoint) + .header("x-api-key", &self.0.api_key) + .header("anthropic-version", "2023-06-01") + .header("content-type", "application/json") + .body(body.to_string()) + .send() + .with_context(|| format!("request to {} failed", self.0.endpoint))?; + let status = resp.status(); + let text = resp.text().unwrap_or_default(); + if !status.is_success() { + bail!( + "anthropic API returned {status}: {}", + truncate_for_error(&text) + ); + } + parse_anthropic_response(&text) + } +} + +pub fn parse_anthropic_response(body: &str) -> Result { + let json: serde_json::Value = + serde_json::from_str(body).context("anthropic response was not JSON")?; + let text = json["content"][0]["text"] + .as_str() + .ok_or_else(|| anyhow!("anthropic response had no content[0].text"))?; + Ok(SummaryOutput { + text: text.to_string(), + model: json["model"].as_str().map(str::to_string), + }) +} + +struct OpenAiCompatibleProvider(HttpProviderConfig); + +impl SummaryProvider for OpenAiCompatibleProvider { + fn kind(&self) -> &'static str { + "openai_compatible" + } + fn model(&self) -> Option<&str> { + Some(&self.0.model) + } + fn summarize(&self, request: &SummaryRequest) -> Result { + let body = openai_request_body(&self.0.model, request)?; + let resp = http_client(self.0.timeout_secs)? + .post(&self.0.endpoint) + .header("authorization", format!("Bearer {}", self.0.api_key)) + .header("content-type", "application/json") + .body(body.to_string()) + .send() + .with_context(|| format!("request to {} failed", self.0.endpoint))?; + let status = resp.status(); + let text = resp.text().unwrap_or_default(); + if !status.is_success() { + bail!( + "openai-compatible API returned {status}: {}", + truncate_for_error(&text) + ); + } + parse_openai_response(&text) + } +} + +pub fn parse_openai_response(body: &str) -> Result { + let json: serde_json::Value = + serde_json::from_str(body).context("openai-compatible response was not JSON")?; + let text = json["choices"][0]["message"]["content"] + .as_str() + .ok_or_else(|| anyhow!("response had no choices[0].message.content"))?; + Ok(SummaryOutput { + text: text.to_string(), + model: json["model"].as_str().map(str::to_string), + }) +} + +fn truncate_for_error(s: &str) -> String { + let trimmed = s.trim(); + if trimmed.chars().count() <= 400 { + return trimmed.to_string(); + } + trimmed.chars().take(400).collect::() + "…" +} + +// ── CLI providers ────────────────────────────────────────────────────────── + +/// Runs `executable args…`, writes `prompt` to its stdin, and returns stdout. +/// +/// `archivr-core` deliberately has no async runtime and the tree carries no +/// `wait_timeout` dependency, so the timeout is enforced by structure rather +/// than by a library: stdout is drained on its own thread and handed back over +/// a channel, which leaves the calling thread free to `recv_timeout` and kill +/// the child if it overruns. stdin is written on a third thread because a +/// 48 KB prompt can exceed the pipe buffer, and writing it inline would +/// deadlock against a child that is waiting for us to read its output. +fn run_cli(executable: &Path, args: &[&str], prompt: &str, timeout_secs: u64) -> Result { + let mut child = Command::new(executable) + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .with_context(|| format!("failed to spawn {}", executable.display()))?; + + let mut stdin = child + .stdin + .take() + .ok_or_else(|| anyhow!("failed to open stdin for {}", executable.display()))?; + let prompt_owned = prompt.to_string(); + thread::spawn(move || { + let _ = stdin.write_all(prompt_owned.as_bytes()); + // Dropping stdin closes the pipe, which is what tells the CLI the + // prompt is complete. + }); + + let stdout = child + .stdout + .take() + .ok_or_else(|| anyhow!("failed to open stdout for {}", executable.display()))?; + let (tx, rx) = mpsc::channel(); + thread::spawn(move || { + let mut buf = String::new(); + use std::io::Read; + let mut stdout = stdout; + let res = stdout.read_to_string(&mut buf).map(|_| buf); + let _ = tx.send(res); + }); + + let collected = match rx.recv_timeout(Duration::from_secs(timeout_secs)) { + Ok(res) => { + res.with_context(|| format!("failed to read stdout of {}", executable.display()))? + } + Err(_) => { + let _ = child.kill(); + let _ = child.wait(); + bail!("{} timed out after {timeout_secs}s", executable.display()); + } + }; + + let status = child + .wait() + .with_context(|| format!("failed to wait for {}", executable.display()))?; + if !status.success() { + let mut stderr = String::new(); + if let Some(mut e) = child.stderr.take() { + use std::io::Read; + let _ = e.read_to_string(&mut stderr); + } + bail!( + "{} exited with {status}: {}", + executable.display(), + truncate_for_error(&stderr) + ); + } + Ok(collected) +} + +struct ClaudeCliProvider(CliProviderConfig); + +impl SummaryProvider for ClaudeCliProvider { + fn kind(&self) -> &'static str { + "claude_cli" + } + fn model(&self) -> Option<&str> { + self.0.model.as_deref() + } + fn summarize(&self, request: &SummaryRequest) -> Result { + if !request.images.is_empty() { + bail!("Claude CLI cannot attach local images; choose an HTTP provider or Codex CLI"); + } + // `claude -p --output-format text` is the documented one-shot + // ("print") mode of the Claude Code CLI: it reads the prompt from + // stdin, writes the answer to stdout, and exits. + let mut args: Vec<&str> = vec!["-p", "--output-format", "text"]; + if let Some(model) = self.0.model.as_deref() { + args.push("--model"); + args.push(model); + } + let out = run_cli( + &self.0.executable, + &args, + &build_combined_prompt(request), + self.0.timeout_secs, + )?; + Ok(SummaryOutput { + text: out, + model: self.0.model.clone(), + }) + } +} + +/// Codex invocation lives in its own module because its one-shot interface is +/// the least stable of the four. +/// +/// Primary form is `codex exec --output-last-message -`, which reads the +/// prompt from stdin and writes ONLY the final assistant message to ``. +/// Without `--output-last-message`, stdout is polluted with a header +/// (`OpenAI Codex vX`, session id, model, sandbox, …) and a footer +/// (`tokens used`, message replay), and the JSON extractor can pick up the +/// echoed user prompt instead of the real answer. Older builds that reject +/// `-` as stdin marker fall back to a positional prompt. +mod codex { + use super::*; + + /// A short-lived path in the OS temp dir. Unique per (pid, wall time) so + /// concurrent summarizations don't collide. + fn last_message_temp_path() -> PathBuf { + let stamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or_default(); + env::temp_dir().join(format!( + "archivr-codex-{}-{}.txt", + std::process::id(), + stamp + )) + } + + fn missing_binary_hint(cfg: &CliProviderConfig) -> &'static str { + // Only nudge users about the env var when we're running the default + // bare "codex" and it failed — an explicit ARCHIVR_CODEX_CLI path + // failure is their configuration, not a discovery gap. + if cfg.executable == Path::new("codex") { + " (hint: set ARCHIVR_CODEX_CLI to your codex binary; on macOS the ChatGPT desktop app installs it at /Applications/ChatGPT.app/Contents/Resources/codex)" + } else { + "" + } + } + + fn read_and_cleanup(path: &Path) -> Option { + let out = std::fs::read_to_string(path).ok()?; + let _ = std::fs::remove_file(path); + let trimmed = out.trim(); + if trimmed.is_empty() { + None + } else { + Some(trimmed.to_string()) + } + } + + pub fn primary_args( + images: &[SummaryImage], + out_path: &Path, + model: Option<&str>, + ) -> Vec { + let mut args = vec!["exec".into()]; + for image in images { + args.push("--image".into()); + args.push(image.archive_file.to_string_lossy().into_owned()); + } + args.push("--output-last-message".into()); + args.push(out_path.to_string_lossy().into_owned()); + if let Some(model) = model { + args.push("--model".into()); + args.push(model.into()); + } + args.push("-".into()); + args + } + + pub fn positional_args( + images: &[SummaryImage], + out_path: &Path, + model: Option<&str>, + prompt: &str, + ) -> Vec { + let mut args = primary_args(images, out_path, model); + args.pop(); + args.push(prompt.into()); + args + } + + pub fn run(cfg: &CliProviderConfig, prompt: &str, images: &[SummaryImage]) -> Result { + let out_path = last_message_temp_path(); + + // Primary: stdin prompt + --output-last-message. + let primary = primary_args(images, &out_path, cfg.model.as_deref()); + let primary_refs: Vec<&str> = primary.iter().map(String::as_str).collect(); + + let primary_err = match run_cli(&cfg.executable, &primary_refs, prompt, cfg.timeout_secs) { + Ok(_) => { + if let Some(text) = read_and_cleanup(&out_path) { + return Ok(text); + } + // Codex succeeded but wrote nothing to the file — extremely + // rare, but treat as a soft failure so we try the fallback. + let _ = std::fs::remove_file(&out_path); + anyhow!("codex produced no last-message output") + } + Err(e) => { + let _ = std::fs::remove_file(&out_path); + e + } + }; + + // Fallback: positional prompt, no stdin, same --output-last-message. + let fb = positional_args(images, &out_path, cfg.model.as_deref(), prompt); + let fb_refs: Vec<&str> = fb.iter().map(String::as_str).collect(); + let out = run_cli(&cfg.executable, &fb_refs, "", cfg.timeout_secs).with_context(|| { + let _ = std::fs::remove_file(&out_path); + format!( + "codex `exec -` failed ({primary_err:#}); positional fallback failed{}", + missing_binary_hint(cfg) + ) + })?; + if let Some(text) = read_and_cleanup(&out_path) { + return Ok(text); + } + // Last resort — the child succeeded but wrote nothing to the file. Fall + // back to raw stdout so the caller has *something* to normalize. + let _ = std::fs::remove_file(&out_path); + Ok(out) + } +} + +struct CodexCliProvider(CliProviderConfig); + +impl SummaryProvider for CodexCliProvider { + fn kind(&self) -> &'static str { + "codex_cli" + } + fn model(&self) -> Option<&str> { + self.0.model.as_deref() + } + fn summarize(&self, request: &SummaryRequest) -> Result { + let out = codex::run(&self.0, &build_combined_prompt(request), &request.images)?; + Ok(SummaryOutput { + text: out, + model: self.0.model.clone(), + }) + } +} + +// ── Content extraction ───────────────────────────────────────────────────── + +/// Strips markup from an archived HTML page. +/// +/// Deliberately regex-based rather than a real parser: `html5ever` is not in +/// the dependency tree, and pulling a full HTML parser in to feed a language +/// model — which tolerates imperfect whitespace and stray angle brackets +/// fine — is not worth the build cost. `\ +

Hello world

"; + let text = strip_html(html); + assert!(text.contains("Hello world")); + assert!(!text.contains("color:red")); + assert!(!text.contains("var x")); + } + + #[test] + fn strip_html_keeps_paragraphs_apart() { + let text = strip_html("

One

Two

"); + // Without block-level break handling these would run together as + // "OneTwo", which reads as a single garbled sentence to the model. + assert!(text.contains("One")); + assert!(text.contains("Two")); + assert!(!text.contains("OneTwo")); + } + + #[test] + fn strip_html_decodes_common_entities() { + assert_eq!( + strip_html("

a & b  c

").replace('\u{a0}', " "), + "a & b c" + ); + } + + #[test] + fn extract_tweet_text_handles_flat_and_wrapped_shapes() { + let flat = serde_json::json!({ "full_text": "tweet body" }); + assert_eq!(extract_tweet_text(&flat).unwrap(), "tweet body"); + + let wrapped = serde_json::json!({ "tweet": { "text": "wrapped body" } }); + assert_eq!(extract_tweet_text(&wrapped).unwrap(), "wrapped body"); + + let threaded = serde_json::json!({ + "full_text": "first", + "thread": [{ "full_text": "second" }], + }); + assert_eq!(extract_tweet_text(&threaded).unwrap(), "first\n\nsecond"); + + assert!(extract_tweet_text(&serde_json::json!({ "id": 1 })).is_none()); + } + + #[test] + fn extract_tweet_text_prefers_x_article_plain_text_over_tco_body() { + let tweet = serde_json::json!({ + "full_text": "https://t.co/article", + "article": { "title": "Skin guide", "plain_text": "Use sunscreen daily." } + }); + assert_eq!( + extract_tweet_text(&tweet).as_deref(), + Some("Skin guide\n\nUse sunscreen daily.") + ); + } + + #[test] + fn extract_tweet_text_uses_article_blocks_when_plain_text_is_empty() { + let tweet = serde_json::json!({"article": { + "title": "Blocks", "plain_text": " ", + "blocks": [ + {"text": "First", "id": "ignored", "media_url": "https://example.test/image"}, + {"children": [{"text": "Second", "enabled": true}]} + ] + }}); + assert_eq!( + extract_tweet_text(&tweet).as_deref(), + Some("Blocks\n\nFirst\n\nSecond") + ); + } + + #[test] + fn extract_tweet_text_keeps_article_block_object_field_order() { + let tweet: serde_json::Value = serde_json::from_str( + r#"{ + "article": { + "title": "Ordered block", + "blocks": [{"heading": "Opening", "content": "Body copy"}] + } + }"#, + ) + .unwrap(); + assert_eq!( + extract_tweet_text(&tweet).as_deref(), + Some("Ordered block\n\nOpening\n\nBody copy") + ); + } + + #[test] + fn extract_tweet_text_falls_back_from_article_preview_to_summary_then_tweet_body() { + let preview = serde_json::json!({ + "full_text": "https://t.co/fallback", + "article": { "title": "Preview", "preview_text": "Preview copy", "summary_text": "Later" } + }); + assert_eq!( + extract_tweet_text(&preview).as_deref(), + Some("Preview\n\nPreview copy") + ); + + let summary = serde_json::json!({ + "full_text": "https://t.co/fallback", + "article": { "title": "Summary", "summary_text": "Summary copy" } + }); + assert_eq!( + extract_tweet_text(&summary).as_deref(), + Some("Summary\n\nSummary copy") + ); + + let empty_article = serde_json::json!({ + "full_text": "https://t.co/fallback", + "article": { "title": "Only a title", "blocks": [{"id": "not text"}] } + }); + assert_eq!( + extract_tweet_text(&empty_article).as_deref(), + Some("https://t.co/fallback") + ); + } + + #[test] + fn build_summary_input_joins_article_backed_tweet_artifacts() { + let temp = tempfile::tempdir().unwrap(); + let paths = crate::archive::initialize_archive( + temp.path(), + &temp.path().join("store"), + "Test archive", + false, + ) + .unwrap(); + let conn = database::open_or_initialize(&paths.archive_path).unwrap(); + let user_id = database::ensure_default_user(&conn).unwrap(); + let run = database::create_archive_run(&conn, user_id, 1).unwrap(); + let source_id = database::upsert_source_identity( + &conn, + "twitter", + "tweet_thread", + Some("thread-1"), + Some("https://x.com/example/status/1"), + "x:thread-1", + ) + .unwrap(); + let entry = database::create_archived_entry( + &conn, + &database::NewEntry { + source_identity_id: source_id, + archive_run_id: run.id, + parent_entry_id: None, + root_entry_id: None, + created_by_user_id: user_id, + owned_by_user_id: user_id, + source_kind: "twitter".to_string(), + entity_kind: "tweet_thread".to_string(), + title: Some("Article thread".to_string()), + visibility: "private".to_string(), + representation_kind: "tweet_thread".to_string(), + source_metadata_json: "{}".to_string(), + display_metadata_json: None, + }, + ) + .unwrap(); + + for (ordinal, (relpath, body)) in [ + ("raw_tweets/article-one.json", "First article body."), + ("raw_tweets/article-two.json", "Second article body."), + ] + .into_iter() + .enumerate() + { + let path = paths.store_path.join(relpath); + std::fs::write( + &path, + serde_json::json!({ + "full_text": format!("https://t.co/{ordinal}"), + "article": { "title": format!("Article {}", ordinal + 1), "plain_text": body } + }) + .to_string(), + ) + .unwrap(); + database::add_entry_artifact( + &conn, + &database::NewArtifact { + entry_id: entry.id, + artifact_role: "raw_tweet_json".to_string(), + storage_area: "raw_tweets".to_string(), + relpath: relpath.to_string(), + blob_id: None, + logical_path: None, + metadata_json: None, + }, + ) + .unwrap(); + } + + let input = + build_summary_input(&paths, &entry.entry_uid, SummaryBuildOptions::default()).unwrap(); + assert!( + input + .request + .content + .contains("First article body.\n\n---\n\nArticle 2\n\nSecond article body.") + ); + } + + fn summary_image_fixture() -> (tempfile::TempDir, ArchivePaths, database::ArchivedEntry) { + let temp = tempfile::tempdir().unwrap(); + let paths = crate::archive::initialize_archive( + temp.path(), + &temp.path().join("store"), + "Test archive", + false, + ) + .unwrap(); + let conn = database::open_or_initialize(&paths.archive_path).unwrap(); + let user_id = database::ensure_default_user(&conn).unwrap(); + let run = database::create_archive_run(&conn, user_id, 1).unwrap(); + let source_id = database::upsert_source_identity( + &conn, + "web", + "page", + Some("summary-image-test"), + Some("https://example.test/summary-image-test"), + "https://example.test/summary-image-test", + ) + .unwrap(); + let entry = database::create_archived_entry( + &conn, + &database::NewEntry { + source_identity_id: source_id, + archive_run_id: run.id, + parent_entry_id: None, + root_entry_id: None, + created_by_user_id: user_id, + owned_by_user_id: user_id, + source_kind: "web".to_string(), + entity_kind: "page".to_string(), + title: Some("Image test".to_string()), + visibility: "private".to_string(), + representation_kind: "webpage".to_string(), + source_metadata_json: "{}".to_string(), + display_metadata_json: None, + }, + ) + .unwrap(); + + let text_relpath = "raw/summary-image-test.txt"; + std::fs::write(paths.store_path.join(text_relpath), "Summary source text.").unwrap(); + database::add_entry_artifact( + &conn, + &database::NewArtifact { + entry_id: entry.id, + artifact_role: "primary_media".to_string(), + storage_area: "raw".to_string(), + relpath: text_relpath.to_string(), + blob_id: None, + logical_path: None, + metadata_json: None, + }, + ) + .unwrap(); + (temp, paths, entry) + } + + #[test] + fn unsupported_summary_content_errors_are_classified_without_relabeling_other_errors() { + let (_temp, paths, entry) = summary_image_fixture(); + let conn = database::open_or_initialize(&paths.archive_path).unwrap(); + conn.execute( + "DELETE FROM entry_artifacts WHERE entry_id = ?1", + [entry.id], + ) + .unwrap(); + + let no_artifact = + build_summary_input(&paths, &entry.entry_uid, SummaryBuildOptions::default()) + .unwrap_err(); + assert!(is_unsupported_summary_content_error(&no_artifact)); + + add_summary_image_artifact(&paths, entry.id, 99, "primary_media", "mp4", "video/mp4", 1); + let video = build_summary_input(&paths, &entry.entry_uid, SummaryBuildOptions::default()) + .unwrap_err(); + assert!(is_unsupported_summary_content_error(&video)); + + let conn = database::open_or_initialize(&paths.archive_path).unwrap(); + conn.execute( + "DELETE FROM entry_artifacts WHERE entry_id = ?1", + [entry.id], + ) + .unwrap(); + let empty_relpath = "raw/empty-summary.txt"; + std::fs::write(paths.store_path.join(empty_relpath), "").unwrap(); + database::add_entry_artifact( + &conn, + &database::NewArtifact { + entry_id: entry.id, + artifact_role: "primary_media".to_string(), + storage_area: "raw".to_string(), + relpath: empty_relpath.to_string(), + blob_id: None, + logical_path: None, + metadata_json: None, + }, + ) + .unwrap(); + drop(conn); + let empty_text = + build_summary_input(&paths, &entry.entry_uid, SummaryBuildOptions::default()) + .unwrap_err(); + assert!(is_unsupported_summary_content_error(&empty_text)); + + std::fs::remove_file(paths.store_path.join(empty_relpath)).unwrap(); + let read_error = + build_summary_input(&paths, &entry.entry_uid, SummaryBuildOptions::default()) + .unwrap_err(); + assert!(!is_unsupported_summary_content_error(&read_error)); + assert_eq!( + UNSUPPORTED_SUMMARY_CONTENT_MESSAGE, + "This entry can’t be summarized yet.\n\nIt doesn’t contain archived text that a summary provider can read. Summaries currently support text notes, web pages, X posts and threads, and X Articles. Video, audio, and image-only entries need a transcript or text source." + ); + + assert!(!is_unsupported_summary_content_error(&anyhow!( + "provider timeout" + ))); + assert!(!is_unsupported_summary_content_error(&anyhow!( + "entry not found: {}", + entry.entry_uid + ))); + } + + fn add_summary_image_artifact( + paths: &ArchivePaths, + entry_id: i64, + ordinal: usize, + role: &str, + extension: &str, + mime_type: &str, + byte_size: u64, + ) { + let conn = database::open_or_initialize(&paths.archive_path).unwrap(); + let relpath = format!("raw/summary-image-{ordinal}.{extension}"); + std::fs::write(paths.store_path.join(&relpath), "image fixture").unwrap(); + let blob_id = database::upsert_blob( + &conn, + &database::BlobRecord { + sha256: format!("summary-image-{ordinal:02}"), + byte_size: byte_size.try_into().unwrap(), + mime_type: Some(mime_type.to_string()), + extension: Some(extension.to_string()), + raw_relpath: relpath.clone(), + }, + ) + .unwrap(); + database::add_entry_artifact( + &conn, + &database::NewArtifact { + entry_id, + artifact_role: role.to_string(), + storage_area: "raw".to_string(), + relpath, + blob_id: Some(blob_id), + logical_path: None, + metadata_json: None, + }, + ) + .unwrap(); + } + + #[test] + fn summary_image_selection_filters_candidates_and_stops_at_image_count() { + let (_temp, paths, entry) = summary_image_fixture(); + add_summary_image_artifact(&paths, entry.id, 0, "avatar", "jpg", "image/jpeg", 1); + add_summary_image_artifact(&paths, entry.id, 1, "video", "mp4", "video/mp4", 1); + add_summary_image_artifact(&paths, entry.id, 2, "audio", "mp3", "audio/mpeg", 1); + add_summary_image_artifact(&paths, entry.id, 3, "media", "svg", "image/svg+xml", 1); + add_summary_image_artifact(&paths, entry.id, 4, "media", "png", "image/jpeg", 1); + add_summary_image_artifact( + &paths, + entry.id, + 5, + "media", + "jpg", + "image/jpeg", + MAX_SUMMARY_IMAGE_BYTES + 1, + ); + add_summary_image_artifact(&paths, entry.id, 6, "media", "jpg", "image/jpeg", 1); + add_summary_image_artifact(&paths, entry.id, 7, "media", "png", "image/png", 2); + add_summary_image_artifact(&paths, entry.id, 8, "media", "webp", "image/webp", 3); + add_summary_image_artifact(&paths, entry.id, 9, "media", "gif", "image/gif", 4); + add_summary_image_artifact(&paths, entry.id, 10, "media", "avif", "image/avif", 5); + + let text_only = build_summary_input( + &paths, + &entry.entry_uid, + SummaryBuildOptions { + include_images: false, + }, + ) + .unwrap(); + let visual = build_summary_input( + &paths, + &entry.entry_uid, + SummaryBuildOptions { + include_images: true, + }, + ) + .unwrap(); + + assert!(text_only.request.images.is_empty()); + assert_ne!(text_only.input_sha256, visual.input_sha256); + assert_eq!(visual.request.images.len(), MAX_SUMMARY_IMAGES); + assert_eq!( + visual + .request + .images + .iter() + .map(|image| image.sha256.as_str()) + .collect::>(), + vec![ + "summary-image-06", + "summary-image-07", + "summary-image-08", + "summary-image-09", + ] + ); + assert!( + visual + .request + .images + .iter() + .all(|image| image.byte_size <= MAX_SUMMARY_IMAGE_BYTES) + ); + } + + #[test] + fn summary_image_selection_enforces_aggregate_limit_and_keeps_scanning() { + let (_temp, paths, entry) = summary_image_fixture(); + add_summary_image_artifact( + &paths, + entry.id, + 0, + "media", + "jpg", + "image/jpeg", + 4 * 1024 * 1024, + ); + add_summary_image_artifact( + &paths, + entry.id, + 1, + "media", + "png", + "image/png", + 4 * 1024 * 1024, + ); + add_summary_image_artifact( + &paths, + entry.id, + 2, + "media", + "webp", + "image/webp", + 4 * 1024 * 1024, + ); + add_summary_image_artifact(&paths, entry.id, 3, "media", "gif", "image/gif", 1); + + let visual = build_summary_input( + &paths, + &entry.entry_uid, + SummaryBuildOptions { + include_images: true, + }, + ) + .unwrap(); + + assert_eq!(visual.request.images.len(), 3); + assert_eq!( + visual + .request + .images + .iter() + .map(|image| image.byte_size) + .sum::(), + MAX_SUMMARY_IMAGE_TOTAL_BYTES + ); + assert!( + visual + .request + .images + .iter() + .all(|image| image.sha256 != "summary-image-03") + ); + } + + #[test] + fn summarize_entry_uses_requested_alias_for_cache_and_response_model_for_display() { + struct ResolvedModelProvider; + + impl SummaryProvider for ResolvedModelProvider { + fn kind(&self) -> &'static str { + "anthropic_http" + } + fn model(&self) -> Option<&str> { + Some("claude-3-5-sonnet-latest") + } + fn summarize(&self, _: &SummaryRequest) -> Result { + Ok(SummaryOutput { + text: r#"{"tldr":"t","summary":"s","tags":[]}"#.to_string(), + model: Some("claude-3-5-sonnet-20241022".to_string()), + }) + } + } + + let (_temp, paths, entry) = summary_image_fixture(); + let record = summarize_entry( + &paths, + &entry.entry_uid, + SummaryBuildOptions::default(), + &ResolvedModelProvider, + "v1", + ) + .unwrap(); + + assert_eq!( + record.provider_model.as_deref(), + Some("claude-3-5-sonnet-latest") + ); + assert_eq!( + record.resolved_model.as_deref(), + Some("claude-3-5-sonnet-20241022") + ); + } + + // ── Output normalization ─────────────────────────────────────────────── + + #[test] + fn normalize_summary_json_passes_through_clean_json() { + let raw = r#"{"tldr":"t","summary":"s","tags":["a"]}"#; + let v: serde_json::Value = serde_json::from_str(&normalize_summary_json(raw)).unwrap(); + assert_eq!(v["tldr"], "t"); + assert_eq!(v["tags"][0], "a"); + } + + #[test] + fn normalize_summary_json_strips_markdown_fences() { + let raw = "```json\n{\"tldr\":\"t\",\"summary\":\"s\",\"tags\":[]}\n```"; + let v: serde_json::Value = serde_json::from_str(&normalize_summary_json(raw)).unwrap(); + assert_eq!(v["summary"], "s"); + } + + #[test] + fn normalize_summary_json_recovers_json_wrapped_in_prose() { + let raw = + "Sure! Here you go:\n{\"tldr\":\"t\",\"summary\":\"s\",\"tags\":[]}\nHope that helps."; + let v: serde_json::Value = serde_json::from_str(&normalize_summary_json(raw)).unwrap(); + assert_eq!(v["tldr"], "t"); + } + + #[test] + fn normalize_summary_json_wraps_unparseable_output_rather_than_losing_it() { + // A model that ignored the format instruction still produced something + // a human can read; discarding it would be worse than a missing tldr. + let v: serde_json::Value = + serde_json::from_str(&normalize_summary_json("just prose")).unwrap(); + assert_eq!(v["summary"], "just prose"); + assert_eq!(v["tldr"], ""); + } + + // ── CLI runner ───────────────────────────────────────────────────────── + + #[test] + fn run_cli_round_trips_stdin_to_stdout() { + // `cat` stands in for a provider CLI: it proves the prompt reaches the + // child's stdin and the child's stdout comes back intact. + let out = run_cli(Path::new("cat"), &[], "prompt text", 30).unwrap(); + assert_eq!(out, "prompt text"); + } + + #[test] + fn run_cli_kills_a_child_that_overruns_its_timeout() { + let err = run_cli(Path::new("sleep"), &["30"], "", 1) + .unwrap_err() + .to_string(); + assert!(err.contains("timed out"), "got: {err}"); + } + + #[test] + fn run_cli_reports_a_nonzero_exit() { + let err = run_cli(Path::new("false"), &[], "", 30) + .unwrap_err() + .to_string(); + assert!(err.contains("exited with"), "got: {err}"); + } +} diff --git a/crates/archivr-server/src/main.rs b/crates/archivr-server/src/main.rs index b191e9e..72be507 100644 --- a/crates/archivr-server/src/main.rs +++ b/crates/archivr-server/src/main.rs @@ -98,6 +98,17 @@ async fn main() -> Result<()> { ), _ => {} } + match archivr_core::database::fail_stalled_entry_summaries(&conn) { + Ok(n) if n > 0 => eprintln!( + "info: marked {n} stalled summary attempt(s) as failed in '{}'", + archive.id + ), + Err(e) => eprintln!( + "warn: stalled summary cleanup failed for '{}': {e:#}", + archive.id + ), + _ => {} + } } } diff --git a/crates/archivr-server/src/routes.rs b/crates/archivr-server/src/routes.rs index ec8b474..ff15fb4 100644 --- a/crates/archivr-server/src/routes.rs +++ b/crates/archivr-server/src/routes.rs @@ -29,7 +29,7 @@ use std::{ time::{Duration, Instant}, }; -use archivr_core::{archive, capture, database, downloader}; +use archivr_core::{archive, capture, database, downloader, summarizer}; use axum::{ Json, Router, extract::{ConnectInfo, DefaultBodyLimit, Multipart, Path, Query, Request, State}, @@ -49,6 +49,10 @@ use rusqlite::OptionalExtension; const LOGIN_WINDOW: Duration = Duration::from_secs(15 * 60); const LOGIN_MAX_ATTEMPTS: usize = 5; +const MAX_TEXT_CAPTURE_BODY_BYTES: usize = 2 * 1024 * 1024; +// JSON can expand each body byte into a six-byte `\\u00XX` escape sequence, +// plus a small request envelope. +const MAX_TEXT_CAPTURE_REQUEST_BYTES: usize = MAX_TEXT_CAPTURE_BODY_BYTES * 6 + 64 * 1024; // Short-lived token granting unauthenticated access to one specific artifact. // Used so Cast / AirPlay devices (which carry no session cookie) can fetch media. @@ -268,6 +272,10 @@ pub fn app_with_state(state: AppState) -> Router { "/api/archives/:archive_id/entries/:entry_uid/rearchive", post(rearchive_handler), ) + .route( + "/api/archives/:archive_id/entries/:entry_uid/summary", + get(entry_summary_handler).post(request_entry_summary_handler), + ) .route( "/api/archives/:archive_id/entries/:entry_uid/favicon", get(serve_entry_favicon), @@ -275,6 +283,11 @@ pub fn app_with_state(state: AppState) -> Router { .route("/api/archives/:archive_id/blobs/:sha256", get(serve_blob)) .route("/api/archives/:archive_id/runs", get(list_runs)) .route("/api/archives/:archive_id/captures", post(capture_handler)) + .route( + "/api/archives/:archive_id/captures/text", + post(capture_text_handler) + .layer(DefaultBodyLimit::max(MAX_TEXT_CAPTURE_REQUEST_BYTES)), + ) .route( "/api/archives/:archive_id/uploads", post(upload_handler) @@ -508,11 +521,210 @@ async fn entry_detail( return Err(ApiError::unauthorized("login required")); } } - let detail = archive::get_entry_detail(&conn, &entry_uid)? + let mut detail = archive::get_entry_detail(&conn, &entry_uid)? .ok_or(ApiError::not_found("entry not found"))?; + if matches!(auth_user, AuthUser::Guest) { + let entry_id = database::entry_id_for_uid(&conn, &entry_uid)? + .ok_or(ApiError::not_found("entry not found"))?; + detail.latest_summary = database::latest_completed_entry_summary(&conn, entry_id)?; + detail.summary_attempt = None; + } Ok(Json(detail)) } +#[derive(Debug, serde::Deserialize)] +struct SummaryRequestBody { + provider: String, + #[serde(default)] + force: bool, + #[serde(default)] + include_images: bool, +} + +/// `GET /api/archives/:id/entries/:uid/summary` +/// +/// Read-only, gated exactly like entry detail: a guest may read a summary only +/// for an entry whose content they could already read. Returns +/// `{ entry_uid, summary }` with a null summary when none has been requested, +/// which is also what the frontend polls while a job is running. +async fn entry_summary_handler( + State(state): State, + auth_user: AuthUser, + Path((archive_id, entry_uid)): Path<(String, String)>, +) -> Result, ApiError> { + let mounted = mounted_archive(&state, &archive_id)?; + let conn = database::open_or_initialize(&mounted.archive_path)?; + if matches!(auth_user, AuthUser::Guest) + && !database::is_entry_publicly_accessible(&conn, &entry_uid)? + { + return Err(ApiError::unauthorized("login required")); + } + let entry_id = database::entry_id_for_uid(&conn, &entry_uid)? + .ok_or(ApiError::not_found("entry not found"))?; + let (summary, attempt) = if matches!(auth_user, AuthUser::Guest) { + (database::latest_completed_entry_summary(&conn, entry_id)?, None) + } else { + ( + database::latest_completed_entry_summary(&conn, entry_id)?, + database::latest_entry_summary_attempt(&conn, entry_id)?, + ) + }; + let mut body = serde_json::json!({ "entry_uid": entry_uid, "summary": summary }); + if !matches!(auth_user, AuthUser::Guest) { + body["attempt"] = serde_json::to_value(attempt)?; + } + Ok(Json(body)) +} + +/// `POST /api/archives/:id/entries/:uid/summary` +/// +/// Manual-only summary generation. Body: `{ "provider": "...", "force": false, +/// "include_images": false }`. +/// +/// Provider configuration and content extraction are both resolved *before* +/// spawning, so a missing env var or an unsummarizable artifact comes back as a +/// synchronous 400 naming the exact problem rather than as a background job the +/// caller has to poll only to learn about a config typo. +/// +/// Returns 200 with the existing row when an identical cache key already +/// completed and `force` is false; otherwise 202 with a pending row. +async fn request_entry_summary_handler( + State(state): State, + auth_user: AuthUser, + Path((archive_id, entry_uid)): Path<(String, String)>, + Json(body): Json, +) -> Result<(StatusCode, Json), ApiError> { + auth_user.require_role(ROLE_USER)?; + let mounted = mounted_archive(&state, &archive_id)?; + let archive_paths = + archive::read_archive_paths(&mounted.archive_path).map_err(ApiError::from)?; + + // 1. Provider config from the environment. The error text carries the exact + // variable name, which is the whole point of returning it as a 400. + let provider_cfg = summarizer::provider_from_env(&body.provider) + .map_err(|e| ApiError::bad_request(&format!("{e:#}")))?; + if body.include_images && matches!(provider_cfg, summarizer::ProviderConfig::ClaudeCli(_)) { + return Err(ApiError::bad_request( + "Claude CLI cannot attach local images; choose an HTTP provider or Codex CLI", + )); + } + let provider = summarizer::provider_from_config(provider_cfg); + let summary_options = summarizer::SummaryBuildOptions { + include_images: body.include_images, + }; + + // 2. Preflight extraction and SQLite cache/attempt work are synchronous + // core operations, so keep them off the Axum runtime. This also means the + // input claimed here is passed directly to the provider worker below. + let preflight_paths = archive_paths.clone(); + let preflight_uid = entry_uid.clone(); + let provider_kind = provider.kind().to_string(); + let provider_model = provider.model().map(str::to_string); + let force = body.force; + enum PreflightOutcome { + Cached(database::EntrySummaryRecord), + Pending { input: summarizer::SummaryInput, summary_uid: String }, + } + let outcome = tokio::task::spawn_blocking(move || -> anyhow::Result { + let conn = database::open_or_initialize(&preflight_paths.archive_path)?; + let entry_id = database::entry_id_for_uid(&conn, &preflight_uid)? + .ok_or_else(|| anyhow::anyhow!("entry not found"))?; + // Preserve the route's historical 404 before attempting content + // extraction, whose own missing-entry error includes the uid. + let input = summarizer::build_summary_input(&preflight_paths, &preflight_uid, summary_options)?; + if !force { + if let Some(existing) = database::find_entry_summary( + &conn, entry_id, &provider_kind, provider_model.as_deref(), + summarizer::PROMPT_VERSION, &input.input_sha256, + )? { + if existing.status == "completed" { + return Ok(PreflightOutcome::Cached(existing)); + } + } + } + let summary_uid = database::upsert_pending_entry_summary( + &conn, entry_id, &provider_kind, provider_model.as_deref(), + summarizer::PROMPT_VERSION, &input.input_sha256, + )?; + Ok(PreflightOutcome::Pending { input, summary_uid }) + }) + .await + .map_err(|e| ApiError::internal(&format!("summary preflight task failed: {e}")))? + .map_err(|e| { + if summarizer::is_unsupported_summary_content_error(&e) { + ApiError::bad_request(summarizer::UNSUPPORTED_SUMMARY_CONTENT_MESSAGE) + } else if format!("{e:#}") == "entry not found" { + ApiError::not_found("entry not found") + } else { + ApiError::bad_request(&format!("{e:#}")) + } + })?; + let (input, summary_uid) = match outcome { + PreflightOutcome::Cached(existing) => return Ok(( + StatusCode::OK, + serde_json::to_value(&existing).map(Json) + .map_err(|e| ApiError::internal(&e.to_string()))?, + )), + PreflightOutcome::Pending { input, summary_uid } => (input, summary_uid), + }; + + let archive_path = mounted.archive_path.clone(); + let summary_uid_bg = summary_uid.clone(); + tokio::task::spawn_blocking(move || { + // The input and attempt were claimed during blocking preflight, so no + // row is reset and no archive content is read twice. + if let Err(e) = + summarizer::summarize_prebuilt_entry( + &archive_paths, + input, + &summary_uid_bg, + provider.as_ref(), + ) + { + eprintln!("warn: summary {summary_uid_bg}: {e:#}"); + record_background_summary_failure(&archive_path, &summary_uid_bg, &e); + } + }); + + Ok(( + StatusCode::ACCEPTED, + Json(serde_json::json!({ + "summary_uid": summary_uid, + "status": "pending", + "entry_uid": entry_uid, + })), + )) +} + +fn summary_failure_error_text(error: &anyhow::Error) -> String { + if summarizer::is_unsupported_summary_content_error(error) { + summarizer::UNSUPPORTED_SUMMARY_CONTENT_MESSAGE.to_string() + } else { + format!("{error:#}") + } +} + +fn record_background_summary_failure( + archive_path: &std::path::Path, + summary_uid: &str, + error: &anyhow::Error, +) { + if let Ok(conn) = database::open_or_initialize(archive_path) { + if let Ok(Some(row)) = database::get_entry_summary_by_uid(&conn, summary_uid) { + if row.status != "failed" { + database::update_entry_summary_status( + &conn, + summary_uid, + "failed", + None, + Some(&summary_failure_error_text(error)), + ) + .ok(); + } + } + } +} + async fn list_runs( State(state): State, auth_user: AuthUser, @@ -922,6 +1134,14 @@ struct CaptureBody { sync: bool, } +#[derive(Debug, serde::Deserialize)] +struct CaptureTextBody { + title: String, + body: String, + /// MIME type: "text/plain" or "text/markdown" (defaults to "text/markdown") + mime: Option, +} + #[derive(Debug, serde::Deserialize)] struct ProbeQuery { locator: String, @@ -1187,6 +1407,105 @@ async fn capture_handler( )) } +async fn capture_text_handler( + State(state): State, + auth_user: AuthUser, + Path(archive_id): Path, + Json(body): Json, +) -> Result<(StatusCode, Json), ApiError> { + auth_user.require_role(ROLE_USER)?; + + // Validate title and body + if body.title.trim().is_empty() { + return Err(ApiError::bad_request("title must not be empty")); + } + if body.body.trim().is_empty() { + return Err(ApiError::bad_request("body must not be empty")); + } + if body.body.len() > MAX_TEXT_CAPTURE_BODY_BYTES { + return Err(ApiError::bad_request("body must not exceed 2 MiB")); + } + + // Determine MIME type (default to markdown) + let mime = body.mime.as_deref().unwrap_or("text/markdown"); + + // Validate MIME type + if mime != "text/plain" && mime != "text/markdown" { + return Err(ApiError::bad_request( + "unsupported MIME type: must be 'text/plain' or 'text/markdown'" + )); + } + + let mounted = mounted_archive(&state, &archive_id)?; + let archive_paths = + archive::read_archive_paths(&mounted.archive_path).map_err(ApiError::from)?; + + // Create job record in the archive DB. + let conn = database::open_or_initialize(&mounted.archive_path)?; + let job_uid = database::create_capture_job(&conn, &archive_id)?; + drop(conn); + + // Spawn background text capture. + let title = body.title.trim().to_string(); + let text_body = body.body; + let mime_str = mime.to_string(); + let job_uid_bg = job_uid.clone(); + let archive_path = mounted.archive_path.clone(); + let archive_id_bg = archive_id.clone(); + + tokio::task::spawn_blocking(move || { + let conn = match database::open_or_initialize(&archive_path) { + Ok(c) => c, + Err(e) => { + eprintln!("warn: capture job {job_uid_bg}: db open failed: {e:#}"); + return; + } + }; + database::update_capture_job_status(&conn, &job_uid_bg, "running", None, None, None).ok(); + + match capture::perform_text_capture( + &archive_paths, + &title, + &text_body, + &mime_str, + Some(&archive_id_bg), + ) { + Ok(result) => { + let job_status = if result.status == "completed" { + "completed" + } else { + "failed" + }; + database::update_capture_job_status( + &conn, + &job_uid_bg, + job_status, + Some(&result.run_uid), + None, + None, + ) + .ok(); + } + Err(e) => { + database::update_capture_job_status( + &conn, + &job_uid_bg, + "failed", + None, + Some(&format!("{e:#}")), + None, + ) + .ok(); + } + } + }); + + Ok(( + StatusCode::ACCEPTED, + Json(serde_json::json!({ "job_uid": job_uid, "status": "pending" })), + )) +} + async fn upload_handler( State(state): State, auth_user: AuthUser, @@ -2746,6 +3065,46 @@ mod tests { .unwrap() } + fn add_summary_test_artifact( + archive_path: &std::path::Path, + entry_id: i64, + relpath: &str, + role: &str, + mime_type: &str, + contents: &[u8], + ) { + let paths = archive::read_archive_paths(archive_path).unwrap(); + let full_path = paths.store_path.join(relpath); + std::fs::create_dir_all(full_path.parent().unwrap()).unwrap(); + std::fs::write(&full_path, contents).unwrap(); + + let conn = database::open_or_initialize(archive_path).unwrap(); + let blob_id = database::upsert_blob( + &conn, + &database::BlobRecord { + sha256: format!("test-summary-{}", relpath.replace('/', "-")), + byte_size: contents.len().try_into().unwrap(), + mime_type: Some(mime_type.to_string()), + extension: relpath.rsplit('.').next().map(str::to_string), + raw_relpath: relpath.to_string(), + }, + ) + .unwrap(); + database::add_entry_artifact( + &conn, + &database::NewArtifact { + entry_id, + artifact_role: role.to_string(), + storage_area: "raw".to_string(), + relpath: relpath.to_string(), + blob_id: Some(blob_id), + logical_path: None, + metadata_json: None, + }, + ) + .unwrap(); + } + async fn body_json(response: axum::response::Response) -> serde_json::Value { let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) .await @@ -2757,6 +3116,312 @@ mod tests { Body::from(serde_json::to_vec(payload).unwrap()) } + #[tokio::test] + async fn summary_include_images_rejects_claude_cli_without_creating_row() { + let dir = tempfile::tempdir().unwrap(); + let (registry, archive_path, auth_path) = make_test_registry(&dir); + let entry = make_test_entry(&archive_path); + let session_cookie = make_test_session(&auth_path); + + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("POST") + .uri(format!("/api/archives/test/entries/{}/summary", entry.entry_uid)) + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(json_body(&serde_json::json!({ + "provider": "claude_cli", + "include_images": true, + }))) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!( + body_json(response).await["error"], + "Claude CLI cannot attach local images; choose an HTTP provider or Codex CLI" + ); + let conn = database::open_or_initialize(&archive_path).unwrap(); + assert!(database::latest_entry_summary(&conn, entry.id).unwrap().is_none()); + } + + #[tokio::test] + async fn summary_preflight_returns_safe_message_for_unsupported_video_content() { + let dir = tempfile::tempdir().unwrap(); + let (registry, archive_path, auth_path) = make_test_registry(&dir); + let entry = make_test_entry(&archive_path); + add_summary_test_artifact( + &archive_path, + entry.id, + "raw/private-video.mp4", + "primary_media", + "video/mp4", + b"video fixture", + ); + let session_cookie = make_test_session(&auth_path); + let previous_codex_cli = std::env::var_os("ARCHIVR_CODEX_CLI"); + unsafe { std::env::set_var("ARCHIVR_CODEX_CLI", "/usr/bin/false") }; + + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("POST") + .uri(format!("/api/archives/test/entries/{}/summary", entry.entry_uid)) + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(json_body(&serde_json::json!({ "provider": "codex_cli" }))) + .unwrap(), + ) + .await + .unwrap(); + match previous_codex_cli { + Some(value) => unsafe { std::env::set_var("ARCHIVR_CODEX_CLI", value) }, + None => unsafe { std::env::remove_var("ARCHIVR_CODEX_CLI") }, + } + + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let error = body_json(response).await["error"].as_str().unwrap().to_string(); + assert_eq!(error, summarizer::UNSUPPORTED_SUMMARY_CONTENT_MESSAGE); + assert!(!error.contains("raw/")); + assert!(!error.contains("mime")); + assert!(!error.contains("v1 unsupported")); + } + + #[tokio::test] + async fn summary_request_for_missing_entry_returns_not_found_before_preflight() { + let dir = tempfile::tempdir().unwrap(); + let (registry, _archive_path, auth_path) = make_test_registry(&dir); + let session_cookie = make_test_session(&auth_path); + let previous_codex_cli = std::env::var_os("ARCHIVR_CODEX_CLI"); + unsafe { std::env::set_var("ARCHIVR_CODEX_CLI", "/usr/bin/false") }; + + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/archives/test/entries/ent_missing/summary") + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(json_body(&serde_json::json!({ "provider": "codex_cli" }))) + .unwrap(), + ) + .await + .unwrap(); + match previous_codex_cli { + Some(value) => unsafe { std::env::set_var("ARCHIVR_CODEX_CLI", value) }, + None => unsafe { std::env::remove_var("ARCHIVR_CODEX_CLI") }, + } + + assert_eq!(response.status(), StatusCode::NOT_FOUND); + assert_eq!(body_json(response).await["error"], "entry not found"); + } + + #[tokio::test] + async fn public_summary_endpoints_hide_failed_diagnostics_but_authenticated_users_keep_them() { + let dir = tempfile::tempdir().unwrap(); + let (registry, archive_path, auth_path) = make_test_registry(&dir); + let entry = make_test_entry(&archive_path); + let session = make_test_session(&auth_path); + let conn = database::open_or_initialize(&archive_path).unwrap(); + let completed_uid = database::upsert_pending_entry_summary( + &conn, entry.id, "codex_cli", None, summarizer::PROMPT_VERSION, "completed-public-test", + ) + .unwrap(); + database::update_entry_summary_status( + &conn, &completed_uid, "completed", Some("previous completed summary"), None, + ) + .unwrap(); + let summary_uid = database::upsert_pending_entry_summary( + &conn, entry.id, "codex_cli", None, summarizer::PROMPT_VERSION, "failed-public-test", + ) + .unwrap(); + database::update_entry_summary_status( + &conn, &summary_uid, "failed", None, Some("provider secret: raw diagnostic"), + ) + .unwrap(); + drop(conn); + let collection = api_make_collection( + registry.clone(), auth_path.clone(), &session, "Public summaries", "public-summaries", 3, false, + ) + .await; + api_add_to_coll( + registry.clone(), auth_path.clone(), &session, &collection, &entry.entry_uid, 3, + ) + .await; + + let public_summary = app(registry.clone(), auth_path.clone()) + .oneshot(Request::builder() + .uri(format!("/api/archives/test/entries/{}/summary", entry.entry_uid)) + .body(Body::empty()).unwrap()) + .await.unwrap(); + assert_eq!(public_summary.status(), StatusCode::OK); + let public_summary = body_json(public_summary).await; + assert_eq!(public_summary["summary"]["summary_uid"], completed_uid); + assert!(public_summary.get("attempt").is_none()); + + let public_detail = app(registry.clone(), auth_path.clone()) + .oneshot(Request::builder() + .uri(format!("/api/archives/test/entries/{}", entry.entry_uid)) + .body(Body::empty()).unwrap()) + .await.unwrap(); + assert_eq!(public_detail.status(), StatusCode::OK); + let public_detail = body_json(public_detail).await; + assert_eq!(public_detail["latest_summary"]["summary_uid"], completed_uid); + assert!(public_detail["summary_attempt"].is_null()); + + let authenticated_summary = app(registry.clone(), auth_path.clone()) + .oneshot(Request::builder() + .uri(format!("/api/archives/test/entries/{}/summary", entry.entry_uid)) + .header("cookie", &session) + .body(Body::empty()).unwrap()) + .await.unwrap(); + let authenticated_summary = body_json(authenticated_summary).await; + assert_eq!(authenticated_summary["summary"]["summary_uid"], completed_uid); + assert_eq!(authenticated_summary["summary"]["summary_text"], "previous completed summary"); + assert_eq!(authenticated_summary["attempt"]["status"], "failed"); + assert_eq!(authenticated_summary["attempt"]["error_text"], "provider secret: raw diagnostic"); + + let authenticated_detail = app(registry, auth_path) + .oneshot(Request::builder() + .uri(format!("/api/archives/test/entries/{}", entry.entry_uid)) + .header("cookie", &session) + .body(Body::empty()).unwrap()) + .await.unwrap(); + let authenticated_detail = body_json(authenticated_detail).await; + assert_eq!(authenticated_detail["latest_summary"]["summary_uid"], completed_uid); + assert_eq!(authenticated_detail["latest_summary"]["summary_text"], "previous completed summary"); + assert_eq!(authenticated_detail["summary_attempt"]["status"], "failed"); + assert_eq!(authenticated_detail["summary_attempt"]["error_text"], "provider secret: raw diagnostic"); + } + + #[test] + fn background_summary_failure_stores_safe_copy_only_for_unsupported_content() { + let dir = tempfile::tempdir().unwrap(); + let (_registry, archive_path, _auth_path) = make_test_registry(&dir); + let entry = make_test_entry(&archive_path); + add_summary_test_artifact( + &archive_path, + entry.id, + "raw/private-video.mp4", + "primary_media", + "video/mp4", + b"video fixture", + ); + let unsupported = summarizer::build_summary_input( + &archive::read_archive_paths(&archive_path).unwrap(), + &entry.entry_uid, + summarizer::SummaryBuildOptions::default(), + ) + .unwrap_err(); + assert_eq!( + summary_failure_error_text(&unsupported), + summarizer::UNSUPPORTED_SUMMARY_CONTENT_MESSAGE + ); + + let conn = database::open_or_initialize(&archive_path).unwrap(); + let summary_uid = database::upsert_pending_entry_summary( + &conn, + entry.id, + "codex_cli", + Some("test"), + summarizer::PROMPT_VERSION, + "unsupported-content-test", + ) + .unwrap(); + drop(conn); + record_background_summary_failure(&archive_path, &summary_uid, &unsupported); + let conn = database::open_or_initialize(&archive_path).unwrap(); + let stored = database::get_entry_summary_by_uid(&conn, &summary_uid) + .unwrap() + .unwrap(); + assert_eq!(stored.status, "failed"); + assert_eq!( + stored.error_text.as_deref(), + Some(summarizer::UNSUPPORTED_SUMMARY_CONTENT_MESSAGE) + ); + + let provider = anyhow::anyhow!("provider response was malformed"); + assert_eq!( + summary_failure_error_text(&provider), + "provider response was malformed" + ); + } + + #[tokio::test] + async fn summary_include_images_uses_distinct_cache_identity() { + let dir = tempfile::tempdir().unwrap(); + let (registry, archive_path, auth_path) = make_test_registry(&dir); + let entry = make_test_entry(&archive_path); + add_summary_test_artifact( + &archive_path, + entry.id, + "raw/summary-test.html", + "primary_media", + "text/html", + b"
summary fixture
", + ); + add_summary_test_artifact( + &archive_path, + entry.id, + "raw/summary-test.jpg", + "media", + "image/jpeg", + b"image fixture", + ); + let session_cookie = make_test_session(&auth_path); + let previous_codex_cli = std::env::var_os("ARCHIVR_CODEX_CLI"); + unsafe { std::env::set_var("ARCHIVR_CODEX_CLI", "/usr/bin/false") }; + + let text_response = app(registry.clone(), auth_path.clone()) + .oneshot( + Request::builder() + .method("POST") + .uri(format!("/api/archives/test/entries/{}/summary", entry.entry_uid)) + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(json_body(&serde_json::json!({ "provider": "codex_cli" }))) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(text_response.status(), StatusCode::ACCEPTED); + + let image_response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("POST") + .uri(format!("/api/archives/test/entries/{}/summary", entry.entry_uid)) + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(json_body(&serde_json::json!({ + "provider": "codex_cli", + "include_images": true, + }))) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(image_response.status(), StatusCode::ACCEPTED); + match previous_codex_cli { + Some(value) => unsafe { std::env::set_var("ARCHIVR_CODEX_CLI", value) }, + None => unsafe { std::env::remove_var("ARCHIVR_CODEX_CLI") }, + } + + let conn = database::open_or_initialize(&archive_path).unwrap(); + let input_hashes: Vec = conn + .prepare("SELECT input_sha256 FROM entry_summaries WHERE entry_id = ?1") + .unwrap() + .query_map([entry.id], |row| row.get(0)) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!(input_hashes.len(), 2); + assert_ne!(input_hashes[0], input_hashes[1]); + } + #[tokio::test] async fn archives_endpoint_lists_mounted_archives() { let dir = tempfile::tempdir().unwrap(); @@ -3680,6 +4345,291 @@ mod tests { ); } + #[tokio::test] + async fn text_capture_post_returns_accepted_with_job_uid() { + let dir = tempfile::tempdir().unwrap(); + let (registry, _, auth_path) = make_test_registry(&dir); + let session_cookie = make_test_session(&auth_path); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/archives/test/captures/text") + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(Body::from( + r#"{"title":"Test Note","body":"Test content","mime":"text/markdown"}"#, + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::ACCEPTED); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert!( + json["job_uid"].as_str().is_some(), + "response must have job_uid" + ); + assert_eq!(json["status"], "pending"); + } + + #[tokio::test] + async fn text_capture_accepts_a_body_just_below_two_mebibytes() { + let dir = tempfile::tempdir().unwrap(); + let (registry, _, auth_path) = make_test_registry(&dir); + let session_cookie = make_test_session(&auth_path); + let body = "a".repeat(2 * 1024 * 1024 - 1); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/archives/test/captures/text") + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(json_body(&serde_json::json!({ + "title": "Maximum-size note", + "body": body, + "mime": "text/plain" + }))) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::ACCEPTED); + } + + #[tokio::test] + async fn text_capture_accepts_a_two_mebibyte_body_with_json_escaped_controls() { + let dir = tempfile::tempdir().unwrap(); + let (registry, _, auth_path) = make_test_registry(&dir); + let session_cookie = make_test_session(&auth_path); + let body = "\0".repeat(2 * 1024 * 1024); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/archives/test/captures/text") + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(json_body(&serde_json::json!({ + "title": "Escaped control note", + "body": body, + "mime": "text/plain" + }))) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::ACCEPTED); + } + + #[tokio::test] + async fn text_capture_rejects_a_body_over_two_mebibytes_with_validation_error() { + let dir = tempfile::tempdir().unwrap(); + let (registry, _, auth_path) = make_test_registry(&dir); + let session_cookie = make_test_session(&auth_path); + let body = "a".repeat(2 * 1024 * 1024 + 1); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/archives/test/captures/text") + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(json_body(&serde_json::json!({ + "title": "Oversized note", + "body": body, + "mime": "text/plain" + }))) + .unwrap(), + ) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let response_body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let json: serde_json::Value = serde_json::from_slice(&response_body).unwrap(); + assert_eq!(json["error"], "body must not exceed 2 MiB"); + } + + #[tokio::test] + async fn text_capture_post_preserves_intentional_whitespace() { + let dir = tempfile::tempdir().unwrap(); + let (registry, archive_path, auth_path) = make_test_registry(&dir); + let session_cookie = make_test_session(&auth_path); + let text_body = " \n# Heading\n\nContent with a final newline\n\t \n"; + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/archives/test/captures/text") + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(json_body(&serde_json::json!({ + "title": "Whitespace Note", + "body": text_body, + "mime": "text/markdown" + }))) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::ACCEPTED); + let response_body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let job_uid = serde_json::from_slice::(&response_body).unwrap()["job_uid"] + .as_str() + .unwrap() + .to_string(); + + let status = tokio::time::timeout(std::time::Duration::from_secs(2), async { + loop { + let conn = archivr_core::database::open_or_initialize(&archive_path).unwrap(); + let job = archivr_core::database::get_capture_job(&conn, &job_uid) + .unwrap() + .unwrap(); + if job.status != "pending" && job.status != "running" { + break job.status; + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .expect("text capture job should finish"); + assert_eq!(status, "completed"); + + let archive_paths = archivr_core::archive::read_archive_paths(&archive_path).unwrap(); + let conn = archivr_core::database::open_or_initialize(&archive_path).unwrap(); + let raw_relpath: String = conn + .query_row( + "SELECT b.raw_relpath + FROM entry_artifacts ea + JOIN blobs b ON b.id = ea.blob_id + WHERE ea.artifact_role = 'primary_media'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!( + std::fs::read(archive_paths.store_path.join(raw_relpath)).unwrap(), + text_body.as_bytes() + ); + } + + #[tokio::test] + async fn text_capture_rejects_empty_title() { + let dir = tempfile::tempdir().unwrap(); + let (registry, _, auth_path) = make_test_registry(&dir); + let session_cookie = make_test_session(&auth_path); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/archives/test/captures/text") + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(Body::from( + r#"{"title":"","body":"Test content","mime":"text/plain"}"#, + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert!(json["error"] + .as_str() + .is_some_and(|e| e.contains("title must not be empty"))); + } + + #[tokio::test] + async fn text_capture_rejects_empty_body() { + let dir = tempfile::tempdir().unwrap(); + let (registry, _, auth_path) = make_test_registry(&dir); + let session_cookie = make_test_session(&auth_path); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/archives/test/captures/text") + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(Body::from( + r#"{"title":"Test Note","body":"","mime":"text/plain"}"#, + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert!(json["error"] + .as_str() + .is_some_and(|e| e.contains("body must not be empty"))); + } + + #[tokio::test] + async fn text_capture_rejects_unsupported_mime() { + let dir = tempfile::tempdir().unwrap(); + let (registry, _, auth_path) = make_test_registry(&dir); + let session_cookie = make_test_session(&auth_path); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/archives/test/captures/text") + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(Body::from( + r#"{"title":"Test Note","body":"Test content","mime":"text/html"}"#, + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert!(json["error"] + .as_str() + .is_some_and(|e| e.contains("unsupported MIME type"))); + } + + #[tokio::test] + async fn text_capture_requires_auth() { + let (test_app, _dir) = make_test_app(); + let response = test_app + .oneshot( + Request::builder() + .method("POST") + .uri("/api/archives/test/captures/text") + .header("content-type", "application/json") + .body(Body::from( + r#"{"title":"Test","body":"Content"}"#, + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + } + #[tokio::test] async fn probe_requires_auth() { let (test_app, _dir) = make_test_app(); diff --git a/crates/archivr-server/static/assets/index-1h0SqIvL.css b/crates/archivr-server/static/assets/index-1h0SqIvL.css new file mode 100644 index 0000000..6ff3448 --- /dev/null +++ b/crates/archivr-server/static/assets/index-1h0SqIvL.css @@ -0,0 +1 @@ +@import"https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@500;600&family=Spectral:wght@500;600&display=swap";:root{color-scheme:light;--ink: #20251f;--muted: #6b6f66;--muted-2: #8a8d83;--paper: #f5f0e7;--paper-2: #e9e1d2;--paper-3: #fffaf0;--line: #d2c6b5;--line-soft: #e5dccd;--accent: #8d3f30;--accent-2: #b78342;--link: #245f72;--top: #141d18;--field: #fffdf7;--r: 3px;--r2: 6px;--r3: 10px;--sans: "Helvetica Neue", Helvetica, Arial, sans-serif;--serif: "Spectral", Georgia, "Times New Roman", serif;--display: "Cormorant Garamond", Georgia, serif}*{box-sizing:border-box}body{margin:0;min-height:100vh;background:var(--paper);color:var(--ink);font-family:var(--sans);font-size:14px;-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}button,input,select{font:inherit}.workspace,.context-rail{scrollbar-width:thin;scrollbar-color:var(--line) transparent}.workspace::-webkit-scrollbar,.context-rail::-webkit-scrollbar{width:11px;height:11px}.workspace::-webkit-scrollbar-track,.context-rail::-webkit-scrollbar-track{background:transparent}.workspace::-webkit-scrollbar-thumb,.context-rail::-webkit-scrollbar-thumb{background:var(--line);border-radius:999px;border:3px solid transparent;background-clip:padding-box}.workspace::-webkit-scrollbar-thumb:hover,.context-rail::-webkit-scrollbar-thumb:hover{background:var(--muted-2);background-clip:padding-box;border:3px solid transparent}.topbar{height:58px;display:grid;grid-template-columns:auto auto 1fr auto auto;align-items:center;gap:26px;padding:0 22px;background:var(--top);color:#efe6d6;border-bottom:3px solid var(--accent)}.brand{font-family:var(--display);font-weight:600;font-size:30px;line-height:1;letter-spacing:.01em;color:#f4ead8}.switcher{position:relative;display:inline-flex;align-items:center}.switcher select{-moz-appearance:none;appearance:none;-webkit-appearance:none;border:1px solid rgba(247,238,223,.2);background:#f7eedf0f;color:#f1e8d8;font-family:var(--sans);font-weight:550;font-size:13.5px;letter-spacing:.04em;padding:8px 32px 8px 15px;cursor:pointer;border-radius:6px;transition:background .15s ease,border-color .15s ease}.switcher select:hover{background:#f7eedf1c;border-color:#f7eedf57}.switcher:after{content:"";position:absolute;right:15px;top:50%;width:6px;height:6px;margin-top:-5px;border-right:1.2px solid #b6ab98;border-bottom:1.2px solid #b6ab98;transform:rotate(45deg);pointer-events:none}.switchers{display:flex;gap:8px;align-items:center;min-width:0}.nav{display:flex;gap:22px;justify-content:flex-end;min-width:0}.nav-link{border:0;background:transparent;color:#cdc1ad;cursor:pointer;padding:6px 0;font-size:12.5px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;position:relative}.nav-link:hover,.nav-link.is-active{color:#f4ead8}.nav-link.is-active:after{content:"";position:absolute;left:0;right:0;bottom:-2px;height:1px;background:var(--accent-2)}.capture-button{display:inline-flex;align-items:center;gap:8px;position:relative;overflow:hidden;border:0;background:linear-gradient(180deg,color-mix(in srgb,var(--accent) 88%,#fff) 0%,var(--accent) 55%);color:#f7eddd;padding:10px 18px;cursor:pointer;font-size:12px;font-weight:600;letter-spacing:.15em;text-transform:uppercase;border-radius:var(--r);box-shadow:inset 0 1px #fff5e629,0 1px 2px #141d184d;transition:filter .18s ease,box-shadow .18s ease}.capture-button:hover{filter:brightness(.93);box-shadow:inset 0 1px #fff5e61f,0 2px 6px #141d1857}.capture-button:before{content:"";position:absolute;top:0;bottom:0;left:0;width:45%;background:linear-gradient(100deg,transparent 0%,rgba(255,246,232,.45) 50%,transparent 100%);transform:translate(-180%) skew(-18deg);pointer-events:none}@media (prefers-reduced-motion: no-preference){.capture-button:hover:before{animation:cap-sheen .7s ease}}@keyframes cap-sheen{0%{transform:translate(-180%) skew(-18deg)}to{transform:translate(340%) skew(-18deg)}}.app-shell{height:calc(100vh - 58px);display:grid;grid-template-columns:minmax(0,1fr) 340px}.workspace{min-width:0;overflow:auto;display:flex;flex-direction:column}.view{display:none}.view.is-active{display:block}.toolbar{position:sticky;top:0;z-index:3;display:flex;align-items:center;gap:16px;padding:12px 22px;background:color-mix(in srgb,var(--paper) 88%,white);border-bottom:1px solid var(--line-soft)}.search-field{position:relative;flex:1 1 auto;min-width:0;display:flex;align-items:center;height:42px;background:var(--field);border:1px solid var(--line);border-radius:20px;transition:border-color .15s ease,box-shadow .15s ease}.search-field:focus-within{border-color:var(--accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 14%,transparent)}.search-field .ico{display:grid;place-items:center;width:46px;height:100%;color:var(--muted-2);flex-shrink:0}.search-field .ico svg{width:16px;height:16px}.search-input{flex:1;min-width:0;height:100%;border:0;background:transparent;color:var(--ink);padding:0 6px 0 0;font-size:14px;letter-spacing:.01em;outline:none}.search-input::placeholder{color:var(--muted-2)}.search-field .kbd{margin-right:12px;display:inline-flex;align-items:center;padding:3px 7px;font-size:11px;color:var(--muted);background:var(--paper-2);border:1px solid var(--line-soft);border-radius:var(--r);flex-shrink:0}.result-count{flex-shrink:0;font-size:13px;color:var(--muted);letter-spacing:.02em;white-space:nowrap}.result-count b{color:var(--ink);font-weight:600;font-variant-numeric:tabular-nums}.tag-filter-badge{display:inline-flex;align-items:center;gap:4px;background:var(--accent);color:#fff;border:0;border-radius:var(--r);font-size:12px;padding:2px 8px;cursor:pointer;margin-left:8px}.tag-filter-badge:hover{opacity:.85}.entry-table{width:100%;font-size:12.5px}.entry-header-row{display:flex;align-items:stretch;position:sticky;top:67px;z-index:2;background:color-mix(in srgb,var(--paper) 92%,white);border-bottom:1px solid var(--line-soft);color:var(--muted);font-size:10.5px;text-transform:uppercase;letter-spacing:.08em}.entry-header-row>div{padding:9px 10px;flex-shrink:0;font-weight:600;display:flex;align-items:center}#entries-body>div{display:flex;align-items:center;cursor:default;border-bottom:1px solid var(--line-soft)}#entries-body>div>div{padding:7px 10px;flex-shrink:0;overflow:hidden}#entries-body>div:not(.entry-row-outer):nth-child(2n){background:#f2ede5}#entries-body>div:not(.entry-row-outer):nth-child(odd){background:var(--paper-3)}#entries-body>.entry-row-outer--light{background:var(--paper-3)}#entries-body>.entry-row-outer--dark{background:#f2ede5}#entries-body>div.is-selected{background:#eee2d2;box-shadow:inset 0 0 0 2px var(--accent)}#entries-body>div.is-multi-selected{background:#eee2d2;box-shadow:inset 0 0 0 2px var(--accent)}.col-added{width:162px;color:var(--muted)}.col-title{flex:1 1 0;min-width:0;overflow:hidden;display:flex;align-items:center;gap:.42em}.col-type{width:116px}.col-size{width:100px;display:flex;flex-direction:column;justify-content:center;gap:1px}.size-total{font-variant-numeric:tabular-nums}.size-cached-pct{font-size:10px;color:var(--muted);opacity:.8;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.col-url{flex:0 0 30%;min-width:0;overflow:hidden}.entry-header-row .col-added,#entries-body>div .col-added{padding-left:22px}.entry-header-row>div:last-child,#entries-body>div>div:last-child{padding-right:22px}.entry-title{color:var(--link);font-weight:700;min-width:0}.entry-header-row>div{padding:9px 10px;flex-shrink:0;font-weight:600}.source-icon{display:flex;align-items:center;justify-content:center;width:1.05em;height:1.05em;flex-shrink:0}.source-icon>*{width:100%;height:100%;display:flex;align-items:center;justify-content:center}.source-icon svg{width:100%;height:100%}.url-cell{color:#555b55;white-space:nowrap;text-overflow:ellipsis;word-break:break-all}#entries-body .url-cell:hover{overflow:visible;white-space:normal}.type-pill{display:inline-block;padding:2px 6px;background:#d8e3df;color:#275a5f;border:1px solid #bfd0ca;border-radius:var(--r)}.col-check{display:none;width:40px;flex-shrink:0;align-items:center;justify-content:center;padding:0!important;cursor:pointer}.row-checkbox{-webkit-appearance:none;-moz-appearance:none;appearance:none;padding:0;border:1.5px solid var(--line);cursor:pointer;display:block;width:17px;height:17px;border-radius:4px;background:var(--paper-3);transition:border-color .15s ease,background .15s ease;position:relative;flex-shrink:0}.row-checkbox.is-checked{background:var(--accent);border-color:var(--accent)}.row-checkbox.is-checked:after{content:"";position:absolute;left:4px;top:2px;width:5px;height:8px;border:2px solid #fff;border-top:none;border-left:none;transform:rotate(45deg)}@media (pointer: coarse){.col-check{display:flex}.entry-header-row .col-added,#entries-body>div .col-added{padding-left:10px}}#runs-view .entry-table{border-collapse:collapse;table-layout:auto}#runs-view .entry-table th{position:sticky;top:0;z-index:1;text-align:left;padding:10px;background:color-mix(in srgb,var(--paper) 92%,white);color:var(--muted);border-bottom:1px solid var(--line-soft);font-size:10.5px;text-transform:uppercase;letter-spacing:.08em}#runs-view .entry-table td{padding:10px;border-bottom:1px solid var(--line-soft);vertical-align:top}#runs-view .entry-table tr:nth-child(2n) td{background:#f2ede5}#runs-view .entry-table tr:nth-child(odd) td{background:var(--paper-3)}.context-rail{border-left:1px solid var(--line);background:var(--paper);padding:20px 20px 32px;overflow:auto}.rail-eyebrow{font-size:10.5px;font-weight:600;letter-spacing:.16em;text-transform:uppercase;color:var(--muted-2);margin-bottom:16px}.rail-title{display:block;font-family:var(--sans);font-weight:700;font-size:15.5px;line-height:1.4;color:var(--ink);margin:0 0 16px;word-break:break-word}.url-tile{display:flex;align-items:center;gap:9px;padding:10px 12px;background:var(--paper-3);border:1px solid var(--line);border-radius:var(--r3);margin-bottom:20px;text-decoration:none}.url-tile:hover{background:var(--field);border-color:var(--accent)}.url-tile .ico{color:var(--ink);flex-shrink:0;display:grid;place-items:center}.url-tile .ico svg{width:15px;height:15px}.url-tile .u-text{min-width:0;flex:1;font-size:12.5px;color:var(--link);font-family:ui-monospace,SF Mono,Menlo,monospace;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.url-tile .ext{color:var(--muted-2);flex-shrink:0}.url-tile .ext svg{width:13px;height:13px;display:block}.meta-list{margin-bottom:24px;border-top:1px solid var(--line-soft)}.meta-item{display:grid;grid-template-columns:92px 1fr;gap:14px;align-items:baseline;padding:9px 0;border-bottom:1px solid var(--line-soft)}.meta-k{font-size:10.5px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--muted-2)}.meta-v{font-size:13.5px;color:var(--ink);word-break:break-word;line-height:1.4}.meta-v.mono{font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:12px;color:var(--muted)}.rail-section{margin-bottom:24px}.rail-section-heading{display:flex;align-items:baseline;gap:8px;font-size:10.5px;font-weight:600;text-transform:uppercase;letter-spacing:.12em;color:var(--muted-2);margin-bottom:9px;padding-bottom:8px;border-bottom:1px solid var(--line)}.rail-section-heading .num{color:var(--muted-2);font-weight:600}.artifact-list{list-style:none;margin:0;padding:0}.artifact-link{display:flex;align-items:baseline;justify-content:space-between;gap:12px;padding:7px 2px;border-bottom:1px solid var(--line-soft);text-decoration:none}.artifact-link:last-child{border-bottom:0}.artifact-name{font-size:13px;color:var(--link);min-width:0;word-break:break-word}.artifact-link:hover .artifact-name{text-decoration:underline}.artifact-size{font-size:11.5px;color:var(--muted-2);flex-shrink:0;font-variant-numeric:tabular-nums}.artifact-group{list-style:none}.artifact-group-header{width:100%;background:none;border:none;border-bottom:1px solid var(--line-soft);cursor:pointer;text-align:left;color:inherit;font:inherit}.artifact-group-header:hover .artifact-name{text-decoration:underline}.artifact-group-chevron{display:inline-block;font-style:normal;transition:transform .15s ease;transform:rotate(0);transform-origin:45% 50%;margin-right:3px}.artifact-group-chevron.open{transform:rotate(90deg)}.artifact-group-body{padding-left:14px}.tags-wrap{display:flex;flex-wrap:wrap;gap:7px;margin:0 0 12px}.tag-pill{display:inline-flex;align-items:center;gap:7px;background:var(--paper-2);border:1px solid var(--line);border-radius:var(--r);font-size:12px;padding:4px 7px 4px 10px;color:var(--ink)}.tag-pill .remove{border:0;background:transparent;cursor:pointer;color:var(--muted-2);width:15px;height:15px;display:grid;place-items:center;font-size:13px;line-height:1}.tag-pill .remove:hover{color:var(--accent)}.tags-empty{font-size:13px;color:var(--muted);margin:0 0 11px}.tag-input-wrap{display:flex;align-items:center;gap:8px;background:var(--field);border:1px solid var(--line);border-radius:var(--r2);padding:2px 2px 2px 11px;transition:border-color .15s ease,box-shadow .15s ease}.tag-input-wrap:focus-within{border-color:var(--accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 12%,transparent)}.tag-input-wrap .hash{color:var(--muted-2);font-size:13px}.tag-input{flex:1;min-width:0;border:0;background:transparent;color:var(--ink);font-size:13px;padding:6px 0;outline:none;font-family:ui-monospace,SF Mono,Menlo,monospace}.tag-add-btn{border:0;background:var(--ink);color:var(--paper-3);padding:6px 13px;font-size:11.5px;letter-spacing:.06em;text-transform:uppercase;border-radius:var(--r);cursor:pointer;white-space:nowrap}.tag-add-btn:hover{background:#2c332b}.coll-row{display:flex;align-items:center;justify-content:space-between;gap:12px;overflow:hidden;padding:9px 13px;background:var(--field);border:1px solid var(--line);border-radius:var(--r2);margin-bottom:6px;transition:border-color .15s ease}.coll-row:hover{border-color:var(--accent)}.coll-name{font-size:13px;color:var(--ink);font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.vis-badge{display:inline-flex;align-items:center;gap:6px;font-size:11px;color:var(--muted);background:var(--paper-2);border:1px solid var(--line-soft);border-radius:999px;padding:3px 10px}.vis-badge:before{content:"";width:6px;height:6px;border-radius:50%;background:var(--accent-2)}.bulk-panel{padding-top:2px}.bulk-count{font-size:13px;color:var(--muted);margin-bottom:22px}.bulk-count-num{font-size:22px;font-weight:700;color:var(--ink);line-height:1;margin-right:4px}.bulk-coll-row{display:flex;align-items:center;gap:8px}.bulk-coll-select{flex:1;min-width:0;height:32px;padding:0 8px;border:1px solid var(--line);border-radius:var(--r);background:var(--field);color:var(--ink);font-size:13px;cursor:pointer;outline:none;transition:border-color .15s ease}.bulk-coll-select:focus{border-color:var(--accent)}.tag-add-btn:disabled{opacity:.45;cursor:default}.rail-delete-zone{margin-top:24px;padding-top:20px;border-top:1px solid var(--line-soft)}.rail-delete-btn{width:100%;padding:8px 14px;background:none;border:1px solid color-mix(in srgb,var(--accent) 45%,transparent);color:var(--accent);border-radius:var(--r);cursor:pointer;font-size:12.5px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;transition:background .15s ease,border-color .15s ease}.rail-delete-btn:hover{background:color-mix(in srgb,var(--accent) 8%,transparent);border-color:var(--accent)}.rail-rearchive-btn{width:100%;padding:6px 12px;background:var(--surface-2, #2a2a2a);color:var(--text, #e0e0e0);border:1px solid var(--border, #444);border-radius:4px;cursor:pointer;font-size:13px}.rail-rearchive-btn:hover:not(:disabled){background:var(--surface-3, #333)}.rail-rearchive-btn:disabled{opacity:.6;cursor:not-allowed}.capture-dialog{border:1px solid var(--line);background:var(--paper);padding:0;width:min(540px,calc(100vw - 32px));border-radius:var(--r3);box-shadow:0 20px 60px #141d1847}.capture-dialog::backdrop{background:#141d1873}.capture-dialog-inner{padding:28px}.capture-dialog-title{margin:0;font-size:22px;font-family:var(--display);font-weight:600}.capture-label{display:block;font-size:11px;font-weight:600;margin-bottom:6px;color:var(--muted-2);text-transform:uppercase;letter-spacing:.06em}.capture-input{width:100%;height:44px;border:1px solid var(--line);background:var(--field);color:var(--ink);padding:0 14px;font-size:15px;margin-bottom:10px;border-radius:var(--r2);outline:none;transition:border-color .15s ease,box-shadow .15s ease}.capture-input:focus{border-color:var(--accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 14%,transparent)}.form-field .capture-input{margin-bottom:0}.capture-error{color:var(--accent);font-size:13px;margin-bottom:10px;min-height:18px}.capture-actions{display:flex;flex-direction:column;gap:8px;margin-top:18px}.capture-submit{border:0;background:var(--ink);color:var(--paper);padding:13px 20px;border-radius:var(--r2);cursor:pointer;font-weight:600;font-size:15px;width:100%;min-width:220px;letter-spacing:.01em}.capture-submit:hover{opacity:.85}.capture-submit:disabled{opacity:.45;cursor:default}.capture-cancel{border:0;background:none;color:var(--muted);padding:7px 18px;border-radius:var(--r);cursor:pointer;font-size:13px;text-align:center;width:100%}.capture-cancel:hover{color:var(--ink);background:var(--paper-2)}.capture-advanced{margin-top:12px}.capture-advanced-toggle{display:flex;align-items:center;gap:5px;background:none;border:0;cursor:pointer;color:var(--muted);font-size:12.5px;padding:4px 0;border-radius:var(--r)}.capture-advanced-toggle:hover{color:var(--ink)}.capture-chevron{width:14px;height:14px;flex-shrink:0;transition:transform .18s ease}.capture-chevron--open{transform:rotate(180deg)}.capture-advanced-panel{margin-top:8px;padding:10px 12px;border:1px solid var(--line);border-radius:var(--r2);background:var(--paper-2)}.capture-ext-row{display:flex;align-items:center;justify-content:space-between;gap:12px;cursor:default}.capture-ext-label{flex:1;min-width:0}.capture-ext-name{display:block;font-size:13px;font-weight:600;color:var(--ink)}.capture-ext-desc{display:block;font-size:11.5px;color:var(--muted);margin-top:1px}.capture-dialog-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:20px}.capture-dialog-close{flex-shrink:0;background:none;border:0;cursor:pointer;color:var(--muted);width:28px;height:28px;display:grid;place-items:center;border-radius:var(--r);padding:0}.capture-dialog-close svg{width:14px;height:14px}.capture-dialog-close:hover{background:var(--paper-2);color:var(--ink)}.capture-rows{display:flex;flex-direction:column;gap:8px;margin-bottom:8px}.capture-row{display:flex;flex-direction:column;gap:3px}.capture-row-main{display:flex;align-items:center;gap:8px}.capture-row-main .capture-input{margin-bottom:0}.capture-quality{flex-shrink:0;height:32px;padding:0 6px;border:1px solid var(--line);border-radius:var(--r);background:var(--paper);color:var(--ink);font-size:12px;cursor:pointer;outline:none;transition:border-color .15s}.capture-quality:hover{border-color:var(--accent-2)}.capture-quality:focus{border-color:var(--accent)}.capture-quality:disabled{opacity:.5;cursor:default}.capture-quality-probing{flex-shrink:0;font-size:12px;color:var(--muted);padding:0 4px;letter-spacing:.05em}.capture-quality-hint{flex-shrink:0;font-size:12px;color:var(--muted);font-style:italic}.capture-quality-hint--error{color:#c05000;font-style:normal}.cap-dot{flex-shrink:0;width:20px;height:20px;border-radius:50%;display:grid;place-items:center;font-size:10px;font-weight:700;line-height:1}.cap-dot--idle{background:var(--paper-2)}.cap-dot--running{background:#fdefd8;color:#8a4f10}.cap-dot--ok{background:#d8eddf;color:#235c35}.cap-dot--err{background:#f5ddd8;color:#8d3f30}.cap-spinner{display:block;width:10px;height:10px;border:2px solid currentColor;border-top-color:transparent;border-radius:50%;animation:cap-spin .7s linear infinite}@keyframes cap-spin{to{transform:rotate(360deg)}}.capture-row-action{flex-shrink:0;background:none;border:0;cursor:pointer;color:var(--muted);width:28px;height:28px;display:grid;place-items:center;border-radius:var(--r);padding:0}.capture-row-action svg{width:12px;height:12px}.capture-row-action:hover{color:var(--accent);background:var(--paper-2)}.capture-row-remove:hover{color:var(--accent)}.capture-row-error{margin:0;padding-left:28px;font-size:12px;color:var(--accent);line-height:1.45}.capture-text-row>.capture-row-main{align-items:flex-start}.capture-text-icon{flex-shrink:0;width:20px;height:44px;display:grid;place-items:center;color:var(--muted)}.capture-text-inputs{flex:1 1 auto;min-width:0;display:flex;flex-direction:column;gap:8px}.capture-text-input{width:100%;border:1px solid var(--line);background:var(--field);color:var(--ink);border-radius:var(--r2);outline:none;transition:border-color .15s ease,box-shadow .15s ease;font-family:inherit}.capture-text-input:focus{border-color:var(--accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 14%,transparent)}.capture-text-title{height:44px;padding:0 14px;font-size:15px}.capture-text-body{min-height:140px;padding:10px 14px;font-size:14px;line-height:1.55;resize:vertical}.capture-text-body::placeholder,.capture-text-title::placeholder{color:var(--muted)}.capture-text-footer{display:flex;align-items:center;gap:8px;justify-content:flex-end}.capture-text-mime{flex-shrink:0;height:28px;padding:0 26px 0 10px;border:1px solid var(--line);border-radius:var(--r);background:var(--paper);color:var(--ink);font-size:12px;cursor:pointer;outline:none;transition:border-color .15s;-moz-appearance:none;appearance:none;-webkit-appearance:none;background-image:url("data:image/svg+xml;utf8,");background-repeat:no-repeat;background-position:right 8px center}.capture-text-mime:hover{border-color:var(--accent-2)}.capture-text-mime:focus{border-color:var(--accent)}.capture-text-row .capture-row-action{margin-top:8px}.capture-add-row{display:flex;align-items:center;gap:7px;width:100%;background:none;border:1px dashed var(--line);border-radius:var(--r);color:var(--muted);font-size:13px;cursor:pointer;padding:7px 12px;margin-top:4px;margin-bottom:18px;transition:border-color .15s,color .15s,background .15s}.capture-add-row svg{width:13px;height:13px;flex-shrink:0}.capture-add-row:hover{border-color:var(--accent-2);color:var(--ink);background:var(--paper-2)}.capture-add-row-group{display:flex;gap:8px;margin-top:4px;margin-bottom:18px}.capture-add-row-group .capture-add-row{margin-top:0;margin-bottom:0;flex:1}.capture-dialog--dragover .capture-dialog-inner{outline:2px dashed var(--accent);outline-offset:-6px;border-radius:var(--r3)}.capture-file-icon{flex-shrink:0;color:var(--muted);display:flex;align-items:center}.capture-file-name{flex:1;min-width:0;font-size:13.5px;color:var(--ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.capture-file-name--error{color:var(--accent)}.capture-file-progress-wrap{flex-shrink:0;display:flex;align-items:center;gap:6px}.capture-file-progress-bar{width:80px;height:4px;border-radius:2px;background:var(--paper-2);overflow:hidden;border:1px solid var(--line)}.capture-file-progress-fill{display:block;height:100%;background:var(--ink);border-radius:2px;transition:width .1s ease}.capture-file-progress-pct{font-size:11px;color:var(--muted);min-width:28px;text-align:right}.capture-file-badge{flex-shrink:0;width:18px;height:18px;border-radius:50%;display:grid;place-items:center;font-size:11px;font-weight:700;line-height:1}.capture-file-badge--done{background:#d8eddf;color:#235c35}.capture-file-badge--error{background:#f5ddd8;color:#8d3f30}.toast-stack{position:fixed;bottom:24px;right:24px;z-index:9000;display:flex;flex-direction:column;gap:10px;width:340px;max-width:calc(100vw - 32px);pointer-events:none}.toast{pointer-events:auto;background:var(--paper);border:1px solid var(--line);border-radius:var(--r2);box-shadow:0 6px 24px #141d182e,0 1px 4px #141d181a;overflow:hidden;animation:toast-slide-in .22s cubic-bezier(.22,.68,0,1.2)}@keyframes toast-slide-in{0%{opacity:0;transform:translateY(10px) scale(.97)}to{opacity:1;transform:translateY(0) scale(1)}}.toast--error{border-left:3px solid var(--accent)}.toast--warning{border-left:3px solid #e8a000}.toast--success{border-left:3px solid #22a855}.toast-top{display:flex;align-items:flex-start;gap:10px;padding:12px 12px 12px 14px}.toast-icon{flex-shrink:0;font-size:13px;font-weight:700;color:var(--accent);margin-top:2px}.toast--success .toast-icon{color:#22a855}.toast--warning .toast-icon{color:#e8a000}.toast-body{flex:1;min-width:0}.toast-headline{display:block;font-size:13.5px;font-weight:600;color:var(--ink);line-height:1.3}.toast-locator{display:block;font-size:12px;color:var(--muted);margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.toast-btns{display:flex;align-items:center;gap:6px;flex-shrink:0}.toast-view-btn{background:none;border:1px solid var(--line);color:var(--link);font-size:12px;cursor:pointer;padding:3px 9px;border-radius:var(--r);white-space:nowrap}.toast-view-btn:hover{background:var(--paper-2);border-color:var(--link)}.toast-dismiss{background:none;border:0;cursor:pointer;color:var(--muted);font-size:20px;line-height:1;width:24px;height:24px;display:grid;place-items:center;border-radius:var(--r);padding:0}.toast-dismiss:hover{color:var(--ink);background:var(--paper-2)}.toast-error-detail{margin:0;padding:10px 14px 12px;font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:11.5px;line-height:1.55;color:var(--muted);background:var(--paper-2);border-top:1px solid var(--line);white-space:pre-wrap;word-break:break-word;max-height:200px;overflow-y:auto}.toast-warning-detail{margin:0;padding:10px 14px 12px;font-size:12px;line-height:1.55;color:var(--muted);background:var(--paper-2);border-top:1px solid var(--line);white-space:pre-wrap;word-break:break-word}.toast-ignore-btn{color:var(--muted)}.ext-toggle{flex-shrink:0;position:relative;width:44px;height:24px;border-radius:12px;background:var(--line);border:0;cursor:pointer;transition:background .18s ease;padding:0}.ext-toggle--sm{width:36px;height:20px;border-radius:10px}.ext-toggle--on{background:var(--ink)}.ext-toggle:disabled{opacity:.4;cursor:default}.ext-toggle-knob{position:absolute;top:3px;left:3px;width:18px;height:18px;border-radius:50%;background:var(--paper);transition:transform .18s ease;display:block;box-shadow:0 1px 3px #0003}.ext-toggle--sm .ext-toggle-knob{width:14px;height:14px;top:3px;left:3px}.ext-toggle--on .ext-toggle-knob{transform:translate(20px)}.ext-toggle--sm.ext-toggle--on .ext-toggle-knob{transform:translate(16px)}.ext-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:12px}.ext-card{border:1px solid var(--line);border-radius:var(--r2);padding:16px 18px;background:var(--paper)}.ext-card-header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px}.ext-card-info{flex:1;min-width:0}.ext-card-name{display:block;font-weight:600;font-size:14px;margin-bottom:4px}.ext-card-desc{display:block;font-size:13px;color:var(--muted);line-height:1.5}.ext-card-hint{display:block;font-size:12px;color:#e8a000;margin-top:6px}.ext-card-hint code{font-size:11.5px}.form-hint{font-size:13px;color:var(--muted);line-height:1.55;margin:0}.muted{color:var(--muted)}.admin-view{padding:22px}.admin-list{display:grid;gap:10px;max-width:780px}.admin-archive{border:1px solid var(--line);background:var(--paper-3);padding:12px;border-radius:var(--r2)}.tag-tree{padding:20px 22px;max-width:320px}.tag-tree-header{display:flex;align-items:baseline;gap:10px;margin-bottom:14px;border-bottom:1px solid var(--line-soft);padding-bottom:10px}.tag-tree-title{font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.07em}.tag-tree-active{font-size:12px;color:var(--muted-2);font-style:italic}.tag-tree-list{list-style:none;margin:0;padding:0}.tag-children{padding-left:16px}.tag-node-btn{border:0;background:transparent;color:var(--link);cursor:pointer;padding:3px 0;text-align:left;font-size:13px;display:block;width:100%}.tag-node-btn:hover{text-decoration:underline}.tag-node-btn.is-active{font-weight:600;color:var(--ink)}.tag-node-row{display:flex;align-items:center;gap:4px}.tag-node-row .tag-node-btn{flex:1 1 0;min-width:0;display:flex;align-items:center;gap:4px;width:auto}.tag-node-btn .edit-icon{width:.75em;height:.75em;flex-shrink:0;vertical-align:-.1em;opacity:.35}.tag-node-btn:hover .edit-icon{opacity:.65}.tag-node-delete{flex-shrink:0;border:0;background:transparent;color:var(--muted-2);cursor:pointer;padding:0 3px;font-size:14px;line-height:1;opacity:0}.tag-node-row:hover .tag-node-delete{opacity:1}.tag-node-delete:hover{color:var(--accent)}.tag-rename-input{font-size:13px;flex:1 1 0;min-width:0;padding:2px 5px;border:1px solid var(--accent);border-radius:var(--r);background:var(--field);color:var(--ink);outline:none}.tag-node-label{flex-shrink:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tag-node-count{font-size:11px;color:var(--muted-2);font-weight:400;flex-shrink:0;margin-left:3px}.tag-tree-header{align-items:center}.tag-tree-actions{margin-left:auto;display:flex;gap:4px}.tag-tree-action-btn{font-size:11px;padding:2px 7px;border:1px solid var(--line);border-radius:var(--r);background:transparent;color:var(--muted);cursor:pointer;line-height:1.5;white-space:nowrap;transition:background .1s,color .1s}.tag-tree-action-btn:hover:not(:disabled){background:var(--paper-2);color:var(--ink)}.tag-tree-action-btn:disabled{opacity:.4;cursor:default}.tag-tree-action-btn--cancel{border-color:var(--accent);color:var(--accent)}.tag-tree-action-btn--cancel:hover{background:color-mix(in srgb,var(--accent) 8%,transparent)}.tag-tree-title--move{font-style:italic;color:var(--accent-2)}.tag-node-row--move-select .tag-node-btn{cursor:crosshair;color:var(--ink)}.tag-node-row--move-select .tag-node-btn:hover{background:color-mix(in srgb,var(--link) 10%,transparent);text-decoration:none;border-radius:var(--r)}.tag-picker-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:200;background:#00000073;display:flex;align-items:center;justify-content:center;padding:20px}.tag-picker-modal{background:var(--paper);border-radius:var(--r3);box-shadow:0 16px 56px #0000003d;width:300px;max-width:100%;display:flex;flex-direction:column;max-height:60vh}.tag-picker-header{display:flex;align-items:center;padding:12px 14px;border-bottom:1px solid var(--line);flex-shrink:0;gap:8px}.tag-picker-title{flex:1;font-size:13px;font-weight:600;color:var(--ink);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tag-picker-close{width:26px;height:26px;border-radius:50%;border:none;background:transparent;color:var(--muted-2);font-size:18px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0}.tag-picker-close:hover{background:var(--paper-2);color:var(--ink)}.tag-picker-body{flex:1;min-height:0;overflow-y:auto;padding:8px 12px 12px}.tag-picker-root-btn{display:block;width:100%;text-align:left;padding:5px 8px;margin-bottom:6px;border:1px dashed var(--line);border-radius:var(--r);background:transparent;color:var(--muted);font-size:12px;cursor:pointer}.tag-picker-root-btn:hover{background:var(--paper-2);color:var(--ink);border-color:var(--muted-2)}.tag-picker-tree{border-top:1px solid var(--line-soft);padding-top:6px;margin-top:2px}.tag-picker-node-btn{border:0;background:transparent;color:var(--link);cursor:pointer;padding:3px 6px;text-align:left;font-size:13px;display:block;width:100%;border-radius:var(--r)}.tag-picker-node-btn:hover{background:var(--paper-2);text-decoration:none}.tag-picker-empty{font-size:13px;color:var(--muted-2);margin:6px 0 0}.collections-view{padding:24px}.collections-heading{margin:0 0 16px;font-size:22px;font-family:var(--display);font-weight:600}.collections-error{color:var(--accent);font-size:13px;margin-bottom:8px}.coll-dismiss{background:none;border:none;cursor:pointer;color:var(--accent);font-size:16px;line-height:1;padding:0 4px}.collections-layout{display:grid;grid-template-columns:220px 1fr;gap:0;border:1px solid var(--line);border-radius:var(--r2);min-height:340px}.collections-sidebar{border-right:1px solid var(--line);overflow-y:auto}.coll-sidebar-row{display:flex;flex-direction:column;width:100%;padding:10px 14px;border:none;border-bottom:1px solid var(--line-soft);background:none;cursor:pointer;text-align:left;gap:2px}.coll-sidebar-row:hover{background:var(--paper-2)}.coll-sidebar-row.is-active{background:var(--paper-2);border-left:3px solid var(--accent)}.coll-row-name{font-size:14px;font-weight:600;color:var(--ink)}.coll-row-meta{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.04em}.coll-detail{padding:20px 24px;display:flex;flex-direction:column;gap:16px}.coll-detail--empty{justify-content:center;align-items:center}.coll-detail-header{display:flex;align-items:center;gap:12px}.coll-detail-name{margin:0;font-size:18px;font-family:var(--display);font-weight:600;flex:1}.coll-detail-name--editable{cursor:pointer}.coll-detail-name--editable:hover{color:var(--link)}.coll-edit-hint{font-size:14px;opacity:.5;margin-left:4px}.coll-rename-input{flex:1;font-size:16px;font-family:var(--display);border:1px solid var(--line);padding:4px 8px;background:var(--field);color:var(--ink);border-radius:var(--r)}.coll-delete-btn{border:1px solid var(--accent);background:none;color:var(--accent);padding:5px 12px;font-size:13px;cursor:pointer;border-radius:var(--r)}.coll-delete-btn:hover{background:var(--accent);color:var(--paper)}.coll-detail-vis{display:flex;align-items:center;gap:10px}.coll-vis-label{font-size:13px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.04em;white-space:nowrap}.coll-vis-select{border:1px solid var(--line);background:var(--paper-3);color:var(--ink);padding:4px 8px;font-size:13px;border-radius:var(--r)}.coll-section-heading{font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.06em;margin-bottom:8px}.coll-entries-section{flex:1}.coll-entries-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:2px}.coll-entry-row{display:flex;align-items:center;gap:10px;padding:7px 0;border-bottom:1px solid var(--line-soft)}.coll-entry-info{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.coll-entry-title{font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.coll-entry-kind{font-size:11px;text-transform:uppercase;letter-spacing:.04em}.coll-entry-actions{display:flex;align-items:center;gap:6px;flex-shrink:0}.coll-entry-vis-select{border:1px solid var(--line);background:var(--paper-3);color:var(--ink);padding:3px 6px;font-size:12px;border-radius:var(--r)}.coll-entry-remove{border:none;background:none;cursor:pointer;color:var(--muted);font-size:18px;line-height:1;padding:0 4px}.coll-entry-remove:hover{color:var(--accent)}.coll-add-entry-form{border-top:1px solid var(--line-soft);padding-top:12px}.coll-add-entry-row{display:flex;gap:8px;align-items:center}.coll-add-entry-input{flex:1;border:1px solid var(--line);background:var(--paper-3);color:var(--ink);padding:6px 10px;font-size:13px;min-width:0;border-radius:var(--r)}.coll-add-btn{border:none;background:var(--ink);color:var(--paper);padding:6px 14px;font-size:13px;font-weight:600;cursor:pointer;white-space:nowrap;border-radius:var(--r)}.coll-add-btn:hover{opacity:.85}.coll-add-btn:disabled{opacity:.45;cursor:default}.rail-public-summary{padding:4px 0}.rail-public-summary .rail-title{margin:0 0 10px}.auth-loading{min-height:100vh;display:flex;align-items:center;justify-content:center;color:var(--muted);font-size:15px;background:var(--paper)}.user-menu{display:flex;align-items:center;gap:14px;padding-left:6px;flex-shrink:0}.user-name{font-size:12.5px;color:var(--muted-2);letter-spacing:.01em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:140px}.logout-btn{border:1px solid rgba(255,255,255,.18);background:transparent;color:#c8bfb0;font-size:12px;padding:4px 11px;border-radius:var(--r);cursor:pointer;white-space:nowrap;transition:background .15s,color .15s}.logout-btn:hover{background:#ffffff1a;color:var(--paper)}.logout-btn:disabled{opacity:.5;cursor:default}.login-page,.setup-page{min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;background:var(--paper)}.login-card,.setup-card{width:100%;max-width:360px;padding:40px 36px 44px;background:var(--paper-3);border:1px solid var(--line);border-radius:var(--r3);box-shadow:0 2px 20px #141d1812}.login-brand,.setup-brand{font-family:var(--display);font-size:32px;font-weight:600;color:var(--ink);letter-spacing:-.01em;margin:0 0 6px}.login-tagline,.setup-tagline{font-size:13px;color:var(--muted);margin:0 0 28px}.login-field,.setup-field{display:flex;flex-direction:column;gap:5px;margin-bottom:14px}.login-label,.setup-label{font-size:11.5px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.06em}.login-input,.setup-input{width:100%;border:1px solid var(--line);background:var(--field);color:var(--ink);padding:9px 11px;font-size:14px;border-radius:var(--r2);outline:none;transition:border-color .15s}.login-input:focus,.setup-input:focus{border-color:var(--accent)}.login-error,.setup-error{font-size:13px;color:var(--accent);margin:4px 0 8px}.login-submit,.setup-submit{width:100%;margin-top:8px;border:none;background:var(--top);color:var(--paper);font-size:14px;font-weight:600;padding:11px 16px;border-radius:var(--r2);cursor:pointer;letter-spacing:.02em;transition:opacity .15s}.login-submit:hover,.setup-submit:hover{opacity:.85}.login-submit:disabled,.setup-submit:disabled{opacity:.45;cursor:default}.view-tabs{display:flex;gap:2px;margin-bottom:22px;border-bottom:1px solid var(--line-soft);padding-bottom:0}.view-tab{border:none;background:none;color:var(--muted);font-size:13px;font-weight:600;padding:7px 14px;cursor:pointer;border-bottom:2px solid transparent;margin-bottom:-1px;letter-spacing:.02em;transition:color .12s;text-transform:uppercase;letter-spacing:.06em;font-size:11.5px}.view-tab:hover{color:var(--ink)}.view-tab.is-active{color:var(--ink);border-bottom-color:var(--accent)}.form-section{margin-bottom:32px}.form-section h2{font-size:14px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.06em;margin:0 0 14px}.form-row{display:flex;gap:8px;margin-bottom:10px}.form-field{display:flex;flex-direction:column;gap:5px;margin-bottom:12px}.form-label{font-size:11.5px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}.field-input{border:1px solid var(--line);background:var(--field);color:var(--ink);padding:8px 10px;font-size:13.5px;border-radius:var(--r);outline:none;transition:border-color .15s;min-width:0}.field-input:focus{border-color:var(--accent)}.field-input--flex{flex:1}.form-msg{font-size:13px;margin:6px 0}.form-msg--ok{color:var(--link)}.form-msg--err{color:var(--accent)}.btn-primary{border:none;background:var(--top);color:var(--paper);font-size:13px;font-weight:600;padding:8px 16px;border-radius:var(--r);cursor:pointer;white-space:nowrap}.btn-primary:hover{opacity:.85}.btn-primary:disabled{opacity:.45;cursor:default}.btn-ghost{border:1px solid var(--line);background:none;color:var(--ink);font-size:13px;padding:7px 14px;border-radius:var(--r);cursor:pointer}.btn-ghost:hover{background:var(--paper-2)}.btn-danger{border:1px solid var(--accent);background:none;color:var(--accent);font-size:13px;padding:7px 14px;border-radius:var(--r);cursor:pointer}.btn-danger:hover{background:var(--accent);color:var(--paper)}.admin-view h1{font-family:var(--display);font-weight:600;font-size:26px;margin:0 0 20px}.admin-table{width:100%;border-collapse:collapse;font-size:13px;margin-bottom:28px}.admin-table th{text-align:left;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:var(--muted);padding:8px 10px;border-bottom:1px solid var(--line);background:var(--paper-2)}.admin-table th:first-child{padding-left:16px}.admin-table td{padding:9px 10px;border-bottom:1px solid var(--line-soft);color:var(--ink);vertical-align:middle}.admin-table td:first-child{padding-left:16px}.admin-table tr:hover td{background:var(--paper-2)}.admin-row-disabled td{opacity:.45}.admin-section{margin-bottom:36px;max-width:860px}.admin-section h2{font-size:14px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.06em;margin:0 0 14px}.admin-section h3{font-size:13px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.05em;margin:22px 0 10px}.admin-form{display:flex;flex-direction:column;gap:8px;max-width:480px}.admin-input{border:1px solid var(--line);background:var(--field);color:var(--ink);padding:8px 10px;font-size:13.5px;border-radius:var(--r);outline:none;transition:border-color .15s}.admin-input:focus{border-color:var(--accent)}.admin-action-btn{border:1px solid var(--line);background:none;color:var(--ink);font-size:12px;padding:4px 10px;border-radius:var(--r);cursor:pointer;white-space:nowrap}.admin-action-btn:hover{border-color:var(--accent);color:var(--accent)}.status-badge{display:inline-block;padding:2px 8px;border-radius:var(--r);font-size:11.5px;font-weight:600;text-transform:uppercase;letter-spacing:.04em}.status-active{background:#d8eddf;color:#235c35;border:1px solid #b4d9be}.status-disabled{background:#ede8e0;color:var(--muted);border:1px solid var(--line)}.run-status{display:inline-block;padding:2px 8px;border-radius:var(--r);font-size:11.5px;font-weight:600;text-transform:uppercase;letter-spacing:.04em}.run-status--completed{background:#d8eddf;color:#235c35;border:1px solid #b4d9be}.run-status--failed{background:#f5ddd8;color:#8d3f30;border:1px solid #e0b8b0}.run-status--in-progress{background:#fdefd8;color:#8a4f10;border:1px solid #f0cfa0}.run-row--failed{cursor:pointer}.run-row--failed:hover td{background:#fdf0ed!important}.run-expand-hint{margin-left:6px;font-size:10px;color:var(--accent);vertical-align:middle}.run-error-row td{padding:0!important;background:var(--paper-2)!important}.run-error-detail{margin:0;padding:10px 16px 12px;font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:11.5px;line-height:1.55;color:var(--muted);white-space:pre-wrap;word-break:break-word;max-height:220px;overflow-y:auto}.token-banner{background:#d8eddf;border:1px solid #b4d9be;padding:12px 14px;margin-bottom:16px;font-size:13px;border-radius:var(--r2)}.token-banner code{word-break:break-all;display:block;margin-top:6px;padding:6px 8px;background:var(--field);border:1px solid var(--line);border-radius:var(--r);font-size:12px;font-family:ui-monospace,SF Mono,Menlo,monospace}.token-dismiss{margin-top:8px;font-size:12px;border:1px solid var(--line);background:none;cursor:pointer;padding:3px 8px;border-radius:var(--r);color:var(--muted)}.token-dismiss:hover{background:var(--paper-2)}.token-row{display:flex;align-items:center;justify-content:space-between;border:1px solid var(--line);background:var(--paper-3);padding:10px 12px;border-radius:var(--r);margin-bottom:6px}.token-row-info strong{font-size:14px;display:block}.token-row-info .muted{font-size:12px;margin-top:2px}.token-create-row{display:flex;gap:8px;margin-bottom:16px}.checkbox-row{display:flex;align-items:center;gap:10px;margin-bottom:12px;cursor:pointer;font-size:14px}.checkbox-row input[type=checkbox]{width:15px;height:15px;accent-color:var(--accent)}.coll-create-details{margin-top:16px}.coll-create-details summary{font-weight:600;cursor:pointer;font-size:13px;color:var(--link);list-style:none;display:flex;align-items:center;gap:6px;padding:8px 12px;border:1px solid var(--line-soft);border-radius:var(--r2);background:var(--paper-3);width:fit-content}.coll-create-details summary:hover{background:var(--paper-2)}.coll-create-details[open] summary{border-bottom-left-radius:0;border-bottom-right-radius:0}.coll-create-form{border:1px solid var(--line-soft);border-top:none;padding:14px;border-radius:0 0 var(--r2) var(--r2);background:var(--paper-3);display:flex;flex-direction:column;gap:10px;max-width:440px}@media (max-width: 900px){.topbar{grid-template-columns:1fr auto;height:auto;min-height:58px;padding:12px}.switcher,.nav{grid-column:1 / -1}.nav{justify-content:flex-start;overflow-x:auto}.app-shell{height:auto;grid-template-columns:1fr}.context-rail{border-left:0;border-top:1px solid var(--line)}.entry-table{min-width:860px}}.rail-title--editable{cursor:pointer}.rail-title--editable:hover{opacity:.75}.rail-title--editable .edit-icon{display:inline-block;width:.75em;height:.75em;margin-left:.35em;vertical-align:middle;opacity:0;transition:opacity .1s;flex-shrink:0}.rail-title--editable:hover .edit-icon{opacity:.5}.rail-title-input{width:100%;font:inherit;font-size:inherit;font-weight:600;background:transparent;border:none;border-bottom:1px solid currentColor;color:inherit;padding:0;margin:0 0 8px;outline:none}.preview-panel{flex:1;display:flex;flex-direction:column;min-height:0}.preview-panel-loading,.preview-panel-empty{flex:1;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:8px;color:var(--muted-2);font-size:14px;text-align:center;padding:24px}.preview-video-wrap{flex:1;display:flex;align-items:center;justify-content:center;background:#0d0d0b;min-height:200px}.preview-video-wrap video{max-width:100%;max-height:100%;width:100%;display:block}.video-tv-controls{position:absolute;top:10px;right:10px;display:flex;gap:6px;z-index:10}.video-tv-btn{display:flex;align-items:center;justify-content:center;width:34px;height:34px;padding:0;border:none;border-radius:6px;background:#00000080;color:#ffffffd1;cursor:pointer;backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px);transition:background .15s,color .15s}.video-tv-btn:hover{background:#000000b8;color:#fff}google-cast-launcher.video-tv-btn{color:#ffffffd1}.video-tv-loading{width:100%;min-height:200px;background:#0d0d0b}.preview-iframe-wrap{flex:1;display:flex;flex-direction:column;min-height:0}.preview-iframe-toolbar{display:flex;flex-direction:column;gap:2px;padding:6px 12px;background:var(--paper-2);border-bottom:1px solid var(--line);flex-shrink:0;text-transform:none;letter-spacing:normal}.preview-iframe-toolbar span{font-size:11px;color:var(--muted-2)}.preview-iframe-toolbar a{margin-left:auto;color:var(--link);font-size:12px;text-decoration:none;padding:3px 8px;border:1px solid var(--line);border-radius:var(--r2);background:var(--field);transition:border-color .12s}.preview-iframe-toolbar a:hover{border-color:var(--accent);text-decoration:none}.preview-iframe-wrap iframe{flex:1;width:100%;border:none;background:#fff;min-height:0}.preview-image-wrap{flex:1;display:flex;align-items:center;justify-content:center;padding:20px;background:var(--paper-2)}.preview-image-wrap img{max-width:100%;max-height:100%;object-fit:contain;border-radius:var(--r3);cursor:zoom-in;display:block;box-shadow:0 4px 24px #0000001a}.preview-tweet-wrap{flex:1;min-height:0;overflow-y:auto;padding:12px 16px;background:var(--paper-2);scrollbar-width:thin;scrollbar-color:var(--line) transparent}.preview-tweet-wrap::-webkit-scrollbar{width:8px}.preview-tweet-wrap::-webkit-scrollbar-track{background:transparent}.preview-tweet-wrap::-webkit-scrollbar-thumb{background:var(--line);border-radius:999px;border:2px solid transparent;background-clip:padding-box}.preview-tweet-wrap::-webkit-scrollbar-thumb:hover{background:var(--muted-2);background-clip:padding-box;border:2px solid transparent}.tw-card{border:1px solid var(--line);border-radius:12px;padding:16px;background:var(--paper);max-width:560px;margin:0 auto 12px}.tw-thread{max-width:560px;margin:0 auto}.tw-thread-item{display:flex;gap:0;margin-bottom:0}.tw-thread-connector{display:flex;flex-direction:column;align-items:center;flex-shrink:0;width:52px;padding-top:2px}.tw-thread-avatar-col{display:flex;flex-direction:column;align-items:center;flex-shrink:0}.tw-thread-line{width:2px;background:var(--line);flex:1;min-height:16px;margin:4px 0}.tw-thread-body{flex:1;min-width:0;padding:0 0 16px 12px}.tw-thread-body:last-child{padding-bottom:0}.tw-avatar{width:40px;height:40px;border-radius:50%;object-fit:cover;flex-shrink:0;display:block}.tw-avatar-ph{width:40px;height:40px;border-radius:50%;background:var(--paper-2);border:1px solid var(--line);flex-shrink:0}.tw-header{display:flex;align-items:baseline;gap:6px;flex-wrap:wrap;margin-bottom:6px}.tw-author-name{font-size:14.5px;font-weight:700;color:var(--ink)}.tw-author-handle{font-size:13px;color:var(--muted-2)}.tw-dot{color:var(--muted-2);font-size:13px}.tw-date{font-size:13px;color:var(--muted-2)}.tw-text{font-size:15px;line-height:1.65;color:var(--ink);white-space:pre-line;word-break:break-word;margin-bottom:10px}.tw-text a{color:var(--link);text-decoration:none}.tw-text a:hover{text-decoration:underline}.tw-stats{display:flex;gap:20px;color:var(--muted-2);font-size:13px;margin-top:10px;padding-top:10px;border-top:1px solid var(--line-soft)}.tw-stats span{display:flex;align-items:center;gap:4px}.tw-article{max-width:598px;margin:0 auto}.tw-article-cover{width:100%;display:block;object-fit:cover;max-height:380px}.tw-article-meta{padding:20px 16px 0}.tw-article-title{font-size:22px;font-weight:800;letter-spacing:-.3px;color:var(--ink);line-height:1.3;margin-bottom:14px}.tw-article-author-row{display:flex;align-items:center;gap:12px;margin-bottom:14px}.tw-article-author-name{font-size:14px;font-weight:700;color:var(--ink)}.tw-article-author-sub{font-size:13px;color:var(--muted-2)}.tw-article-divider{border:none;border-top:1px solid var(--line);margin:0}.tw-article-body{padding:8px 16px 60px}.tw-b-h1{font-size:24px;font-weight:800;letter-spacing:-.3px;color:var(--ink);line-height:1.25;margin:22px 0 10px}.tw-b-h2{font-size:19px;font-weight:700;letter-spacing:-.15px;color:var(--ink);line-height:1.3;margin:20px 0 8px}.tw-b-p{font-size:16px;color:var(--ink);line-height:1.72;margin-bottom:14px}.tw-b-p:empty{display:none}.tw-b-spacer{height:6px;display:block}.tw-b-blockquote{border-left:3px solid var(--line);padding:2px 14px;margin:14px 0;color:var(--muted);font-size:16px;line-height:1.65}.tw-b-hr{border:none;border-top:1px solid var(--line);margin:24px 0}.tw-b-img{width:100%;display:block;border-radius:10px;margin:14px 0}.tw-b-ul,.tw-b-ol{margin:10px 0 14px;padding-left:26px}.tw-b-li{font-size:16px;color:var(--ink);line-height:1.65;margin-bottom:6px}.tw-b-code{font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:.875em;background:var(--paper-2);padding:2px 5px;border-radius:4px;color:var(--ink)}.tw-b-pre{background:var(--paper-2);border:1px solid var(--line);border-radius:8px;padding:14px 16px;overflow-x:auto;margin:12px 0}.tw-b-pre code{font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:13px;line-height:1.6}.tw-b-tweet-link{display:flex;align-items:center;gap:10px;border:1px solid var(--line);border-radius:10px;padding:12px 14px;margin:12px 0;color:var(--muted);font-size:14px;text-decoration:none;background:var(--paper-3);transition:background .12s}.tw-b-tweet-link:hover{background:var(--field)}.tw-b-tweet-link svg{flex-shrink:0;color:var(--ink)}.audio-bar{position:fixed;bottom:0;left:0;right:0;height:72px;background:var(--paper);border-top:1px solid var(--line);display:flex;align-items:center;gap:20px;padding:0 24px;z-index:100;box-shadow:0 -2px 16px #00000014}.audio-bar-info{display:flex;align-items:center;gap:10px;min-width:0;flex:0 0 200px}.audio-bar-icon{flex-shrink:0;width:20px;height:20px;display:flex;align-items:center;justify-content:center}.audio-bar-icon svg{width:20px;height:20px}.audio-bar-title{font-size:13px;color:var(--ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0;font-weight:500}.audio-bar-controls{flex:1;display:flex;align-items:center;gap:12px;min-width:0}.audio-bar-play-btn{width:38px;height:38px;border-radius:50%;background:var(--accent);color:var(--paper);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:background .12s,transform .1s}.audio-bar-play-btn:hover{background:var(--accent-2)}.audio-bar-play-btn:active{transform:scale(.93)}.audio-bar-play-btn svg{width:15px;height:15px}.audio-bar-seek{flex:1;min-width:0;display:flex;align-items:center;gap:8px}.audio-bar-seek input[type=range]{flex:1;accent-color:var(--accent);height:4px;cursor:pointer;min-width:0}.audio-bar-time{font-size:11.5px;color:var(--muted-2);white-space:nowrap;min-width:80px;text-align:right;font-variant-numeric:tabular-nums}.audio-bar-right{flex:0 0 auto;display:flex;align-items:center;gap:10px}.audio-bar-volume{display:flex;align-items:center;gap:6px}.audio-bar-volume svg{width:14px;height:14px;color:var(--muted-2);flex-shrink:0}.audio-bar-volume input[type=range]{width:72px;accent-color:var(--accent);cursor:pointer}.audio-bar-close{width:28px;height:28px;border-radius:50%;border:none;background:transparent;color:var(--muted-2);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:18px;padding:0;line-height:1;transition:background .12s,color .12s}.audio-bar-close:hover{background:var(--field);color:var(--ink)}.preview-modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:200;background:#0000008c;display:flex;align-items:center;justify-content:center;padding:20px}.preview-modal{background:var(--paper);border-radius:12px;box-shadow:0 24px 80px #00000047;width:90vw;max-width:1100px;max-height:88vh;display:flex;flex-direction:column;overflow:hidden}.preview-modal--full{height:88vh}.preview-modal--full .preview-modal-body{max-height:none}.preview-modal-header{display:flex;align-items:center;padding:14px 18px;border-bottom:1px solid var(--line);flex-shrink:0;gap:12px}.preview-modal-title{flex:1;min-width:0;font-size:14px;font-weight:600;color:var(--ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.preview-modal-close{width:30px;height:30px;border-radius:50%;border:none;background:transparent;color:var(--muted-2);font-size:20px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:background .12s,color .12s}.preview-modal-close:hover{background:var(--field);color:var(--ink)}.preview-modal-body{flex:1;min-height:0;overflow:hidden;display:flex;flex-direction:column;max-height:calc(88vh - 52px)}.rail-preview-btn{display:block;width:100%;padding:8px 12px;margin-bottom:16px;background:var(--accent);color:var(--paper);border:none;border-radius:var(--r3);font-size:13px;font-weight:600;cursor:pointer;text-align:center;transition:background .12s}.rail-preview-btn:hover{background:var(--accent-2)}.preview-modal-newtab{display:flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:var(--r2);color:var(--muted-2);text-decoration:none;font-size:16px;flex-shrink:0;transition:background .12s,color .12s}.preview-modal-newtab:hover{background:var(--field);color:var(--ink)}body.has-audio-bar{padding-bottom:56px}.in-progress-entry-row{box-sizing:border-box;min-width:0;padding:7px 22px;gap:9px;color:var(--muted);white-space:nowrap}.in-progress-entry-row__spinner{width:16px;height:16px;border-width:2px;color:var(--accent);flex-shrink:0}.in-progress-entry-row__locator{min-width:0;overflow:hidden;text-overflow:ellipsis;font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:11.5px}.in-progress-entry-row__status{display:inline-flex;align-items:center;gap:5px;flex-shrink:0;color:var(--muted-2);font-size:11.5px}.in-progress-entry-row__kind{font-size:10.5px;opacity:.85}@media (pointer: coarse){.in-progress-entry-row{padding-inline:10px}}#entries-body>.entry-row-outer{display:block;border-bottom:none}#entries-body>.entry-row-outer>.entry-row-main{display:flex;align-items:center;cursor:default;border-bottom:1px solid var(--line-soft);padding:0;flex-shrink:unset;overflow:visible}#entries-body>.entry-row-outer>.entry-row-main>div{padding:7px 10px;flex-shrink:0;overflow:hidden}#entries-body>.entry-row-outer>.entry-row-main>div:last-child{padding-right:22px}#entries-body>.entry-row-outer>.entry-row-main .col-added{padding-left:22px}#entries-body>.entry-row-outer.is-selected{background:unset;outline:none;box-shadow:none}#entries-body>.entry-row-outer.is-multi-selected{background:unset;outline:none;box-shadow:none}#entries-body>.entry-row-outer.is-selected>.entry-row-main{background:#eee2d2;box-shadow:inset 0 0 0 2px var(--accent)}#entries-body>.entry-row-outer.is-multi-selected>.entry-row-main{background:#eee2d2;box-shadow:inset 0 0 0 2px var(--accent)}#entries-body>.entry-row-outer .url-cell:hover{overflow:visible;white-space:normal}#entries-body>.entry-row-outer>.child-entries{display:block;padding:0;flex-shrink:unset;overflow:visible;border-left:2px solid var(--line-soft);margin-left:32px}.child-entry-row{display:flex;align-items:center;cursor:default;border-bottom:1px solid var(--line-soft);opacity:.88}.child-entry-row:hover{opacity:1}.child-entry-row:last-child{border-bottom:none}.child-entry-row--light{background:#fafaf8}.child-entry-row--dark{background:#f2f0ec}.child-entry-row.is-selected,.child-entry-row.is-multi-selected{background:#eee2d2;box-shadow:inset 0 0 0 2px var(--accent);opacity:1}.child-entry-row>div{padding:6px 10px;flex-shrink:0;overflow:hidden}.child-entry-row .col-added{padding-left:22px}.child-entry-row>div:last-child{padding-right:22px}.entry-expand-btn{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;flex-shrink:0;padding:0;margin-right:2px;background:none;border:none;cursor:pointer;opacity:.45;color:inherit;transition:opacity .15s}.entry-expand-btn:focus{outline:none}.entry-expand-btn:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:2px}.entry-expand-btn:before{content:"";display:block;width:0;height:0;border-top:4px solid transparent;border-bottom:4px solid transparent;border-left:6px solid currentColor;transition:transform .15s}.entry-expand-btn:hover{opacity:1}.entry-expand-btn.is-expanded:before{transform:rotate(90deg)}.child-count-badge{display:inline-block;margin-left:5px;padding:0 5px;font-size:.72em;font-weight:600;background:color-mix(in srgb,var(--line-soft) 60%,transparent);border-radius:10px;opacity:.75;vertical-align:middle;line-height:1.6}.child-entries-loading{padding:8px 12px;font-size:.85em;opacity:.55}.capture-playlist-toggle{display:inline-flex;align-items:center;gap:4px;font-size:.75rem;color:var(--muted);background:none;border:none;cursor:pointer;padding:2px 6px}.capture-playlist-toggle:hover{color:var(--text)}.capture-playlist-toggle--left{flex-shrink:0;padding:2px 4px;font-size:.7rem}.capture-conflict-badge{font-size:.7rem;color:#c07000;background:#fff3cd;border:1px solid #e0a000;border-radius:4px;padding:1px 6px;margin-left:6px}.capture-playlist-items{border-top:1px solid var(--line-soft);max-height:320px;overflow-y:auto;scrollbar-width:thin;scrollbar-color:var(--line) transparent}.capture-playlist-item{display:flex;align-items:center;gap:8px;padding:5px 10px 5px 14px;font-size:.8rem;border-bottom:1px solid var(--line-soft);border-left:3px solid transparent}.capture-playlist-item:last-of-type{border-bottom:none}.capture-playlist-item--conflict{border-left-color:#c07000;background:color-mix(in srgb,#c07000 6%,transparent)}.capture-playlist-item-title{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text);opacity:.9}.capture-item-quality{font-size:.73rem;padding:2px 4px;border:1px solid var(--line);border-radius:3px;background:var(--paper-3);color:var(--text);flex-shrink:0}.capture-playlist-conflict-badge{font-size:.68rem;font-weight:600;color:#c07000;white-space:nowrap;flex-shrink:0}.capture-playlist-item-remove{flex-shrink:0;display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;padding:0;border:none;background:none;color:var(--muted);cursor:pointer;border-radius:3px;opacity:.3;transition:opacity .1s,color .1s}.capture-playlist-item:hover .capture-playlist-item-remove,.capture-playlist-item-remove:focus-visible{opacity:1}.capture-playlist-item-remove:hover{color:#c04000;opacity:1}@media (pointer: coarse){.capture-playlist-item-remove{opacity:1}}.capture-playlist-item-remove{font-size:.75rem;line-height:1}.capture-sync-row{display:flex;align-items:center;gap:6px;padding:6px 12px;font-size:.78rem;color:var(--muted);border-top:1px solid var(--line-soft);cursor:pointer}.capture-sync-row input[type=checkbox]{cursor:pointer}.rail-summary-body{margin-bottom:10px}.rail-summary-tldr{margin:0 0 8px;font-size:13.5px;font-weight:600;color:var(--ink);line-height:1.45}.rail-summary-text{margin:0 0 8px;font-size:13px;color:var(--ink);line-height:1.55}.rail-summary-tags{display:flex;flex-wrap:wrap;gap:5px;margin-bottom:8px}.rail-summary-tag{font-size:11px;padding:2px 7px;border:1px solid var(--line);border-radius:999px;color:var(--muted)}.rail-summary-provider{margin:0;font-size:11px;color:var(--muted-2);letter-spacing:.02em}.rail-summary-status{display:flex;align-items:center;gap:7px;margin:0 0 8px;font-size:12.5px;color:var(--muted)}.rail-summary-info{margin:0 0 8px;padding:8px;color:var(--muted);background:var(--paper-2);border:1px solid var(--line-soft);border-radius:4px}.rail-summary-info__heading{margin:0 0 4px;color:var(--ink);font-size:12.5px;font-weight:600}.rail-summary-info__detail{margin:0;font-size:12px;line-height:1.45}.rail-summary-error{margin:0 0 8px}.rail-summary-spinner{width:11px;height:11px;border:1.5px solid var(--line);border-top-color:var(--muted);border-radius:50%;animation:rail-summary-spin .7s linear infinite;flex-shrink:0}@keyframes rail-summary-spin{to{transform:rotate(360deg)}}@media (prefers-reduced-motion: reduce){.rail-summary-spinner{animation:none}}.rail-summary-controls{display:flex;flex-direction:column;gap:6px}.rail-summary-select{width:100%;padding:5px 8px;font-size:12.5px;color:var(--ink);background:var(--paper);border:1px solid var(--line);border-radius:4px}.rail-summary-image-option{padding:7px 8px;color:var(--muted);background:var(--paper);border:1px solid var(--line);border-radius:4px}.rail-summary-image-option__label{display:flex;align-items:center;gap:6px;color:var(--ink);font-size:12.5px;cursor:pointer}.rail-summary-image-option__label input[type=checkbox]{margin:0;accent-color:var(--accent);cursor:pointer}.rail-summary-image-option__label input[type=checkbox]:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.rail-summary-image-option__note{margin:5px 0 0;font-size:11px;line-height:1.4}.rail-summary-image-option--disabled{color:var(--muted-2);background:var(--paper)}.rail-summary-image-option--disabled .rail-summary-image-option__label{color:var(--muted-2);cursor:not-allowed}.rail-summary-image-option--disabled .rail-summary-image-option__label input[type=checkbox]{cursor:not-allowed}.text-preview{padding:32px 40px 48px;max-width:780px;margin:0 auto;font-family:var(--sans);color:var(--ink);overflow:auto;height:100%;box-sizing:border-box}.text-preview--loading,.text-preview--error{padding:24px;color:var(--muted);font-size:13px}.text-preview--error{color:var(--accent)}.text-preview__title{font-family:var(--serif, var(--sans));font-size:22px;font-weight:600;margin:0 0 20px;line-height:1.25;color:var(--ink)}.text-preview__body{white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word;font-family:ui-monospace,SF Mono,Menlo,Consolas,monospace;font-size:13.5px;line-height:1.65;color:var(--ink);background:var(--paper);border:1px solid var(--line);border-radius:var(--r2);padding:16px 18px;margin:0}.text-preview__mime{margin-top:12px;font-size:11px;color:var(--muted);letter-spacing:.04em;text-align:right} diff --git a/crates/archivr-server/static/assets/index-9VVEGfc7.js b/crates/archivr-server/static/assets/index-9VVEGfc7.js new file mode 100644 index 0000000..df50044 --- /dev/null +++ b/crates/archivr-server/static/assets/index-9VVEGfc7.js @@ -0,0 +1,49 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const i of l)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(l){const i={};return l.integrity&&(i.integrity=l.integrity),l.referrerPolicy&&(i.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?i.credentials="include":l.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(l){if(l.ep)return;l.ep=!0;const i=n(l);fetch(l.href,i)}})();var Ku={exports:{}},bs={},Xu={exports:{}},re={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var yl=Symbol.for("react.element"),jf=Symbol.for("react.portal"),Sf=Symbol.for("react.fragment"),Nf=Symbol.for("react.strict_mode"),_f=Symbol.for("react.profiler"),Cf=Symbol.for("react.provider"),Ef=Symbol.for("react.context"),bf=Symbol.for("react.forward_ref"),Tf=Symbol.for("react.suspense"),Pf=Symbol.for("react.memo"),Lf=Symbol.for("react.lazy"),So=Symbol.iterator;function Rf(e){return e===null||typeof e!="object"?null:(e=So&&e[So]||e["@@iterator"],typeof e=="function"?e:null)}var Ju={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Gu=Object.assign,Yu={};function jr(e,t,n){this.props=e,this.context=t,this.refs=Yu,this.updater=n||Ju}jr.prototype.isReactComponent={};jr.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};jr.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Zu(){}Zu.prototype=jr.prototype;function Na(e,t,n){this.props=e,this.context=t,this.refs=Yu,this.updater=n||Ju}var _a=Na.prototype=new Zu;_a.constructor=Na;Gu(_a,jr.prototype);_a.isPureReactComponent=!0;var No=Array.isArray,ec=Object.prototype.hasOwnProperty,Ca={current:null},tc={key:!0,ref:!0,__self:!0,__source:!0};function nc(e,t,n){var r,l={},i=null,a=null;if(t!=null)for(r in t.ref!==void 0&&(a=t.ref),t.key!==void 0&&(i=""+t.key),t)ec.call(t,r)&&!tc.hasOwnProperty(r)&&(l[r]=t[r]);var o=arguments.length-2;if(o===1)l.children=n;else if(1>>1,ne=M[G];if(0>>1;Gl(Se,V))cel(Ie,Se)?(M[G]=Ie,M[ce]=V,G=ce):(M[G]=Se,M[Z]=V,G=Z);else if(cel(Ie,V))M[G]=Ie,M[ce]=V,G=ce;else break e}}return L}function l(M,L){var V=M.sortIndex-L.sortIndex;return V!==0?V:M.id-L.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var a=Date,o=a.now();e.unstable_now=function(){return a.now()-o}}var u=[],d=[],y=1,g=null,h=3,v=!1,x=!1,S=!1,N=typeof setTimeout=="function"?setTimeout:null,p=typeof clearTimeout=="function"?clearTimeout:null,f=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function m(M){for(var L=n(d);L!==null;){if(L.callback===null)r(d);else if(L.startTime<=M)r(d),L.sortIndex=L.expirationTime,t(u,L);else break;L=n(d)}}function k(M){if(S=!1,m(M),!x)if(n(u)!==null)x=!0,Be(C);else{var L=n(d);L!==null&&we(k,L.startTime-M)}}function C(M,L){x=!1,S&&(S=!1,p(j),j=-1),v=!0;var V=h;try{for(m(L),g=n(u);g!==null&&(!(g.expirationTime>L)||M&&!X());){var G=g.callback;if(typeof G=="function"){g.callback=null,h=g.priorityLevel;var ne=G(g.expirationTime<=L);L=e.unstable_now(),typeof ne=="function"?g.callback=ne:g===n(u)&&r(u),m(L)}else r(u);g=n(u)}if(g!==null)var se=!0;else{var Z=n(d);Z!==null&&we(k,Z.startTime-L),se=!1}return se}finally{g=null,h=V,v=!1}}var E=!1,T=null,j=-1,P=5,R=-1;function X(){return!(e.unstable_now()-RM||125G?(M.sortIndex=V,t(d,M),n(u)===null&&M===n(d)&&(S?(p(j),j=-1):S=!0,we(k,V-G))):(M.sortIndex=ne,t(u,M),x||v||(x=!0,Be(C))),M},e.unstable_shouldYield=X,e.unstable_wrapCallback=function(M){var L=h;return function(){var V=h;h=L;try{return M.apply(this,arguments)}finally{h=V}}}})(ac);ic.exports=ac;var Hf=ic.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Wf=c,xt=Hf;function I(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Li=Object.prototype.hasOwnProperty,Vf=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Co={},Eo={};function Qf(e){return Li.call(Eo,e)?!0:Li.call(Co,e)?!1:Vf.test(e)?Eo[e]=!0:(Co[e]=!0,!1)}function qf(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Kf(e,t,n,r){if(t===null||typeof t>"u"||qf(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function it(e,t,n,r,l,i,a){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=a}var Xe={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Xe[e]=new it(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Xe[t]=new it(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Xe[e]=new it(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Xe[e]=new it(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Xe[e]=new it(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Xe[e]=new it(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Xe[e]=new it(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Xe[e]=new it(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Xe[e]=new it(e,5,!1,e.toLowerCase(),null,!1,!1)});var ba=/[\-:]([a-z])/g;function Ta(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(ba,Ta);Xe[t]=new it(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(ba,Ta);Xe[t]=new it(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(ba,Ta);Xe[t]=new it(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Xe[e]=new it(e,1,!1,e.toLowerCase(),null,!1,!1)});Xe.xlinkHref=new it("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Xe[e]=new it(e,1,!1,e.toLowerCase(),null,!0,!0)});function Pa(e,t,n,r){var l=Xe.hasOwnProperty(t)?Xe[t]:null;(l!==null?l.type!==0:r||!(2o||l[a]!==i[o]){var u=` +`+l[a].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=a&&0<=o);break}}}finally{ti=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Or(e):""}function Xf(e){switch(e.tag){case 5:return Or(e.type);case 16:return Or("Lazy");case 13:return Or("Suspense");case 19:return Or("SuspenseList");case 0:case 2:case 15:return e=ni(e.type,!1),e;case 11:return e=ni(e.type.render,!1),e;case 1:return e=ni(e.type,!0),e;default:return""}}function $i(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Gn:return"Fragment";case Jn:return"Portal";case Ri:return"Profiler";case La:return"StrictMode";case zi:return"Suspense";case Ii:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case cc:return(e.displayName||"Context")+".Consumer";case uc:return(e._context.displayName||"Context")+".Provider";case Ra:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case za:return t=e.displayName||null,t!==null?t:$i(e.type)||"Memo";case un:t=e._payload,e=e._init;try{return $i(e(t))}catch{}}return null}function Jf(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return $i(t);case 8:return t===La?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Sn(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function fc(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Gf(e){var t=fc(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(a){r=""+a,i.call(this,a)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(a){r=""+a},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Cl(e){e._valueTracker||(e._valueTracker=Gf(e))}function pc(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=fc(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function rs(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Di(e,t){var n=t.checked;return be({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function To(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Sn(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function hc(e,t){t=t.checked,t!=null&&Pa(e,"checked",t,!1)}function Oi(e,t){hc(e,t);var n=Sn(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Ai(e,t.type,n):t.hasOwnProperty("defaultValue")&&Ai(e,t.type,Sn(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Po(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Ai(e,t,n){(t!=="number"||rs(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Ar=Array.isArray;function or(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=El.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Zr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Hr={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Yf=["Webkit","ms","Moz","O"];Object.keys(Hr).forEach(function(e){Yf.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Hr[t]=Hr[e]})});function vc(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Hr.hasOwnProperty(e)&&Hr[e]?(""+t).trim():t+"px"}function xc(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=vc(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var Zf=be({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Bi(e,t){if(t){if(Zf[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(I(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(I(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(I(61))}if(t.style!=null&&typeof t.style!="object")throw Error(I(62))}}function Ui(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Hi=null;function Ia(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Wi=null,ur=null,cr=null;function zo(e){if(e=wl(e)){if(typeof Wi!="function")throw Error(I(280));var t=e.stateNode;t&&(t=zs(t),Wi(e.stateNode,e.type,t))}}function wc(e){ur?cr?cr.push(e):cr=[e]:ur=e}function kc(){if(ur){var e=ur,t=cr;if(cr=ur=null,zo(e),t)for(e=0;e>>=0,e===0?32:31-(cp(e)/dp|0)|0}var bl=64,Tl=4194304;function Mr(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function as(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,a=n&268435455;if(a!==0){var o=a&~l;o!==0?r=Mr(o):(i&=a,i!==0&&(r=Mr(i)))}else a=n&~l,a!==0?r=Mr(a):i!==0&&(r=Mr(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,i=t&-t,l>=i||l===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function vl(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-It(t),e[t]=n}function mp(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Vr),Uo=" ",Ho=!1;function Bc(e,t){switch(e){case"keyup":return Hp.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Uc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Yn=!1;function Vp(e,t){switch(e){case"compositionend":return Uc(t);case"keypress":return t.which!==32?null:(Ho=!0,Uo);case"textInput":return e=t.data,e===Uo&&Ho?null:e;default:return null}}function Qp(e,t){if(Yn)return e==="compositionend"||!Ua&&Bc(e,t)?(e=Mc(),Ql=Ma=pn=null,Yn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=qo(n)}}function Qc(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Qc(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function qc(){for(var e=window,t=rs();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=rs(e.document)}return t}function Ha(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function th(e){var t=qc(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Qc(n.ownerDocument.documentElement,n)){if(r!==null&&Ha(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,i=Math.min(r.start,l);r=r.end===void 0?i:Math.min(r.end,l),!e.extend&&i>r&&(l=r,r=i,i=l),l=Ko(n,i);var a=Ko(n,r);l&&a&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Zn=null,Ji=null,qr=null,Gi=!1;function Xo(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Gi||Zn==null||Zn!==rs(r)||(r=Zn,"selectionStart"in r&&Ha(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),qr&&sl(qr,r)||(qr=r,r=cs(Ji,"onSelect"),0nr||(e.current=ra[nr],ra[nr]=null,nr--)}function ge(e,t){nr++,ra[nr]=e.current,e.current=t}var Nn={},et=Cn(Nn),dt=Cn(!1),Mn=Nn;function gr(e,t){var n=e.type.contextTypes;if(!n)return Nn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in n)l[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function ft(e){return e=e.childContextTypes,e!=null}function fs(){xe(dt),xe(et)}function nu(e,t,n){if(et.current!==Nn)throw Error(I(168));ge(et,t),ge(dt,n)}function nd(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(I(108,Jf(e)||"Unknown",l));return be({},n,r)}function ps(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Nn,Mn=et.current,ge(et,e),ge(dt,dt.current),!0}function ru(e,t,n){var r=e.stateNode;if(!r)throw Error(I(169));n?(e=nd(e,t,Mn),r.__reactInternalMemoizedMergedChildContext=e,xe(dt),xe(et),ge(et,e)):xe(dt),ge(dt,n)}var Jt=null,Is=!1,gi=!1;function rd(e){Jt===null?Jt=[e]:Jt.push(e)}function ph(e){Is=!0,rd(e)}function En(){if(!gi&&Jt!==null){gi=!0;var e=0,t=de;try{var n=Jt;for(de=1;e>=a,l-=a,Gt=1<<32-It(t)+l|n<j?(P=T,T=null):P=T.sibling;var R=h(p,T,m[j],k);if(R===null){T===null&&(T=P);break}e&&T&&R.alternate===null&&t(p,T),f=i(R,f,j),E===null?C=R:E.sibling=R,E=R,T=P}if(j===m.length)return n(p,T),je&&Ln(p,j),C;if(T===null){for(;jj?(P=T,T=null):P=T.sibling;var X=h(p,T,R.value,k);if(X===null){T===null&&(T=P);break}e&&T&&X.alternate===null&&t(p,T),f=i(X,f,j),E===null?C=X:E.sibling=X,E=X,T=P}if(R.done)return n(p,T),je&&Ln(p,j),C;if(T===null){for(;!R.done;j++,R=m.next())R=g(p,R.value,k),R!==null&&(f=i(R,f,j),E===null?C=R:E.sibling=R,E=R);return je&&Ln(p,j),C}for(T=r(p,T);!R.done;j++,R=m.next())R=v(T,p,j,R.value,k),R!==null&&(e&&R.alternate!==null&&T.delete(R.key===null?j:R.key),f=i(R,f,j),E===null?C=R:E.sibling=R,E=R);return e&&T.forEach(function(H){return t(p,H)}),je&&Ln(p,j),C}function N(p,f,m,k){if(typeof m=="object"&&m!==null&&m.type===Gn&&m.key===null&&(m=m.props.children),typeof m=="object"&&m!==null){switch(m.$$typeof){case _l:e:{for(var C=m.key,E=f;E!==null;){if(E.key===C){if(C=m.type,C===Gn){if(E.tag===7){n(p,E.sibling),f=l(E,m.props.children),f.return=p,p=f;break e}}else if(E.elementType===C||typeof C=="object"&&C!==null&&C.$$typeof===un&&iu(C)===E.type){n(p,E.sibling),f=l(E,m.props),f.ref=zr(p,E,m),f.return=p,p=f;break e}n(p,E);break}else t(p,E);E=E.sibling}m.type===Gn?(f=An(m.props.children,p.mode,k,m.key),f.return=p,p=f):(k=es(m.type,m.key,m.props,null,p.mode,k),k.ref=zr(p,f,m),k.return=p,p=k)}return a(p);case Jn:e:{for(E=m.key;f!==null;){if(f.key===E)if(f.tag===4&&f.stateNode.containerInfo===m.containerInfo&&f.stateNode.implementation===m.implementation){n(p,f.sibling),f=l(f,m.children||[]),f.return=p,p=f;break e}else{n(p,f);break}else t(p,f);f=f.sibling}f=Ni(m,p.mode,k),f.return=p,p=f}return a(p);case un:return E=m._init,N(p,f,E(m._payload),k)}if(Ar(m))return x(p,f,m,k);if(br(m))return S(p,f,m,k);Dl(p,m)}return typeof m=="string"&&m!==""||typeof m=="number"?(m=""+m,f!==null&&f.tag===6?(n(p,f.sibling),f=l(f,m),f.return=p,p=f):(n(p,f),f=Si(m,p.mode,k),f.return=p,p=f),a(p)):n(p,f)}return N}var vr=ad(!0),od=ad(!1),gs=Cn(null),ys=null,sr=null,qa=null;function Ka(){qa=sr=ys=null}function Xa(e){var t=gs.current;xe(gs),e._currentValue=t}function ia(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function fr(e,t){ys=e,qa=sr=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(ct=!0),e.firstContext=null)}function bt(e){var t=e._currentValue;if(qa!==e)if(e={context:e,memoizedValue:t,next:null},sr===null){if(ys===null)throw Error(I(308));sr=e,ys.dependencies={lanes:0,firstContext:e}}else sr=sr.next=e;return t}var In=null;function Ja(e){In===null?In=[e]:In.push(e)}function ud(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,Ja(t)):(n.next=l.next,l.next=n),t.interleaved=n,nn(e,r)}function nn(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var cn=!1;function Ga(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function cd(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Zt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function xn(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,oe&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,nn(e,n)}return l=r.interleaved,l===null?(t.next=t,Ja(r)):(t.next=l.next,l.next=t),r.interleaved=t,nn(e,n)}function Kl(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Da(e,n)}}function au(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var a={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?l=i=a:i=i.next=a,n=n.next}while(n!==null);i===null?l=i=t:i=i.next=t}else l=i=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function vs(e,t,n,r){var l=e.updateQueue;cn=!1;var i=l.firstBaseUpdate,a=l.lastBaseUpdate,o=l.shared.pending;if(o!==null){l.shared.pending=null;var u=o,d=u.next;u.next=null,a===null?i=d:a.next=d,a=u;var y=e.alternate;y!==null&&(y=y.updateQueue,o=y.lastBaseUpdate,o!==a&&(o===null?y.firstBaseUpdate=d:o.next=d,y.lastBaseUpdate=u))}if(i!==null){var g=l.baseState;a=0,y=d=u=null,o=i;do{var h=o.lane,v=o.eventTime;if((r&h)===h){y!==null&&(y=y.next={eventTime:v,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var x=e,S=o;switch(h=t,v=n,S.tag){case 1:if(x=S.payload,typeof x=="function"){g=x.call(v,g,h);break e}g=x;break e;case 3:x.flags=x.flags&-65537|128;case 0:if(x=S.payload,h=typeof x=="function"?x.call(v,g,h):x,h==null)break e;g=be({},g,h);break e;case 2:cn=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,h=l.effects,h===null?l.effects=[o]:h.push(o))}else v={eventTime:v,lane:h,tag:o.tag,payload:o.payload,callback:o.callback,next:null},y===null?(d=y=v,u=g):y=y.next=v,a|=h;if(o=o.next,o===null){if(o=l.shared.pending,o===null)break;h=o,o=h.next,h.next=null,l.lastBaseUpdate=h,l.shared.pending=null}}while(!0);if(y===null&&(u=g),l.baseState=u,l.firstBaseUpdate=d,l.lastBaseUpdate=y,t=l.shared.interleaved,t!==null){l=t;do a|=l.lane,l=l.next;while(l!==t)}else i===null&&(l.shared.lanes=0);Un|=a,e.lanes=a,e.memoizedState=g}}function ou(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=vi.transition;vi.transition={};try{e(!1),t()}finally{de=n,vi.transition=r}}function Ed(){return Tt().memoizedState}function yh(e,t,n){var r=kn(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},bd(e))Td(t,n);else if(n=ud(e,t,n,r),n!==null){var l=lt();$t(n,e,r,l),Pd(n,t,r)}}function vh(e,t,n){var r=kn(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(bd(e))Td(t,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var a=t.lastRenderedState,o=i(a,n);if(l.hasEagerState=!0,l.eagerState=o,Dt(o,a)){var u=t.interleaved;u===null?(l.next=l,Ja(t)):(l.next=u.next,u.next=l),t.interleaved=l;return}}catch{}finally{}n=ud(e,t,l,r),n!==null&&(l=lt(),$t(n,e,r,l),Pd(n,t,r))}}function bd(e){var t=e.alternate;return e===Ee||t!==null&&t===Ee}function Td(e,t){Kr=ws=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Pd(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Da(e,n)}}var ks={readContext:bt,useCallback:Ge,useContext:Ge,useEffect:Ge,useImperativeHandle:Ge,useInsertionEffect:Ge,useLayoutEffect:Ge,useMemo:Ge,useReducer:Ge,useRef:Ge,useState:Ge,useDebugValue:Ge,useDeferredValue:Ge,useTransition:Ge,useMutableSource:Ge,useSyncExternalStore:Ge,useId:Ge,unstable_isNewReconciler:!1},xh={readContext:bt,useCallback:function(e,t){return Bt().memoizedState=[e,t===void 0?null:t],e},useContext:bt,useEffect:cu,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Jl(4194308,4,jd.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Jl(4194308,4,e,t)},useInsertionEffect:function(e,t){return Jl(4,2,e,t)},useMemo:function(e,t){var n=Bt();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Bt();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=yh.bind(null,Ee,e),[r.memoizedState,e]},useRef:function(e){var t=Bt();return e={current:e},t.memoizedState=e},useState:uu,useDebugValue:so,useDeferredValue:function(e){return Bt().memoizedState=e},useTransition:function(){var e=uu(!1),t=e[0];return e=gh.bind(null,e[1]),Bt().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Ee,l=Bt();if(je){if(n===void 0)throw Error(I(407));n=n()}else{if(n=t(),We===null)throw Error(I(349));Bn&30||hd(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,cu(gd.bind(null,r,i,e),[e]),r.flags|=2048,pl(9,md.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Bt(),t=We.identifierPrefix;if(je){var n=Yt,r=Gt;n=(r&~(1<<32-It(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=dl++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=a.createElement(n,{is:r.is}):(e=a.createElement(n),n==="select"&&(a=e,r.multiple?a.multiple=!0:r.size&&(a.size=r.size))):e=a.createElementNS(e,n),e[Ut]=t,e[ol]=r,Fd(e,t,!1,!1),t.stateNode=e;e:{switch(a=Ui(n,r),n){case"dialog":ve("cancel",e),ve("close",e),l=r;break;case"iframe":case"object":case"embed":ve("load",e),l=r;break;case"video":case"audio":for(l=0;lkr&&(t.flags|=128,r=!0,Ir(i,!1),t.lanes=4194304)}else{if(!r)if(e=xs(a),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Ir(i,!0),i.tail===null&&i.tailMode==="hidden"&&!a.alternate&&!je)return Ye(t),null}else 2*Re()-i.renderingStartTime>kr&&n!==1073741824&&(t.flags|=128,r=!0,Ir(i,!1),t.lanes=4194304);i.isBackwards?(a.sibling=t.child,t.child=a):(n=i.last,n!==null?n.sibling=a:t.child=a,i.last=a)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Re(),t.sibling=null,n=Ce.current,ge(Ce,r?n&1|2:n&1),t):(Ye(t),null);case 22:case 23:return fo(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?mt&1073741824&&(Ye(t),t.subtreeFlags&6&&(t.flags|=8192)):Ye(t),null;case 24:return null;case 25:return null}throw Error(I(156,t.tag))}function Eh(e,t){switch(Va(t),t.tag){case 1:return ft(t.type)&&fs(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return xr(),xe(dt),xe(et),eo(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Za(t),null;case 13:if(xe(Ce),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(I(340));yr()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return xe(Ce),null;case 4:return xr(),null;case 10:return Xa(t.type._context),null;case 22:case 23:return fo(),null;case 24:return null;default:return null}}var Al=!1,Ze=!1,bh=typeof WeakSet=="function"?WeakSet:Set,W=null;function ir(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Pe(e,t,r)}else n.current=null}function ma(e,t,n){try{n()}catch(r){Pe(e,t,r)}}var ku=!1;function Th(e,t){if(Yi=os,e=qc(),Ha(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var a=0,o=-1,u=-1,d=0,y=0,g=e,h=null;t:for(;;){for(var v;g!==n||l!==0&&g.nodeType!==3||(o=a+l),g!==i||r!==0&&g.nodeType!==3||(u=a+r),g.nodeType===3&&(a+=g.nodeValue.length),(v=g.firstChild)!==null;)h=g,g=v;for(;;){if(g===e)break t;if(h===n&&++d===l&&(o=a),h===i&&++y===r&&(u=a),(v=g.nextSibling)!==null)break;g=h,h=g.parentNode}g=v}n=o===-1||u===-1?null:{start:o,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(Zi={focusedElem:e,selectionRange:n},os=!1,W=t;W!==null;)if(t=W,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,W=e;else for(;W!==null;){t=W;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var S=x.memoizedProps,N=x.memoizedState,p=t.stateNode,f=p.getSnapshotBeforeUpdate(t.elementType===t.type?S:Lt(t.type,S),N);p.__reactInternalSnapshotBeforeUpdate=f}break;case 3:var m=t.stateNode.containerInfo;m.nodeType===1?m.textContent="":m.nodeType===9&&m.documentElement&&m.removeChild(m.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(I(163))}}catch(k){Pe(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,W=e;break}W=t.return}return x=ku,ku=!1,x}function Xr(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&ma(t,n,i)}l=l.next}while(l!==r)}}function Os(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function ga(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Hd(e){var t=e.alternate;t!==null&&(e.alternate=null,Hd(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Ut],delete t[ol],delete t[na],delete t[dh],delete t[fh])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Wd(e){return e.tag===5||e.tag===3||e.tag===4}function ju(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Wd(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function ya(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=ds));else if(r!==4&&(e=e.child,e!==null))for(ya(e,t,n),e=e.sibling;e!==null;)ya(e,t,n),e=e.sibling}function va(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(va(e,t,n),e=e.sibling;e!==null;)va(e,t,n),e=e.sibling}var qe=null,Rt=!1;function on(e,t,n){for(n=n.child;n!==null;)Vd(e,t,n),n=n.sibling}function Vd(e,t,n){if(Ht&&typeof Ht.onCommitFiberUnmount=="function")try{Ht.onCommitFiberUnmount(Ts,n)}catch{}switch(n.tag){case 5:Ze||ir(n,t);case 6:var r=qe,l=Rt;qe=null,on(e,t,n),qe=r,Rt=l,qe!==null&&(Rt?(e=qe,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):qe.removeChild(n.stateNode));break;case 18:qe!==null&&(Rt?(e=qe,n=n.stateNode,e.nodeType===8?mi(e.parentNode,n):e.nodeType===1&&mi(e,n),rl(e)):mi(qe,n.stateNode));break;case 4:r=qe,l=Rt,qe=n.stateNode.containerInfo,Rt=!0,on(e,t,n),qe=r,Rt=l;break;case 0:case 11:case 14:case 15:if(!Ze&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,a=i.destroy;i=i.tag,a!==void 0&&(i&2||i&4)&&ma(n,t,a),l=l.next}while(l!==r)}on(e,t,n);break;case 1:if(!Ze&&(ir(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){Pe(n,t,o)}on(e,t,n);break;case 21:on(e,t,n);break;case 22:n.mode&1?(Ze=(r=Ze)||n.memoizedState!==null,on(e,t,n),Ze=r):on(e,t,n);break;default:on(e,t,n)}}function Su(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new bh),t.forEach(function(r){var l=Ah.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function Pt(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=a),r&=~i}if(r=l,r=Re()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Lh(r/1960))-r,10e?16:e,hn===null)var r=!1;else{if(e=hn,hn=null,Ns=0,oe&6)throw Error(I(331));var l=oe;for(oe|=4,W=e.current;W!==null;){var i=W,a=i.child;if(W.flags&16){var o=i.deletions;if(o!==null){for(var u=0;uRe()-uo?On(e,0):oo|=n),pt(e,t)}function Zd(e,t){t===0&&(e.mode&1?(t=Tl,Tl<<=1,!(Tl&130023424)&&(Tl=4194304)):t=1);var n=lt();e=nn(e,t),e!==null&&(vl(e,t,n),pt(e,n))}function Oh(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Zd(e,n)}function Ah(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(I(314))}r!==null&&r.delete(t),Zd(e,n)}var ef;ef=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||dt.current)ct=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return ct=!1,_h(e,t,n);ct=!!(e.flags&131072)}else ct=!1,je&&t.flags&1048576&&ld(t,ms,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Gl(e,t),e=t.pendingProps;var l=gr(t,et.current);fr(t,n),l=no(null,t,r,e,l,n);var i=ro();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,ft(r)?(i=!0,ps(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,Ga(t),l.updater=Ds,t.stateNode=l,l._reactInternals=t,oa(t,r,e,n),t=da(null,t,r,!0,i,n)):(t.tag=0,je&&i&&Wa(t),rt(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Gl(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=Fh(r),e=Lt(r,e),l){case 0:t=ca(null,t,r,e,n);break e;case 1:t=vu(null,t,r,e,n);break e;case 11:t=gu(null,t,r,e,n);break e;case 14:t=yu(null,t,r,Lt(r.type,e),n);break e}throw Error(I(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Lt(r,l),ca(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Lt(r,l),vu(e,t,r,l,n);case 3:e:{if(Od(t),e===null)throw Error(I(387));r=t.pendingProps,i=t.memoizedState,l=i.element,cd(e,t),vs(t,r,null,n);var a=t.memoizedState;if(r=a.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){l=wr(Error(I(423)),t),t=xu(e,t,r,n,l);break e}else if(r!==l){l=wr(Error(I(424)),t),t=xu(e,t,r,n,l);break e}else for(yt=vn(t.stateNode.containerInfo.firstChild),vt=t,je=!0,zt=null,n=od(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(yr(),r===l){t=rn(e,t,n);break e}rt(e,t,r,n)}t=t.child}return t;case 5:return dd(t),e===null&&sa(t),r=t.type,l=t.pendingProps,i=e!==null?e.memoizedProps:null,a=l.children,ea(r,l)?a=null:i!==null&&ea(r,i)&&(t.flags|=32),Dd(e,t),rt(e,t,a,n),t.child;case 6:return e===null&&sa(t),null;case 13:return Ad(e,t,n);case 4:return Ya(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=vr(t,null,r,n):rt(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Lt(r,l),gu(e,t,r,l,n);case 7:return rt(e,t,t.pendingProps,n),t.child;case 8:return rt(e,t,t.pendingProps.children,n),t.child;case 12:return rt(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,i=t.memoizedProps,a=l.value,ge(gs,r._currentValue),r._currentValue=a,i!==null)if(Dt(i.value,a)){if(i.children===l.children&&!dt.current){t=rn(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var o=i.dependencies;if(o!==null){a=i.child;for(var u=o.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=Zt(-1,n&-n),u.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var y=d.pending;y===null?u.next=u:(u.next=y.next,y.next=u),d.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),ia(i.return,n,t),o.lanes|=n;break}u=u.next}}else if(i.tag===10)a=i.type===t.type?null:i.child;else if(i.tag===18){if(a=i.return,a===null)throw Error(I(341));a.lanes|=n,o=a.alternate,o!==null&&(o.lanes|=n),ia(a,n,t),a=i.sibling}else a=i.child;if(a!==null)a.return=i;else for(a=i;a!==null;){if(a===t){a=null;break}if(i=a.sibling,i!==null){i.return=a.return,a=i;break}a=a.return}i=a}rt(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,fr(t,n),l=bt(l),r=r(l),t.flags|=1,rt(e,t,r,n),t.child;case 14:return r=t.type,l=Lt(r,t.pendingProps),l=Lt(r.type,l),yu(e,t,r,l,n);case 15:return Id(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Lt(r,l),Gl(e,t),t.tag=1,ft(r)?(e=!0,ps(t)):e=!1,fr(t,n),Ld(t,r,l),oa(t,r,l,n),da(null,t,r,!0,e,n);case 19:return Md(e,t,n);case 22:return $d(e,t,n)}throw Error(I(156,t.tag))};function tf(e,t){return bc(e,t)}function Mh(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ct(e,t,n,r){return new Mh(e,t,n,r)}function ho(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Fh(e){if(typeof e=="function")return ho(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Ra)return 11;if(e===za)return 14}return 2}function jn(e,t){var n=e.alternate;return n===null?(n=Ct(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function es(e,t,n,r,l,i){var a=2;if(r=e,typeof e=="function")ho(e)&&(a=1);else if(typeof e=="string")a=5;else e:switch(e){case Gn:return An(n.children,l,i,t);case La:a=8,l|=8;break;case Ri:return e=Ct(12,n,t,l|2),e.elementType=Ri,e.lanes=i,e;case zi:return e=Ct(13,n,t,l),e.elementType=zi,e.lanes=i,e;case Ii:return e=Ct(19,n,t,l),e.elementType=Ii,e.lanes=i,e;case dc:return Ms(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case uc:a=10;break e;case cc:a=9;break e;case Ra:a=11;break e;case za:a=14;break e;case un:a=16,r=null;break e}throw Error(I(130,e==null?e:typeof e,""))}return t=Ct(a,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function An(e,t,n,r){return e=Ct(7,e,r,t),e.lanes=n,e}function Ms(e,t,n,r){return e=Ct(22,e,r,t),e.elementType=dc,e.lanes=n,e.stateNode={isHidden:!1},e}function Si(e,t,n){return e=Ct(6,e,null,t),e.lanes=n,e}function Ni(e,t,n){return t=Ct(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Bh(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=li(0),this.expirationTimes=li(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=li(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function mo(e,t,n,r,l,i,a,o,u){return e=new Bh(e,t,n,o,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ct(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ga(i),e}function Uh(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(sf)}catch(e){console.error(e)}}sf(),sc.exports=wt;var qh=sc.exports,af,Lu=qh;af=Lu.createRoot,Lu.hydrateRoot;async function ze(e,t){const n=await fetch(e,t);if(!n.ok)throw new Error(`${n.status} ${n.statusText}`);return n.json()}async function Ru(){return ze("/api/archives")}async function zu(e,t=null){const n=t?`/api/archives/${e}/entries?collection=${encodeURIComponent(t)}`:`/api/archives/${e}/entries`;return ze(n)}async function Kh(e,t,n,r=null){const l=new URLSearchParams;return t&&l.set("q",t),n&&l.set("tag",n),r&&l.set("collection",r),ze(`/api/archives/${e}/entries/search?${l}`)}async function Br(e,t){return ze(`/api/archives/${e}/entries/${t}`)}async function Xh(e,t,{signal:n}={}){return ze(`/api/archives/${e}/entries/${t}/summary`,{signal:n})}async function Jh(e,t,{provider:n,force:r=!1,includeImages:l=!1,signal:i}={}){const a=await fetch(`/api/archives/${e}/entries/${t}/summary`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:n,force:r,include_images:l}),signal:i});if(!a.ok){const o=await a.text();let u=o.trim();try{u=JSON.parse(o).error||u}catch{}throw new Error(u||`Summary request failed (${a.status})`)}return a.json()}async function Gh(e,{signal:t}={}){const n=await fetch(e,{credentials:"same-origin",signal:t});if(!n.ok)throw new Error(`HTTP ${n.status}`);return n.text()}async function Yh(e,t){return ze(`/api/archives/${e}/entries/${t}/children`)}function Zh(e,t,n){return Promise.all(n.map(r=>ze(`/api/archives/${e}/entries/${t}/artifacts/${r}`)))}async function em(e){if(!e||e.length===0)return{};const t=await fetch("/api/util/resolve-tco",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return t.ok?t.json():{}}async function tm(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:n??null})});if(!r.ok)throw new Error(await r.text())}async function Bl(e,t){return ze(`/api/archives/${e}/entries/${t}/tags`)}async function Iu(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/tags`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tag_path:n})});if(!r.ok)throw new Error(`Failed to add tag (${r.status})`)}async function nm(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/tags/${n}`,{method:"DELETE"});if(!r.ok)throw new Error(`Remove failed (${r.status})`)}async function $u(e,t){const n=await fetch(`/api/archives/${e}/entries/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`Delete failed (${n.status})`)}async function rm(e,t,n){const r=await fetch(`/api/archives/${e}/tags/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n})});if(!r.ok)throw new Error(await r.text());return r.json()}async function lm(e,t){const n=await fetch(`/api/archives/${e}/tags/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(await n.text())}async function sm(e,t){const n=await fetch(`/api/archives/${e}/tags`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok)throw new Error(await n.text());return n.json()}async function im(e,t,n){const r=await fetch(`/api/archives/${e}/tags/${t}/move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parent_uid:n??null})});if(!r.ok)throw new Error(await r.text());return r.json()}async function _i(e){return ze(`/api/archives/${e}/runs`)}async function Ul(e){return ze(`/api/archives/${e}/tags`)}async function am(e,t,n=null,r=null){const l={locator:t};n&&n!=="best"&&(l.quality=n),r&&(typeof r.ublock_enabled=="boolean"&&(l.ublock_enabled=r.ublock_enabled),typeof r.reader_mode=="boolean"&&(l.reader_mode=r.reader_mode),typeof r.cookie_ext_enabled=="boolean"&&(l.cookie_ext_enabled=r.cookie_ext_enabled),typeof r.modal_closer_enabled=="boolean"&&(l.modal_closer_enabled=r.modal_closer_enabled),typeof r.via_freedium=="boolean"&&(l.via_freedium=r.via_freedium),r.per_item_quality&&typeof r.per_item_quality=="object"&&Object.keys(r.per_item_quality).length>0&&(l.per_item_quality=r.per_item_quality),r.sync===!0&&(l.sync=!0));const i=await fetch(`/api/archives/${e}/captures`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!i.ok){const a=await i.json().catch(()=>({})),o=new Error(a.error||`HTTP ${i.status}`);throw o.status=i.status,o}return i.json()}async function om(e,{title:t,body:n,mime:r="text/markdown"}){const l={title:t,body:n};r&&r!=="text/markdown"&&(l.mime=r);const i=await fetch(`/api/archives/${e}/captures/text`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!i.ok){const a=await i.json().catch(()=>({})),o=new Error(a.error||`HTTP ${i.status}`);throw o.status=i.status,o}return i.json()}async function um(e,t){return ze(`/api/archives/${e}/captures/probe?locator=${encodeURIComponent(t)}`)}async function cm(e,t){const n=await fetch(`/api/archives/${e}/captures/probe-playlist`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({locator:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function of(e,t){return ze(`/api/archives/${e}/capture_jobs/${t}`)}async function dm(){return(await(await fetch("/api/auth/setup")).json()).setup_required===!0}async function fm(e,t){const n=await fetch("/api/auth/setup",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({username:e,password:t})});if(!n.ok)throw new Error((await n.json()).error||"Setup failed");return n.json()}async function pm(e,t){const n=await fetch("/api/auth/login",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({username:e,password:t})});if(!n.ok)throw new Error((await n.json()).error||"Login failed");return n.json()}async function hm(){await fetch("/api/auth/logout",{method:"POST"})}async function mm(){const e=await fetch("/api/auth/me");return e.status===401?null:e.json()}async function gm(e){const t=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({display_name:e})});if(!t.ok)throw new Error(await t.text())}async function ym(e){const t=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function vm(e,t){const n=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({current_password:e,new_password:t})});if(!n.ok){let r=await n.text();try{r=JSON.parse(r).error??r}catch{}throw new Error(r)}}async function xm(){return ze("/api/auth/tokens")}async function wm(e){const t=await fetch("/api/auth/tokens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})});if(!t.ok)throw new Error(await t.text());return t.json()}async function km(e){const t=await fetch(`/api/auth/tokens/${e}`,{method:"DELETE"});if(!t.ok)throw new Error(await t.text())}async function xo(){return ze("/api/admin/instance-settings")}async function ts(e){const t=await fetch("/api/admin/instance-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function jm(){return ze("/api/admin/users")}async function Sm(e,t,n){const r=await fetch("/api/admin/users",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,password:t,email:n||void 0})});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.error||`HTTP ${r.status}`)}return r.json()}async function Nm(e,t){const n=await fetch(`/api/admin/users/${e}/status`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function _m(){return ze("/api/admin/roles")}async function Cm(e,t){const n=await fetch("/api/admin/roles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:e,name:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function wo(e){return ze(`/api/archives/${e}/collections`)}async function Em(e,t,n,r=2,l=!0){const i=await fetch(`/api/archives/${e}/collections`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:t,slug:n,default_visibility_bits:r,requires_auth:l})});if(!i.ok){const a=await i.json().catch(()=>({error:i.statusText}));throw new Error(a.error||i.statusText)}return i.json()}async function bm(e,t){return ze(`/api/archives/${e}/collections/${t}`)}async function Sa(e,t,n,r=2){const l=await fetch(`/api/archives/${e}/collections/${t}/entries`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({entry_uid:n,visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}}async function Tm(e,t,n){const r=await fetch(`/api/archives/${e}/collections/${t}/entries/${n}`,{method:"DELETE"});if(!r.ok){const l=await r.json().catch(()=>({error:r.statusText}));throw new Error(l.error||r.statusText)}}async function Pm(e,t,n,r){const l=await fetch(`/api/archives/${e}/collections/${t}/entries/${n}`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}}async function Du(e,t){return ze(`/api/archives/${e}/entries/${t}/collections`)}async function Ci(e,t,n){const r=await fetch(`/api/archives/${e}/collections/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.error??r.statusText)}}async function Lm(e,t){const n=await fetch(`/api/archives/${e}/collections/${t}`,{method:"DELETE"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error??n.statusText)}}async function Rm(e){return ze(`/api/archives/${e}/blob-cleanup`)}async function zm(e){const t=await fetch(`/api/archives/${e}/blob-cleanup`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error??t.statusText)}return t.json()}async function Im(e,t){const n=await fetch(`/api/archives/${e}/entries/${t}/rearchive`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`rearchive failed: ${n.status}`)}return n.json()}async function $m(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/artifacts/${n}/media-token`,{method:"POST"});if(!r.ok)throw new Error(`media-token ${r.status}`);return r.json()}async function Dm(){return ze("/api/admin/cookie-rules")}async function Om(e,t,n){const r=await fetch("/api/admin/cookie-rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url_pattern:e||null,pattern_kind:t,cookies_json:n})});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.message||`HTTP ${r.status}`)}return r.json()}async function Am(e,t){const n=await fetch(`/api/admin/cookie-rules/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`HTTP ${n.status}`)}}async function Mm(e){const t=await fetch(`/api/admin/cookie-rules/${e}`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.message||`HTTP ${t.status}`)}}function Fm(e,t,n){let r;return{promise:new Promise((i,a)=>{const o=new FormData;o.append("file",t),r=new XMLHttpRequest,r.open("POST",`/api/archives/${e}/uploads`),r.upload.addEventListener("progress",u=>{u.lengthComputable&&n&&n(Math.round(u.loaded/u.total*100))}),r.addEventListener("load",()=>{if(r.status>=200&&r.status<300)try{i(JSON.parse(r.responseText))}catch{a(new Error("Invalid server response"))}else{let u=`Upload failed (${r.status})`;try{u=JSON.parse(r.responseText).message||u}catch{}a(new Error(u))}}),r.addEventListener("error",()=>a(new Error("Network error during upload"))),r.addEventListener("abort",()=>a(new Error("Upload cancelled"))),r.send(o)}),abort:()=>r==null?void 0:r.abort()}}async function Ei(e,t){try{await fetch(`/api/archives/${e}/uploads`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({locator:t})})}catch{}}const Bm=window.fetch;window.fetch=async(...e)=>{var n;const t=await Bm(...e);return t.status===401&&((typeof e[0]=="string"?e[0]:((n=e[0])==null?void 0:n.url)??"").includes("/api/auth/")||window.dispatchEvent(new CustomEvent("auth:expired"))),t};function Um({onLogin:e}){const[t,n]=c.useState(""),[r,l]=c.useState(""),[i,a]=c.useState(null),[o,u]=c.useState(!1);async function d(y){y.preventDefault(),a(null),u(!0);try{const g=await pm(t,r);e(g)}catch(g){a(g.message)}finally{u(!1)}}return s.jsx("div",{className:"login-page",children:s.jsxs("div",{className:"login-card",children:[s.jsx("h1",{className:"login-brand",children:"Archivr"}),s.jsx("p",{className:"login-tagline",children:"Sign in to your archive"}),s.jsxs("form",{onSubmit:d,children:[s.jsxs("div",{className:"login-field",children:[s.jsx("label",{className:"login-label",htmlFor:"login-username",children:"Username"}),s.jsx("input",{className:"login-input",id:"login-username",type:"text",value:t,onChange:y=>n(y.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),s.jsxs("div",{className:"login-field",children:[s.jsx("label",{className:"login-label",htmlFor:"login-password",children:"Password"}),s.jsx("input",{className:"login-input",id:"login-password",type:"password",value:r,onChange:y=>l(y.target.value),required:!0,autoComplete:"current-password"})]}),i&&s.jsx("p",{className:"login-error",children:i}),s.jsx("button",{className:"login-submit",type:"submit",disabled:o,children:o?"Signing in…":"Sign in"})]})]})})}function Hm({onComplete:e}){const[t,n]=c.useState(""),[r,l]=c.useState(""),[i,a]=c.useState(""),[o,u]=c.useState(null),[d,y]=c.useState(!1);async function g(h){if(h.preventDefault(),r!==i){u("Passwords do not match");return}if(r.length<8){u("Password must be at least 8 characters");return}u(null),y(!0);try{await fm(t,r),e()}catch(v){u(v.message)}finally{y(!1)}}return s.jsx("div",{className:"setup-page",children:s.jsxs("div",{className:"setup-card",children:[s.jsx("h1",{className:"setup-brand",children:"Archivr"}),s.jsx("p",{className:"setup-tagline",children:"Create your owner account to get started."}),s.jsxs("form",{onSubmit:g,children:[s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-username",children:"Username"}),s.jsx("input",{className:"setup-input",id:"setup-username",type:"text",value:t,onChange:h=>n(h.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-password",children:"Password"}),s.jsx("input",{className:"setup-input",id:"setup-password",type:"password",value:r,onChange:h=>l(h.target.value),required:!0,autoComplete:"new-password"})]}),s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-confirm",children:"Confirm password"}),s.jsx("input",{className:"setup-input",id:"setup-confirm",type:"password",value:i,onChange:h=>a(h.target.value),required:!0,autoComplete:"new-password"})]}),o&&s.jsx("p",{className:"setup-error",children:o}),s.jsx("button",{className:"setup-submit",type:"submit",disabled:d,children:d?"Creating account…":"Create account"})]})]})})}function Wm({archives:e,archiveId:t,onArchiveChange:n,view:r,onViewChange:l,onCaptureClick:i,collections:a,selectedCollectionUid:o,onCollectionChange:u,isPublicSession:d,onSignInClick:y}){const{currentUser:g,setCurrentUser:h}=c.useContext(Vs)??{},[v,x]=c.useState(!1);async function S(){x(!0),await hm(),h(null),window.location.reload()}const N=a.find(m=>m.slug==="_default_"),p=!d||!!N&&!N.requires_auth,f=a.filter(m=>m.slug!=="_default_").filter(m=>!d||!m.requires_auth);return s.jsxs("header",{className:"topbar",children:[s.jsx("div",{className:"brand",children:"Archivr"}),s.jsxs("div",{className:"switchers",children:[!d&&s.jsx("div",{className:"switcher",children:s.jsx("select",{"aria-label":"Select archive",value:t??"",onChange:m=>n(m.target.value),children:e.map(m=>s.jsx("option",{value:m.id,children:m.label},m.id))})}),f.length>0&&s.jsx("div",{className:"switcher",children:s.jsxs("select",{"aria-label":"Select collection",value:o??"",onChange:m=>u(m.target.value||null),children:[p&&s.jsx("option",{value:"",children:"All entries"}),f.map(m=>s.jsx("option",{value:m.collection_uid,children:m.name},m.collection_uid))]})})]}),d?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1}}),s.jsx("button",{className:"logout-btn",onClick:y,children:"Sign in"})]}):s.jsxs(s.Fragment,{children:[s.jsx("nav",{className:"nav","aria-label":"Primary",children:["archive","tags","collections","runs","admin","settings"].map(m=>s.jsx("button",{className:`nav-link${r===m?" is-active":""}`,onClick:()=>l(m),children:m.charAt(0).toUpperCase()+m.slice(1)},m))}),s.jsx("button",{className:"capture-button",onClick:i,children:"Capture"}),g&&s.jsxs("div",{className:"user-menu",children:[s.jsx("span",{className:"user-name",children:g.display_name||g.username}),s.jsx("button",{className:"logout-btn",onClick:S,disabled:v,children:v?"Logging out…":"Log out"})]})]})]})}let ml=1;function uf(e){const t=e.trim(),n=t.toLowerCase();for(const r of["yt:","youtube:"])if(n.startsWith(r)){const l=n.slice(r.length);return!!(l.startsWith("video/")||l.startsWith("short/")||l.startsWith("shorts/")||/^[a-z0-9_-]{11}$/i.test(l))}if(n.startsWith("ytm:"))return!n.slice(4).startsWith("playlist/");for(const r of["x:","twitter:","tweet:"])if(n.startsWith(r))return n.slice(r.length).startsWith("media:");if(n.startsWith("spotify:"))return!1;if(n.startsWith("instagram:")||n.startsWith("facebook:")||n.startsWith("tiktok:")||n.startsWith("reddit:")||n.startsWith("snapchat:"))return!0;if(n.startsWith("http://")||n.startsWith("https://")){if(/^https?:\/\/music\.youtube\.com\/watch/.test(n)||/^https?:\/\/(?:www\.)?(?:youtu\.be\/[0-9A-Za-z_-]+|youtube\.com\/watch\?v=[0-9A-Za-z_-]+|youtube\.com\/shorts\/[0-9A-Za-z_-]+)/.test(t)||n.startsWith("https://x.com/")||n.startsWith("http://x.com/")||/^https?:\/\/(?:www\.)?instagram\.com\//.test(n)||/^https?:\/\/(?:www\.)?facebook\.com\//.test(n)||n.startsWith("https://fb.watch/")||n.startsWith("http://fb.watch/")||/^https?:\/\/(?:www\.)?tiktok\.com\//.test(n)||/^https?:\/\/(?:www\.)?reddit\.com\//.test(n)||n.startsWith("https://redd.it/")||n.startsWith("http://redd.it/")||/^https?:\/\/(?:www\.)?snapchat\.com\//.test(n))return!0;if(n.startsWith("https://open.spotify.com/")||n.startsWith("http://open.spotify.com/"))return!1}return!1}function Dn(e){const t=e.trim(),n=t.toLowerCase();for(const r of["yt:","youtube:"])if(n.startsWith(r)){const l=n.slice(r.length);return l.startsWith("playlist/")||l.startsWith("@")||l.startsWith("channel/")||l.startsWith("c/")||l.startsWith("user/")}if(n.startsWith("ytm:"))return n.slice(4).startsWith("playlist/");if(n.startsWith("spotify:")){const r=n.slice(8);return r.startsWith("album:")||r.startsWith("playlist:")}if(n.startsWith("http://")||n.startsWith("https://"))try{const r=new URL(t),l=r.hostname;if((l==="youtube.com"||l==="www.youtube.com")&&(r.pathname==="/playlist"&&r.searchParams.has("list")||r.pathname.startsWith("/@")||r.pathname.startsWith("/channel/")||r.pathname.startsWith("/c/")||r.pathname.startsWith("/user/"))||l==="music.youtube.com"&&r.pathname==="/playlist"&&r.searchParams.has("list")||l==="open.spotify.com"&&(r.pathname.startsWith("/album/")||r.pathname.startsWith("/playlist/")))return!0}catch{}return!1}function Xn(e=""){return{id:ml++,locator:e,quality:"best",probeState:"idle",probeQualities:null,probeHasAudio:!1,status:"idle",error:null,jobUid:null,archiveId:null,playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1,syncEnabled:!1}}function Vm(e){return{id:ml++,kind:"file",filename:e,uploadProgress:0,uploadStatus:"uploading",uploadLocator:null,uploadError:null,locator:"",quality:"best",probeState:"idle",probeQualities:null,probeHasAudio:!1,playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1,syncEnabled:!1,error:null,status:"idle"}}function Qm(){return{id:ml++,kind:"text",title:"",body:"",mime:"text/markdown",locator:"",quality:"best",probeState:"idle",probeQualities:null,probeHasAudio:!1,playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1,syncEnabled:!1,error:null,status:"idle"}}function qm(e,t){return e==="best"?t.map(n=>({...n,quality:"best"})):e==="audio"?t.map(n=>n.has_audio?{...n,quality:"audio"}:n.quality!==null?n:{...n,quality:null}):t.map(n=>n.qualities.includes(e)?{...n,quality:e}:n.quality!==null?n:{...n,quality:null})}function Ou(e){return Array.isArray(e.playlistItems)&&e.playlistItems.some(t=>t.quality===null)}function Km({open:e,archiveId:t,onClose:n,onCaptured:r,onToast:l,onJobStarted:i,onJobSettled:a,activeJobs:o=[]}){const u=c.useRef(null),d=c.useRef(!0),y=c.useRef(new Map),g=c.useRef(new Map),h=c.useRef(new Map),v=c.useRef(t);c.useEffect(()=>{v.current=t},[t]);const x=c.useRef(null),[S,N]=c.useState(!1),p=c.useRef([]),f=c.useRef(!1),m=c.useRef(new Map),k=c.useRef(r),C=c.useRef(l);c.useEffect(()=>{k.current=r},[r]),c.useEffect(()=>{C.current=l},[l]);const E=c.useRef(i),T=c.useRef(a);c.useEffect(()=>{E.current=i},[i]),c.useEffect(()=>{T.current=a},[a]);const[j,P]=c.useState(()=>{try{const w=JSON.parse(sessionStorage.getItem("captureItems")||"null");if(Array.isArray(w)&&w.length>0){const B=w.filter(O=>!O.status||O.status==="idle");if(B.length>0)return B.forEach(O=>{O.id>=ml&&(ml=O.id+1)}),B.map(O=>({...Xn(O.locator),...O}))}}catch{}return[Xn()]});c.useEffect(()=>{sessionStorage.setItem("captureItems",JSON.stringify(j.filter(w=>w.kind!=="file")))},[j]),c.useEffect(()=>{p.current=j},[j]);const[R,X]=c.useState(!1),[H,Y]=c.useState(null),[te,fe]=c.useState(null),[Be,we]=c.useState(!0),[M,L]=c.useState(!0),[V,G]=c.useState(!0);c.useEffect(()=>{xo().then(w=>{fe(w),we(w.cookie_ext_enabled??!0),L(w.modal_closer_enabled??!0)}).catch(()=>fe({}))},[]);const ne=H!==null?H:(te==null?void 0:te.ublock_enabled)??!0,[se,Z]=c.useState(!1);c.useEffect(()=>{["captureDialogLocator","captureDialogError","captureDialogBusy","captureDialogJobStatus","captureDialogJobUid"].forEach(w=>sessionStorage.removeItem(w)),o.forEach(w=>{w.jobUid&&!y.current.has(w.jobUid)&&Se(w.id,w.jobUid,w.locator,w.archiveId,null)})},[]),c.useEffect(()=>{const w=u.current;if(!w)return;const B=()=>{if(g.current.forEach(O=>clearTimeout(O)),g.current.clear(),!f.current){const O=v.current;p.current.forEach($=>{var F;$.kind==="file"&&($.uploadStatus==="uploading"?((F=m.current.get($.id))==null||F(),m.current.delete($.id)):$.uploadStatus==="done"&&$.uploadLocator&&Ei(O,$.uploadLocator).catch(()=>{}))})}f.current=!1,n()};return w.addEventListener("close",B),()=>w.removeEventListener("close",B)},[n]),c.useEffect(()=>{const w=u.current;w&&(e?(d.current||P([Xn()]),d.current=!1,w.open||w.showModal()):(g.current.forEach(B=>clearTimeout(B)),g.current.clear(),w.open&&w.close()))},[e]),c.useEffect(()=>()=>{y.current.forEach(w=>clearInterval(w)),g.current.forEach(w=>clearTimeout(w))},[]);function Se(w,B,O,$,F=null){if(y.current.has(B))return;const U=setInterval(async()=>{var ye,ue,Te,pe;try{const $e=await of($,B);if($e.status==="completed"){clearInterval(y.current.get(B)),y.current.delete(B),await Promise.resolve((ye=k.current)==null?void 0:ye.call(k)),(ue=T.current)==null||ue.call(T,w);try{const ie=$e.notes_json?JSON.parse($e.notes_json):null;if(ie!=null&&ie.ublock_skipped||ie!=null&&ie.cookie_ext_skipped){const ot=ie.ublock_skipped&&ie.cookie_ext_skipped?"Captured without ad-blocking or cookie-consent extension. Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config.":ie.ublock_skipped?"Captured without ad-blocking. ARCHIVR_UBLOCK=true but ARCHIVR_UBLOCK_EXT is not set or the path is invalid.":"Captured without cookie-consent extension. ARCHIVR_COOKIE_EXT is not set or the path is invalid.";C.current(ot,O,"warning"),ce(F,"warning",O)}else F||C.current(null,O,"success"),ce(F,"archived")}catch{F||C.current(null,O,"success"),ce(F,"archived")}}else if($e.status==="failed"){clearInterval(y.current.get(B)),y.current.delete(B),(Te=T.current)==null||Te.call(T,w);const ie=$e.error_text||"Capture failed.";C.current(ie,O),ce(F,"failed",O)}}catch($e){clearInterval(y.current.get(B)),y.current.delete(B),(pe=T.current)==null||pe.call(T,w);const ie=$e.message||"Network error";C.current(ie,O),ce(F,"failed",O)}},500);y.current.set(B,U)}function ce(w,B,O=null){if(!w)return;const $=h.current.get(w);if(!$||(B==="archived"||B==="warning"?($.archived++,B==="warning"&&($.warnings++,O&&$.warningLocators.push(O))):($.failed++,O&&$.failedLocators.push(O)),$.archived+$.failed<$.total))return;h.current.delete(w);const{archived:F,warnings:U,failed:ye,failedLocators:ue,warningLocators:Te}=$;let pe;if(F===0)pe=`${ye} failed`;else{const ot=U>0?`${F} archived (${U} with warnings)`:`${F} archived`;pe=ye>0?`${ot}, ${ye} failed`:ot}const $e=F===0?"error":ye>0||U>0?"warning":"success",ie=[];ue.length>0&&ie.push(`Failed: +${ue.map(ot=>` ${ot}`).join(` +`)}`),Te.length>0&&ie.push(`With warnings: +${Te.map(ot=>` ${ot}`).join(` +`)}`);const nt=ie.length>0?ie.join(` +`):null;C.current(nt,null,$e,pe)}async function Ie(w,B){var Te,pe,$e;const O=v.current,$=((Te=crypto.randomUUID)==null?void 0:Te.call(crypto))??`job-${Date.now()}-${Math.random()}`;if(w.type==="text"){try{const ie=await om(O,{title:w.title,body:w.body,mime:w.mime}),nt=`text:${w.title}`;(pe=E.current)==null||pe.call(E,{id:$,jobUid:ie.job_uid,locator:nt,archiveId:O}),Se($,ie.job_uid,nt,O,B)}catch(ie){const nt=ie.message||"Submission failed.";C.current(nt,`text:${w.title}`),ce(B,"failed",`text:${w.title}`)}return}const F=w.locator,U=w.quality,ye=w.extraExtensions||{},ue={ublock_enabled:ne,reader_mode:se,cookie_ext_enabled:Be,modal_closer_enabled:M,via_freedium:V,...ye};try{const ie=await am(O,F,U,ue);($e=E.current)==null||$e.call(E,{id:$,jobUid:ie.job_uid,locator:F,archiveId:O}),Se($,ie.job_uid,F,O,B)}catch(ie){const nt=ie.message||"Submission failed.";C.current(nt,F),ce(B,"failed",F),F.startsWith("file://")&&ie.status&&Ei(O,F).catch(()=>{})}}function at(){var $,F;if(j.some(U=>U.kind==="file"&&U.uploadStatus==="uploading"))return;const w=j.filter(U=>U.kind==="file"?U.uploadStatus==="done"&&U.uploadLocator:U.kind==="text"?U.title.trim()&&U.body.trim():U.locator.trim());if(w.length===0||w.some(U=>U.kind!=="file"&&U.kind!=="text"&&Ou(U))||w.some(U=>U.kind!=="file"&&U.kind!=="text"&&(U.probeState==="probing"||Dn(U.locator)&&U.playlistProbeState!=="done"))||w.some(U=>U.kind!=="file"&&U.kind!=="text"&&Array.isArray(U.playlistItems)&&U.playlistItems.length===0))return;const B=w.length>1?(($=crypto.randomUUID)==null?void 0:$.call(crypto))??`batch-${Date.now()}`:null;B&&h.current.set(B,{total:w.length,archived:0,warnings:0,failed:0,failedLocators:[],warningLocators:[]});const O=w.map(U=>U.kind==="file"?{type:"file",locator:U.uploadLocator,quality:"best",extraExtensions:{}}:U.kind==="text"?{type:"text",title:U.title.trim(),body:U.body,mime:U.mime}:{type:"url",locator:U.locator.trim(),quality:U.playlistItems!==null?null:U.quality||"best",extraExtensions:U.playlistItems!==null?{per_item_quality:Object.fromEntries(U.playlistItems.map(ye=>[ye.id,ye.quality])),sync:U.syncEnabled}:{}});f.current=!0,P([Xn()]),(F=u.current)==null||F.close(),O.forEach(U=>Ie(U,B))}function ht(){P(w=>[...w,Xn()])}function Vt(w){var O;clearTimeout(g.current.get(w)),g.current.delete(w);const B=p.current.find($=>$.id===w);(B==null?void 0:B.kind)==="file"&&(B.uploadStatus==="uploading"?((O=m.current.get(w))==null||O(),m.current.delete(w)):B.uploadStatus==="done"&&B.uploadLocator&&Ei(v.current,B.uploadLocator).catch(()=>{})),P($=>{const F=$.filter(U=>U.id!==w);return F.length===0?[Xn()]:F})}function Qt(w,B){if(clearTimeout(g.current.get(w)),P(O=>O.map($=>$.id===w?{...$,locator:B,probeState:"idle",probeQualities:null,probeHasAudio:!1,quality:"best",playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1}:$)),uf(B)){const O=setTimeout(async()=>{g.current.delete(w),P($=>$.map(F=>F.id===w?{...F,probeState:"probing"}:F));try{const $=await um(v.current,B.trim());P(F=>F.map(U=>{if(U.id!==w||U.locator!==B)return U;const ye=$.qualities??[],ue=$.has_audio??!1,Te=ye.length===0&&ue?"audio":"best";return{...U,probeState:"done",probeQualities:ye,probeHasAudio:ue,quality:Te}}))}catch{P($=>$.map(F=>F.id===w?{...F,probeState:"idle",probeQualities:null}:F))}},600);g.current.set(w,O)}else if(Dn(B)){const O=setTimeout(async()=>{g.current.delete(w),P($=>$.map(F=>F.id===w?{...F,playlistProbeState:"probing"}:F));try{const $=await cm(v.current,B.trim());P(F=>F.map(U=>U.id!==w||U.locator!==B?U:{...U,playlistProbeState:"done",playlistInfo:$,playlistItems:$.items.map(ye=>({...ye,quality:null})),playlistQuality:null}))}catch{P($=>$.map(F=>F.id===w?{...F,playlistProbeState:"error"}:F))}},800);g.current.set(w,O)}}function jt(w,B){P(O=>O.map($=>$.id===w?{...$,quality:B}:$))}function Oe(w,B){P(O=>O.map($=>{if($.id!==w)return $;const F=qm(B,$.playlistItems);return{...$,playlistQuality:B,playlistItems:F}}))}function Je(w,B,O){P($=>$.map(F=>F.id!==w?F:{...F,playlistItems:F.playlistItems.map(U=>U.id===B?{...U,quality:O}:U)}))}function tt(w){P(B=>B.map(O=>O.id===w?{...O,playlistExpanded:!O.playlistExpanded}:O))}function D(w,B){P(O=>O.map($=>$.id===w?{...$,syncEnabled:B}:$))}function K(w,B){P(O=>O.map($=>$.id!==w?$:{...$,playlistItems:$.playlistItems.filter(F=>F.id!==B)}))}function Ne(w){const B=Array.from(w);B.length!==0&&B.forEach(O=>{const $=Vm(O.name);P(ue=>ue.length===1&&!ue[0].kind&&!ue[0].locator.trim()?[$]:[...ue,$]);const F=v.current,{promise:U,abort:ye}=Fm(F,O,ue=>{P(Te=>Te.map(pe=>pe.id===$.id?{...pe,uploadProgress:ue}:pe))});m.current.set($.id,ye),U.then(ue=>{m.current.delete($.id),P(Te=>Te.map(pe=>pe.id===$.id?{...pe,uploadStatus:"done",uploadLocator:ue.locator,uploadProgress:100}:pe))}).catch(ue=>{m.current.delete($.id),ue.message!=="Upload cancelled"&&P(Te=>Te.map(pe=>pe.id===$.id?{...pe,uploadStatus:"error",uploadError:ue.message}:pe))})})}function Ve(w){w.preventDefault(),w.stopPropagation(),w.dataTransfer.types.includes("Files")&&N(!0)}function qt(w){w.currentTarget.contains(w.relatedTarget)||N(!1)}function Qe(w){w.preventDefault(),w.stopPropagation(),N(!1),Ne(w.dataTransfer.files)}function Kt(w){Ne(w.target.files),w.target.value=""}const Qn=j.some(w=>w.kind==="file"&&w.uploadStatus==="uploading"),Ot=j.filter(w=>w.kind==="file"?w.uploadStatus==="done"&&w.uploadLocator:w.kind==="text"?w.title.trim()&&w.body.trim():w.locator.trim()).length,Le=j.some(w=>w.kind!=="file"&&w.kind!=="text"&&Ou(w)),bn=j.some(w=>w.kind!=="file"&&w.kind!=="text"&&Array.isArray(w.playlistItems)&&w.playlistItems.length===0),At=j.some(w=>w.kind!=="file"&&w.kind!=="text"&&(w.probeState==="probing"||Dn(w.locator)&&w.playlistProbeState!=="done"));return s.jsx("dialog",{ref:u,className:`capture-dialog${S?" capture-dialog--dragover":""}`,onDragOver:Ve,onDragLeave:qt,onDrop:Qe,children:s.jsxs("div",{className:"capture-dialog-inner",children:[s.jsxs("div",{className:"capture-dialog-header",children:[s.jsx("h2",{className:"capture-dialog-title",children:"Capture"}),s.jsx("button",{type:"button",className:"capture-dialog-close",onClick:()=>{var w;return(w=u.current)==null?void 0:w.close()},"aria-label":"Close",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),s.jsx("div",{className:"capture-rows",children:j.map((w,B)=>w.kind==="file"?s.jsx(Jm,{item:w,onRemove:()=>Vt(w.id)},w.id):w.kind==="text"?s.jsx(Gm,{item:w,autoFocus:B===j.length-1,onTitleChange:O=>P($=>$.map(F=>F.id===w.id?{...F,title:O}:F)),onBodyChange:O=>P($=>$.map(F=>F.id===w.id?{...F,body:O}:F)),onMimeChange:O=>P($=>$.map(F=>F.id===w.id?{...F,mime:O}:F)),onRemove:()=>Vt(w.id),onSubmit:at},w.id):s.jsx(Xm,{item:w,autoFocus:B===j.length-1,onLocatorChange:O=>Qt(w.id,O),onQualityChange:O=>jt(w.id,O),onRemove:()=>Vt(w.id),onSubmit:at,onPlaylistQualityChange:O=>Oe(w.id,O),onPlaylistItemQualityChange:(O,$)=>Je(w.id,O,$),onPlaylistToggle:()=>tt(w.id),onSyncChange:O=>D(w.id,O),onPlaylistItemDelete:O=>K(w.id,O)},w.id))}),s.jsx("input",{ref:x,type:"file",multiple:!0,hidden:!0,onChange:Kt,"aria-hidden":"true",tabIndex:-1}),s.jsxs("div",{className:"capture-add-row-group",children:[s.jsxs("button",{type:"button",className:"capture-add-row",onClick:ht,children:[s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"8",y1:"2",x2:"8",y2:"14"}),s.jsx("line",{x1:"2",y1:"8",x2:"14",y2:"8"})]}),"Add URL"]}),s.jsxs("button",{type:"button",className:"capture-add-row capture-add-file",onClick:()=>{var w;return(w=x.current)==null?void 0:w.click()},children:[s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{x:"3",y:"1",width:"10",height:"14",rx:"1.5"}),s.jsx("line",{x1:"5.5",y1:"5.5",x2:"10.5",y2:"5.5"}),s.jsx("line",{x1:"5.5",y1:"8",x2:"10.5",y2:"8"}),s.jsx("line",{x1:"5.5",y1:"10.5",x2:"8.5",y2:"10.5"})]}),"Upload file"]}),s.jsxs("button",{type:"button",className:"capture-add-row capture-add-text",onClick:()=>P(w=>[...w,Qm()]),children:[s.jsx("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M2 3h12M2 7h12M2 11h8"})}),"Add text"]})]}),s.jsxs("div",{className:"capture-advanced",children:[s.jsxs("button",{type:"button",className:"capture-advanced-toggle",onClick:()=>X(w=>!w),"aria-expanded":R,children:[s.jsx("svg",{className:`capture-chevron${R?" capture-chevron--open":""}`,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("polyline",{points:"4 6 8 10 12 6"})}),"Advanced options"]}),R&&s.jsxs("div",{className:"capture-advanced-panel",children:[s.jsxs("label",{className:"capture-ext-row",children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"uBlock Origin Lite"}),s.jsx("span",{className:"capture-ext-desc",children:"Block ads during this capture"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":ne,className:`ext-toggle ext-toggle--sm${ne?" ext-toggle--on":""}`,onClick:()=>Y(w=>w===null?!ne:!w),"aria-label":"Toggle uBlock for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Block cookie banners"}),s.jsx("span",{className:"capture-ext-desc",children:"Dismiss cookie consent banners during this capture"}),!(te!=null&&te.cookie_ext_available)&&s.jsxs("span",{className:"capture-ext-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":Be,className:`ext-toggle ext-toggle--sm${Be?" ext-toggle--on":""}`,onClick:()=>we(w=>!w),"aria-label":"Toggle cookie banner blocking for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Reader mode"}),s.jsx("span",{className:"capture-ext-desc",children:"Distil to article text via Readability (off by default)"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":se,className:`ext-toggle ext-toggle--sm${se?" ext-toggle--on":""}`,onClick:()=>Z(w=>!w),"aria-label":"Toggle reader mode for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Close modals and dialogs"}),s.jsx("span",{className:"capture-ext-desc",children:"Auto-dismiss cookie banners and overlays during this capture"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":M,className:`ext-toggle ext-toggle--sm${M?" ext-toggle--on":""}`,onClick:()=>L(w=>!w),"aria-label":"Toggle modal closer for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Freedium mirror"}),s.jsx("span",{className:"capture-ext-desc",children:"Route paywalled articles through a Freedium mirror (Medium, NYT, WaPo, etc.)"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":V,className:`ext-toggle ext-toggle--sm${V?" ext-toggle--on":""}`,onClick:()=>G(w=>!w),"aria-label":"Toggle Freedium mirror for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]})]})]}),s.jsxs("div",{className:"capture-actions",children:[s.jsx("button",{type:"button",className:"capture-submit",onClick:at,disabled:Ot===0||Le||At||bn||Qn,children:Ot>1?`Archive ${Ot}`:"Archive"}),s.jsx("button",{type:"button",className:"capture-cancel",onClick:()=>{var w;return(w=u.current)==null?void 0:w.close()},children:"Cancel"})]})]})})}function Xm({item:e,autoFocus:t,onLocatorChange:n,onQualityChange:r,onRemove:l,onSubmit:i,onPlaylistQualityChange:a,onPlaylistItemQualityChange:o,onPlaylistToggle:u,onSyncChange:d,onPlaylistItemDelete:y}){const g=c.useRef(null);c.useEffect(()=>{var x;t&&((x=g.current)==null||x.focus())},[t]);const h=(()=>{if(Dn(e.locator)){if(e.playlistProbeState==="probing")return s.jsx("span",{className:"capture-quality-probing","aria-label":"Probing playlist…",children:"…"});if(e.playlistProbeState==="done"){const x=[...new Set(e.playlistItems.flatMap(p=>p.qualities.map(f=>parseInt(f))))].sort((p,f)=>f-p),S=e.playlistItems.every(p=>p.has_audio),N=e.playlistItems.filter(p=>p.quality===null).length;return s.jsxs(s.Fragment,{children:[s.jsxs("select",{className:"capture-quality",value:e.playlistQuality??"",onChange:p=>a(p.target.value),"aria-label":"Playlist quality",children:[!e.playlistQuality&&s.jsx("option",{value:"",disabled:!0,children:"Select quality…"}),s.jsx("option",{value:"best",children:"Best quality"}),x.map(p=>s.jsxs("option",{value:`${p}p`,children:[p,"p"]},p)),S&&s.jsx("option",{value:"audio",children:"Audio only"})]}),N>0&&s.jsxs("span",{className:"capture-conflict-badge",children:[N," need selection"]})]})}return e.playlistProbeState==="error"?s.jsx("span",{className:"capture-quality-hint capture-quality-hint--error",children:"Probe failed — edit URL to retry"}):null}if(!uf(e.locator))return null;if(e.probeState==="probing")return s.jsx("span",{className:"capture-quality-probing","aria-label":"Checking available qualities",children:"…"});if(e.probeState==="done"){const x=e.probeQualities??[],S=e.probeHasAudio??!1;return x.length===0&&!S?s.jsx("span",{className:"capture-quality-hint",children:"No media detected"}):x.length===0&&S?s.jsx("select",{className:"capture-quality",value:"audio",onChange:N=>r(N.target.value),"aria-label":"Video quality",children:s.jsx("option",{value:"audio",children:"Audio only"})}):s.jsxs("select",{className:"capture-quality",value:e.quality||"best",onChange:N=>r(N.target.value),"aria-label":"Video quality",children:[s.jsx("option",{value:"best",children:"Best quality"}),x.map(N=>s.jsx("option",{value:N,children:N},N)),S&&s.jsx("option",{value:"audio",children:"Audio only"})]})}return null})(),v=Dn(e.locator)&&e.playlistProbeState==="done"?s.jsxs("label",{className:"capture-sync-row",children:[s.jsx("input",{type:"checkbox",checked:e.syncEnabled,onChange:x=>d(x.target.checked)}),s.jsx("span",{children:"Sync — skip already-archived videos"})]}):null;return s.jsxs("div",{className:"capture-row",children:[s.jsxs("div",{className:"capture-row-main",children:[Dn(e.locator)&&e.playlistProbeState==="done"?s.jsx("button",{type:"button",className:"capture-playlist-toggle capture-playlist-toggle--left",onClick:u,"aria-label":e.playlistExpanded?"Collapse video list":"Expand video list","aria-expanded":e.playlistExpanded,children:e.playlistExpanded?"▲":"▼"}):null,s.jsx("input",{ref:g,className:"capture-input",type:"text",placeholder:"https://… · yt:ID · ytm:ID · tweet:ID · x:ID",value:e.locator,onChange:x=>n(x.target.value),onKeyDown:x=>{x.key==="Enter"&&i()},autoComplete:"off",spellCheck:!1}),h,s.jsx("button",{type:"button",className:"capture-row-action capture-row-remove",onClick:l,"aria-label":"Remove",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),e.error&&s.jsx("p",{className:"capture-row-error",children:e.error}),Dn(e.locator)&&e.playlistProbeState==="done"&&e.playlistExpanded?s.jsxs("div",{className:"capture-playlist-items",children:[e.playlistItems.map(x=>s.jsxs("div",{className:`capture-playlist-item${x.quality===null?" capture-playlist-item--conflict":""}`,children:[s.jsx("span",{className:"capture-playlist-item-title",children:x.title||x.url}),s.jsxs("select",{className:"capture-item-quality",value:x.quality??"",onChange:S=>o(x.id,S.target.value),"aria-label":`Quality for ${x.title||x.url}`,children:[x.quality===null&&s.jsx("option",{value:"",disabled:!0,children:"Choose…"}),s.jsx("option",{value:"best",children:"Best quality"}),x.qualities.map(S=>s.jsx("option",{value:S,children:S},S)),x.has_audio&&s.jsx("option",{value:"audio",children:"Audio only"})]}),x.quality===null&&s.jsx("span",{className:"capture-playlist-conflict-badge",children:"Choose quality"}),s.jsx("button",{type:"button",className:"capture-playlist-item-remove","aria-label":`Remove ${x.title||x.url}`,onClick:()=>y(x.id),children:"×"})]},x.id)),v]}):v]})}function Jm({item:e,onRemove:t}){const n=e.uploadStatus==="uploading",r=e.uploadStatus==="done",l=e.uploadStatus==="error";return s.jsxs("div",{className:"capture-row",children:[s.jsxs("div",{className:"capture-row-main",children:[s.jsx("span",{className:"capture-file-icon","aria-hidden":"true",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",style:{width:14,height:14},children:[s.jsx("rect",{x:"3",y:"1",width:"10",height:"14",rx:"1.5"}),s.jsx("line",{x1:"5.5",y1:"5.5",x2:"10.5",y2:"5.5"}),s.jsx("line",{x1:"5.5",y1:"8",x2:"10.5",y2:"8"}),s.jsx("line",{x1:"5.5",y1:"10.5",x2:"8.5",y2:"10.5"})]})}),s.jsx("span",{className:`capture-file-name${l?" capture-file-name--error":""}`,children:e.filename}),n&&s.jsxs("span",{className:"capture-file-progress-wrap","aria-label":`Uploading ${e.uploadProgress}%`,children:[s.jsx("span",{className:"capture-file-progress-bar",children:s.jsx("span",{className:"capture-file-progress-fill",style:{width:`${e.uploadProgress}%`}})}),s.jsxs("span",{className:"capture-file-progress-pct",children:[e.uploadProgress,"%"]})]}),r&&s.jsx("span",{className:"capture-file-badge capture-file-badge--done","aria-label":"Upload complete",children:s.jsx("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{width:11,height:11},children:s.jsx("polyline",{points:"3 8.5 6.5 12 13 5"})})}),l&&s.jsx("span",{className:"capture-file-badge capture-file-badge--error",children:"!"}),s.jsx("button",{type:"button",className:"capture-row-action capture-row-remove",onClick:t,"aria-label":"Remove",disabled:n,children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),l&&s.jsx("p",{className:"capture-row-error",children:e.uploadError||"Upload failed"})]})}function Gm({item:e,autoFocus:t,onTitleChange:n,onBodyChange:r,onMimeChange:l,onRemove:i,onSubmit:a}){const o=c.useRef(null);return c.useEffect(()=>{var u;t&&((u=o.current)==null||u.focus())},[t]),s.jsx("div",{className:"capture-row capture-text-row",children:s.jsxs("div",{className:"capture-row-main",children:[s.jsx("span",{className:"capture-text-icon","aria-hidden":"true",children:s.jsx("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",style:{width:14,height:14},children:s.jsx("path",{d:"M2 3h12M2 7h12M2 11h8"})})}),s.jsxs("div",{className:"capture-text-inputs",children:[s.jsx("input",{ref:o,className:"capture-text-input capture-text-title",type:"text",placeholder:"Title",value:e.title,onChange:u=>n(u.target.value),maxLength:500}),s.jsx("textarea",{className:"capture-text-input capture-text-body",placeholder:"Body (markdown or plain text)",value:e.body,onChange:u=>r(u.target.value),rows:6}),s.jsx("div",{className:"capture-text-footer",children:s.jsxs("select",{className:"capture-text-mime",value:e.mime,onChange:u=>l(u.target.value),children:[s.jsx("option",{value:"text/markdown",children:"Markdown"}),s.jsx("option",{value:"text/plain",children:"Plain text"})]})})]}),s.jsx("button",{type:"button",className:"capture-row-action capture-row-remove",onClick:i,"aria-label":"Remove",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]})})}const Ym=["list=","/playlist/","/channel/","yt:playlist:","yt:channel:","ytm:playlist:","spotify:playlist:","spotify:album:"];function Zm(e){const t=e.toLowerCase();return Ym.some(n=>t.includes(n))}function eg(e){return e.length>80?`${e.slice(0,79)}…`:e}function tg({locator:e=""}){const t=String(e),n=Zm(t);return s.jsxs("div",{className:"in-progress-entry-row",role:"status","aria-live":"polite",children:[s.jsx("span",{className:"cap-spinner in-progress-entry-row__spinner","aria-hidden":"true"}),s.jsx("span",{className:"in-progress-entry-row__locator",title:t,children:eg(t)}),s.jsxs("span",{className:"in-progress-entry-row__status",children:["Archiving…",n&&s.jsx("span",{className:"in-progress-entry-row__kind",children:"(playlist)"})]})]})}function gl(e){if(!e)return"0 B";const t=["B","KB","MB","GB"];let n=e,r=0;for(;n>=1024&&r").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}function gt(e){return ng(e)??""}function ko(e){if(!e)return"";const t=new Date(e);if(isNaN(t))return e;const n=r=>String(r).padStart(2,"0");return`${t.getUTCFullYear()}-${n(t.getUTCMonth()+1)}-${n(t.getUTCDate())} ${n(t.getUTCHours())}:${n(t.getUTCMinutes())}`}const Au={youtube:'',youtube_music:'',spotify:'',x:'',instagram:'',facebook:'',tiktok:'',reddit:'',snapchat:'',local:'',web:'',other:'?'};function Ws(e){return Au[e]??Au.other}function cf(e){return e.split("/").map(t=>t?t.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"").join("/")}function rg({entry:e,index:t,onRowClick:n,selectedUids:r}){const l=(r==null?void 0:r.size)===1&&r.has(e.entry_uid),i=(r==null?void 0:r.size)>=2&&r.has(e.entry_uid),a=["child-entry-row",t%2===0?"child-entry-row--light":"child-entry-row--dark",l&&"is-selected",i&&"is-multi-selected"].filter(Boolean).join(" ");return s.jsxs("div",{className:a,tabIndex:0,"data-entry-uid":e.entry_uid,onMouseDown:o=>{o.shiftKey&&o.preventDefault()},onClick:o=>n(e,o),onKeyDown:o=>{o.key==="Enter"&&n(e,o)},children:[s.jsx("div",{className:"col-check","aria-hidden":"true"}),s.jsx("div",{className:"col-added",children:ko(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[s.jsx("span",{className:"source-icon",children:s.jsx("span",{dangerouslySetInnerHTML:{__html:Ws(e.source_kind)}})}),s.jsx("span",{className:"entry-title",children:gt(e.title)||gt(e.entry_uid)})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"type-pill",children:gt(e.entity_kind)})}),s.jsx("div",{className:"col-size",children:s.jsx("span",{className:"size-total",children:gl(e.total_artifact_bytes)})}),s.jsx("div",{className:"url-cell col-url",children:gt(e.original_url)})]})}function lg({entry:e,archiveId:t,rowIndex:n,isSelected:r,isMultiSelected:l,onRowClick:i,selectedUids:a,deletedUids:o,isPublicSession:u}){const[d,y]=c.useState(!1),[g,h]=c.useState(!1),[v,x]=c.useState(null),[S,N]=c.useState(!1),f=e.source_kind==="web"&&e.entity_kind==="page"&&e.has_favicon&&t&&!d?s.jsx("img",{src:`/api/archives/${t}/entries/${e.entry_uid}/favicon`,width:"16",height:"16",alt:"",onError:()=>y(!0),style:{objectFit:"contain"}}):s.jsx("span",{dangerouslySetInnerHTML:{__html:Ws(e.source_kind)}}),m=r||l,k=e.child_count>0&&!u;function C(j){j.stopPropagation(),i(e,{ctrlKey:!0,metaKey:!1,shiftKey:!1,preventDefault(){}})}async function E(j){if(j.stopPropagation(),g){h(!1);return}if(h(!0),v===null&&!S){N(!0);try{const P=await Yh(t,e.entry_uid);x(P)}catch{x([])}finally{N(!1)}}}const T=["entry-row-outer",n%2===0?"entry-row-outer--light":"entry-row-outer--dark",r&&"is-selected",l&&"is-multi-selected"].filter(Boolean).join(" ");return s.jsxs("div",{className:T,"data-entry-uid":e.entry_uid,children:[s.jsxs("div",{className:"entry-row-main",tabIndex:0,onMouseDown:j=>{j.shiftKey&&j.preventDefault()},onClick:j=>i(e,j),onKeyDown:j=>{j.key==="Enter"&&i(e,j)},children:[s.jsx("div",{className:"col-check",children:s.jsx("button",{type:"button",className:`row-checkbox${m?" is-checked":""}`,"aria-pressed":m,"aria-label":m?"Deselect entry":"Select entry",onClick:C,onKeyDown:j=>j.stopPropagation()})}),s.jsx("div",{className:"col-added",children:ko(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[k&&s.jsx("button",{type:"button",className:`entry-expand-btn${g?" is-expanded":""}`,"aria-label":g?"Collapse children":`Expand ${e.child_count} items`,"aria-expanded":g,onClick:E,onKeyDown:j=>j.stopPropagation()}),s.jsx("span",{className:"source-icon",children:f}),s.jsx("span",{className:"entry-title",children:gt(e.title)||gt(e.entry_uid)}),k&&s.jsx("span",{className:"child-count-badge","aria-hidden":"true",children:e.child_count})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"type-pill",children:gt(e.entity_kind)})}),s.jsxs("div",{className:"col-size",children:[s.jsx("span",{className:"size-total",children:gl(e.total_artifact_bytes)}),e.cached_bytes>0&&e.cacheable_bytes>0&&s.jsxs("span",{className:"size-cached-pct",title:`${gl(e.cached_bytes)} already on disk from an earlier entry`,children:[Math.round(e.cached_bytes/e.cacheable_bytes*100),"% cached"]})]}),s.jsx("div",{className:"url-cell col-url",children:gt(e.original_url)})]}),g&&s.jsxs(s.Fragment,{children:[S&&s.jsx("div",{className:"child-entries-loading",children:"Loading…"}),s.jsx("div",{className:"child-entries","aria-label":`${e.child_count} child entries`,children:v&&v.filter(j=>!(o!=null&&o.has(j.entry_uid))).map((j,P)=>s.jsx(rg,{entry:j,index:P,onRowClick:i,selectedUids:a},j.entry_uid))})]})]})}function sg({entries:e,selectedUids:t,onRowClick:n,archiveId:r,pendingCaptures:l=[],deletedUids:i,isPublicSession:a}){return s.jsx("section",{id:"archive-view",className:"view is-active",children:s.jsxs("div",{className:"entry-table",children:[s.jsxs("div",{className:"entry-header-row",children:[s.jsx("div",{className:"col-check","aria-hidden":"true"}),s.jsx("div",{className:"col-added",children:"Added"}),s.jsx("div",{className:"col-title",children:"Title"}),s.jsx("div",{className:"col-type",children:"Type"}),s.jsx("div",{className:"col-size",children:"Size"}),s.jsx("div",{className:"col-url",children:"Original URL"})]}),s.jsxs("div",{id:"entries-body",children:[l.filter(o=>o.archiveId===r).reverse().map(o=>s.jsx(tg,{locator:o.locator},o.id)),e.map((o,u)=>s.jsx(lg,{entry:o,rowIndex:u,archiveId:r,isSelected:t.size===1&&t.has(o.entry_uid),isMultiSelected:t.size>=2&&t.has(o.entry_uid),onRowClick:n,selectedUids:t,deletedUids:i,isPublicSession:a},o.entry_uid))]})]})})}function ig(e){if(!e)return"—";try{return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return e}}function ag({status:e}){const t=e==="completed"?"run-status--completed":e==="failed"?"run-status--failed":e==="in_progress"?"run-status--in-progress":"",n=e?e.replace(/_/g," "):"—";return s.jsx("span",{className:`run-status ${t}`,children:n})}function og({runs:e}){const[t,n]=c.useState(null);function r(l){n(i=>i===l?null:l)}return s.jsx("section",{id:"runs-view",className:"view is-active",children:s.jsxs("table",{className:"entry-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Started"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Requested"}),s.jsx("th",{children:"Completed"}),s.jsx("th",{children:"Failed"})]})}),s.jsx("tbody",{children:e.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:5,style:{color:"var(--muted)",padding:"24px 16px",textAlign:"center"},children:"No runs yet."})}):e.map(l=>{const i=l.status==="failed"&&l.error_summary,a=t===l.run_uid;return[s.jsxs("tr",{className:i?"run-row run-row--failed":"run-row",onClick:i?()=>r(l.run_uid):void 0,title:i?a?"Click to hide error":"Click to view error":void 0,children:[s.jsx("td",{children:ig(l.started_at)}),s.jsxs("td",{children:[s.jsx(ag,{status:l.status}),i&&s.jsx("span",{className:"run-expand-hint","aria-hidden":"true",children:a?"▴":"▾"})]}),s.jsx("td",{children:l.requested_count??"—"}),s.jsx("td",{children:l.completed_count??"—"}),s.jsx("td",{children:l.failed_count??"—"})]},l.run_uid),i&&a&&s.jsx("tr",{className:"run-error-row",children:s.jsx("td",{colSpan:5,children:s.jsx("pre",{className:"run-error-detail",children:l.error_summary})})},`${l.run_uid}-detail`)]})})]})})}const ug=4;function cg({archives:e}){const{currentUser:t}=c.useContext(Vs)??{},n=t&&(t.role_bits&ug)!==0,[r,l]=c.useState("users"),[i,a]=c.useState([]),[o,u]=c.useState([]),[d,y]=c.useState(!1),[g,h]=c.useState(null),[v,x]=c.useState(""),[S,N]=c.useState(""),[p,f]=c.useState(""),[m,k]=c.useState(null),[C,E]=c.useState(!1),[T,j]=c.useState(""),[P,R]=c.useState(""),[X,H]=c.useState(null),[Y,te]=c.useState(!1),fe=c.useCallback(async()=>{if(n){y(!0),h(null);try{const[L,V]=await Promise.all([jm(),_m()]);a(L),u(V)}catch(L){h(L.message)}finally{y(!1)}}},[n]);c.useEffect(()=>{fe()},[fe]);async function Be(L){const V=L.status==="active"?"disabled":"active";try{await Nm(L.user_uid,V),a(G=>G.map(ne=>ne.user_uid===L.user_uid?{...ne,status:V}:ne))}catch(G){h(G.message)}}async function we(L){if(L.preventDefault(),!v.trim()||!S){k("Username and password required");return}E(!0),k(null);try{await Sm(v.trim(),S,p.trim()||void 0),x(""),N(""),f(""),await fe()}catch(V){k(V.message)}finally{E(!1)}}async function M(L){if(L.preventDefault(),!T.trim()||!P.trim()){H("Slug and name required");return}te(!0),H(null);try{await Cm(T.trim(),P.trim()),j(""),R(""),await fe()}catch(V){H(V.message)}finally{te(!1)}}return n?s.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[s.jsx("h1",{children:"Admin"}),s.jsxs("div",{className:"view-tabs",children:[s.jsx("button",{className:`view-tab${r==="users"?" is-active":""}`,onClick:()=>l("users"),children:"Users"}),s.jsx("button",{className:`view-tab${r==="roles"?" is-active":""}`,onClick:()=>l("roles"),children:"Roles"}),s.jsx("button",{className:`view-tab${r==="archives"?" is-active":""}`,onClick:()=>l("archives"),children:"Archives"})]}),g&&s.jsx("div",{className:"form-msg form-msg--err",children:g}),r==="users"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Users"}),d?s.jsx("p",{className:"muted",children:"Loading…"}):s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Username"}),s.jsx("th",{children:"Email"}),s.jsx("th",{children:"Roles"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:i.map(L=>s.jsxs("tr",{className:L.status==="disabled"?"admin-row-disabled":"",children:[s.jsx("td",{children:L.username}),s.jsx("td",{className:"muted",children:L.email||"—"}),s.jsx("td",{children:L.role_slugs.join(", ")||"—"}),s.jsx("td",{children:s.jsx("span",{className:`status-badge status-${L.status}`,children:L.status})}),s.jsx("td",{children:s.jsx("button",{className:"admin-action-btn",onClick:()=>Be(L),children:L.status==="active"?"Ban":"Unban"})})]},L.user_uid))})]}),s.jsx("h3",{children:"Create User"}),s.jsxs("form",{className:"admin-form",onSubmit:we,children:[s.jsx("input",{className:"admin-input",placeholder:"Username",value:v,onChange:L=>x(L.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"password",placeholder:"Password (min 8 chars)",value:S,onChange:L=>N(L.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"email",placeholder:"Email (optional)",value:p,onChange:L=>f(L.target.value)}),m&&s.jsx("div",{className:"form-msg form-msg--err",children:m}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:C,children:C?"Creating…":"Create User"})]})]}),r==="roles"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Roles"}),d?s.jsx("p",{className:"muted",children:"Loading…"}):s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Slug"}),s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Level"}),s.jsx("th",{children:"Bit"}),s.jsx("th",{children:"Built-in"})]})}),s.jsx("tbody",{children:o.map(L=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:L.slug})}),s.jsx("td",{children:L.name}),s.jsx("td",{children:L.level}),s.jsx("td",{children:L.bit_position}),s.jsx("td",{children:L.is_builtin?"✓":""})]},L.role_uid))})]}),s.jsx("h3",{children:"Create Custom Role"}),s.jsxs("form",{className:"admin-form",onSubmit:M,children:[s.jsx("input",{className:"admin-input",placeholder:"Slug (e.g. moderator)",value:T,onChange:L=>j(L.target.value),required:!0}),s.jsx("input",{className:"admin-input",placeholder:"Display Name (e.g. Moderator)",value:P,onChange:L=>R(L.target.value),required:!0}),X&&s.jsx("div",{className:"form-msg form-msg--err",children:X}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:Y,children:Y?"Creating…":"Create Role"})]})]}),r==="archives"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Mounted Archives"}),s.jsx("div",{className:"admin-list",children:e.map(L=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:L.label}),s.jsx("div",{className:"muted",children:L.archive_path})]},L.id))})]})]}):s.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[s.jsx("h1",{children:"Admin"}),s.jsx("p",{className:"muted",children:"You need admin privileges to access this panel."}),s.jsx("h2",{children:"Mounted Archives"}),s.jsx("div",{className:"admin-list",children:e.map(L=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:L.label}),s.jsx("div",{className:"muted",children:L.archive_path})]},L.id))})]})}function df({node:e,onPick:t}){var n;return s.jsxs("li",{children:[s.jsx("button",{className:"tag-picker-node-btn",title:e.tag.full_path,onClick:()=>t(e.tag),children:e.tag.slug}),((n=e.children)==null?void 0:n.length)>0&&s.jsx("div",{className:"tag-children",children:s.jsx("ul",{className:"tag-tree-list",children:e.children.map(r=>s.jsx(df,{node:r,onPick:t},r.tag.tag_uid))})})]})}function Mu({title:e,tagNodes:t,excludeUid:n,onPick:r,onCancel:l}){c.useEffect(()=>{function o(u){u.key==="Escape"&&(u.preventDefault(),u.stopPropagation(),l())}return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[l]);function i(o){return o.filter(u=>u.tag.tag_uid!==n).map(u=>({...u,children:i(u.children)}))}const a=n?i(t):t;return s.jsx("div",{className:"tag-picker-backdrop",onClick:o=>{o.target===o.currentTarget&&l()},children:s.jsxs("div",{className:"tag-picker-modal",role:"dialog","aria-modal":"true",children:[s.jsxs("div",{className:"tag-picker-header",children:[s.jsx("span",{className:"tag-picker-title",children:e}),s.jsx("button",{className:"tag-picker-close",onClick:l,title:"Cancel","aria-label":"Cancel",children:"×"})]}),s.jsxs("div",{className:"tag-picker-body",children:[s.jsx("button",{className:"tag-picker-root-btn",onClick:()=>r(null),title:"Place at root level (no parent)",children:"↑ Root tag (no parent)"}),a.length>0?s.jsx("ul",{className:"tag-tree-list tag-picker-tree",children:a.map(o=>s.jsx(df,{node:o,onPick:r},o.tag.tag_uid))}):s.jsx("p",{className:"tag-picker-empty",children:"No other tags available."})]})]})})}function ff({parentPath:e,archiveId:t,onDone:n,onCancel:r}){const[l,i]=c.useState(""),a=c.useRef(!1);async function o(){const u=l.trim();if(!u){r();return}const d=e?`${e}/${u}`:`/${u}`;try{await sm(t,d),n()}catch(y){alert(y.message||"Create failed"),r()}}return s.jsx("input",{className:"tag-rename-input",autoFocus:!0,placeholder:"tag name",value:l,onChange:u=>i(u.target.value),onKeyDown:u=>{u.key==="Enter"&&u.currentTarget.blur(),u.key==="Escape"&&(a.current=!0,u.currentTarget.blur())},onBlur:()=>{a.current?(a.current=!1,r()):o()}})}function pf({node:e,archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:d,onMoveSourceSelect:y,pendingCreateParentUid:g,onCreateDone:h,onCreateCancel:v}){var X;const x=n===e.tag.full_path,[S,N]=c.useState(!1),[p,f]=c.useState(""),m=c.useRef(!1);function k(){if(S)return;if(d){y(e);return}const H=x?null:e.tag.full_path;r(H),l("archive")}function C(H){H.stopPropagation(),!d&&(f(e.tag.slug),N(!0))}async function E(){const H=p.trim();if(!H||H===e.tag.slug){N(!1);return}try{const Y=await rm(t,e.tag.tag_uid,H);i(e.tag.full_path,Y.full_path),o()}catch{}finally{N(!1)}}async function T(H){var te;H.stopPropagation();const Y=((te=e.children)==null?void 0:te.length)>0?`Delete tag "${e.tag.full_path}" and all its child tags? This cannot be undone.`:`Delete tag "${e.tag.full_path}"? This cannot be undone.`;if(window.confirm(Y))try{await lm(t,e.tag.tag_uid),a(e.tag.full_path),o()}catch{}}const j={archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:d,onMoveSourceSelect:y,pendingCreateParentUid:g,onCreateDone:h,onCreateCancel:v},P=g===e.tag.tag_uid,R=((X=e.children)==null?void 0:X.length)>0;return s.jsxs("li",{children:[s.jsxs("div",{className:`tag-node-row${d?" tag-node-row--move-select":""}`,children:[S?s.jsx("input",{className:"tag-rename-input",autoFocus:!0,value:p,onChange:H=>f(H.target.value),onKeyDown:H=>{H.key==="Enter"&&H.currentTarget.blur(),H.key==="Escape"&&(m.current=!0,H.currentTarget.blur())},onBlur:()=>{m.current?(m.current=!1,N(!1)):E()}}):s.jsxs("button",{className:`tag-node-btn${x?" is-active":""}${d?" tag-node-btn--move-select":""}`,title:d?`Select "${e.tag.full_path}" to move`:e.tag.full_path,onClick:k,onDoubleClick:d?void 0:C,children:[s.jsx("span",{className:"tag-node-label",children:u?e.tag.name:e.tag.slug}),s.jsx("span",{className:"tag-node-count",children:e.children.length===0?`(${e.entry_count})`:`(${e.entry_count}) (${e.subtree_count} Total)`}),!d&&s.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",title:"Rename tag",onClick:H=>{H.stopPropagation(),C(H)},children:s.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),!S&&!d&&s.jsx("button",{className:"remove tag-node-delete",title:`Delete "${e.tag.full_path}"`,onClick:T,"aria-label":`Delete "${e.tag.full_path}"`,children:"×"})]}),(R||P)&&s.jsx("div",{className:"tag-children",children:s.jsxs("ul",{className:"tag-tree-list",children:[e.children.map(H=>s.jsx(pf,{node:H,...j},H.tag.tag_uid)),P&&s.jsx("li",{children:s.jsx(ff,{parentPath:e.tag.full_path,archiveId:t,onDone:h,onCancel:v})})]})})]})}function dg({archiveId:e,tagNodes:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u}){const[d,y]=c.useState(null),[g,h]=c.useState(null);function v(){y("select-source"),h(null)}function x(){y(null),h(null)}c.useEffect(()=>{if(d!=="select-source")return;function Y(te){te.key==="Escape"&&(te.preventDefault(),te.stopPropagation(),x())}return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[d]);function S(Y){h(Y),y("select-dest")}async function N(Y){const te=g.tag.full_path,fe=g.tag.tag_uid,Be=(Y==null?void 0:Y.tag_uid)??null;x();try{const we=await im(e,fe,Be);i(te,we.full_path),o()}catch(we){alert(we.message||"Move failed")}}const[p,f]=c.useState(null),[m,k]=c.useState(void 0);function C(){f("select-parent"),k(void 0)}function E(){f(null),k(void 0)}function T(Y){k(Y??null),f("input")}function j(){f(null),k(void 0),o()}const P=d==="select-source",R=p==="input"?m?m.tag_uid:"__root__":void 0,X={archiveId:e,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:P,onMoveSourceSelect:S,pendingCreateParentUid:R,onCreateDone:j,onCreateCancel:E},H=R==="__root__";return s.jsxs("section",{id:"tags-view",className:"view is-active",children:[s.jsxs("div",{className:"tag-tree",children:[s.jsx("div",{className:"tag-tree-header",children:P?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"tag-tree-title tag-tree-title--move",children:"Select a tag to move"}),s.jsx("button",{className:"tag-tree-action-btn tag-tree-action-btn--cancel",onClick:x,children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"tag-tree-title",children:"Tags"}),n&&s.jsxs("span",{className:"tag-tree-active",title:n,children:["Filtering: ",n]}),s.jsxs("div",{className:"tag-tree-actions",children:[s.jsx("button",{className:"tag-tree-action-btn",onClick:C,title:"Create a new tag",disabled:!!p||!!d,children:"+ New"}),s.jsx("button",{className:"tag-tree-action-btn",onClick:v,title:"Move a tag to a different parent",disabled:!!p||!!d||t.length===0,children:"Move"})]})]})}),t.length===0&&!H?s.jsx("p",{className:"muted",style:{padding:"8px 0"},children:"No tags yet."}):s.jsxs("ul",{className:"tag-tree-list",children:[t.map(Y=>s.jsx(pf,{node:Y,...X},Y.tag.tag_uid)),H&&s.jsx("li",{children:s.jsx(ff,{parentPath:null,archiveId:e,onDone:j,onCancel:E})})]})]}),p==="select-parent"&&s.jsx(Mu,{title:"Create tag under…",tagNodes:t,excludeUid:null,onPick:T,onCancel:E}),d==="select-dest"&&g&&s.jsx(Mu,{title:`Move "${g.tag.slug}" under…`,tagNodes:t,excludeUid:g.tag.tag_uid,onPick:N,onCancel:x})]})}const Ur=[{value:0,label:"Private"},{value:2,label:"Users only"},{value:3,label:"Public"}],fg=e=>{var t;return((t=Ur.find(n=>n.value===e))==null?void 0:t.label)??String(e)};function pg({archiveId:e}){const[t,n]=c.useState([]),[r,l]=c.useState(!1),[i,a]=c.useState(null),[o,u]=c.useState(null),[d,y]=c.useState(null),[g,h]=c.useState(!1),[v,x]=c.useState(null),[S,N]=c.useState(""),[p,f]=c.useState(""),[m,k]=c.useState(2),[C,E]=c.useState(!1),[T,j]=c.useState(!0),[P,R]=c.useState(null),[X,H]=c.useState(""),[Y,te]=c.useState(2),[fe,Be]=c.useState(!1),[we,M]=c.useState(null),[L,V]=c.useState(!1),[G,ne]=c.useState(""),se=c.useRef(null),Z=t.find(D=>D.collection_uid===o)??null,Se=(Z==null?void 0:Z.slug)==="_default_",ce=c.useCallback(async()=>{if(e){l(!0),a(null);try{const D=await wo(e);n(D)}catch(D){a(D.message)}finally{l(!1)}}},[e]),Ie=c.useCallback(async D=>{if(!D){y(null);return}h(!0),x(null);try{const K=await bm(e,D);y(K)}catch(K){x(K.message)}finally{h(!1)}},[e]);c.useEffect(()=>{ce()},[ce]),c.useEffect(()=>{Ie(o)},[o,Ie]),c.useEffect(()=>{L&&se.current&&se.current.focus()},[L]),c.useEffect(()=>{d!=null&&te(d.default_visibility_bits)},[d]);async function at(D){D.preventDefault();const K=S.trim(),Ne=p.trim();if(!(!K||!Ne)){E(!0),R(null);try{const Ve=await Em(e,K,Ne,m,T);N(""),f(""),k(2),j(!0),await ce(),u(Ve.collection_uid)}catch(Ve){R(Ve.message)}finally{E(!1)}}}async function ht(){const D=G.trim();if(!D||!Z){V(!1);return}try{await Ci(e,Z.collection_uid,{name:D}),await ce(),y(K=>K&&{...K,name:D})}catch(K){a(K.message)}finally{V(!1)}}async function Vt(D){if(Z)try{await Ci(e,Z.collection_uid,{default_visibility_bits:D}),await ce(),y(K=>K&&{...K,default_visibility_bits:D})}catch(K){a(K.message)}}async function Qt(D){if(Z)try{await Ci(e,Z.collection_uid,{requires_auth:D}),await ce(),y(K=>K&&{...K,requires_auth:D})}catch(K){a(K.message)}}async function jt(){if(Z&&window.confirm(`Delete collection "${Z.name}"? Entries will not be deleted.`))try{await Lm(e,Z.collection_uid),u(null),y(null),await ce()}catch(D){a(D.message)}}async function Oe(D){D.preventDefault();const K=X.trim();if(!(!K||!Z)){Be(!0),M(null);try{await Sa(e,Z.collection_uid,K,Y),H(""),await Ie(Z.collection_uid)}catch(Ne){M(Ne.message)}finally{Be(!1)}}}async function Je(D){if(Z)try{await Tm(e,Z.collection_uid,D),await Ie(Z.collection_uid)}catch(K){x(K.message)}}async function tt(D,K){if(Z)try{await Pm(e,Z.collection_uid,D,K),y(Ne=>Ne&&{...Ne,entries:Ne.entries.map(Ve=>Ve.entry_uid===D?{...Ve,collection_visibility_bits:K}:Ve)})}catch(Ne){x(Ne.message)}}return e?s.jsxs("div",{className:"collections-view",children:[s.jsx("h2",{className:"collections-heading",children:"Collections"}),r&&s.jsx("div",{className:"muted",children:"Loading…"}),i&&s.jsxs("div",{className:"collections-error",children:[i," ",s.jsx("button",{onClick:()=>a(null),className:"coll-dismiss",children:"×"})]}),s.jsxs("div",{className:"collections-layout",children:[s.jsxs("div",{className:"collections-sidebar",children:[t.map(D=>s.jsxs("button",{className:`coll-sidebar-row${o===D.collection_uid?" is-active":""}`,onClick:()=>u(D.collection_uid),children:[s.jsx("span",{className:"coll-row-name",children:D.name}),s.jsx("span",{className:"coll-row-meta",children:fg(D.default_visibility_bits)})]},D.collection_uid)),t.length===0&&!r&&s.jsx("div",{className:"muted",style:{padding:"8px 12px"},children:"No collections yet."})]}),Z?s.jsxs("div",{className:"coll-detail",children:[s.jsxs("div",{className:"coll-detail-header",children:[L?s.jsx("input",{ref:se,className:"coll-rename-input",value:G,onChange:D=>ne(D.target.value),onBlur:ht,onKeyDown:D=>{D.key==="Enter"&&ht(),D.key==="Escape"&&V(!1)}}):s.jsxs("h3",{className:`coll-detail-name${Se?"":" coll-detail-name--editable"}`,title:Se?void 0:"Click to rename",onClick:()=>{Se||(ne(Z.name),V(!0))},children:[(d==null?void 0:d.name)??Z.name,!Se&&s.jsx("span",{className:"coll-edit-hint",children:" ✎"})]}),!Se&&s.jsx("button",{className:"coll-delete-btn",onClick:jt,title:"Delete collection",children:"Delete"})]}),s.jsxs("div",{className:"coll-detail-vis",children:[s.jsx("span",{className:"coll-vis-label",children:"Entries' default visibility"}),s.jsx("select",{className:"coll-vis-select",value:(d==null?void 0:d.default_visibility_bits)??Z.default_visibility_bits,onChange:D=>Vt(Number(D.target.value)),children:Ur.map(D=>s.jsx("option",{value:D.value,children:D.label},D.value))})]}),s.jsxs("div",{className:"coll-detail-vis",children:[s.jsx("span",{className:"coll-vis-label",children:"Collection access"}),s.jsxs("label",{className:"coll-auth-label",children:[s.jsx("input",{type:"checkbox",checked:!!((d==null?void 0:d.requires_auth)??Z.requires_auth),onChange:D=>Qt(D.target.checked)})," Require authentication to view"]})]}),s.jsxs("div",{className:"coll-entries-section",children:[s.jsx("div",{className:"coll-section-heading",children:"Entries"}),g&&s.jsx("div",{className:"muted",children:"Loading…"}),v&&s.jsx("div",{className:"collections-error",children:v}),!g&&d&&(d.entries.length===0?s.jsx("div",{className:"muted",children:"No entries in this collection."}):s.jsx("ul",{className:"coll-entries-list",children:d.entries.map(D=>s.jsxs("li",{className:"coll-entry-row",children:[s.jsxs("div",{className:"coll-entry-info",children:[s.jsx("span",{className:"coll-entry-title",children:D.title||D.entry_uid}),s.jsx("span",{className:"coll-entry-kind muted",children:D.source_kind})]}),s.jsxs("div",{className:"coll-entry-actions",children:[s.jsx("select",{className:"coll-entry-vis-select",value:D.collection_visibility_bits,onChange:K=>tt(D.entry_uid,Number(K.target.value)),children:Ur.map(K=>s.jsx("option",{value:K.value,children:K.label},K.value))}),!Se&&s.jsx("button",{className:"coll-entry-remove",onClick:()=>Je(D.entry_uid),title:"Remove from collection",children:"×"})]})]},D.entry_uid))}))]}),!Se&&s.jsxs("form",{className:"coll-add-entry-form",onSubmit:Oe,children:[s.jsx("div",{className:"coll-section-heading",children:"Add entry"}),s.jsxs("div",{className:"coll-add-entry-row",children:[s.jsx("input",{className:"coll-add-entry-input",type:"text",value:X,onChange:D=>H(D.target.value),placeholder:"entry_uid",required:!0}),s.jsx("select",{className:"coll-vis-select",value:Y,onChange:D=>te(Number(D.target.value)),children:Ur.map(D=>s.jsx("option",{value:D.value,children:D.label},D.value))}),s.jsx("button",{className:"coll-add-btn",type:"submit",disabled:fe,children:fe?"…":"Add"})]}),we&&s.jsx("div",{className:"collections-error",style:{marginTop:4},children:we})]})]}):s.jsx("div",{className:"coll-detail coll-detail--empty",children:s.jsx("div",{className:"muted",children:"Select a collection to view details."})})]}),s.jsxs("details",{className:"coll-create-details",children:[s.jsx("summary",{children:"+ Create collection"}),s.jsxs("form",{className:"coll-create-form",onSubmit:at,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-name",children:"Name"}),s.jsx("input",{className:"capture-input",id:"coll-name",type:"text",value:S,onChange:D=>{N(D.target.value),p||f(D.target.value.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""))},placeholder:"My Collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-slug",children:"Slug"}),s.jsx("input",{className:"capture-input",id:"coll-slug",type:"text",value:p,onChange:D=>f(D.target.value),placeholder:"my-collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-vis",children:"Entries' default visibility"}),s.jsx("select",{className:"capture-input",id:"coll-vis",style:{height:42},value:m,onChange:D=>k(Number(D.target.value)),children:Ur.map(D=>s.jsx("option",{value:D.value,children:D.label},D.value))})]}),s.jsx("div",{className:"form-field",children:s.jsxs("label",{className:"form-label",children:[s.jsx("input",{type:"checkbox",checked:T,onChange:D=>j(D.target.checked)})," Require authentication to view"]})}),P&&s.jsx("div",{className:"collections-error",children:P}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:C,children:C?"Creating…":"Create collection"})]})]})]}):s.jsx("div",{className:"view-placeholder",children:"Select an archive."})}const hg=4;function mg({tab:e,onTabChange:t,archiveId:n}){const{currentUser:r,setCurrentUser:l}=c.useContext(Vs)??{},i=r&&(r.role_bits&hg)!==0,a=["profile","tokens",...i?["instance","cookies","extensions","storage"]:[]],o={profile:"Profile",tokens:"API Tokens",instance:"Instance",cookies:"Cookies",extensions:"Extensions",storage:"Storage"};return s.jsxs("section",{className:"admin-view",children:[s.jsx("h1",{children:"Settings"}),s.jsx("div",{className:"view-tabs",children:a.map(u=>s.jsx("button",{className:`view-tab${e===u?" is-active":""}`,onClick:()=>t(u),children:o[u]},u))}),e==="profile"&&s.jsx(gg,{currentUser:r,setCurrentUser:l}),e==="tokens"&&s.jsx(yg,{}),e==="instance"&&i&&s.jsx(vg,{}),e==="cookies"&&i&&s.jsx(wg,{}),e==="extensions"&&i&&s.jsx(kg,{}),e==="storage"&&i&&s.jsx(xg,{archiveId:n})]})}function gg({currentUser:e,setCurrentUser:t}){const[n,r]=c.useState((e==null?void 0:e.display_name)??""),[l,i]=c.useState(!1),[a,o]=c.useState(null),[u,d]=c.useState(""),[y,g]=c.useState(""),[h,v]=c.useState(""),[x,S]=c.useState(!1),[N,p]=c.useState(null);async function f(k){k.preventDefault(),i(!0),o(null);try{await gm(n),t(C=>({...C,display_name:n||null})),o({ok:!0,text:"Saved."})}catch(C){o({ok:!1,text:C.message})}finally{i(!1)}}async function m(k){if(k.preventDefault(),y!==h){p({ok:!1,text:"Passwords do not match."});return}S(!0),p(null);try{await vm(u,y),d(""),g(""),v(""),p({ok:!0,text:"Password changed."})}catch(C){p({ok:!1,text:C.message})}finally{S(!1)}}return s.jsxs("div",{style:{maxWidth:440},children:[s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Display Name"}),s.jsxs("form",{onSubmit:f,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"display-name",children:"Name shown in the UI"}),s.jsx("input",{className:"field-input",id:"display-name",placeholder:(e==null?void 0:e.username)??"",value:n,onChange:k=>r(k.target.value)})]}),a&&s.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:l,children:l?"Saving…":"Save"})]})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Display Preferences"}),s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:(e==null?void 0:e.humanize_slugs)??!1,onChange:async k=>{const C=k.target.checked;try{await ym({humanize_slugs:C}),t(E=>({...E,humanize_slugs:C}))}catch{}}}),s.jsx("span",{className:"form-label",style:{margin:0},children:"Humanize tag display"})]}),s.jsx("p",{className:"muted",style:{fontSize:13,margin:"4px 0 0"},children:'When on, tag paths show as "X / Articles" instead of "x/articles".'})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Change Password"}),s.jsxs("form",{onSubmit:m,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"cur-pw",children:"Current password"}),s.jsx("input",{className:"field-input",id:"cur-pw",type:"password",value:u,onChange:k=>d(k.target.value),required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"new-pw",children:"New password"}),s.jsx("input",{className:"field-input",id:"new-pw",type:"password",value:y,onChange:k=>g(k.target.value),required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"confirm-pw",children:"Confirm new password"}),s.jsx("input",{className:"field-input",id:"confirm-pw",type:"password",value:h,onChange:k=>v(k.target.value),required:!0})]}),N&&s.jsx("div",{className:`form-msg form-msg--${N.ok?"ok":"err"}`,children:N.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:x,children:x?"Changing…":"Change Password"})]})]})]})}function yg(){const[e,t]=c.useState([]),[n,r]=c.useState(!0),[l,i]=c.useState(null),[a,o]=c.useState(""),[u,d]=c.useState(!1),[y,g]=c.useState(null),h=c.useCallback(async()=>{r(!0),i(null);try{t(await xm())}catch(S){i(S.message)}finally{r(!1)}},[]);c.useEffect(()=>{h()},[h]);async function v(S){if(S.preventDefault(),!!a.trim()){d(!0);try{const N=await wm(a.trim());g(N),o(""),h()}catch(N){i(N.message)}finally{d(!1)}}}async function x(S){try{await km(S),t(N=>N.filter(p=>p.token_uid!==S))}catch(N){i(N.message)}}return s.jsx("div",{style:{maxWidth:600},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"API Tokens"}),y&&s.jsxs("div",{className:"token-banner",children:[s.jsx("strong",{children:"Token created."})," Copy it now — it won't be shown again.",s.jsx("code",{children:y.raw_token}),s.jsx("button",{className:"token-dismiss",onClick:()=>g(null),children:"Dismiss"})]}),s.jsxs("form",{className:"token-create-row",onSubmit:v,children:[s.jsx("input",{className:"field-input field-input--flex",placeholder:"Token name",value:a,onChange:S=>o(S.target.value),required:!0}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:u,children:u?"Creating…":"Create token"})]}),l&&s.jsx("div",{className:"form-msg form-msg--err",children:l}),n?s.jsx("div",{className:"muted",children:"Loading…"}):s.jsxs("div",{children:[e.length===0&&s.jsx("div",{className:"muted",children:"No tokens yet."}),e.map(S=>s.jsxs("div",{className:"token-row",children:[s.jsxs("div",{className:"token-row-info",children:[s.jsx("strong",{children:S.name}),s.jsxs("div",{className:"muted",children:["Created ",S.created_at.slice(0,10),S.last_used_at&&` · Last used ${S.last_used_at.slice(0,10)}`]})]}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"4px 10px"},onClick:()=>x(S.token_uid),children:"Revoke"})]},S.token_uid))]})]})})}function vg(){const[e,t]=c.useState(null),[n,r]=c.useState(!0),[l,i]=c.useState(null),[a,o]=c.useState(!1),[u,d]=c.useState(null);c.useEffect(()=>{(async()=>{try{t(await xo())}catch(g){i(g.message)}finally{r(!1)}})()},[]);async function y(g){g.preventDefault(),o(!0),d(null);try{await ts(e),d({ok:!0,text:"Saved."})}catch(h){d({ok:!1,text:h.message})}finally{o(!1)}}return n?s.jsx("div",{className:"muted",children:"Loading…"}):l?s.jsx("div",{className:"form-msg form-msg--err",children:l}):e?s.jsx("div",{style:{maxWidth:440},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Instance Settings"}),s.jsxs("form",{onSubmit:y,children:[[["public_index_enabled","Public index (unauthenticated browsing)"],["public_entry_content_enabled","Public entry content"],["open_registration_enabled","Open registration"]].map(([g,h])=>s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:!!e[g],onChange:v=>t(x=>({...x,[g]:v.target.checked}))}),h]},g)),s.jsxs("div",{className:"form-field",style:{marginTop:4},children:[s.jsx("label",{className:"form-label",children:"Default entry visibility"}),s.jsxs("select",{className:"field-input",value:e.default_entry_visibility,onChange:g=>t(h=>({...h,default_entry_visibility:Number(g.target.value)})),children:[s.jsx("option",{value:0,children:"Private"}),s.jsx("option",{value:2,children:"Unlisted"}),s.jsx("option",{value:3,children:"Public"})]})]}),u&&s.jsx("div",{className:`form-msg form-msg--${u.ok?"ok":"err"}`,children:u.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:a,children:a?"Saving…":"Save Settings"})]})]})}):null}function bi(e){if(e===0)return"0 B";const t=["B","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(1024));return`${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`}function xg({archiveId:e}){const[t,n]=c.useState("idle"),[r,l]=c.useState(null),[i,a]=c.useState(null),[o,u]=c.useState(null);function d(){n("idle"),l(null),a(null),u(null)}async function y(){n("scanning"),u(null),l(null);try{const v=await Rm(e);l(v),n("scanned")}catch(v){u(v.message),n("error")}}async function g(){n("deleting"),u(null);try{const v=await zm(e);a(v),n("done")}catch(v){u(v.message),n("error")}}const h=r&&r.deletable_files===0&&r.orphaned_blob_rows===0;return s.jsx("div",{style:{maxWidth:440},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Orphan Cleanup"}),s.jsxs("p",{className:"muted",style:{marginBottom:16},children:["Scan for blob files and database records that are no longer referenced by any archive entry and safely delete them."," ",s.jsx("strong",{children:"Cleanup is blocked while captures are running."})]}),!e&&s.jsx("div",{className:"muted",children:"No archive selected."}),e&&t==="idle"&&s.jsx("button",{className:"btn-ghost",onClick:y,children:"Scan for orphaned blobs"}),t==="scanning"&&s.jsx("div",{className:"muted",children:"Scanning…"}),t==="scanned"&&r&&h&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"form-msg form-msg--ok",children:"Archive is clean — nothing to remove."}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:d,children:"Done"})]}),t==="scanned"&&r&&!h&&s.jsxs("div",{children:[s.jsxs("div",{style:{marginBottom:14,lineHeight:1.6},children:["Found ",s.jsx("strong",{children:r.deletable_files})," unreferenced file",r.deletable_files!==1?"s":""," ","and ",s.jsx("strong",{children:r.orphaned_blob_rows})," orphaned DB record",r.orphaned_blob_rows!==1?"s":""," ","— ",s.jsx("strong",{children:bi(r.total_bytes)})," recoverable."]}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsxs("button",{className:"btn-danger",onClick:g,children:["Delete (",bi(r.total_bytes),")"]}),s.jsx("button",{className:"btn-ghost",onClick:d,children:"Cancel"})]})]}),t==="deleting"&&s.jsx("div",{className:"muted",children:"Deleting…"}),t==="done"&&i&&s.jsxs("div",{children:[s.jsxs("div",{className:"form-msg form-msg--ok",children:["Freed ",s.jsx("strong",{children:bi(i.freed_bytes)})," ","— removed ",i.deleted_files," file",i.deleted_files!==1?"s":""," ","and ",i.deleted_blob_rows," DB record",i.deleted_blob_rows!==1?"s":"","."]}),i.errors&&i.errors.length>0&&s.jsxs("div",{className:"form-msg form-msg--err",style:{marginTop:6},children:[i.errors.length," file",i.errors.length!==1?"s":""," could not be deleted."]}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:d,children:"Scan again"})]}),t==="error"&&s.jsxs("div",{children:[s.jsx("div",{className:"form-msg form-msg--err",children:o}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:d,children:"Try again"})]})]})})}function wg(){const[e,t]=c.useState(null),[n,r]=c.useState(!0),[l,i]=c.useState(null),[a,o]=c.useState("global"),[u,d]=c.useState(""),[y,g]=c.useState("{}"),[h,v]=c.useState(null),[x,S]=c.useState(!1),[N,p]=c.useState({});c.useEffect(()=>{f()},[]);async function f(){r(!0),i(null);try{t(await Dm())}catch(j){i(j.message)}finally{r(!1)}}async function m(j){j.preventDefault();try{JSON.parse(y)}catch{v({ok:!1,text:'cookies must be valid JSON, e.g. {"session": "abc"}'});return}S(!0),v(null);try{await Om(a==="global"?null:u.trim(),a,y),d(""),g("{}"),o("global"),v({ok:!0,text:"Rule added."}),await f()}catch(P){v({ok:!1,text:P.message})}finally{S(!1)}}async function k(j){try{await Mm(j),await f()}catch(P){i(P.message)}}function C(j){p(P=>({...P,[j.rule_uid]:{cookiesInput:j.cookies_json,saving:!1,msg:null}}))}function E(j){p(P=>{const R={...P};return delete R[j],R})}async function T(j){const P=N[j.rule_uid];try{JSON.parse(P.cookiesInput)}catch{p(R=>({...R,[j.rule_uid]:{...R[j.rule_uid],msg:{ok:!1,text:"Invalid JSON"}}}));return}p(R=>({...R,[j.rule_uid]:{...R[j.rule_uid],saving:!0,msg:null}}));try{await Am(j.rule_uid,{cookies_json:P.cookiesInput}),E(j.rule_uid),await f()}catch(R){p(X=>({...X,[j.rule_uid]:{...X[j.rule_uid],saving:!1,msg:{ok:!1,text:R.message}}}))}}return n?s.jsx("div",{className:"muted",children:"Loading…"}):l?s.jsx("div",{className:"form-msg form-msg--err",children:l}):s.jsx("div",{style:{maxWidth:560},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Cookie Rules"}),s.jsx("p",{className:"muted",style:{marginBottom:12},children:"Cookies are injected into every capture network request (yt-dlp, HTTP downloads, web-page snapshots). Global rules apply to all URLs; wildcard and regex rules apply only to matching URLs."}),e&&e.length>0?s.jsxs("table",{className:"data-table",style:{width:"100%",marginBottom:16},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Pattern"}),s.jsx("th",{children:"Cookies"}),s.jsx("th",{style:{width:100},children:"Actions"})]})}),s.jsx("tbody",{children:e.map(j=>{const P=N[j.rule_uid],R=j.url_pattern?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"muted",children:[j.pattern_kind,":"]})," ",s.jsx("code",{children:j.url_pattern})]}):s.jsx("span",{className:"muted",children:"global (all URLs)"});return s.jsxs("tr",{children:[s.jsx("td",{children:R}),s.jsx("td",{children:P?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:12,width:"100%",minHeight:60},value:P.cookiesInput,onChange:X=>p(H=>({...H,[j.rule_uid]:{...H[j.rule_uid],cookiesInput:X.target.value}}))}),P.msg&&s.jsx("div",{className:`form-msg form-msg--${P.msg.ok?"ok":"err"}`,children:P.msg.text}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[s.jsx("button",{className:"btn-primary",style:{fontSize:12,padding:"2px 8px"},disabled:P.saving,onClick:()=>T(j),children:P.saving?"Saving…":"Save"}),s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>E(j.rule_uid),children:"Cancel"})]})]}):s.jsx("code",{style:{fontSize:12,wordBreak:"break-all"},children:j.cookies_json})}),s.jsx("td",{children:!P&&s.jsxs("div",{style:{display:"flex",gap:6},children:[s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>C(j),children:"Edit"}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"2px 8px"},onClick:()=>k(j.rule_uid),children:"Del"})]})})]},j.rule_uid)})})]}):s.jsx("p",{className:"muted",style:{marginBottom:16},children:"No cookie rules defined."}),s.jsx("h3",{style:{marginBottom:8},children:"Add Rule"}),s.jsxs("form",{onSubmit:m,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:"Pattern type"}),s.jsxs("select",{className:"field-input",value:a,onChange:j=>o(j.target.value),children:[s.jsx("option",{value:"global",children:"Global (all URLs)"}),s.jsx("option",{value:"wildcard",children:"Wildcard (e.g. *.youtube.com)"}),s.jsx("option",{value:"regex",children:"Regex (matched against full URL)"})]})]}),a!=="global"&&s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:a==="wildcard"?"URL/hostname pattern":"Regex pattern"}),s.jsx("input",{className:"field-input",type:"text",value:u,onChange:j=>d(j.target.value),placeholder:a==="wildcard"?"*.youtube.com or https://example.com/*":".*\\.youtube\\.com.*",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:"Cookies (JSON object)"}),s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:13,minHeight:70},value:y,onChange:j=>g(j.target.value),placeholder:'{"SESSION": "abc123", "token": "xyz"}',required:!0})]}),h&&s.jsx("div",{className:`form-msg form-msg--${h.ok?"ok":"err"}`,children:h.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:x,children:x?"Adding…":"Add Rule"})]})]})})}function kg(){const[e,t]=c.useState(null),[n,r]=c.useState(!0),[l,i]=c.useState(!1),[a,o]=c.useState(null);c.useEffect(()=>{(async()=>{try{t(await xo())}catch(N){o({ok:!1,text:N.message})}finally{r(!1)}})()},[]);async function u(N){i(!0),o(null);try{await ts({ublock_enabled:N}),t(p=>({...p,ublock_enabled:N})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function d(N){i(!0),o(null);try{await ts({cookie_ext_enabled:N}),t(p=>({...p,cookie_ext_enabled:N})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function y(N){i(!0),o(null);try{await ts({modal_closer_enabled:N}),t(p=>({...p,modal_closer_enabled:N})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}if(n)return s.jsx("div",{className:"muted",children:"Loading\\u2026"});const g=(e==null?void 0:e.ublock_ext_available)??!1,h=(e==null?void 0:e.ublock_enabled)??!0,v=(e==null?void 0:e.cookie_ext_available)??!1,x=(e==null?void 0:e.cookie_ext_enabled)??!0,S=(e==null?void 0:e.modal_closer_enabled)??!0;return s.jsx("div",{children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Extensions"}),s.jsx("p",{className:"form-hint",style:{marginBottom:20},children:"Extensions run inside the browser during WebPage captures and can block ads, accept cookie banners, and more. Changes take effect on the next capture."}),s.jsxs("div",{className:"ext-grid",children:[s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"uBlock Origin Lite"}),s.jsx("span",{className:"ext-card-desc",children:"Blocks ads, trackers, and other page clutter during archiving via Chrome’s declarativeNetRequest API (Manifest V3)."}),!g&&s.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_UBLOCK_EXT"})," to the unpacked extension directory to enable."]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":h,className:`ext-toggle${h?" ext-toggle--on":""}`,onClick:()=>u(!h),disabled:l,"aria-label":"Toggle uBlock Origin Lite",children:s.jsx("span",{className:"ext-toggle-knob"})})]})}),s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"I Still Don’t Care About Cookies"}),s.jsx("span",{className:"ext-card-desc",children:"Dismiss cookie consent banners during archiving."}),!v&&s.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})," to the unpacked extension directory to enable."]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":x,className:`ext-toggle${x?" ext-toggle--on":""}`,onClick:()=>d(!x),disabled:l,"aria-label":"Toggle I Still Don't Care About Cookies",children:s.jsx("span",{className:"ext-toggle-knob"})})]})}),s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"Modal & Dialog Closer"}),s.jsx("span",{className:"ext-card-desc",children:"Auto-dismiss cookie banners, consent overlays, and other modal dialogs before a WebPage capture is taken. Implemented as an injected browser script; no external extension required."})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":S,className:`ext-toggle${S?" ext-toggle--on":""}`,onClick:()=>y(!S),disabled:l,"aria-label":"Toggle Modal and Dialog Closer",children:s.jsx("span",{className:"ext-toggle-knob"})})]})})]}),a&&s.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text})]})})}const Fu={0:"Private",1:"Public",2:"Users only",3:"Public"},ns=[{value:"anthropic_http",label:"Anthropic API"},{value:"openai_compatible",label:"OpenAI-compatible API"},{value:"claude_cli",label:"Claude CLI"},{value:"codex_cli",label:"Codex CLI"}],jg=Object.fromEntries(ns.map(e=>[e.value,e.label])),Bu="archivr:summary:provider",Sg=1500,hf="This entry can’t be summarized yet.",mf="It doesn’t contain archived text that a summary provider can read. Summaries currently support text notes, web pages, X posts and threads, and X Articles. Video, audio, and image-only entries need a transcript or text source.",Uu=`${hf} + +${mf}`;function Ng(e){if(!e)return null;try{const t=JSON.parse(e);if(t&&typeof t=="object")return{tldr:typeof t.tldr=="string"?t.tldr:"",summary:typeof t.summary=="string"?t.summary:"",tags:Array.isArray(t.tags)?t.tags.filter(n=>typeof n=="string"):[]}}catch{}return{tldr:"",summary:e,tags:[]}}const _g=()=>s.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M7 17 17 7M9 7h8v8"})});function Cg({archiveId:e,selectedEntry:t,selectedUids:n,selectedEntries:r,detail:l,onTagFilterSet:i,tagNodes:a,onTagsRefresh:o,onEntryTitleChange:u,onEntryDeleted:d,onBulkDeleted:y,humanizeTags:g,onDetailRefresh:h,onOpenPreview:v,onPlay:x,isPublicSession:S}){var qn,Cr,Er;const[N,p]=c.useState([]),[f,m]=c.useState(""),[k,C]=c.useState([]),[E,T]=c.useState(""),j=c.useRef(0),P=c.useRef(!1),[R,X]=c.useState(!1),[H,Y]=c.useState(""),[te,fe]=c.useState("idle"),[Be,we]=c.useState(""),M=c.useRef(null),[L,V]=c.useState(!1);c.useEffect(()=>{V(!1)},[(qn=l==null?void 0:l.summary)==null?void 0:qn.entry_uid]);const[G,ne]=c.useState(null),[se,Z]=c.useState(null),[Se,ce]=c.useState(""),[Ie,at]=c.useState(!1),[ht,Vt]=c.useState(()=>{try{return sessionStorage.getItem(Bu)||ns[0].value}catch{return ns[0].value}}),[Qt,jt]=c.useState(!1),Oe=c.useRef(null),Je=c.useRef(null),tt=c.useRef(null),D=c.useRef(null),K=e&&(t!=null&&t.entry_uid)?`${e}:${t.entry_uid}`:null;D.current=K;const Ne=(n==null?void 0:n.size)>=2,[Ve,qt]=c.useState(""),[Qe,Kt]=c.useState("idle"),[Qn,Ot]=c.useState(""),[Le,bn]=c.useState([]),[At,w]=c.useState(""),[B,O]=c.useState("idle"),[$,F]=c.useState(""),[U,ye]=c.useState("idle"),[ue,Te]=c.useState(""),[pe,$e]=c.useState("idle"),[ie,nt]=c.useState("");c.useEffect(()=>{const b=++j.current;if(M.current&&(clearInterval(M.current),M.current=null),fe("idle"),we(""),!t||!e){p([]),C([]);return}if(S){p([]),C([]);return}X(!1),Y(""),P.current=!1,p([]),Promise.all([Bl(e,t.entry_uid),Du(e,t.entry_uid)]).then(([q,ae])=>{b===j.current&&(p(q),C(ae))}).catch(()=>{})},[t,e,S]),c.useEffect(()=>()=>{clearInterval(M.current)},[]),c.useLayoutEffect(()=>{var q,ae,he;clearInterval(Oe.current),Oe.current=null,(q=Je.current)==null||q.abort(),Je.current=null,(ae=tt.current)==null||ae.abort(),tt.current=null;const b=((he=l==null?void 0:l.summary)==null?void 0:he.entry_uid)===(t==null?void 0:t.entry_uid);ne(b?l.latest_summary??null:null),Z(b?l.summary_attempt??null:null),ce(""),at(!1),jt(!1)},[e,t==null?void 0:t.entry_uid,(Cr=l==null?void 0:l.summary)==null?void 0:Cr.entry_uid]);const ot=se==null?void 0:se.status;c.useEffect(()=>{var sn;if(clearInterval(Oe.current),Oe.current=null,ot!=="pending"&&ot!=="running"||!e||!((sn=l==null?void 0:l.summary)!=null&&sn.entry_uid))return;const b=l.summary.entry_uid,q=`${e}:${b}`;if(K!==q)return;const ae=new AbortController;Je.current=ae;const St=setInterval(async()=>{var me;try{const an=await Xh(e,b,{signal:ae.signal});if(ae.signal.aborted||D.current!==q)return;ne(an.summary??null),Z(an.attempt??null);const Ys=(me=an.attempt)==null?void 0:me.status;Ys!=="pending"&&Ys!=="running"&&(clearInterval(St),Oe.current===St&&(Oe.current=null),at(!1),Ys==="completed"&&D.current===q&&(h==null||h()))}catch{if(ae.signal.aborted||D.current!==q)return}},Sg);return Oe.current=St,()=>{clearInterval(St),Oe.current===St&&(Oe.current=null),ae.abort(),Je.current===ae&&(Je.current=null)}},[ot,e,t==null?void 0:t.entry_uid,(Er=l==null?void 0:l.summary)==null?void 0:Er.entry_uid,K]),c.useEffect(()=>()=>{var b,q;clearInterval(Oe.current),(b=Je.current)==null||b.abort(),(q=tt.current)==null||q.abort()},[]);async function Qs(b=!1){var St,sn;if(!e||!((St=l==null?void 0:l.summary)!=null&&St.entry_uid)||Ie)return;const q=l.summary.entry_uid,ae=`${e}:${q}`;if(D.current!==ae)return;const he=new AbortController;(sn=tt.current)==null||sn.abort(),tt.current=he,at(!0),ce("");try{const me=await Jh(e,q,{provider:ht,force:b,includeImages:Qt,signal:he.signal});if(he.signal.aborted||D.current!==ae)return;me.status==="completed"?(ne(me),Z(null),at(!1),D.current===ae&&(h==null||h())):Z({...me??{},status:"pending"})}catch(me){if(he.signal.aborted||D.current!==ae)return;ce(me.message||"Summary request failed"),at(!1)}finally{tt.current===he&&(tt.current=null)}}function qs(b){Vt(b),b==="claude_cli"&&jt(!1);try{sessionStorage.setItem(Bu,b)}catch{}}c.useEffect(()=>{if(!e){bn([]);return}wo(e).then(bn).catch(()=>bn([]))},[e]),c.useEffect(()=>{qt(""),Kt("idle"),Ot(""),w(""),O("idle"),F(""),ye("idle"),Te(""),$e("idle"),nt("")},[n]);async function Ks(){const b=n.size;if(!window.confirm(`Delete ${b} entr${b===1?"y":"ies"}? This cannot be undone.`))return;ye("running");const q=new Set;for(const ae of n)try{await $u(e,ae),q.add(ae)}catch{}ye("idle"),y==null||y(q)}async function Tn(){const b=Ve.trim();if(b){Kt("running"),Ot("");try{for(const q of n)await Iu(e,q,b);qt(""),Kt("done"),o==null||o(),setTimeout(()=>Kt("idle"),1800)}catch(q){Ot(q.message),Kt("error")}}}async function _r(){if(!At)return;O("running"),F("");const b=[],q=Le.find(ae=>ae.collection_uid===At);for(const ae of n)try{await Sa(e,At,ae,(q==null?void 0:q.default_visibility_bits)??2)}catch{b.push(ae)}b.length>0?(F(`Failed for ${b.length} entr${b.length===1?"y":"ies"}.`),O("error")):(O("done"),setTimeout(()=>O("idle"),1800))}async function Pn(){if(!ue||!t)return;$e("running"),nt("");const b=Le.find(q=>q.collection_uid===ue);try{await Sa(e,ue,t.entry_uid,(b==null?void 0:b.default_visibility_bits)??2),$e("done"),Te("");const q=await Du(e,t.entry_uid);C(q),setTimeout(()=>$e("idle"),1800)}catch(q){nt(q.message),$e("error")}}async function jl(){const b=H.trim()||null;try{await tm(e,t.entry_uid,b),u==null||u(t.entry_uid,b)}catch{}finally{X(!1)}}async function Sl(){const b=f.trim();if(!(!b||!t))try{await Iu(e,t.entry_uid,b),m(""),T("");const q=await Bl(e,t.entry_uid);p(q),o()}catch(q){T(q.message)}}async function Xs(b){try{await nm(e,t.entry_uid,b);const q=await Bl(e,t.entry_uid);p(q),o()}catch{}}async function Js(){if(!(!t||!e)&&window.confirm("Delete this entry? This cannot be undone."))try{await $u(e,t.entry_uid),d==null||d(t.entry_uid)}catch{}}async function Gs(){if(!t||!e||te==="running")return;const b=j.current,q=t.entry_uid;fe("running"),we("");try{const{job_uid:ae}=await Im(e,q);if(j.current!==b)return;M.current=setInterval(async()=>{try{const he=await of(e,ae);if(he.status==="completed"){if(clearInterval(M.current),M.current=null,j.current!==b)return;fe("done");const St=await Bl(e,q);if(j.current!==b)return;p(St),h==null||h()}else if(he.status==="failed"){if(clearInterval(M.current),M.current=null,j.current!==b)return;fe("error"),we(he.error_text||"Re-archive failed.")}}catch{if(clearInterval(M.current),M.current=null,j.current!==b)return;fe("error"),we("Network error while polling.")}},500)}catch(ae){if(j.current!==b)return;fe("error"),we(ae.message||"Failed to start re-archive.")}}const _=l?[["Added",ko(l.summary.archived_at)],["Source",l.summary.source_kind],["Type",l.summary.entity_kind],["Visibility",Fu[l.summary.visibility]??l.summary.visibility],["Root",l.structured_root_relpath]]:[],z=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),A=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv","pdf","html","htm","md","markdown","txt","jpg","jpeg","png","gif","webp","avif","svg","bmp"]),Q=l?l.artifacts.findIndex(b=>b.artifact_role==="primary_media"):-1,J=Q>=0?l.artifacts[Q]:null,le=J?J.relpath.split(".").pop().toLowerCase():"",_e=J&&z.has(le),Ue=Q>=0&&t?`/api/archives/${e}/entries/${t.entry_uid}/artifacts/${Q}`:null,ke=l&&!_e&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread"||J&&A.has(le));return s.jsxs("aside",{className:"context-rail",children:[s.jsx("div",{className:"rail-eyebrow",children:"Context"}),Ne?S?s.jsxs("p",{className:"bulk-count",children:[s.jsx("span",{className:"bulk-count-num",children:n.size})," entries selected"]}):s.jsxs("div",{className:"bulk-panel",children:[s.jsxs("p",{className:"bulk-count",children:[s.jsx("span",{className:"bulk-count-num",children:n.size})," entries selected"]}),s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Assign tag"}),Qn&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:Qn}),s.jsxs("div",{className:"tag-input-wrap",children:[s.jsx("span",{className:"hash",children:"/"}),s.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:Ve,onChange:b=>qt(b.target.value),onKeyDown:b=>{b.key==="Enter"&&Tn()}}),s.jsx("button",{className:"tag-add-btn",onClick:Tn,disabled:Qe==="running"||!Ve.trim(),children:Qe==="running"?"…":Qe==="done"?"✓":"Add"})]})]}),Le.length>0&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Add to collection"}),s.jsxs("div",{className:"bulk-coll-row",children:[s.jsxs("select",{className:"bulk-coll-select",value:At,onChange:b=>w(b.target.value),children:[s.jsx("option",{value:"",children:"Pick a collection…"}),Le.filter(b=>b.slug!=="_default_").map(b=>s.jsx("option",{value:b.collection_uid,children:b.name},b.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:_r,disabled:!At||B==="running",children:B==="running"?"…":B==="done"?"✓":B==="error"?"!":"Add"})]}),$&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"6px 0 0"},children:$})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:Ks,disabled:U==="running",children:U==="running"?"Deleting…":`Delete ${n.size} entr${n.size===1?"y":"ies"}`})})]}):t?l?s.jsxs(s.Fragment,{children:[S?s.jsx("h2",{className:"rail-title",children:gt(l.summary.title)||gt(l.summary.entry_uid)}):R?s.jsx("input",{className:"rail-title-input",autoFocus:!0,value:H,onChange:b=>Y(b.target.value),onKeyDown:b=>{b.key==="Enter"&&b.currentTarget.blur(),b.key==="Escape"&&(P.current=!0,b.currentTarget.blur())},onBlur:()=>{P.current?X(!1):jl(),P.current=!1}}):s.jsxs("h2",{className:"rail-title rail-title--editable",title:"Click to rename",onClick:()=>{Y(l.summary.title??""),X(!0)},children:[gt(l.summary.title)||gt(l.summary.entry_uid),s.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),l.summary.original_url&&s.jsxs("a",{className:"url-tile",href:l.summary.original_url,target:"_blank",rel:"noopener noreferrer",children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:Ws(l.summary.source_kind)}}),s.jsx("span",{className:"u-text",children:l.summary.original_url}),s.jsx("span",{className:"ext",children:s.jsx(_g,{})})]}),_e&&x&&s.jsx("button",{className:"rail-preview-btn",onClick:()=>x(Ue,t),children:"▶ Play"}),ke&&v&&s.jsx("button",{className:"rail-preview-btn",onClick:v,children:"Preview"}),(()=>{const b=(G==null?void 0:G.status)==="completed"?Ng(G.summary_text):null,q=(se==null?void 0:se.status)==="pending"||(se==null?void 0:se.status)==="running",ae=(se==null?void 0:se.status)==="failed"&&se.error_text===Uu||Se===Uu;return S&&!b?null:s.jsxs("div",{className:"rail-section rail-summary",children:[s.jsx("div",{className:"rail-section-heading",children:"Summary"}),b&&s.jsxs("div",{className:"rail-summary-body",children:[b.tldr&&s.jsx("p",{className:"rail-summary-tldr",children:b.tldr}),b.summary&&s.jsx("p",{className:"rail-summary-text",children:b.summary}),b.tags.length>0&&s.jsx("div",{className:"rail-summary-tags",children:b.tags.map(he=>s.jsx("span",{className:"rail-summary-tag",children:he},he))}),s.jsxs("p",{className:"rail-summary-provider",children:[jg[G.provider_kind]||G.provider_kind,G.resolved_model||G.provider_model?` · ${G.resolved_model||G.provider_model}`:""]})]}),q&&s.jsxs("p",{className:"rail-summary-status",children:[s.jsx("span",{className:"rail-summary-spinner","aria-hidden":"true"}),"Generating…"]}),ae&&!S&&s.jsxs("div",{className:"rail-summary-info",role:"status",children:[s.jsx("p",{className:"rail-summary-info__heading",children:hf}),s.jsx("p",{className:"rail-summary-info__detail",children:mf})]}),(se==null?void 0:se.status)==="failed"&&se.error_text&&!ae&&!S&&s.jsx("p",{className:"form-msg form-msg--err rail-summary-error",children:se.error_text}),Se&&!ae&&s.jsx("p",{className:"form-msg form-msg--err rail-summary-error",children:Se}),!S&&!q&&s.jsxs("div",{className:"rail-summary-controls",children:[s.jsx("select",{className:"rail-summary-select",value:ht,onChange:he=>qs(he.target.value),"aria-label":"Summary provider",children:ns.map(he=>s.jsx("option",{value:he.value,children:he.label},he.value))}),s.jsxs("div",{className:`rail-summary-image-option${ht==="claude_cli"?" rail-summary-image-option--disabled":""}`,children:[s.jsxs("label",{className:"rail-summary-image-option__label",children:[s.jsx("input",{type:"checkbox",checked:Qt,disabled:ht==="claude_cli",onChange:he=>jt(he.target.checked)}),"Include attached images"]}),s.jsx("p",{className:"rail-summary-image-option__note",children:ht==="claude_cli"?"Claude CLI cannot attach local images. Choose an HTTP provider or Codex CLI.":"Selected archived images are sent to the chosen provider. Up to 4 supported images (5 MiB each, 12 MiB total) can be attached; unsupported or oversized artifacts are skipped."})]}),s.jsx("button",{className:"rail-rearchive-btn",onClick:()=>Qs(!!b),disabled:Ie,children:Ie?"…":b?"Regenerate":"Generate"})]})]})})(),s.jsx("div",{className:"meta-list",children:_.filter(([,b])=>b!=null&&b!=="").map(([b,q])=>s.jsxs("div",{className:"meta-item",children:[s.jsx("span",{className:"meta-k",children:b}),s.jsx("span",{className:`meta-v${b==="Root"?" mono":""}`,children:gt(q)})]},b))}),l.artifacts.length>0&&(()=>{const b=l.artifacts.map((me,an)=>({...me,_idx:an})),q=b.filter(me=>me.artifact_role==="font"),ae=b.filter(me=>me.artifact_role!=="font"),he=q.reduce((me,an)=>me+(an.byte_size||0),0),St=l.summary.entry_uid,sn=me=>s.jsx("li",{children:s.jsxs("a",{href:`/api/archives/${e}/entries/${St}/artifacts/${me._idx}`,target:"_blank",rel:"noopener noreferrer",className:"artifact-link",children:[s.jsx("span",{className:"artifact-name",children:me.artifact_role==="font"?me.relpath.split("/").pop():me.artifact_role.replace(/_/g," ")}),s.jsx("span",{className:"artifact-size",children:me.byte_size!=null?gl(me.byte_size):"—"})]})},me._idx);return s.jsxs("div",{className:"rail-section",children:[s.jsxs("div",{className:"rail-section-heading",children:["Artifacts ",s.jsx("span",{className:"num",children:l.artifacts.length})]}),s.jsxs("ul",{className:"artifact-list",children:[ae.map(sn),q.length>0&&s.jsxs("li",{className:"artifact-group",children:[s.jsxs("button",{type:"button",className:"artifact-group-header artifact-link","aria-expanded":L,onClick:()=>V(me=>!me),children:[s.jsxs("span",{className:"artifact-name",children:[s.jsx("span",{"aria-hidden":"true",className:`artifact-group-chevron${L?" open":""}`,children:"›"}),` fonts (${q.length})`]}),s.jsx("span",{className:"artifact-size",children:gl(he)})]}),L&&s.jsx("ul",{className:"artifact-list artifact-group-body",children:q.map(sn)})]})]})]})})()]}):s.jsx("p",{className:"tags-empty",children:"Loading\\u2026"}):s.jsx("p",{className:"tags-empty",children:"Select an entry."}),t&&!Ne&&!S&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Tags"}),N.length===0?s.jsx("p",{className:"tags-empty",children:"No tags yet."}):s.jsx("div",{className:"tags-wrap",children:N.map(b=>s.jsxs("span",{className:"tag-pill",title:b.full_path,children:[g?cf(b.full_path):b.full_path,s.jsx("button",{className:"remove",title:`Remove tag ${b.full_path}`,onClick:()=>Xs(b.tag_uid),children:"×"})]},b.tag_uid))}),E&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:E}),s.jsxs("div",{className:"tag-input-wrap",children:[s.jsx("span",{className:"hash",children:"/"}),s.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:f,onChange:b=>m(b.target.value),onKeyDown:b=>{b.key==="Enter"&&Sl()}}),s.jsx("button",{className:"tag-add-btn",onClick:Sl,children:"Add"})]})]}),(k.length>0||Le.filter(b=>b.slug!=="_default_").length>0)&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Collections"}),k.map(b=>s.jsxs("div",{className:"coll-row",children:[s.jsx("span",{className:"coll-name",children:b.name}),s.jsx("span",{className:"vis-badge",children:Fu[b.visibility_bits]??`bits:${b.visibility_bits}`})]},b.collection_uid)),Le.filter(b=>b.slug!=="_default_").length>0&&s.jsxs("div",{className:"bulk-coll-row",style:{marginTop:8},children:[s.jsxs("select",{className:"bulk-coll-select",value:ue,onChange:b=>Te(b.target.value),children:[s.jsx("option",{value:"",children:"Add to collection…"}),Le.filter(b=>b.slug!=="_default_").map(b=>s.jsx("option",{value:b.collection_uid,children:b.name},b.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:Pn,disabled:!ue||pe==="running",children:pe==="running"?"…":pe==="done"?"✓":pe==="error"?"!":"Add"})]}),ie&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"4px 0 0"},children:ie})]}),l&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread")&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Actions"}),s.jsx("button",{className:"rail-rearchive-btn",onClick:Gs,disabled:te==="running",children:te==="running"?"Re-archiving…":"Re-archive"}),te==="done"&&s.jsx("p",{className:"form-msg form-msg--ok",style:{marginTop:"6px"},children:"Re-archived successfully."}),te==="error"&&s.jsx("p",{className:"form-msg form-msg--err",style:{marginTop:"6px"},children:Be})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:Js,children:"Delete entry"})})]})]})}const Eg=/\/api\/archives\/([^/]+)\/entries\/([^/]+)\/artifacts\/(\d+)/;function bg(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M5 17H3a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h18a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-2"}),s.jsx("polygon",{points:"12 15 17 21 7 21 12 15"})]})}function Tg({src:e,contentType:t="video/mp4"}){const n=c.useRef(null),[r,l]=c.useState(null),[i,a]=c.useState(!1),[o,u]=c.useState(!1);c.useEffect(()=>{if(!e){l(null);return}const g=e.match(Eg);if(!g){l(e);return}let h=!1;return l(null),$m(g[1],g[2],parseInt(g[3],10)).then(({url:v})=>{h||l(v)}).catch(()=>{h||l(e)}),()=>{h=!0}},[e]),c.useEffect(()=>{n.current&&n.current.load()},[r]),c.useEffect(()=>{u(typeof HTMLVideoElement<"u"&&"webkitShowPlaybackTargetPicker"in HTMLVideoElement.prototype)},[]),c.useEffect(()=>{var h;const g=v=>{if(v)try{cast.framework.CastContext.getInstance().setOptions({receiverApplicationId:chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,autoJoinPolicy:chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}),a(!0)}catch{}};if((h=window.cast)!=null&&h.framework)g(!0);else if(window.__onGCastApiAvailable=g,!document.querySelector('script[src*="cast_sender"]')){const v=document.createElement("script");v.src="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1",document.head.appendChild(v)}},[]),c.useEffect(()=>{if(!i||!r)return;const g=cast.framework.CastContext.getInstance(),{CastContextEventType:h,SessionState:v}=cast.framework,x=N=>{if(!N)return;const p=new chrome.cast.media.MediaInfo(window.location.origin+r,t);N.loadMedia(new chrome.cast.media.LoadRequest(p)).catch(()=>{})};x(g.getCurrentSession());const S=N=>{(N.sessionState===v.SESSION_STARTED||N.sessionState===v.SESSION_RESUMED)&&x(g.getCurrentSession())};return g.addEventListener(h.SESSION_STATE_CHANGED,S),()=>g.removeEventListener(h.SESSION_STATE_CHANGED,S)},[i,r,t]);const d=()=>{var g,h;(h=(g=n.current)==null?void 0:g.webkitShowPlaybackTargetPicker)==null||h.call(g)},y=i||o;return s.jsx("div",{className:"preview-video-wrap",style:{position:"relative"},children:e?s.jsxs(s.Fragment,{children:[r?s.jsxs("video",{ref:n,controls:!0,autoPlay:!1,playsInline:!0,"x-webkit-airplay":"allow",style:{width:"100%",maxHeight:"100%",display:"block"},children:[s.jsx("source",{src:r}),"Your browser does not support the video element."]}):s.jsx("div",{className:"video-tv-loading","aria-label":"Loading video…"}),y&&r&&s.jsxs("div",{className:"video-tv-controls",children:[o&&s.jsx("button",{className:"video-tv-btn",title:"AirPlay to device","aria-label":"AirPlay to device",onClick:d,children:s.jsx(bg,{})}),i&&s.jsx("google-cast-launcher",{className:"video-tv-btn",title:"Cast to TV"})]})]}):s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No video available"})})}function Hu({src:e,type:t,title:n,originalUrl:r}){const l=r||e,i=n||null;return s.jsxs("div",{className:"preview-iframe-wrap",style:{flex:1,minHeight:0,display:"flex",flexDirection:"column"},children:[s.jsxs("div",{className:"preview-iframe-toolbar",style:{display:"flex",flexDirection:"column",gap:"2px",padding:"6px 12px",borderBottom:"1px solid var(--line-soft)",background:"var(--paper-2)",flexShrink:0},children:[i&&s.jsx("span",{style:{fontSize:"0.85rem",fontWeight:600,color:"var(--ink)",fontFamily:"var(--sans)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",color:"var(--muted)",fontFamily:"var(--sans)"},children:l}),s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",style:{fontSize:"0.78rem",color:"var(--accent)",textDecoration:"none",whiteSpace:"nowrap",fontFamily:"var(--sans)",flexShrink:0},children:t==="pdf"?"Open PDF ↗":"Open in new tab ↗"})]})]}),s.jsx("iframe",{src:e,sandbox:"allow-same-origin allow-popups",allow:"autoplay 'none'",referrerPolicy:"no-referrer",style:{flex:1,border:"none",width:"100%",minHeight:0},title:i||(t==="pdf"?"PDF preview":"Page preview")})]})}function Pg({src:e,alt:t}){return s.jsx("div",{className:"preview-image-wrap",style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",background:"var(--paper-2)",overflow:"hidden"},children:s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",style:{display:"contents"},children:s.jsx("img",{src:e,alt:t||"",style:{objectFit:"contain",maxHeight:"100%",maxWidth:"100%",display:"block",cursor:"pointer"}})})})}function gf(e){return e?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(new Date(e*1e3)):""}function Wu(e){return!e||!e.includes("&")?e:e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}const ee={card:{background:"var(--paper)",border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",maxWidth:"560px",margin:"0 auto",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},threadOuter:{border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",maxWidth:"560px",margin:"0 auto",background:"var(--paper)",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},tweetRow:{display:"flex",gap:"10px",padding:"10px 12px"},tweetRowThread:{display:"flex",gap:"10px",padding:"10px 12px 0"},leftCol:{display:"flex",flexDirection:"column",alignItems:"center",flexShrink:0,width:"36px"},rightCol:{flex:1,minWidth:0,paddingBottom:"8px"},avatar:{width:"36px",height:"36px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},avatarPh:{width:"36px",height:"36px",borderRadius:"50%",background:"var(--line)",flexShrink:0},threadLine:{flex:1,width:"2px",background:"var(--line-soft, var(--line))",margin:"4px 0",minHeight:"12px",borderRadius:"1px"},authorRow:{display:"flex",alignItems:"baseline",gap:"4px",flexWrap:"wrap",marginBottom:"4px",lineHeight:"1.3"},authorName:{fontWeight:"700",fontSize:"14px",color:"var(--ink)"},authorHandle:{fontSize:"13px",color:"var(--muted)"},datePart:{fontSize:"13px",color:"var(--muted)"},tweetText:{fontSize:"14px",lineHeight:"1.5",color:"var(--ink)",whiteSpace:"pre-line",marginBottom:"8px",wordBreak:"break-word"},stats:{display:"flex",gap:"12px",fontSize:"13px",color:"var(--muted)"},link:{color:"var(--accent)",textDecoration:"none"},loading:{padding:"24px 16px",textAlign:"center",color:"var(--muted)",fontSize:"14px"},error:{padding:"24px 16px",textAlign:"center",color:"var(--alert)",fontSize:"14px"},mediaGrid:{marginBottom:"8px",borderRadius:"10px",overflow:"hidden",border:"1px solid var(--line)"},mediaImg:{display:"block",width:"100%",objectFit:"cover",maxHeight:"260px"},mediaVideo:{display:"block",width:"100%",maxHeight:"260px",background:"#000"},article:{maxWidth:"560px",margin:"0 auto",border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",background:"var(--paper)",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},aCover:{width:"100%",display:"block",objectFit:"cover",maxHeight:"280px"},aMeta:{padding:"10px 14px 0"},aTweetTitle:{fontSize:"20px",fontWeight:"800",letterSpacing:"-0.3px",color:"var(--ink)",lineHeight:"1.3",marginBottom:"8px"},aAuthorRow:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},aAvatar:{width:"36px",height:"36px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},aAvatarPh:{width:"36px",height:"36px",borderRadius:"50%",background:"var(--line)",flexShrink:0},aAuthorName:{fontSize:"14px",fontWeight:"700",color:"var(--ink)",lineHeight:"1.3"},aAuthorSub:{fontSize:"13px",color:"var(--muted)",lineHeight:"1.3"},aDivider:{border:"none",borderTop:"1px solid var(--line)",margin:"0"},aBody:{padding:"4px 14px 16px"},bH1:{fontSize:"22px",fontWeight:"800",letterSpacing:"-0.4px",color:"var(--ink)",lineHeight:"1.25",margin:"16px 0 6px"},bH2:{fontSize:"18px",fontWeight:"700",letterSpacing:"-0.2px",color:"var(--ink)",lineHeight:"1.3",margin:"14px 0 4px"},bP:{fontSize:"15px",color:"var(--ink)",lineHeight:"1.65",marginBottom:"12px",marginTop:"0"},bSpacer:{height:"4px",display:"block"},bQuote:{borderLeft:"3px solid var(--line)",padding:"2px 12px",margin:"12px 0",color:"var(--muted)",fontSize:"15px",lineHeight:"1.6"},bHr:{border:"none",borderTop:"1px solid var(--line)",margin:"14px 0"},bImg:{width:"100%",display:"block",borderRadius:"8px",margin:"12px 0"},bUl:{margin:"8px 0 12px",paddingLeft:"24px"},bOl:{margin:"8px 0 12px",paddingLeft:"24px"},bLi:{fontSize:"15px",color:"var(--ink)",lineHeight:"1.6",marginBottom:"4px"},bTweet:{display:"flex",alignItems:"center",gap:"10px",border:"1px solid var(--line)",borderRadius:"10px",padding:"10px 14px",margin:"12px 0",color:"var(--muted)",fontSize:"14px",textDecoration:"none"},bMdPre:{borderRadius:"8px",margin:"10px 0",overflow:"auto",background:"var(--paper-3, var(--field))",padding:"12px 14px"},bMdCode:{fontFamily:"ui-monospace, 'Cascadia Code', 'Fira Code', Menlo, Consolas, monospace",fontSize:"12px",lineHeight:"1.6",color:"var(--ink)",background:"transparent",display:"block"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:"var(--paper-3, var(--field))",padding:"1px 5px",borderRadius:"4px",color:"var(--ink)"},qtBadge:{fontSize:"11px",color:"var(--muted)",display:"inline-flex",alignItems:"center",gap:"2px",marginLeft:"4px",letterSpacing:"0.03em",flexShrink:0},lightboxBackdrop:{position:"fixed",inset:0,zIndex:500,background:"rgba(0,0,0,0.92)",display:"flex",alignItems:"center",justifyContent:"center",padding:"20px"},lightboxContent:{display:"flex",flexDirection:"column",alignItems:"center",gap:"10px",maxWidth:"90vw",maxHeight:"90vh"},lightboxToolbar:{display:"flex",alignItems:"center",gap:"10px",alignSelf:"flex-end"},lightboxImg:{maxWidth:"88vw",maxHeight:"80vh",objectFit:"contain",borderRadius:"6px",display:"block"},lightboxNav:{display:"flex",gap:"12px",alignItems:"center"},lightboxNavBtn:{background:"rgba(255,255,255,0.18)",border:"none",color:"#fff",fontSize:"20px",cursor:"pointer",borderRadius:"50%",width:"36px",height:"36px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,flexShrink:0},lightboxBtn:{background:"rgba(255,255,255,0.18)",border:"none",color:"#fff",fontSize:"16px",cursor:"pointer",borderRadius:"50%",width:"30px",height:"30px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,flexShrink:0},lightboxLink:{color:"rgba(255,255,255,0.7)",textDecoration:"none",fontSize:"14px"},lightboxCounter:{color:"rgba(255,255,255,0.6)",fontSize:"13px"}},Ae={bg:"#000000",border:"#2f3336",text:"#e7e9ea",dim:"#71767b",accent:"#1d9bf0",codeBg:"#16181c"},Ti={article:{background:Ae.bg,color:Ae.text,minHeight:"100%",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif'},articleInner:{maxWidth:"598px",margin:"0 auto",paddingBottom:"80px"},aCover:{width:"100%",display:"block",objectFit:"cover",maxHeight:"420px"},aMeta:{padding:"20px 16px 0"},aTweetTitle:{fontSize:"34px",fontWeight:"800",letterSpacing:"-0.5px",color:Ae.text,lineHeight:"44px",marginBottom:"16px"},aAuthorRow:{display:"flex",alignItems:"center",gap:"12px",marginBottom:"16px"},aAvatar:{width:"40px",height:"40px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},aAvatarPh:{width:"40px",height:"40px",borderRadius:"50%",background:Ae.border,flexShrink:0},aAuthorName:{fontSize:"15px",fontWeight:"700",color:Ae.text,lineHeight:"1.3"},aAuthorSub:{fontSize:"15px",color:Ae.dim,lineHeight:"1.3"},aDivider:{border:"none",borderTop:`1px solid ${Ae.border}`,margin:"0"},aBody:{padding:"4px 16px 0"},bH1:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:Ae.text,lineHeight:"36px",margin:"24px 0 10px"},bH2:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:Ae.text,lineHeight:"36px",margin:"24px 0 10px"},bP:{fontSize:"17px",color:Ae.text,lineHeight:"1.5",marginBottom:"16px",marginTop:"0"},bSpacer:{height:"6px",display:"block"},bQuote:{borderLeft:`3px solid ${Ae.border}`,padding:"2px 14px",margin:"14px 0",color:Ae.dim,fontSize:"17px",lineHeight:"1.5"},bHr:{border:"none",borderTop:`1px solid ${Ae.border}`,margin:"28px 0"},bImg:{width:"100%",display:"block",borderRadius:"12px",margin:"16px 0"},bUl:{margin:"10px 0 16px",paddingLeft:"28px"},bOl:{margin:"10px 0 16px",paddingLeft:"28px"},bLi:{fontSize:"17px",color:Ae.text,lineHeight:"1.5",marginBottom:"6px"},bTweet:{display:"flex",alignItems:"center",gap:"12px",border:`1px solid ${Ae.border}`,borderRadius:"12px",padding:"14px 16px",margin:"14px 0",color:Ae.dim,fontSize:"15px",textDecoration:"none"},bMdPre:{borderRadius:"12px",margin:"12px 0",overflow:"auto",background:"#1e2029"},bMdCode:{fontFamily:"ui-monospace, 'Cascadia Code', 'Fira Code', Menlo, Consolas, monospace",fontSize:"13px",lineHeight:"1.65",padding:"18px 20px",display:"block",color:Ae.text,background:"transparent"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:Ae.codeBg,padding:"2px 6px",borderRadius:"4px",color:"#e6edf3"},link:{color:Ae.accent,textDecoration:"none"}};function Lg(e,t,n){const r={};return n&&n.forEach((l,i)=>{l.relpath&&(r[l.relpath]=`/api/archives/${e}/entries/${t}/artifacts/${i}`)}),r}function hr(e,t,n){return e&&n[e]?n[e]:t||null}function yf(){return s.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",style:{flexShrink:0,color:"var(--ink)"},children:s.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.748l7.73-8.835L1.254 2.25H8.08l4.259 5.63L18.244 2.25zm-1.161 17.52h1.833L7.084 4.126H5.117L17.083 19.77z"})})}function jo(e,t,...n){var r;if(e.fromIndex!=null&&e.toIndex!=null)return{s:e.fromIndex,e:e.toIndex};if(((r=e.indices)==null?void 0:r.length)===2)return{s:e.indices[0],e:e.indices[1]};if(t)for(const l of n){if(!l)continue;const i=t.indexOf(l);if(i!==-1)return{s:i,e:i+l.length}}return null}function vf(e,t){const n=e.expanded_url||e.url||e.text||"",r=e.display_url||e.expanded_url||e.url||e.text||"",l=jo(e,t,e.url,e.text,e.display_url,e.expanded_url);return!l||!n?null:{...l,kind:"url",href:n,display:r}}function xf(e,t){const n=e.screen_name||e.name||e.text||"",r=n?`@${n}`:null,l=jo(e,t,r);return!l||!n?null:{...l,kind:"mention",screen_name:n}}const Vu=/https?:\/\/[^\s<>"'\])]+/g,Rg=/[.,;:!?)()]+$/;function Es(e,t){const n=[];let r=0,l;for(Vu.lastIndex=0;(l=Vu.exec(e))!==null;){l.index>r&&n.push(e.slice(r,l.index));let i=l[0].replace(Rg,"");n.push(s.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",style:t,children:i},l.index));const a=l[0].slice(i.length);a&&n.push(a),r=l.index+l[0].length}return r===0?e:(rvf(o,e)).filter(Boolean),...(t.user_mentions||[]).map(o=>xf(o,e)).filter(Boolean)];if(r.length===0&&n.length===0)return Es(Wu(e),ee.link);const l=new Set([0,e.length]);for(const o of r)o.s>=0&&o.s<=e.length&&l.add(o.s),o.e>=0&&o.e<=e.length&&l.add(o.e);for(const[o,u]of n)o>=0&&o<=e.length&&l.add(o),u>=0&&u<=e.length&&l.add(u);const i=(o,u)=>n.some(([d,y])=>d<=o&&y>=u),a=[...l].sort((o,u)=>o-u);return a.slice(0,-1).map((o,u)=>{const d=a[u+1];if(i(o,d))return null;const y=e.slice(o,d),g=r.filter(x=>x.s<=o&&x.e>=d),h=g.find(x=>x.kind==="url");if(h)return s.jsx("a",{href:h.href,target:"_blank",rel:"noopener noreferrer",style:ee.link,children:h.display||y},u);const v=g.find(x=>x.kind==="mention");return v?s.jsx("a",{href:`https://x.com/${v.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:ee.link,children:y},u):s.jsx("span",{children:Es(Wu(y),ee.link)},u)}).filter(o=>o!==null)}function Ig(e,t,n,r,l=ee){if(!e)return null;t=t||[],n=n||[],r=r||[];const i=[];for(const u of t)u.length>0&&i.push({s:u.offset,e:u.offset+u.length,kind:"style",style:u.style});for(const u of n){const d=vf(u,e);d&&i.push(d)}for(const u of r){const d=xf(u,e);d&&i.push(d)}if(i.length===0)return Es(e,l.link);const a=new Set([0,e.length]);for(const u of i)u.s>=0&&u.s<=e.length&&a.add(u.s),u.e>=0&&u.e<=e.length&&a.add(u.e);const o=[...a].sort((u,d)=>u-d);return o.slice(0,-1).map((u,d)=>{const y=o[d+1],g=i.filter(N=>N.s<=u&&N.e>=y),h=e.slice(u,y);let v;if(h.includes(` +`)){const N=h.split(` +`);v=N.flatMap((p,f)=>fN.kind==="style"&&N.style==="Code")&&(v=s.jsx("code",{style:l.iCode,children:v})),g.some(N=>N.kind==="style"&&N.style==="Bold")&&(v=s.jsx("strong",{children:v})),g.some(N=>N.kind==="style"&&N.style==="Italic")&&(v=s.jsx("em",{children:v})),g.some(N=>N.kind==="style"&&N.style==="Underline")&&(v=s.jsx("u",{children:v})),g.some(N=>N.kind==="style"&&N.style==="Strikethrough")&&(v=s.jsx("s",{children:v}));const x=g.find(N=>N.kind==="url");if(x){const N=/^https?:\/\/t\.co\//i.test(v);v=s.jsx("a",{href:x.href,target:"_blank",rel:"noopener noreferrer",style:l.link,children:N?x.display:v})}const S=g.find(N=>N.kind==="mention");return S&&(v=s.jsx("a",{href:`https://x.com/${S.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:l.link,children:v})),s.jsx("span",{children:typeof v=="string"?Es(v,l.link):v},d)})}function $g(e,t,n){const r=(n==null?void 0:n.st)||ee,l=e.resolved_entities||[];return l.length===0?null:l.map((i,a)=>{var o;switch(i.type){case"divider":return s.jsx("hr",{style:r.bHr},a);case"media":{const u=hr(i.local_path,i.url,t);return u?s.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:d=>{var y;!d.metaKey&&!d.ctrlKey&&(d.preventDefault(),(y=n==null?void 0:n.onImgClick)==null||y.call(n,u))},children:s.jsx("img",{src:u,style:r.bImg,loading:"lazy",alt:""})},a):null}case"tweet":return i.tweet_id?s.jsxs("a",{href:`https://x.com/i/status/${i.tweet_id}`,target:"_blank",rel:"noopener noreferrer",style:r.bTweet,children:[s.jsx(yf,{}),"View post on X"]},a):null;case"link":return i.url?s.jsx("p",{style:r.bP,children:s.jsx("a",{href:i.url,target:"_blank",rel:"noopener noreferrer",style:r.link,children:i.url})},a):null;case"markdown":{const u=i.markdown??((o=i.data)==null?void 0:o.markdown)??"";return s.jsx("pre",{style:r.bMdPre,children:s.jsx("code",{style:r.bMdCode,children:u})},a)}case"emoji":return i.url?s.jsx("img",{src:i.url,alt:"",style:{height:"1.2em",verticalAlign:"middle",margin:"0 1px"}},a):null;default:return null}})}function Pi(e,t,n,r){const l=(r==null?void 0:r.st)||ee,i=e.type||"",a=e.text||"",o=e.inline_style_ranges||[],u=e.data||{},d=Ig(a,o,u.urls||[],u.mentions||[],l);switch(i){case"header-one":return s.jsx("h1",{style:l.bH1,children:d},t);case"header-two":{const y=a.match(/(?:x\.com|twitter\.com)\/i\/status\/(\d+)/);return y?s.jsxs("a",{href:`https://x.com/i/status/${y[1]}`,target:"_blank",rel:"noopener noreferrer",style:l.bTweet,children:[s.jsx(yf,{}),"View post on X"]},t):s.jsx("h2",{style:l.bH2,children:d},t)}case"unstyled":return a.trim()?s.jsx("p",{style:l.bP,children:d},t):s.jsx("span",{style:l.bSpacer},t);case"blockquote":return s.jsx("blockquote",{style:l.bQuote,children:d},t);case"unordered-list-item":case"ordered-list-item":return s.jsx("li",{style:l.bLi,children:d},t);case"atomic":return s.jsx("span",{children:$g(e,n,r)},t);default:return a?s.jsx("p",{style:l.bP,children:d},t):null}}function Dg(e,t,n){const r=(n==null?void 0:n.st)||ee,l=[];let i=0;for(;i{r&&(l==null||l(!0))},[r,l]);const o=r?Ti:ee,u=e.cover_media||{},d=e.author||t||{},y=e.first_published_at_secs?gf(e.first_published_at_secs):"",h=[d.screen_name?`@${d.screen_name}`:"",y].filter(Boolean).join(" · "),v=hr(u.local_path,u.url,n),x=hr(d.avatar_local_path,d.avatar_url,n),S=s.jsxs(s.Fragment,{children:[i&&s.jsx(wf,{items:[{src:i,alt:""}],startIndex:0,onClose:()=>a(null)}),v&&s.jsx("a",{href:v,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:N=>{!N.metaKey&&!N.ctrlKey&&(N.preventDefault(),a(v))},children:s.jsx("img",{src:v,style:o.aCover,alt:"Article cover"})}),s.jsxs("div",{style:o.aMeta,children:[e.title&&s.jsx("div",{style:o.aTweetTitle,children:e.title}),s.jsxs("div",{style:o.aAuthorRow,children:[x?s.jsx("img",{src:x,style:o.aAvatar,alt:d.name||""}):s.jsx("div",{style:o.aAvatarPh}),s.jsxs("div",{children:[s.jsx("div",{style:o.aAuthorName,children:d.name||d.screen_name||"Unknown"}),h&&s.jsx("div",{style:o.aAuthorSub,children:h})]})]})]}),s.jsx("hr",{style:o.aDivider}),s.jsx("div",{style:o.aBody,children:Dg(e.blocks||[],n,{onImgClick:a,st:o})})]});return r?s.jsx("div",{style:Ti.article,children:s.jsx("div",{style:Ti.articleInner,children:S})}):s.jsx("div",{style:ee.article,children:S})}function Ag({photos:e,onOpen:t}){const n=e.length;if(n===0)return null;if(n===1)return s.jsx("a",{href:e[0].src,target:"_blank",rel:"noopener noreferrer",style:{display:"block"},onClick:l=>{!l.metaKey&&!l.ctrlKey&&(l.preventDefault(),t(0))},children:s.jsx("img",{src:e[0].src,alt:e[0].alt||"",style:ee.mediaImg,loading:"lazy"})});const r=n<=2?"180px":"140px";return s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gridTemplateRows:n===2?r:`${r} ${r}`,gap:"2px"},children:e.map((l,i)=>s.jsx("a",{href:l.src,target:"_blank",rel:"noopener noreferrer",style:{display:"block",overflow:"hidden",gridRow:n===3&&i===0?"span 2":void 0},onClick:a=>{!a.metaKey&&!a.ctrlKey&&(a.preventDefault(),t(i))},children:s.jsx("img",{src:l.src,alt:l.alt||"",loading:"lazy",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}})},i))})}function wf({items:e,startIndex:t,onClose:n}){const[r,l]=c.useState(t);c.useEffect(()=>{const a=o=>{(o.key==="Escape"||o.key==="ArrowLeft"||o.key==="ArrowRight")&&(o.stopPropagation(),o.preventDefault()),o.key==="Escape"&&n(),o.key==="ArrowRight"&&l(u=>Math.min(u+1,e.length-1)),o.key==="ArrowLeft"&&l(u=>Math.max(u-1,0))};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[n,e.length]);const i=e[r];return s.jsx("div",{style:ee.lightboxBackdrop,onClick:n,children:s.jsxs("div",{style:ee.lightboxContent,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{style:ee.lightboxToolbar,children:[e.length>1&&s.jsxs("span",{style:ee.lightboxCounter,children:[r+1," / ",e.length]}),s.jsx("a",{href:i.src,target:"_blank",rel:"noopener noreferrer",style:ee.lightboxLink,title:"Open in new tab",children:"↗"}),s.jsx("button",{style:ee.lightboxBtn,onClick:n,"aria-label":"Close",children:"×"})]}),s.jsx("img",{src:i.src,alt:i.alt||"",style:ee.lightboxImg}),e.length>1&&s.jsxs("div",{style:ee.lightboxNav,children:[s.jsx("button",{style:ee.lightboxNavBtn,onClick:()=>l(a=>Math.max(a-1,0)),disabled:r===0,children:"‹"}),s.jsx("button",{style:ee.lightboxNavBtn,onClick:()=>l(a=>Math.min(a+1,e.length-1)),disabled:r===e.length-1,children:"›"})]})]})})}function Qu({tweet:e,isInThread:t,isLast:n,artifactMap:r}){var f,m;const[l,i]=c.useState(null),a=e.author||{},o=e.created_at_secs?gf(e.created_at_secs):"",u=e.entities||{},d=hr(a.avatar_local_path,a.avatar_url,r),y=t&&!n,g=e.is_quote_status===!0,h=t?ee.tweetRowThread:ee.tweetRow,v=e.full_text||"",x=((m=(f=e.extended_entities)==null?void 0:f.media)!=null&&m.length?e.extended_entities.media:u.media)||[],S=[],N=[];for(const k of x)if(k.type==="photo"){const C=hr(k.local_path,k.media_url_https,r);C&&S.push({kind:"photo",src:C,alt:k.alt_text||""})}else if(k.type==="video"||k.type==="animated_gif"){const C=k.local_path&&r[k.local_path]||(()=>{var T,j;return(j=(((T=k.video_info)==null?void 0:T.variants)||[]).filter(P=>P.content_type==="video/mp4").sort((P,R)=>(R.bitrate||0)-(P.bitrate||0))[0])==null?void 0:j.url})();C&&N.push({kind:k.type==="animated_gif"?"gif":"video",src:C})}const p=[];for(const k of x){if(!k.url||!(k.type==="photo"?S.some(T=>T.src===hr(k.local_path,k.media_url_https,r)):N.length>0))continue;const E=jo(k,v,k.url);E&&p.push([E.s,E.e])}return s.jsxs(s.Fragment,{children:[l!==null&&s.jsx(wf,{items:S,startIndex:l,onClose:()=>i(null)}),s.jsxs("div",{style:h,children:[s.jsxs("div",{style:ee.leftCol,children:[d?s.jsx("img",{src:d,style:ee.avatar,alt:a.name||""}):s.jsx("div",{style:ee.avatarPh}),y&&s.jsx("div",{style:ee.threadLine})]}),s.jsxs("div",{style:ee.rightCol,children:[s.jsxs("div",{style:ee.authorRow,children:[s.jsx("span",{style:ee.authorName,children:a.name||a.screen_name||"Unknown"}),a.screen_name&&s.jsxs("span",{style:ee.authorHandle,children:["@",a.screen_name]}),o&&s.jsxs("span",{style:ee.datePart,children:["· ",o]}),g&&s.jsx("span",{style:ee.qtBadge,title:"Quote tweet",children:"↻ QT"})]}),s.jsx("div",{style:ee.tweetText,children:zg(v,u,p)}),S.length>0&&s.jsx("div",{style:ee.mediaGrid,children:s.jsx(Ag,{photos:S,onOpen:k=>i(k)})}),N.map((k,C)=>s.jsx("div",{style:ee.mediaGrid,children:s.jsx("video",{src:k.src,style:ee.mediaVideo,controls:!0,loop:k.kind==="gif",muted:k.kind==="gif",autoPlay:k.kind==="gif"})},C)),(e.retweet_count>0||e.favorite_count>0)&&s.jsxs("div",{style:ee.stats,children:[e.favorite_count>0&&s.jsxs("span",{children:["❤️ ",e.favorite_count.toLocaleString()]}),e.retweet_count>0&&s.jsxs("span",{children:["🔁 ",e.retweet_count.toLocaleString()]})]})]})]})]})}function Mg({archiveId:e,entryUid:t,artifacts:n,entityKind:r,fullPage:l,onXArticle:i}){const[a,o]=c.useState(!0),[u,d]=c.useState(null),[y,g]=c.useState([]);if(c.useEffect(()=>{if(o(!0),d(null),g([]),!n||!e||!t){o(!1);return}const x=n.map((N,p)=>({...N,index:p})).filter(N=>N.artifact_role==="raw_tweet_json");if(x.length===0){d("No tweet data found."),o(!1);return}let S=!1;return Zh(e,t,x.map(N=>N.index)).then(async N=>{if(S)return;const p=/https?:\/\/t\.co\/[A-Za-z0-9]+/g,f=T=>{var P;const j=T.full_text||"";return(((P=T.entities)==null?void 0:P.urls)||[]).map(R=>{var X;if(R.fromIndex!=null&&R.toIndex!=null)return[R.fromIndex,R.toIndex];if(((X=R.indices)==null?void 0:X.length)===2)return[R.indices[0],R.indices[1]];if(R.url){const H=j.indexOf(R.url);if(H!==-1)return[H,H+R.url.length]}return null}).filter(Boolean)},m=(T,j,P)=>T.some(([R,X])=>R<=j&&X>=P),k=new Set;for(const T of N){const j=T.full_text||"",P=f(T);let R;for(p.lastIndex=0;(R=p.exec(j))!==null;)m(P,R.index,R.index+R[0].length)||k.add(R[0])}const C=k.size>0?await em([...k]).catch(()=>({})):{},E=N.map(T=>{var H;const j=T.full_text||"",P=f(T),R=[];let X;for(p.lastIndex=0;(X=p.exec(j))!==null;){const Y=X[0],te=C[Y];te&&te!==Y&&!m(P,X.index,X.index+Y.length)&&R.push({url:Y,expanded_url:te,display_url:(()=>{try{const fe=new URL(te);return fe.hostname+(fe.pathname.length>1?"/…":"")}catch{return te}})(),fromIndex:X.index,toIndex:X.index+Y.length})}return R.length===0?T:{...T,entities:{...T.entities||{},urls:[...((H=T.entities)==null?void 0:H.urls)||[],...R]}}});S||g(E)}).catch(N=>{S||d(N.message||"Failed to load tweet.")}).finally(()=>{S||o(!1)}),()=>{S=!0}},[e,t,n]),a)return s.jsx("div",{style:ee.loading,children:"Loading…"});if(u)return s.jsxs("div",{style:ee.error,children:["Error: ",u]});if(y.length===0)return null;const h=Lg(e,t,n);if(r==="tweet_thread")return s.jsx("div",{style:ee.threadOuter,children:y.map((x,S)=>s.jsx(Qu,{tweet:x,isInThread:!0,isLast:S===y.length-1,artifactMap:h},x.id||S))});const v=y[0];return v.is_article&&v.article?s.jsx(Og,{article:v.article,tweetAuthor:v.author,artifactMap:h,fullPage:l,onXArticle:i}):s.jsx("div",{style:ee.card,children:s.jsx(Qu,{tweet:v,isInThread:!1,isLast:!0,artifactMap:h})})}function Fg({src:e,mime:t,title:n}){const[r,l]=c.useState(null),[i,a]=c.useState(null);return c.useEffect(()=>{const o=new AbortController;return l(null),a(null),Gh(e,{signal:o.signal}).then(l).catch(u=>{u.name!=="AbortError"&&a(u.message||String(u))}),()=>o.abort()},[e]),i?s.jsxs("div",{className:"text-preview text-preview--error",children:["Failed to load text: ",i]}):r===null?s.jsx("div",{className:"text-preview text-preview--loading",children:"Loading…"}):s.jsxs("div",{className:"text-preview",children:[n&&s.jsx("h1",{className:"text-preview__title",children:n}),s.jsx("pre",{className:"text-preview__body",children:r}),t&&s.jsx("div",{className:"text-preview__mime",children:t})]})}const Bg=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv"]),Ug=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),Hg=new Set(["jpg","jpeg","png","gif","webp","avif","svg","bmp"]),Wg=new Set(["md","markdown","txt"]),Vg={mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo",m4v:"video/mp4",ogv:"video/ogg"};function kf({archiveId:e,entry:t,detail:n,fullPage:r,onXArticle:l}){if(!t)return s.jsx("div",{className:"preview-panel preview-panel--empty",children:s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"Select an entry to preview"})});if(!n)return s.jsx("div",{className:"preview-panel preview-panel--loading",children:s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"Loading…"})});const{summary:i,artifacts:a}=n,o=i.entry_uid,u=i.entity_kind;if(u==="tweet"||u==="tweet_thread"){const v=s.jsx(Mg,{archiveId:e,entryUid:o,artifacts:a,entityKind:u,fullPage:r,onXArticle:l});return r?v:s.jsx("div",{className:"preview-tweet-wrap",children:v})}const d=a.findIndex(v=>v.artifact_role==="primary_media");if(d===-1)return s.jsxs("div",{className:"preview-panel preview-panel--no-preview",children:[s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No preview available"}),a.length>0&&s.jsx("ul",{style:{marginTop:"12px",paddingLeft:"20px",fontSize:"0.8rem",color:"var(--muted-2)",fontFamily:"var(--sans)"},children:a.map((v,x)=>s.jsxs("li",{children:[v.artifact_role,": ",v.relpath]},x))})]});const y=a[d],g=`/api/archives/${e}/entries/${o}/artifacts/${d}`,h=y.relpath.split(".").pop().toLowerCase();return Bg.has(h)?s.jsx("div",{className:"preview-panel",children:s.jsx(Tg,{src:g,contentType:Vg[h]||"video/mp4"})}):Ug.has(h)?s.jsxs("div",{className:"preview-panel preview-panel--audio",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"12px",padding:"24px",fontFamily:"var(--sans)"},children:[s.jsx("span",{style:{fontSize:"2rem"},children:"🎵"}),s.jsx("span",{style:{color:"var(--ink)",fontSize:"0.95rem",fontWeight:600},children:i.title||o}),s.jsx("audio",{src:g,controls:!0,style:{marginTop:"8px",width:"100%",maxWidth:"400px"}})]}):h==="pdf"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(Hu,{src:g,type:"pdf",title:i.title,originalUrl:i.original_url})}):h==="html"||h==="htm"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(Hu,{src:g,type:"page",title:i.title,originalUrl:i.original_url})}):Wg.has(h)?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0,overflow:"auto"},children:s.jsx(Fg,{src:g,mime:y.mime_type,title:i.title})}):Hg.has(h)?s.jsx("div",{className:"preview-panel",style:{height:"100%"},children:s.jsx(Pg,{src:g,alt:i.title||"Image"})}):s.jsxs("div",{className:"preview-panel preview-panel--no-preview",children:[s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No preview available"}),s.jsx("ul",{style:{marginTop:"12px",paddingLeft:"20px",fontSize:"0.8rem",color:"var(--muted-2)",fontFamily:"var(--sans)"},children:a.map((v,x)=>s.jsxs("li",{children:[v.artifact_role,": ",v.relpath]},x))})]})}function Qg({archiveId:e,entry:t,detail:n,onClose:r}){var l,i;return c.useEffect(()=>{const a=o=>{o.key==="Escape"&&r()};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[r]),s.jsx("div",{className:"preview-modal-backdrop",onClick:r,children:s.jsxs("div",{className:`preview-modal${((l=n==null?void 0:n.summary)==null?void 0:l.entity_kind)==="tweet"||((i=n==null?void 0:n.summary)==null?void 0:i.entity_kind)==="tweet_thread"?"":" preview-modal--full"}`,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{className:"preview-modal-header",children:[s.jsx("span",{className:"preview-modal-title",children:(t==null?void 0:t.title)||(t==null?void 0:t.entry_uid)||"Preview"}),s.jsx("a",{className:"preview-modal-newtab",href:`/preview/${e}/${t==null?void 0:t.entry_uid}`,target:"_blank",rel:"noopener noreferrer",title:"Open in new tab",children:"↗"}),s.jsx("button",{className:"preview-modal-close",onClick:r,"aria-label":"Close preview",children:"×"})]}),s.jsx("div",{className:"preview-modal-body",children:s.jsx(kf,{archiveId:e,entry:t,detail:n})})]})})}function qu(e){if(!isFinite(e)||isNaN(e))return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`}function qg({entry:e,src:t,archiveId:n,onClose:r}){const l=c.useRef(null),[i,a]=c.useState(!1),[o,u]=c.useState(0),[d,y]=c.useState(NaN),[g,h]=c.useState(1);c.useEffect(()=>{!l.current||!t||(l.current.load(),u(0),y(NaN),a(!1))},[t]),c.useEffect(()=>{l.current&&(l.current.volume=g)},[g]);function v(){const f=l.current;f&&(i?f.pause():f.play().catch(()=>{}))}function x(f){const m=l.current;if(!m||!isFinite(d))return;const k=Number(f.target.value);m.currentTime=k,u(k)}function S(f){h(Number(f.target.value))}const N=(e==null?void 0:e.title)||(e==null?void 0:e.entry_uid)||"Unknown",p=(e==null?void 0:e.source_kind)||"other";return s.jsxs(s.Fragment,{children:[s.jsx("audio",{ref:l,src:t||void 0,preload:"auto",onPlay:()=>a(!0),onPause:()=>a(!1),onEnded:()=>a(!1),onTimeUpdate:()=>{var f;return u(((f=l.current)==null?void 0:f.currentTime)??0)},onLoadedMetadata:()=>{var f;return y(((f=l.current)==null?void 0:f.duration)??NaN)},onDurationChange:()=>{var f;return y(((f=l.current)==null?void 0:f.duration)??NaN)},style:{display:"none"}}),s.jsxs("div",{className:"audio-bar",style:{position:"fixed",bottom:0,left:0,right:0,zIndex:100,background:"var(--paper-3)",borderTop:"1px solid var(--line)",display:"flex",alignItems:"center",gap:"16px",padding:"0 16px",height:"56px",fontFamily:"var(--sans)"},children:[s.jsxs("div",{className:"audio-bar-info",style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0,flex:"0 1 220px",overflow:"hidden"},children:[s.jsx("span",{className:"source-icon",style:{flexShrink:0,width:"18px",height:"18px",display:"flex",alignItems:"center"},dangerouslySetInnerHTML:{__html:Ws(p)}}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.85rem",color:"var(--ink)"},title:N,children:N})]}),s.jsxs("div",{className:"audio-bar-controls",style:{display:"flex",alignItems:"center",gap:"10px",flex:"1 1 0",minWidth:0},children:[s.jsx("button",{onClick:v,"aria-label":i?"Pause":"Play",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"var(--ink)",flexShrink:0,fontSize:"1.2rem",lineHeight:1},children:i?"⏸":"▶"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--muted)",whiteSpace:"nowrap",flexShrink:0},children:qu(o)}),s.jsx("input",{type:"range",min:0,max:isFinite(d)?d:0,step:.1,value:isFinite(o)?o:0,onChange:x,"aria-label":"Seek",style:{flex:1,minWidth:0,accentColor:"var(--accent)"}}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--muted)",whiteSpace:"nowrap",flexShrink:0},children:qu(d)})]}),s.jsxs("div",{className:"audio-bar-right",style:{display:"flex",alignItems:"center",gap:"8px",flex:"0 1 160px"},children:[s.jsx("span",{style:{fontSize:"0.85rem",color:"var(--muted)",flexShrink:0},children:"🔊"}),s.jsx("input",{type:"range",min:0,max:1,step:.01,value:g,onChange:S,"aria-label":"Volume",style:{width:"80px",accentColor:"var(--accent)"}}),s.jsx("button",{onClick:r,"aria-label":"Close audio player",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"var(--muted)",fontSize:"1rem",lineHeight:1,marginLeft:"4px"},children:"✕"})]})]})]})}function Kg({archiveId:e,entryUid:t}){var h,v;const[n,r]=c.useState(null),[l,i]=c.useState(!0),[a,o]=c.useState(null),[u,d]=c.useState(!1);c.useEffect(()=>{if(!u)return;const x=document.documentElement,S=document.body,N=x.style.colorScheme,p=S.style.background;return x.style.colorScheme="dark",S.style.background="#000",()=>{x.style.colorScheme=N,S.style.background=p}},[u]),c.useEffect(()=>{d(!1),Br(e,t).then(x=>{r(x),i(!1)}).catch(x=>{o((x==null?void 0:x.message)||"Failed to load entry"),i(!1)})},[e,t]);const y=((h=n==null?void 0:n.summary)==null?void 0:h.title)||t,g=(v=n==null?void 0:n.summary)==null?void 0:v.original_url;return s.jsxs("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column",background:u?"#000":"var(--paper)",fontFamily:"var(--sans)"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",padding:u?"8px 12px":"10px 16px",borderBottom:u?"none":"1px solid var(--line)",flexShrink:0,position:u?"sticky":"relative",top:0,zIndex:20,background:u?"rgba(0,0,0,0.82)":"var(--paper-2)",backdropFilter:u?"blur(12px)":"none",WebkitBackdropFilter:u?"blur(12px)":"none"},children:[s.jsx("a",{href:"/",style:{color:u?"#1d9bf0":"var(--accent)",textDecoration:"none",fontSize:"13px",flexShrink:0},children:"← Archive"}),s.jsx("span",{style:{flex:1,fontSize:"14px",fontWeight:600,color:u?"#e7e9ea":"var(--ink)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:y}),g&&s.jsx("a",{href:g,target:"_blank",rel:"noopener noreferrer",style:{color:u?"#71767b":"var(--muted)",textDecoration:"none",fontSize:"13px",flexShrink:0},children:"Original ↗"})]}),s.jsxs("div",{style:u?{flex:1}:{flex:1,minHeight:0,overflow:"auto",display:"flex",flexDirection:"column"},children:[l&&s.jsx("div",{style:{padding:"48px",textAlign:"center",color:"var(--muted)",fontSize:"14px"},children:"Loading…"}),a&&s.jsx("div",{style:{padding:"48px",textAlign:"center",color:"var(--alert)",fontSize:"14px"},children:a}),n&&s.jsx(kf,{archiveId:e,entry:n.summary,detail:n,fullPage:!0,onXArticle:d})]})]})}const Xg=7e3;function Jg({toasts:e,onDismiss:t,onIgnoreUblock:n}){return e.length?s.jsx("div",{className:"toast-stack",role:"log","aria-live":"polite","aria-label":"Notifications",children:e.map(r=>s.jsx(Yg,{toast:r,onDismiss:t,onIgnoreUblock:n},r.id))}):null}function Gg(e){if(!e)return null;if(e.length<=52)return e;try{const{hostname:t,pathname:n,search:r}=new URL(e),l=n.split("/").filter(Boolean),i=(l[l.length-1]??"")+r,a=i?`${t}/…/${i}`:t;return a.length<=56?a:a.slice(0,53)+"…"}catch{return"…"+e.slice(-51)}}function Yg({toast:e,onDismiss:t,onIgnoreUblock:n}){const[r,l]=c.useState(!1),i=e.type==="warning",a=e.type==="success";c.useEffect(()=>{if(r)return;const u=setTimeout(()=>t(e.id),Xg);return()=>clearTimeout(u)},[r,e.id,t]);const o=Gg(e.locator);return a?s.jsx("div",{className:"toast toast--success",role:"alert","aria-atomic":"true",children:s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✓"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Archived"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsx("div",{className:"toast-btns",children:s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})})]})}):i?s.jsxs("div",{className:"toast toast--warning",role:"alert","aria-atomic":"true",children:[s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"⚠"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Archived with warnings"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsxs("div",{className:"toast-btns",children:[e.text&&s.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(u=>!u),"aria-expanded":r,children:r?"Hide":"Details"}),e.locator&&s.jsx("button",{type:"button",className:"toast-view-btn toast-ignore-btn",onClick:()=>{n==null||n(),t(e.id)},children:"Ignore"}),s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&s.jsx("p",{className:"toast-warning-detail",children:e.text||"The page was captured but one or more browser extensions were unavailable (ad-blocking or cookie-consent). Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config."})]}):s.jsxs("div",{className:"toast toast--error",role:"alert","aria-atomic":"true",children:[s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✕"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Capture failed"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsxs("div",{className:"toast-btns",children:[e.text&&s.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(u=>!u),children:r?"Hide":"View error"}),s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&e.text&&s.jsx("pre",{className:"toast-error-detail",children:e.text})]})}const Vs=c.createContext(null),Zg=["archive","tags","collections","runs","admin","settings"],ey=["profile","tokens","instance","cookies","extensions","storage"],Dr=(()=>{const e=window.location.pathname.match(/^\/preview\/([^/]+)\/([^/]+)/);return e?{archiveId:e[1],entryUid:e[2]}:null})();function Ft(){const e=window.location.pathname.split("/").filter(Boolean),t=Zg.includes(e[0])?e[0]:"archive",n=t==="settings"&&ey.includes(e[1])?e[1]:"profile",r=new URLSearchParams(window.location.search),l=r.get("q")??"",i=t==="archive"?r.get("tag")??null:null,a=t==="archive"?r.get("entry")??null:null,o=t==="archive"?r.get("collection")??null:null,u=o==="main"?null:o,d=r.get("archive")??null;return{view:t,settingsTab:n,q:l,tag:i,entry:a,collection:u,archive:d}}function ty(e,t){return e==="archive"?"/":e==="settings"?`/settings/${t}`:`/${e}`}function ny(){const[e,t]=c.useState("loading"),[n,r]=c.useState(null);c.useEffect(()=>{(async()=>{var A,Q,J;if(await dm()){t("setup");return}const z=await mm();if(!z){const{collection:le,archive:_e}=Ft();try{const Ue=await Ru(),ke=_e?((A=Ue.find(qn=>qn.id===_e))==null?void 0:A.id)??((Q=Ue[0])==null?void 0:Q.id):(J=Ue[0])==null?void 0:J.id;if(ke){await zu(ke,le),i(Ue),o(ke),d(le),t("authenticated");return}}catch{}t("login");return}r(z),t("authenticated")})()},[]),c.useEffect(()=>{const _=()=>{n&&(r(null),t("login"))};return window.addEventListener("auth:expired",_),()=>window.removeEventListener("auth:expired",_)},[n]),c.useEffect(()=>{const _=()=>{const{view:z,settingsTab:A,q:Q,tag:J,entry:le,collection:_e}=Ft();P(z),X(A),Y(Q),T(J),p(le),m(null),C(le?new Set([le]):new Set),d(_e)};return window.addEventListener("popstate",_),()=>window.removeEventListener("popstate",_)},[]);const[l,i]=c.useState([]),[a,o]=c.useState(null),[u,d]=c.useState(()=>Ft().collection),[y,g]=c.useState([]),[h,v]=c.useState([]),[x,S]=c.useState(()=>new Set),[N,p]=c.useState(()=>Ft().entry),[f,m]=c.useState(null),[k,C]=c.useState(()=>{const _=Ft().entry;return _?new Set([_]):new Set}),[E,T]=c.useState(()=>Ft().tag),[j,P]=c.useState(()=>Ft().view),[R,X]=c.useState(()=>Ft().settingsTab),[H,Y]=c.useState(()=>Ft().q),[te,fe]=c.useState(""),[Be,we]=c.useState(!1),[M,L]=c.useState([]),[V,G]=c.useState([]),[ne,se]=c.useState(()=>sessionStorage.getItem("captureDialogOpen")==="true"),[Z,Se]=c.useState([]),ce=c.useRef(0),[Ie,at]=c.useState(()=>{try{const _=JSON.parse(sessionStorage.getItem("pendingCaptures")||"[]");if(Array.isArray(_))return _}catch{}return[]});c.useEffect(()=>{sessionStorage.setItem("pendingCaptures",JSON.stringify(Ie))},[Ie]);const[ht,Vt]=c.useState(()=>sessionStorage.getItem("ublockWarningIgnored")==="true"),[Qt,jt]=c.useState(null),Oe=c.useRef(0),Je=c.useRef(null),tt=c.useRef(!1),D=c.useRef(!0),K=c.useRef(null),Ne=c.useRef(0),Ve=c.useRef(new Map),qt=(n==null?void 0:n.humanize_slugs)??!1;c.useEffect(()=>{const _=++Oe.current;jt(null),!(!f||!a)&&Br(a,f.entry_uid).then(z=>{_===Oe.current&&jt(z)}).catch(()=>{})},[f,a]),c.useEffect(()=>{sessionStorage.setItem("captureDialogOpen",ne)},[ne]);const Qe=c.useCallback(async(_,z,A,Q)=>{if(_){we(!0);try{let J;z||A?J=await Kh(_,z,A,Q):J=await zu(_,Q),v(J),C(le=>{if(le.size<2)return le;const _e=new Set(J.map(ke=>ke.entry_uid)),Ue=new Set([...le].filter(ke=>_e.has(ke)));return Ue.size===le.size?le:Ue}),fe(J.length===0?"No results":`${J.length} result${J.length===1?"":"s"}`)}catch{v([]),fe("Search failed. Try again.")}finally{we(!1)}}},[]);c.useEffect(()=>{e==="authenticated"&&(a||Ru().then(_=>{if(i(_),_.length>0){const{archive:z}=Ft(),A=z?_.find(Q=>Q.id===z):null;o((A==null?void 0:A.id)??_[0].id)}}))},[e,a]),c.useEffect(()=>{if(!a)return;const _=!n;if(D.current){D.current=!1;const A=[];_||(A.push(_i(a).then(L)),A.push(Ul(a).then(G))),A.length&&Promise.all(A);return}T(null),m(null),p(null),C(new Set),d(null);const z=[Qe(a,"",null,null)];_||(z.push(_i(a).then(L)),z.push(Ul(a).then(G))),Promise.all(z)},[a,n]),c.useEffect(()=>{if(a===null)return;const _=setTimeout(()=>{Qe(a,H,E,u)},300);return()=>clearTimeout(_)},[H,a,u]),c.useEffect(()=>{a!==null&&(E!==null&&P("archive"),Qe(a,H,E,u))},[E,a,u]);const Kt=c.useCallback(_=>{o(_),d(null);const z=new URLSearchParams(window.location.search);z.set("archive",_),z.delete("collection");const A=z.toString();history.replaceState(null,"",window.location.pathname+(A?"?"+A:""))},[]);c.useEffect(()=>{if(!a){g([]);return}wo(a).then(g).catch(()=>g([]))},[a]);const Qn=c.useCallback(_=>{if(!n){const Q=_?y.find(J=>J.collection_uid===_):y.find(J=>J.slug==="_default_");if(Q!=null&&Q.requires_auth){t("login");return}}d(_),m(null),p(null),C(new Set),Qe(a,H,E,_);const z=new URLSearchParams(window.location.search);_?(z.set("collection",_),z.set("archive",a)):(z.delete("collection"),a&&z.set("archive",a));const A=z.toString();history.replaceState(null,"",window.location.pathname+(A?"?"+A:""))},[a,H,E,n,y,Qe]),Ot=c.useCallback(_=>{P(_),_==="tags"&&a&&Ul(a).then(G)},[a]);c.useEffect(()=>{if(Dr)return;const _=ty(j,R);window.location.pathname!==_&&history.pushState(null,"",_+window.location.search)},[j,R]);const Le=c.useCallback(_=>{p(_?_.entry_uid:null),m(_)},[]),bn=c.useCallback((_,z)=>{if(Ve.current.set(_.entry_uid,_),++Ne.current,z.shiftKey&&K.current!==null){z.preventDefault();const A=[...document.querySelectorAll("#entries-body [data-entry-uid]")],Q=A.findIndex(ke=>ke.dataset.entryUid===K.current),J=A.findIndex(ke=>ke.dataset.entryUid===_.entry_uid);if(Q===-1||J===-1){K.current=_.entry_uid,C(new Set([_.entry_uid])),Le(_);return}const le=Math.min(Q,J),_e=Math.max(Q,J),Ue=new Set(A.slice(le,_e+1).map(ke=>ke.dataset.entryUid));C(Ue),Ue.size===1&&Le(_)}else if(z.ctrlKey||z.metaKey){K.current=_.entry_uid;const A=new Set(k);if(A.has(_.entry_uid)?A.delete(_.entry_uid):A.add(_.entry_uid),C(A),A.size===0)Le(null);else if(A.size===1){const[Q]=A,J=Ve.current.get(Q)??h.find(le=>le.entry_uid===Q)??null;if(J)Le(J);else{const le=++Ne.current;Br(a,Q).then(_e=>{le===Ne.current&&(_e!=null&&_e.summary)&&Le(_e.summary)}).catch(()=>{})}}else Le(null)}else K.current=_.entry_uid,C(new Set([_.entry_uid])),Le(_)},[h,k,Le,a]),At=c.useCallback(_=>{T(_)},[]),w=c.useCallback(()=>{T(null)},[]),B=c.useCallback(()=>{a&&Ul(a).then(G)},[a]),O=c.useCallback((_,z)=>{E===_?T(z):E!=null&&E.startsWith(_+"/")&&T(z+E.slice(_.length))},[E]),$=c.useCallback(_=>{(E===_||E!=null&&E.startsWith(_+"/"))&&T(null)},[E]),F=c.useCallback((_,z)=>{v(A=>A.map(Q=>Q.entry_uid===_?{...Q,title:z}:Q)),m(A=>A&&A.entry_uid===_?{...A,title:z}:A),jt(A=>A&&A.summary.entry_uid===_?{...A,summary:{...A.summary,title:z}}:A)},[]),U=c.useCallback(()=>{if(!a||!f)return;const _=++Oe.current;Br(a,f.entry_uid).then(z=>{_===Oe.current&&jt(z)}).catch(()=>{})},[a,f]),ye=c.useCallback(_=>{const z=h.some(A=>A.entry_uid===_);S(A=>{const Q=new Set(A);return Q.add(_),Q}),v(A=>A.filter(Q=>Q.entry_uid!==_)),m(A=>(A==null?void 0:A.entry_uid)===_?null:A),p(A=>A===_?null:A),C(A=>{const Q=new Set(A);return Q.delete(_),Q}),z||Qe(a,H,E,u)},[h,a,H,E,u,Qe]),ue=c.useCallback(_=>{const z=new Set(h.map(Q=>Q.entry_uid)),A=[..._].some(Q=>!z.has(Q));S(Q=>{const J=new Set(Q);return _.forEach(le=>J.add(le)),J}),v(Q=>Q.filter(J=>!_.has(J.entry_uid))),C(new Set),m(null),p(null),A&&Qe(a,H,E,u)},[h,a,H,E,u,Qe]);c.useEffect(()=>{if(k.size>=2)p(null),m(null);else if(k.size===1){const[_]=k;p(_)}else p(null),m(null)},[k]);const Te=c.useMemo(()=>h.filter(_=>k.has(_.entry_uid)),[h,k]);c.useEffect(()=>{if(!N||f)return;const _=h.find(z=>z.entry_uid===N);_&&m(_)},[h,N,f]),c.useEffect(()=>{if(Dr)return;const _=new URLSearchParams(window.location.search).get("archive"),z=new URLSearchParams;H&&z.set("q",H),j==="archive"&&E&&z.set("tag",E),j==="archive"&&N&&z.set("entry",N),j==="archive"&&u?(z.set("collection",u),a&&z.set("archive",a)):_&&a&&z.set("archive",a);const A=z.toString(),Q=window.location.pathname+(A?"?"+A:"");window.location.pathname+window.location.search!==Q&&history.replaceState(null,"",Q)},[H,E,N,u,a,j]),c.useEffect(()=>{const _=z=>{var le,_e,Ue,ke;const A=z.key==="/"&&!z.metaKey&&!z.ctrlKey&&!z.altKey,Q=(z.metaKey||z.ctrlKey)&&z.key==="k";if(!A&&!Q)return;const J=(le=document.activeElement)==null?void 0:le.tagName;A&&(J==="INPUT"||J==="TEXTAREA"||J==="SELECT")||A&&((_e=document.activeElement)!=null&&_e.isContentEditable)||(z.preventDefault(),j==="archive"?((Ue=Je.current)==null||Ue.focus(),(ke=Je.current)==null||ke.select()):(tt.current=!0,P("archive")))};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[j]),c.useEffect(()=>{const _=z=>{var Er,b;if(z.metaKey||z.ctrlKey||z.altKey||z.key!=="j"&&z.key!=="k")return;const A=(Er=document.activeElement)==null?void 0:Er.tagName;if(A==="INPUT"||A==="TEXTAREA"||A==="SELECT"||(b=document.activeElement)!=null&&b.isContentEditable)return;const Q=[...document.querySelectorAll("#entries-body [data-entry-uid]")];if(Q.length===0)return;const[J]=k.size===1?k:[null],le=J?Q.findIndex(q=>q.dataset.entryUid===J):-1,_e=z.key==="j"?Math.min(le+1,Q.length-1):Math.max(le-1,0);if(_e===le&&le!==-1)return;const Ue=Q[_e<0?0:_e],ke=Ue.dataset.entryUid;K.current=ke;const qn=++Ne.current;C(new Set([ke]));const Cr=Ve.current.get(ke)??h.find(q=>q.entry_uid===ke)??null;Cr?Le(Cr):Br(a,ke).then(q=>{qn===Ne.current&&(q!=null&&q.summary)&&Le(q.summary)}).catch(()=>{}),Ue.scrollIntoView({block:"nearest"}),z.preventDefault()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[k,h,Le,a]),c.useEffect(()=>{j==="archive"&&tt.current&&(tt.current=!1,requestAnimationFrame(()=>{var _,z;(_=Je.current)==null||_.focus(),(z=Je.current)==null||z.select()}))},[j]);const pe=c.useCallback(()=>{se(!0)},[]),$e=c.useCallback(()=>{se(!1)},[]),ie=c.useCallback(()=>{if(a)return Promise.allSettled([Qe(a,H,E,u),_i(a).then(L)])},[a,H,E,u,Qe]),nt=c.useCallback((_,z,A="error",Q=null)=>{if(A==="warning"&&ht&&z)return;const J=++ce.current;Se(le=>[...le,{id:J,text:_,locator:z,type:A,headline:Q}])},[ht]),ot=c.useCallback(_=>{Se(z=>z.filter(A=>A.id!==_))},[]),Qs=c.useCallback(()=>{sessionStorage.setItem("ublockWarningIgnored","true"),Vt(!0),Se(_=>_.filter(z=>!(z.type==="warning"&&z.locator)))},[]),qs=c.useCallback(_=>{at(z=>[...z,_])},[]),Ks=c.useCallback(_=>{at(z=>z.filter(A=>A.id!==_))},[]),[Tn,_r]=c.useState(null),[Pn,jl]=c.useState(null),Sl=c.useCallback(()=>{f&&_r(f.entry_uid)},[f]),Xs=c.useCallback(()=>_r(null),[]),Js=c.useCallback((_,z)=>{jl({src:_,entry:z})},[]),Gs=c.useCallback(()=>jl(null),[]);return c.useEffect(()=>{_r(null)},[f]),c.useEffect(()=>{const _=z=>{var Q,J,le;if(z.key!=="Escape"||ne||Tn)return;const A=(Q=document.activeElement)==null?void 0:Q.tagName;A==="INPUT"||A==="TEXTAREA"||A==="SELECT"||k.size>0&&(z.preventDefault(),C(new Set),(le=(J=document.activeElement)==null?void 0:J.blur)==null||le.call(J))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[ne,Tn,k]),c.useEffect(()=>(document.body.classList.toggle("has-audio-bar",!!Pn),()=>document.body.classList.remove("has-audio-bar")),[Pn]),Dr?s.jsx(Kg,{archiveId:Dr.archiveId,entryUid:Dr.entryUid}):e==="loading"?s.jsx("div",{className:"auth-loading",children:"Loading\\u2026"}):e==="setup"?s.jsx(Hm,{onComplete:()=>t("login")}):e==="login"?s.jsx(Um,{onLogin:_=>{r(_),t("authenticated")}}):s.jsx(Vs.Provider,{value:{currentUser:n,setCurrentUser:r},children:s.jsxs(s.Fragment,{children:[s.jsx(Wm,{archives:l,archiveId:a,onArchiveChange:Kt,view:j,onViewChange:Ot,onCaptureClick:pe,collections:y,selectedCollectionUid:u,onCollectionChange:Qn,isPublicSession:!n,onSignInClick:()=>t("login")}),s.jsxs("main",{className:"app-shell",children:[s.jsxs("div",{className:"workspace",children:[j==="archive"&&s.jsxs("div",{className:"toolbar",children:[s.jsxs("div",{className:"search-field",children:[s.jsx("span",{className:"ico","aria-hidden":"true",children:s.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("circle",{cx:"11",cy:"11",r:"7"}),s.jsx("line",{x1:"16.5",y1:"16.5",x2:"21",y2:"21"})]})}),s.jsx("input",{ref:Je,className:"search-input",type:"search","aria-label":"Search archive","aria-busy":Be,placeholder:"Search titles, URLs, types, tags…",value:H,onChange:_=>Y(_.target.value)}),s.jsx("span",{className:"kbd",children:"⌘K"})]}),s.jsxs("span",{className:"result-count",children:[te&&s.jsxs(s.Fragment,{children:[s.jsx("b",{children:te.split(" ")[0]})," ",te.split(" ").slice(1).join(" ")]}),E&&s.jsxs("button",{className:"tag-filter-badge",onClick:w,children:["× ",qt?cf(E):E]})]})]}),j==="archive"&&s.jsx(sg,{entries:h,selectedUids:k,onRowClick:bn,archiveId:a,pendingCaptures:Ie,deletedUids:x,isPublicSession:!n}),j==="runs"&&s.jsx(og,{runs:M}),j==="admin"&&s.jsx(cg,{archives:l}),j==="tags"&&s.jsx(dg,{archiveId:a,tagNodes:V,tagFilter:E,onTagFilterSet:At,onViewChange:Ot,onTagRenamed:O,onTagDeleted:$,onTagsRefresh:B,humanizeTags:qt}),j==="collections"&&s.jsx(pg,{archiveId:a}),j==="settings"&&s.jsx(mg,{tab:R,onTabChange:X,archiveId:a})]}),s.jsx(Cg,{archiveId:a,selectedEntry:f,selectedUids:k,selectedEntries:Te,detail:Qt,onTagFilterSet:At,tagNodes:V,onTagsRefresh:B,onEntryTitleChange:F,onEntryDeleted:ye,onBulkDeleted:ue,humanizeTags:qt,onDetailRefresh:U,onOpenPreview:Sl,onPlay:Js,isPublicSession:!n})]}),Tn&&f&&f.entry_uid===Tn&&s.jsx(Qg,{archiveId:a,entry:f,detail:Qt,onClose:Xs}),Pn&&s.jsx(qg,{entry:Pn.entry,src:Pn.src,archiveId:a,onClose:Gs}),s.jsx(Km,{open:ne,archiveId:a,onClose:$e,onCaptured:ie,onToast:nt,activeJobs:Ie,onJobStarted:qs,onJobSettled:Ks}),s.jsx(Jg,{toasts:Z,onDismiss:ot,onIgnoreUblock:Qs})]})})}af(document.getElementById("root")).render(s.jsx(c.StrictMode,{children:s.jsx(ny,{})})); diff --git a/crates/archivr-server/static/assets/index-B67momER.js b/crates/archivr-server/static/assets/index-B67momER.js deleted file mode 100644 index 0bff979..0000000 --- a/crates/archivr-server/static/assets/index-B67momER.js +++ /dev/null @@ -1,47 +0,0 @@ -(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const i of l)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(l){const i={};return l.integrity&&(i.integrity=l.integrity),l.referrerPolicy&&(i.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?i.credentials="include":l.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(l){if(l.ep)return;l.ep=!0;const i=n(l);fetch(l.href,i)}})();var $u={exports:{}},ks={},Ou={exports:{}},ne={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var dl=Symbol.for("react.element"),cf=Symbol.for("react.portal"),df=Symbol.for("react.fragment"),ff=Symbol.for("react.strict_mode"),pf=Symbol.for("react.profiler"),hf=Symbol.for("react.provider"),mf=Symbol.for("react.context"),gf=Symbol.for("react.forward_ref"),yf=Symbol.for("react.suspense"),vf=Symbol.for("react.memo"),xf=Symbol.for("react.lazy"),po=Symbol.iterator;function wf(e){return e===null||typeof e!="object"?null:(e=po&&e[po]||e["@@iterator"],typeof e=="function"?e:null)}var Au={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Mu=Object.assign,Fu={};function yr(e,t,n){this.props=e,this.context=t,this.refs=Fu,this.updater=n||Au}yr.prototype.isReactComponent={};yr.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};yr.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Bu(){}Bu.prototype=yr.prototype;function da(e,t,n){this.props=e,this.context=t,this.refs=Fu,this.updater=n||Au}var fa=da.prototype=new Bu;fa.constructor=da;Mu(fa,yr.prototype);fa.isPureReactComponent=!0;var ho=Array.isArray,Uu=Object.prototype.hasOwnProperty,pa={current:null},Hu={key:!0,ref:!0,__self:!0,__source:!0};function Wu(e,t,n){var r,l={},i=null,a=null;if(t!=null)for(r in t.ref!==void 0&&(a=t.ref),t.key!==void 0&&(i=""+t.key),t)Uu.call(t,r)&&!Hu.hasOwnProperty(r)&&(l[r]=t[r]);var o=arguments.length-2;if(o===1)l.children=n;else if(1>>1,ee=D[te];if(0>>1;tel(ye,H))cel(Ee,ye)?(D[te]=Ee,D[ce]=H,te=ce):(D[te]=ye,D[Y]=H,te=Y);else if(cel(Ee,H))D[te]=Ee,D[ce]=H,te=ce;else break e}}return P}function l(D,P){var H=D.sortIndex-P.sortIndex;return H!==0?H:D.id-P.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var a=Date,o=a.now();e.unstable_now=function(){return a.now()-o}}var u=[],c=[],y=1,g=null,h=3,v=!1,x=!1,S=!1,N=typeof setTimeout=="function"?setTimeout:null,p=typeof clearTimeout=="function"?clearTimeout:null,f=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function m(D){for(var P=n(c);P!==null;){if(P.callback===null)r(c);else if(P.startTime<=D)r(c),P.sortIndex=P.expirationTime,t(u,P);else break;P=n(c)}}function w(D){if(S=!1,m(D),!x)if(n(u)!==null)x=!0,Ae(C);else{var P=n(c);P!==null&&ge(w,P.startTime-D)}}function C(D,P){x=!1,S&&(S=!1,p(k),k=-1),v=!0;var H=h;try{for(m(P),g=n(u);g!==null&&(!(g.expirationTime>P)||D&&!q());){var te=g.callback;if(typeof te=="function"){g.callback=null,h=g.priorityLevel;var ee=te(g.expirationTime<=P);P=e.unstable_now(),typeof ee=="function"?g.callback=ee:g===n(u)&&r(u),m(P)}else r(u);g=n(u)}if(g!==null)var Re=!0;else{var Y=n(c);Y!==null&&ge(w,Y.startTime-P),Re=!1}return Re}finally{g=null,h=H,v=!1}}var E=!1,b=null,k=-1,T=5,L=-1;function q(){return!(e.unstable_now()-LD||125te?(D.sortIndex=H,t(c,D),n(u)===null&&D===n(c)&&(S?(p(k),k=-1):S=!0,ge(w,H-te))):(D.sortIndex=ee,t(u,D),x||v||(x=!0,Ae(C))),D},e.unstable_shouldYield=q,e.unstable_wrapCallback=function(D){var P=h;return function(){var H=h;h=P;try{return D.apply(this,arguments)}finally{h=H}}}})(Xu);qu.exports=Xu;var Lf=qu.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Rf=d,ht=Lf;function R(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),vi=Object.prototype.hasOwnProperty,zf=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,go={},yo={};function If(e){return vi.call(yo,e)?!0:vi.call(go,e)?!1:zf.test(e)?yo[e]=!0:(go[e]=!0,!1)}function Df(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function $f(e,t,n,r){if(t===null||typeof t>"u"||Df(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function nt(e,t,n,r,l,i,a){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=a}var We={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){We[e]=new nt(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];We[t]=new nt(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){We[e]=new nt(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){We[e]=new nt(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){We[e]=new nt(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){We[e]=new nt(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){We[e]=new nt(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){We[e]=new nt(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){We[e]=new nt(e,5,!1,e.toLowerCase(),null,!1,!1)});var ma=/[\-:]([a-z])/g;function ga(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(ma,ga);We[t]=new nt(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(ma,ga);We[t]=new nt(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(ma,ga);We[t]=new nt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){We[e]=new nt(e,1,!1,e.toLowerCase(),null,!1,!1)});We.xlinkHref=new nt("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){We[e]=new nt(e,1,!1,e.toLowerCase(),null,!0,!0)});function ya(e,t,n,r){var l=We.hasOwnProperty(t)?We[t]:null;(l!==null?l.type!==0:r||!(2o||l[a]!==i[o]){var u=` -`+l[a].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=a&&0<=o);break}}}finally{Us=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Rr(e):""}function Of(e){switch(e.tag){case 5:return Rr(e.type);case 16:return Rr("Lazy");case 13:return Rr("Suspense");case 19:return Rr("SuspenseList");case 0:case 2:case 15:return e=Hs(e.type,!1),e;case 11:return e=Hs(e.type.render,!1),e;case 1:return e=Hs(e.type,!0),e;default:return""}}function ji(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Qn:return"Fragment";case Vn:return"Portal";case xi:return"Profiler";case va:return"StrictMode";case wi:return"Suspense";case ki:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Yu:return(e.displayName||"Context")+".Consumer";case Gu:return(e._context.displayName||"Context")+".Provider";case xa:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case wa:return t=e.displayName||null,t!==null?t:ji(e.type)||"Memo";case ln:t=e._payload,e=e._init;try{return ji(e(t))}catch{}}return null}function Af(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ji(t);case 8:return t===va?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function xn(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function ec(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Mf(e){var t=ec(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(a){r=""+a,i.call(this,a)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(a){r=""+a},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function xl(e){e._valueTracker||(e._valueTracker=Mf(e))}function tc(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=ec(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Xl(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Si(e,t){var n=t.checked;return Se({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function xo(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=xn(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function nc(e,t){t=t.checked,t!=null&&ya(e,"checked",t,!1)}function Ni(e,t){nc(e,t);var n=xn(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?_i(e,t.type,n):t.hasOwnProperty("defaultValue")&&_i(e,t.type,xn(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function wo(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function _i(e,t,n){(t!=="number"||Xl(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var zr=Array.isArray;function rr(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=wl.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function qr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Ar={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Ff=["Webkit","ms","Moz","O"];Object.keys(Ar).forEach(function(e){Ff.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Ar[t]=Ar[e]})});function ic(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Ar.hasOwnProperty(e)&&Ar[e]?(""+t).trim():t+"px"}function ac(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=ic(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var Bf=Se({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function bi(e,t){if(t){if(Bf[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(R(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(R(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(R(61))}if(t.style!=null&&typeof t.style!="object")throw Error(R(62))}}function Ti(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Pi=null;function ka(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Li=null,lr=null,sr=null;function So(e){if(e=hl(e)){if(typeof Li!="function")throw Error(R(280));var t=e.stateNode;t&&(t=Cs(t),Li(e.stateNode,e.type,t))}}function oc(e){lr?sr?sr.push(e):sr=[e]:lr=e}function uc(){if(lr){var e=lr,t=sr;if(sr=lr=null,So(e),t)for(e=0;e>>=0,e===0?32:31-(Yf(e)/Zf|0)|0}var kl=64,jl=4194304;function Ir(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Zl(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,a=n&268435455;if(a!==0){var o=a&~l;o!==0?r=Ir(o):(i&=a,i!==0&&(r=Ir(i)))}else a=n&~l,a!==0?r=Ir(a):i!==0&&(r=Ir(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,i=t&-t,l>=i||l===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function fl(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Rt(t),e[t]=n}function rp(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Fr),Ro=" ",zo=!1;function Tc(e,t){switch(e){case"keyup":return Lp.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Pc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Kn=!1;function zp(e,t){switch(e){case"compositionend":return Pc(t);case"keypress":return t.which!==32?null:(zo=!0,Ro);case"textInput":return e=t.data,e===Ro&&zo?null:e;default:return null}}function Ip(e,t){if(Kn)return e==="compositionend"||!Ta&&Tc(e,t)?(e=Ec(),Ml=Ca=un=null,Kn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Oo(n)}}function Ic(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Ic(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Dc(){for(var e=window,t=Xl();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Xl(e.document)}return t}function Pa(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Hp(e){var t=Dc(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Ic(n.ownerDocument.documentElement,n)){if(r!==null&&Pa(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,i=Math.min(r.start,l);r=r.end===void 0?i:Math.min(r.end,l),!e.extend&&i>r&&(l=r,r=i,i=l),l=Ao(n,i);var a=Ao(n,r);l&&a&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,qn=null,Oi=null,Ur=null,Ai=!1;function Mo(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Ai||qn==null||qn!==Xl(r)||(r=qn,"selectionStart"in r&&Pa(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Ur&&el(Ur,r)||(Ur=r,r=ns(Oi,"onSelect"),0Gn||(e.current=Wi[Gn],Wi[Gn]=null,Gn--)}function fe(e,t){Gn++,Wi[Gn]=e.current,e.current=t}var wn={},Ge=jn(wn),it=jn(!1),zn=wn;function dr(e,t){var n=e.type.contextTypes;if(!n)return wn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in n)l[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function at(e){return e=e.childContextTypes,e!=null}function ls(){me(it),me(Ge)}function Qo(e,t,n){if(Ge.current!==wn)throw Error(R(168));fe(Ge,t),fe(it,n)}function Wc(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(R(108,Af(e)||"Unknown",l));return Se({},n,r)}function ss(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||wn,zn=Ge.current,fe(Ge,e),fe(it,it.current),!0}function Ko(e,t,n){var r=e.stateNode;if(!r)throw Error(R(169));n?(e=Wc(e,t,zn),r.__reactInternalMemoizedMergedChildContext=e,me(it),me(Ge),fe(Ge,e)):me(it),fe(it,n)}var Qt=null,Es=!1,ri=!1;function Vc(e){Qt===null?Qt=[e]:Qt.push(e)}function th(e){Es=!0,Vc(e)}function Sn(){if(!ri&&Qt!==null){ri=!0;var e=0,t=oe;try{var n=Qt;for(oe=1;e>=a,l-=a,Kt=1<<32-Rt(t)+l|n<k?(T=b,b=null):T=b.sibling;var L=h(p,b,m[k],w);if(L===null){b===null&&(b=T);break}e&&b&&L.alternate===null&&t(p,b),f=i(L,f,k),E===null?C=L:E.sibling=L,E=L,b=T}if(k===m.length)return n(p,b),ve&&_n(p,k),C;if(b===null){for(;kk?(T=b,b=null):T=b.sibling;var q=h(p,b,L.value,w);if(q===null){b===null&&(b=T);break}e&&b&&q.alternate===null&&t(p,b),f=i(q,f,k),E===null?C=q:E.sibling=q,E=q,b=T}if(L.done)return n(p,b),ve&&_n(p,k),C;if(b===null){for(;!L.done;k++,L=m.next())L=g(p,L.value,w),L!==null&&(f=i(L,f,k),E===null?C=L:E.sibling=L,E=L);return ve&&_n(p,k),C}for(b=r(p,b);!L.done;k++,L=m.next())L=v(b,p,k,L.value,w),L!==null&&(e&&L.alternate!==null&&b.delete(L.key===null?k:L.key),f=i(L,f,k),E===null?C=L:E.sibling=L,E=L);return e&&b.forEach(function(F){return t(p,F)}),ve&&_n(p,k),C}function N(p,f,m,w){if(typeof m=="object"&&m!==null&&m.type===Qn&&m.key===null&&(m=m.props.children),typeof m=="object"&&m!==null){switch(m.$$typeof){case vl:e:{for(var C=m.key,E=f;E!==null;){if(E.key===C){if(C=m.type,C===Qn){if(E.tag===7){n(p,E.sibling),f=l(E,m.props.children),f.return=p,p=f;break e}}else if(E.elementType===C||typeof C=="object"&&C!==null&&C.$$typeof===ln&&Jo(C)===E.type){n(p,E.sibling),f=l(E,m.props),f.ref=br(p,E,m),f.return=p,p=f;break e}n(p,E);break}else t(p,E);E=E.sibling}m.type===Qn?(f=Rn(m.props.children,p.mode,w,m.key),f.return=p,p=f):(w=Kl(m.type,m.key,m.props,null,p.mode,w),w.ref=br(p,f,m),w.return=p,p=w)}return a(p);case Vn:e:{for(E=m.key;f!==null;){if(f.key===E)if(f.tag===4&&f.stateNode.containerInfo===m.containerInfo&&f.stateNode.implementation===m.implementation){n(p,f.sibling),f=l(f,m.children||[]),f.return=p,p=f;break e}else{n(p,f);break}else t(p,f);f=f.sibling}f=di(m,p.mode,w),f.return=p,p=f}return a(p);case ln:return E=m._init,N(p,f,E(m._payload),w)}if(zr(m))return x(p,f,m,w);if(Sr(m))return S(p,f,m,w);Tl(p,m)}return typeof m=="string"&&m!==""||typeof m=="number"?(m=""+m,f!==null&&f.tag===6?(n(p,f.sibling),f=l(f,m),f.return=p,p=f):(n(p,f),f=ci(m,p.mode,w),f.return=p,p=f),a(p)):n(p,f)}return N}var pr=Xc(!0),Jc=Xc(!1),os=jn(null),us=null,er=null,Ia=null;function Da(){Ia=er=us=null}function $a(e){var t=os.current;me(os),e._currentValue=t}function Ki(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function ar(e,t){us=e,Ia=er=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(st=!0),e.firstContext=null)}function Nt(e){var t=e._currentValue;if(Ia!==e)if(e={context:e,memoizedValue:t,next:null},er===null){if(us===null)throw Error(R(308));er=e,us.dependencies={lanes:0,firstContext:e}}else er=er.next=e;return t}var bn=null;function Oa(e){bn===null?bn=[e]:bn.push(e)}function Gc(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,Oa(t)):(n.next=l.next,l.next=n),t.interleaved=n,Yt(e,r)}function Yt(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var sn=!1;function Aa(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Yc(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Xt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function mn(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,se&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,Yt(e,n)}return l=r.interleaved,l===null?(t.next=t,Oa(r)):(t.next=l.next,l.next=t),r.interleaved=t,Yt(e,n)}function Bl(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Sa(e,n)}}function Go(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var a={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?l=i=a:i=i.next=a,n=n.next}while(n!==null);i===null?l=i=t:i=i.next=t}else l=i=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function cs(e,t,n,r){var l=e.updateQueue;sn=!1;var i=l.firstBaseUpdate,a=l.lastBaseUpdate,o=l.shared.pending;if(o!==null){l.shared.pending=null;var u=o,c=u.next;u.next=null,a===null?i=c:a.next=c,a=u;var y=e.alternate;y!==null&&(y=y.updateQueue,o=y.lastBaseUpdate,o!==a&&(o===null?y.firstBaseUpdate=c:o.next=c,y.lastBaseUpdate=u))}if(i!==null){var g=l.baseState;a=0,y=c=u=null,o=i;do{var h=o.lane,v=o.eventTime;if((r&h)===h){y!==null&&(y=y.next={eventTime:v,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var x=e,S=o;switch(h=t,v=n,S.tag){case 1:if(x=S.payload,typeof x=="function"){g=x.call(v,g,h);break e}g=x;break e;case 3:x.flags=x.flags&-65537|128;case 0:if(x=S.payload,h=typeof x=="function"?x.call(v,g,h):x,h==null)break e;g=Se({},g,h);break e;case 2:sn=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,h=l.effects,h===null?l.effects=[o]:h.push(o))}else v={eventTime:v,lane:h,tag:o.tag,payload:o.payload,callback:o.callback,next:null},y===null?(c=y=v,u=g):y=y.next=v,a|=h;if(o=o.next,o===null){if(o=l.shared.pending,o===null)break;h=o,o=h.next,h.next=null,l.lastBaseUpdate=h,l.shared.pending=null}}while(!0);if(y===null&&(u=g),l.baseState=u,l.firstBaseUpdate=c,l.lastBaseUpdate=y,t=l.shared.interleaved,t!==null){l=t;do a|=l.lane,l=l.next;while(l!==t)}else i===null&&(l.shared.lanes=0);$n|=a,e.lanes=a,e.memoizedState=g}}function Yo(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=si.transition;si.transition={};try{e(!1),t()}finally{oe=n,si.transition=r}}function md(){return _t().memoizedState}function sh(e,t,n){var r=yn(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},gd(e))yd(t,n);else if(n=Gc(e,t,n,r),n!==null){var l=et();zt(n,e,r,l),vd(n,t,r)}}function ih(e,t,n){var r=yn(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(gd(e))yd(t,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var a=t.lastRenderedState,o=i(a,n);if(l.hasEagerState=!0,l.eagerState=o,It(o,a)){var u=t.interleaved;u===null?(l.next=l,Oa(t)):(l.next=u.next,u.next=l),t.interleaved=l;return}}catch{}finally{}n=Gc(e,t,l,r),n!==null&&(l=et(),zt(n,e,r,l),vd(n,t,r))}}function gd(e){var t=e.alternate;return e===je||t!==null&&t===je}function yd(e,t){Hr=fs=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function vd(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Sa(e,n)}}var ps={readContext:Nt,useCallback:qe,useContext:qe,useEffect:qe,useImperativeHandle:qe,useInsertionEffect:qe,useLayoutEffect:qe,useMemo:qe,useReducer:qe,useRef:qe,useState:qe,useDebugValue:qe,useDeferredValue:qe,useTransition:qe,useMutableSource:qe,useSyncExternalStore:qe,useId:qe,unstable_isNewReconciler:!1},ah={readContext:Nt,useCallback:function(e,t){return Mt().memoizedState=[e,t===void 0?null:t],e},useContext:Nt,useEffect:eu,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Hl(4194308,4,cd.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Hl(4194308,4,e,t)},useInsertionEffect:function(e,t){return Hl(4,2,e,t)},useMemo:function(e,t){var n=Mt();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Mt();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=sh.bind(null,je,e),[r.memoizedState,e]},useRef:function(e){var t=Mt();return e={current:e},t.memoizedState=e},useState:Zo,useDebugValue:Qa,useDeferredValue:function(e){return Mt().memoizedState=e},useTransition:function(){var e=Zo(!1),t=e[0];return e=lh.bind(null,e[1]),Mt().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=je,l=Mt();if(ve){if(n===void 0)throw Error(R(407));n=n()}else{if(n=t(),Fe===null)throw Error(R(349));Dn&30||nd(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,eu(ld.bind(null,r,i,e),[e]),r.flags|=2048,ol(9,rd.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Mt(),t=Fe.identifierPrefix;if(ve){var n=qt,r=Kt;n=(r&~(1<<32-Rt(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=il++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=a.createElement(n,{is:r.is}):(e=a.createElement(n),n==="select"&&(a=e,r.multiple?a.multiple=!0:r.size&&(a.size=r.size))):e=a.createElementNS(e,n),e[Ft]=t,e[rl]=r,bd(e,t,!1,!1),t.stateNode=e;e:{switch(a=Ti(n,r),n){case"dialog":he("cancel",e),he("close",e),l=r;break;case"iframe":case"object":case"embed":he("load",e),l=r;break;case"video":case"audio":for(l=0;lgr&&(t.flags|=128,r=!0,Tr(i,!1),t.lanes=4194304)}else{if(!r)if(e=ds(a),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Tr(i,!0),i.tail===null&&i.tailMode==="hidden"&&!a.alternate&&!ve)return Xe(t),null}else 2*Ce()-i.renderingStartTime>gr&&n!==1073741824&&(t.flags|=128,r=!0,Tr(i,!1),t.lanes=4194304);i.isBackwards?(a.sibling=t.child,t.child=a):(n=i.last,n!==null?n.sibling=a:t.child=a,i.last=a)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Ce(),t.sibling=null,n=ke.current,fe(ke,r?n&1|2:n&1),t):(Xe(t),null);case 22:case 23:return Ya(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?ct&1073741824&&(Xe(t),t.subtreeFlags&6&&(t.flags|=8192)):Xe(t),null;case 24:return null;case 25:return null}throw Error(R(156,t.tag))}function mh(e,t){switch(Ra(t),t.tag){case 1:return at(t.type)&&ls(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return hr(),me(it),me(Ge),Ba(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Fa(t),null;case 13:if(me(ke),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(R(340));fr()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return me(ke),null;case 4:return hr(),null;case 10:return $a(t.type._context),null;case 22:case 23:return Ya(),null;case 24:return null;default:return null}}var Ll=!1,Je=!1,gh=typeof WeakSet=="function"?WeakSet:Set,U=null;function tr(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){_e(e,t,r)}else n.current=null}function na(e,t,n){try{n()}catch(r){_e(e,t,r)}}var du=!1;function yh(e,t){if(Mi=es,e=Dc(),Pa(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var a=0,o=-1,u=-1,c=0,y=0,g=e,h=null;t:for(;;){for(var v;g!==n||l!==0&&g.nodeType!==3||(o=a+l),g!==i||r!==0&&g.nodeType!==3||(u=a+r),g.nodeType===3&&(a+=g.nodeValue.length),(v=g.firstChild)!==null;)h=g,g=v;for(;;){if(g===e)break t;if(h===n&&++c===l&&(o=a),h===i&&++y===r&&(u=a),(v=g.nextSibling)!==null)break;g=h,h=g.parentNode}g=v}n=o===-1||u===-1?null:{start:o,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(Fi={focusedElem:e,selectionRange:n},es=!1,U=t;U!==null;)if(t=U,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,U=e;else for(;U!==null;){t=U;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var S=x.memoizedProps,N=x.memoizedState,p=t.stateNode,f=p.getSnapshotBeforeUpdate(t.elementType===t.type?S:Tt(t.type,S),N);p.__reactInternalSnapshotBeforeUpdate=f}break;case 3:var m=t.stateNode.containerInfo;m.nodeType===1?m.textContent="":m.nodeType===9&&m.documentElement&&m.removeChild(m.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(R(163))}}catch(w){_e(t,t.return,w)}if(e=t.sibling,e!==null){e.return=t.return,U=e;break}U=t.return}return x=du,du=!1,x}function Wr(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&na(t,n,i)}l=l.next}while(l!==r)}}function Ps(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function ra(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Ld(e){var t=e.alternate;t!==null&&(e.alternate=null,Ld(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Ft],delete t[rl],delete t[Hi],delete t[Zp],delete t[eh])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Rd(e){return e.tag===5||e.tag===3||e.tag===4}function fu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Rd(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function la(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=rs));else if(r!==4&&(e=e.child,e!==null))for(la(e,t,n),e=e.sibling;e!==null;)la(e,t,n),e=e.sibling}function sa(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(sa(e,t,n),e=e.sibling;e!==null;)sa(e,t,n),e=e.sibling}var Ue=null,Pt=!1;function rn(e,t,n){for(n=n.child;n!==null;)zd(e,t,n),n=n.sibling}function zd(e,t,n){if(Bt&&typeof Bt.onCommitFiberUnmount=="function")try{Bt.onCommitFiberUnmount(js,n)}catch{}switch(n.tag){case 5:Je||tr(n,t);case 6:var r=Ue,l=Pt;Ue=null,rn(e,t,n),Ue=r,Pt=l,Ue!==null&&(Pt?(e=Ue,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Ue.removeChild(n.stateNode));break;case 18:Ue!==null&&(Pt?(e=Ue,n=n.stateNode,e.nodeType===8?ni(e.parentNode,n):e.nodeType===1&&ni(e,n),Yr(e)):ni(Ue,n.stateNode));break;case 4:r=Ue,l=Pt,Ue=n.stateNode.containerInfo,Pt=!0,rn(e,t,n),Ue=r,Pt=l;break;case 0:case 11:case 14:case 15:if(!Je&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,a=i.destroy;i=i.tag,a!==void 0&&(i&2||i&4)&&na(n,t,a),l=l.next}while(l!==r)}rn(e,t,n);break;case 1:if(!Je&&(tr(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){_e(n,t,o)}rn(e,t,n);break;case 21:rn(e,t,n);break;case 22:n.mode&1?(Je=(r=Je)||n.memoizedState!==null,rn(e,t,n),Je=r):rn(e,t,n);break;default:rn(e,t,n)}}function pu(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new gh),t.forEach(function(r){var l=Ch.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function bt(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=a),r&=~i}if(r=l,r=Ce()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*xh(r/1960))-r,10e?16:e,cn===null)var r=!1;else{if(e=cn,cn=null,gs=0,se&6)throw Error(R(331));var l=se;for(se|=4,U=e.current;U!==null;){var i=U,a=i.child;if(U.flags&16){var o=i.deletions;if(o!==null){for(var u=0;uCe()-Ja?Ln(e,0):Xa|=n),ot(e,t)}function Bd(e,t){t===0&&(e.mode&1?(t=jl,jl<<=1,!(jl&130023424)&&(jl=4194304)):t=1);var n=et();e=Yt(e,t),e!==null&&(fl(e,t,n),ot(e,n))}function _h(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Bd(e,n)}function Ch(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(R(314))}r!==null&&r.delete(t),Bd(e,n)}var Ud;Ud=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||it.current)st=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return st=!1,ph(e,t,n);st=!!(e.flags&131072)}else st=!1,ve&&t.flags&1048576&&Qc(t,as,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Wl(e,t),e=t.pendingProps;var l=dr(t,Ge.current);ar(t,n),l=Ha(null,t,r,e,l,n);var i=Wa();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,at(r)?(i=!0,ss(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,Aa(t),l.updater=Ts,t.stateNode=l,l._reactInternals=t,Xi(t,r,e,n),t=Yi(null,t,r,!0,i,n)):(t.tag=0,ve&&i&&La(t),Ze(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Wl(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=bh(r),e=Tt(r,e),l){case 0:t=Gi(null,t,r,e,n);break e;case 1:t=ou(null,t,r,e,n);break e;case 11:t=iu(null,t,r,e,n);break e;case 14:t=au(null,t,r,Tt(r.type,e),n);break e}throw Error(R(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Tt(r,l),Gi(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Tt(r,l),ou(e,t,r,l,n);case 3:e:{if(_d(t),e===null)throw Error(R(387));r=t.pendingProps,i=t.memoizedState,l=i.element,Yc(e,t),cs(t,r,null,n);var a=t.memoizedState;if(r=a.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){l=mr(Error(R(423)),t),t=uu(e,t,r,n,l);break e}else if(r!==l){l=mr(Error(R(424)),t),t=uu(e,t,r,n,l);break e}else for(ft=hn(t.stateNode.containerInfo.firstChild),pt=t,ve=!0,Lt=null,n=Jc(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(fr(),r===l){t=Zt(e,t,n);break e}Ze(e,t,r,n)}t=t.child}return t;case 5:return Zc(t),e===null&&Qi(t),r=t.type,l=t.pendingProps,i=e!==null?e.memoizedProps:null,a=l.children,Bi(r,l)?a=null:i!==null&&Bi(r,i)&&(t.flags|=32),Nd(e,t),Ze(e,t,a,n),t.child;case 6:return e===null&&Qi(t),null;case 13:return Cd(e,t,n);case 4:return Ma(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=pr(t,null,r,n):Ze(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Tt(r,l),iu(e,t,r,l,n);case 7:return Ze(e,t,t.pendingProps,n),t.child;case 8:return Ze(e,t,t.pendingProps.children,n),t.child;case 12:return Ze(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,i=t.memoizedProps,a=l.value,fe(os,r._currentValue),r._currentValue=a,i!==null)if(It(i.value,a)){if(i.children===l.children&&!it.current){t=Zt(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var o=i.dependencies;if(o!==null){a=i.child;for(var u=o.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=Xt(-1,n&-n),u.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var y=c.pending;y===null?u.next=u:(u.next=y.next,y.next=u),c.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),Ki(i.return,n,t),o.lanes|=n;break}u=u.next}}else if(i.tag===10)a=i.type===t.type?null:i.child;else if(i.tag===18){if(a=i.return,a===null)throw Error(R(341));a.lanes|=n,o=a.alternate,o!==null&&(o.lanes|=n),Ki(a,n,t),a=i.sibling}else a=i.child;if(a!==null)a.return=i;else for(a=i;a!==null;){if(a===t){a=null;break}if(i=a.sibling,i!==null){i.return=a.return,a=i;break}a=a.return}i=a}Ze(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,ar(t,n),l=Nt(l),r=r(l),t.flags|=1,Ze(e,t,r,n),t.child;case 14:return r=t.type,l=Tt(r,t.pendingProps),l=Tt(r.type,l),au(e,t,r,l,n);case 15:return jd(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Tt(r,l),Wl(e,t),t.tag=1,at(r)?(e=!0,ss(t)):e=!1,ar(t,n),xd(t,r,l),Xi(t,r,l,n),Yi(null,t,r,!0,e,n);case 19:return Ed(e,t,n);case 22:return Sd(e,t,n)}throw Error(R(156,t.tag))};function Hd(e,t){return gc(e,t)}function Eh(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function jt(e,t,n,r){return new Eh(e,t,n,r)}function eo(e){return e=e.prototype,!(!e||!e.isReactComponent)}function bh(e){if(typeof e=="function")return eo(e)?1:0;if(e!=null){if(e=e.$$typeof,e===xa)return 11;if(e===wa)return 14}return 2}function vn(e,t){var n=e.alternate;return n===null?(n=jt(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Kl(e,t,n,r,l,i){var a=2;if(r=e,typeof e=="function")eo(e)&&(a=1);else if(typeof e=="string")a=5;else e:switch(e){case Qn:return Rn(n.children,l,i,t);case va:a=8,l|=8;break;case xi:return e=jt(12,n,t,l|2),e.elementType=xi,e.lanes=i,e;case wi:return e=jt(13,n,t,l),e.elementType=wi,e.lanes=i,e;case ki:return e=jt(19,n,t,l),e.elementType=ki,e.lanes=i,e;case Zu:return Rs(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Gu:a=10;break e;case Yu:a=9;break e;case xa:a=11;break e;case wa:a=14;break e;case ln:a=16,r=null;break e}throw Error(R(130,e==null?e:typeof e,""))}return t=jt(a,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function Rn(e,t,n,r){return e=jt(7,e,r,t),e.lanes=n,e}function Rs(e,t,n,r){return e=jt(22,e,r,t),e.elementType=Zu,e.lanes=n,e.stateNode={isHidden:!1},e}function ci(e,t,n){return e=jt(6,e,null,t),e.lanes=n,e}function di(e,t,n){return t=jt(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Th(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Vs(0),this.expirationTimes=Vs(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Vs(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function to(e,t,n,r,l,i,a,o,u){return e=new Th(e,t,n,o,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=jt(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Aa(i),e}function Ph(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Kd)}catch(e){console.error(e)}}Kd(),Ku.exports=mt;var Dh=Ku.exports,qd,ku=Dh;qd=ku.createRoot,ku.hydrateRoot;async function Le(e){const t=await fetch(e);if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);return t.json()}async function ju(){return Le("/api/archives")}async function Su(e,t=null){const n=t?`/api/archives/${e}/entries?collection=${encodeURIComponent(t)}`:`/api/archives/${e}/entries`;return Le(n)}async function $h(e,t,n,r=null){const l=new URLSearchParams;return t&&l.set("q",t),n&&l.set("tag",n),r&&l.set("collection",r),Le(`/api/archives/${e}/entries/search?${l}`)}async function $r(e,t){return Le(`/api/archives/${e}/entries/${t}`)}async function Oh(e,t){return Le(`/api/archives/${e}/entries/${t}/children`)}function Ah(e,t,n){return Promise.all(n.map(r=>Le(`/api/archives/${e}/entries/${t}/artifacts/${r}`)))}async function Mh(e){if(!e||e.length===0)return{};const t=await fetch("/api/util/resolve-tco",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return t.ok?t.json():{}}async function Fh(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:n??null})});if(!r.ok)throw new Error(await r.text())}async function Il(e,t){return Le(`/api/archives/${e}/entries/${t}/tags`)}async function Nu(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/tags`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tag_path:n})});if(!r.ok)throw new Error(`Failed to add tag (${r.status})`)}async function Bh(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/tags/${n}`,{method:"DELETE"});if(!r.ok)throw new Error(`Remove failed (${r.status})`)}async function _u(e,t){const n=await fetch(`/api/archives/${e}/entries/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`Delete failed (${n.status})`)}async function Uh(e,t,n){const r=await fetch(`/api/archives/${e}/tags/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n})});if(!r.ok)throw new Error(await r.text());return r.json()}async function Hh(e,t){const n=await fetch(`/api/archives/${e}/tags/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(await n.text())}async function Wh(e,t){const n=await fetch(`/api/archives/${e}/tags`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok)throw new Error(await n.text());return n.json()}async function Vh(e,t,n){const r=await fetch(`/api/archives/${e}/tags/${t}/move`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parent_uid:n??null})});if(!r.ok)throw new Error(await r.text());return r.json()}async function fi(e){return Le(`/api/archives/${e}/runs`)}async function Dl(e){return Le(`/api/archives/${e}/tags`)}async function Qh(e,t,n=null,r=null){const l={locator:t};n&&n!=="best"&&(l.quality=n),r&&(typeof r.ublock_enabled=="boolean"&&(l.ublock_enabled=r.ublock_enabled),typeof r.reader_mode=="boolean"&&(l.reader_mode=r.reader_mode),typeof r.cookie_ext_enabled=="boolean"&&(l.cookie_ext_enabled=r.cookie_ext_enabled),typeof r.modal_closer_enabled=="boolean"&&(l.modal_closer_enabled=r.modal_closer_enabled),typeof r.via_freedium=="boolean"&&(l.via_freedium=r.via_freedium),r.per_item_quality&&typeof r.per_item_quality=="object"&&Object.keys(r.per_item_quality).length>0&&(l.per_item_quality=r.per_item_quality),r.sync===!0&&(l.sync=!0));const i=await fetch(`/api/archives/${e}/captures`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!i.ok){const a=await i.json().catch(()=>({})),o=new Error(a.error||`HTTP ${i.status}`);throw o.status=i.status,o}return i.json()}async function Kh(e,t){return Le(`/api/archives/${e}/captures/probe?locator=${encodeURIComponent(t)}`)}async function qh(e,t){const n=await fetch(`/api/archives/${e}/captures/probe-playlist`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({locator:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function Xd(e,t){return Le(`/api/archives/${e}/capture_jobs/${t}`)}async function Xh(){return(await(await fetch("/api/auth/setup")).json()).setup_required===!0}async function Jh(e,t){const n=await fetch("/api/auth/setup",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({username:e,password:t})});if(!n.ok)throw new Error((await n.json()).error||"Setup failed");return n.json()}async function Gh(e,t){const n=await fetch("/api/auth/login",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({username:e,password:t})});if(!n.ok)throw new Error((await n.json()).error||"Login failed");return n.json()}async function Yh(){await fetch("/api/auth/logout",{method:"POST"})}async function Zh(){const e=await fetch("/api/auth/me");return e.status===401?null:e.json()}async function em(e){const t=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({display_name:e})});if(!t.ok)throw new Error(await t.text())}async function tm(e){const t=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function nm(e,t){const n=await fetch("/api/auth/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({current_password:e,new_password:t})});if(!n.ok){let r=await n.text();try{r=JSON.parse(r).error??r}catch{}throw new Error(r)}}async function rm(){return Le("/api/auth/tokens")}async function lm(e){const t=await fetch("/api/auth/tokens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})});if(!t.ok)throw new Error(await t.text());return t.json()}async function sm(e){const t=await fetch(`/api/auth/tokens/${e}`,{method:"DELETE"});if(!t.ok)throw new Error(await t.text())}async function so(){return Le("/api/admin/instance-settings")}async function ql(e){const t=await fetch("/api/admin/instance-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function im(){return Le("/api/admin/users")}async function am(e,t,n){const r=await fetch("/api/admin/users",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,password:t,email:n||void 0})});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.error||`HTTP ${r.status}`)}return r.json()}async function om(e,t){const n=await fetch(`/api/admin/users/${e}/status`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function um(){return Le("/api/admin/roles")}async function cm(e,t){const n=await fetch("/api/admin/roles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:e,name:t})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`HTTP ${n.status}`)}return n.json()}async function io(e){return Le(`/api/archives/${e}/collections`)}async function dm(e,t,n,r=2,l=!0){const i=await fetch(`/api/archives/${e}/collections`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:t,slug:n,default_visibility_bits:r,requires_auth:l})});if(!i.ok){const a=await i.json().catch(()=>({error:i.statusText}));throw new Error(a.error||i.statusText)}return i.json()}async function fm(e,t){return Le(`/api/archives/${e}/collections/${t}`)}async function ca(e,t,n,r=2){const l=await fetch(`/api/archives/${e}/collections/${t}/entries`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({entry_uid:n,visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}}async function pm(e,t,n){const r=await fetch(`/api/archives/${e}/collections/${t}/entries/${n}`,{method:"DELETE"});if(!r.ok){const l=await r.json().catch(()=>({error:r.statusText}));throw new Error(l.error||r.statusText)}}async function hm(e,t,n,r){const l=await fetch(`/api/archives/${e}/collections/${t}/entries/${n}`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({visibility_bits:r})});if(!l.ok){const i=await l.json().catch(()=>({error:l.statusText}));throw new Error(i.error||l.statusText)}}async function Cu(e,t){return Le(`/api/archives/${e}/entries/${t}/collections`)}async function pi(e,t,n){const r=await fetch(`/api/archives/${e}/collections/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.error??r.statusText)}}async function mm(e,t){const n=await fetch(`/api/archives/${e}/collections/${t}`,{method:"DELETE"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error??n.statusText)}}async function gm(e){return Le(`/api/archives/${e}/blob-cleanup`)}async function ym(e){const t=await fetch(`/api/archives/${e}/blob-cleanup`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error??t.statusText)}return t.json()}async function vm(e,t){const n=await fetch(`/api/archives/${e}/entries/${t}/rearchive`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`rearchive failed: ${n.status}`)}return n.json()}async function xm(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/artifacts/${n}/media-token`,{method:"POST"});if(!r.ok)throw new Error(`media-token ${r.status}`);return r.json()}async function wm(){return Le("/api/admin/cookie-rules")}async function km(e,t,n){const r=await fetch("/api/admin/cookie-rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url_pattern:e||null,pattern_kind:t,cookies_json:n})});if(!r.ok){const l=await r.json().catch(()=>({}));throw new Error(l.message||`HTTP ${r.status}`)}return r.json()}async function jm(e,t){const n=await fetch(`/api/admin/cookie-rules/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`HTTP ${n.status}`)}}async function Sm(e){const t=await fetch(`/api/admin/cookie-rules/${e}`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.message||`HTTP ${t.status}`)}}function Nm(e,t,n){let r;return{promise:new Promise((i,a)=>{const o=new FormData;o.append("file",t),r=new XMLHttpRequest,r.open("POST",`/api/archives/${e}/uploads`),r.upload.addEventListener("progress",u=>{u.lengthComputable&&n&&n(Math.round(u.loaded/u.total*100))}),r.addEventListener("load",()=>{if(r.status>=200&&r.status<300)try{i(JSON.parse(r.responseText))}catch{a(new Error("Invalid server response"))}else{let u=`Upload failed (${r.status})`;try{u=JSON.parse(r.responseText).message||u}catch{}a(new Error(u))}}),r.addEventListener("error",()=>a(new Error("Network error during upload"))),r.addEventListener("abort",()=>a(new Error("Upload cancelled"))),r.send(o)}),abort:()=>r==null?void 0:r.abort()}}async function hi(e,t){try{await fetch(`/api/archives/${e}/uploads`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({locator:t})})}catch{}}const _m=window.fetch;window.fetch=async(...e)=>{var n;const t=await _m(...e);return t.status===401&&((typeof e[0]=="string"?e[0]:((n=e[0])==null?void 0:n.url)??"").includes("/api/auth/")||window.dispatchEvent(new CustomEvent("auth:expired"))),t};function Cm({onLogin:e}){const[t,n]=d.useState(""),[r,l]=d.useState(""),[i,a]=d.useState(null),[o,u]=d.useState(!1);async function c(y){y.preventDefault(),a(null),u(!0);try{const g=await Gh(t,r);e(g)}catch(g){a(g.message)}finally{u(!1)}}return s.jsx("div",{className:"login-page",children:s.jsxs("div",{className:"login-card",children:[s.jsx("h1",{className:"login-brand",children:"Archivr"}),s.jsx("p",{className:"login-tagline",children:"Sign in to your archive"}),s.jsxs("form",{onSubmit:c,children:[s.jsxs("div",{className:"login-field",children:[s.jsx("label",{className:"login-label",htmlFor:"login-username",children:"Username"}),s.jsx("input",{className:"login-input",id:"login-username",type:"text",value:t,onChange:y=>n(y.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),s.jsxs("div",{className:"login-field",children:[s.jsx("label",{className:"login-label",htmlFor:"login-password",children:"Password"}),s.jsx("input",{className:"login-input",id:"login-password",type:"password",value:r,onChange:y=>l(y.target.value),required:!0,autoComplete:"current-password"})]}),i&&s.jsx("p",{className:"login-error",children:i}),s.jsx("button",{className:"login-submit",type:"submit",disabled:o,children:o?"Signing in…":"Sign in"})]})]})})}function Em({onComplete:e}){const[t,n]=d.useState(""),[r,l]=d.useState(""),[i,a]=d.useState(""),[o,u]=d.useState(null),[c,y]=d.useState(!1);async function g(h){if(h.preventDefault(),r!==i){u("Passwords do not match");return}if(r.length<8){u("Password must be at least 8 characters");return}u(null),y(!0);try{await Jh(t,r),e()}catch(v){u(v.message)}finally{y(!1)}}return s.jsx("div",{className:"setup-page",children:s.jsxs("div",{className:"setup-card",children:[s.jsx("h1",{className:"setup-brand",children:"Archivr"}),s.jsx("p",{className:"setup-tagline",children:"Create your owner account to get started."}),s.jsxs("form",{onSubmit:g,children:[s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-username",children:"Username"}),s.jsx("input",{className:"setup-input",id:"setup-username",type:"text",value:t,onChange:h=>n(h.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-password",children:"Password"}),s.jsx("input",{className:"setup-input",id:"setup-password",type:"password",value:r,onChange:h=>l(h.target.value),required:!0,autoComplete:"new-password"})]}),s.jsxs("div",{className:"setup-field",children:[s.jsx("label",{className:"setup-label",htmlFor:"setup-confirm",children:"Confirm password"}),s.jsx("input",{className:"setup-input",id:"setup-confirm",type:"password",value:i,onChange:h=>a(h.target.value),required:!0,autoComplete:"new-password"})]}),o&&s.jsx("p",{className:"setup-error",children:o}),s.jsx("button",{className:"setup-submit",type:"submit",disabled:c,children:c?"Creating account…":"Create account"})]})]})})}function bm({archives:e,archiveId:t,onArchiveChange:n,view:r,onViewChange:l,onCaptureClick:i,collections:a,selectedCollectionUid:o,onCollectionChange:u,isPublicSession:c,onSignInClick:y}){const{currentUser:g,setCurrentUser:h}=d.useContext(As)??{},[v,x]=d.useState(!1);async function S(){x(!0),await Yh(),h(null),window.location.reload()}const N=a.find(m=>m.slug==="_default_"),p=!c||!!N&&!N.requires_auth,f=a.filter(m=>m.slug!=="_default_").filter(m=>!c||!m.requires_auth);return s.jsxs("header",{className:"topbar",children:[s.jsx("div",{className:"brand",children:"Archivr"}),s.jsxs("div",{className:"switchers",children:[!c&&s.jsx("div",{className:"switcher",children:s.jsx("select",{"aria-label":"Select archive",value:t??"",onChange:m=>n(m.target.value),children:e.map(m=>s.jsx("option",{value:m.id,children:m.label},m.id))})}),f.length>0&&s.jsx("div",{className:"switcher",children:s.jsxs("select",{"aria-label":"Select collection",value:o??"",onChange:m=>u(m.target.value||null),children:[p&&s.jsx("option",{value:"",children:"All entries"}),f.map(m=>s.jsx("option",{value:m.collection_uid,children:m.name},m.collection_uid))]})})]}),c?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{flex:1}}),s.jsx("button",{className:"logout-btn",onClick:y,children:"Sign in"})]}):s.jsxs(s.Fragment,{children:[s.jsx("nav",{className:"nav","aria-label":"Primary",children:["archive","tags","collections","runs","admin","settings"].map(m=>s.jsx("button",{className:`nav-link${r===m?" is-active":""}`,onClick:()=>l(m),children:m.charAt(0).toUpperCase()+m.slice(1)},m))}),s.jsx("button",{className:"capture-button",onClick:i,children:"Capture"}),g&&s.jsxs("div",{className:"user-menu",children:[s.jsx("span",{className:"user-name",children:g.display_name||g.username}),s.jsx("button",{className:"logout-btn",onClick:S,disabled:v,children:v?"Logging out…":"Log out"})]})]})]})}let xs=1;function Jd(e){const t=e.trim(),n=t.toLowerCase();for(const r of["yt:","youtube:"])if(n.startsWith(r)){const l=n.slice(r.length);return!!(l.startsWith("video/")||l.startsWith("short/")||l.startsWith("shorts/")||/^[a-z0-9_-]{11}$/i.test(l))}if(n.startsWith("ytm:"))return!n.slice(4).startsWith("playlist/");for(const r of["x:","twitter:","tweet:"])if(n.startsWith(r))return n.slice(r.length).startsWith("media:");if(n.startsWith("spotify:"))return!1;if(n.startsWith("instagram:")||n.startsWith("facebook:")||n.startsWith("tiktok:")||n.startsWith("reddit:")||n.startsWith("snapchat:"))return!0;if(n.startsWith("http://")||n.startsWith("https://")){if(/^https?:\/\/music\.youtube\.com\/watch/.test(n)||/^https?:\/\/(?:www\.)?(?:youtu\.be\/[0-9A-Za-z_-]+|youtube\.com\/watch\?v=[0-9A-Za-z_-]+|youtube\.com\/shorts\/[0-9A-Za-z_-]+)/.test(t)||n.startsWith("https://x.com/")||n.startsWith("http://x.com/")||/^https?:\/\/(?:www\.)?instagram\.com\//.test(n)||/^https?:\/\/(?:www\.)?facebook\.com\//.test(n)||n.startsWith("https://fb.watch/")||n.startsWith("http://fb.watch/")||/^https?:\/\/(?:www\.)?tiktok\.com\//.test(n)||/^https?:\/\/(?:www\.)?reddit\.com\//.test(n)||n.startsWith("https://redd.it/")||n.startsWith("http://redd.it/")||/^https?:\/\/(?:www\.)?snapchat\.com\//.test(n))return!0;if(n.startsWith("https://open.spotify.com/")||n.startsWith("http://open.spotify.com/"))return!1}return!1}function Pn(e){const t=e.trim(),n=t.toLowerCase();for(const r of["yt:","youtube:"])if(n.startsWith(r)){const l=n.slice(r.length);return l.startsWith("playlist/")||l.startsWith("@")||l.startsWith("channel/")||l.startsWith("c/")||l.startsWith("user/")}if(n.startsWith("ytm:"))return n.slice(4).startsWith("playlist/");if(n.startsWith("spotify:")){const r=n.slice(8);return r.startsWith("album:")||r.startsWith("playlist:")}if(n.startsWith("http://")||n.startsWith("https://"))try{const r=new URL(t),l=r.hostname;if((l==="youtube.com"||l==="www.youtube.com")&&(r.pathname==="/playlist"&&r.searchParams.has("list")||r.pathname.startsWith("/@")||r.pathname.startsWith("/channel/")||r.pathname.startsWith("/c/")||r.pathname.startsWith("/user/"))||l==="music.youtube.com"&&r.pathname==="/playlist"&&r.searchParams.has("list")||l==="open.spotify.com"&&(r.pathname.startsWith("/album/")||r.pathname.startsWith("/playlist/")))return!0}catch{}return!1}function Wn(e=""){return{id:xs++,locator:e,quality:"best",probeState:"idle",probeQualities:null,probeHasAudio:!1,status:"idle",error:null,jobUid:null,archiveId:null,playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1,syncEnabled:!1}}function Tm(e){return{id:xs++,kind:"file",filename:e,uploadProgress:0,uploadStatus:"uploading",uploadLocator:null,uploadError:null,locator:"",quality:"best",probeState:"idle",probeQualities:null,probeHasAudio:!1,playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1,syncEnabled:!1,error:null,status:"idle"}}function Pm(e,t){return e==="best"?t.map(n=>({...n,quality:"best"})):e==="audio"?t.map(n=>n.has_audio?{...n,quality:"audio"}:n.quality!==null?n:{...n,quality:null}):t.map(n=>n.qualities.includes(e)?{...n,quality:e}:n.quality!==null?n:{...n,quality:null})}function Eu(e){return Array.isArray(e.playlistItems)&&e.playlistItems.some(t=>t.quality===null)}function Lm({open:e,archiveId:t,onClose:n,onCaptured:r,onToast:l,onJobStarted:i,onJobSettled:a,activeJobs:o=[]}){const u=d.useRef(null),c=d.useRef(!0),y=d.useRef(new Map),g=d.useRef(new Map),h=d.useRef(new Map),v=d.useRef(t);d.useEffect(()=>{v.current=t},[t]);const x=d.useRef(null),[S,N]=d.useState(!1),p=d.useRef([]),f=d.useRef(!1),m=d.useRef(new Map),w=d.useRef(r),C=d.useRef(l);d.useEffect(()=>{w.current=r},[r]),d.useEffect(()=>{C.current=l},[l]);const E=d.useRef(i),b=d.useRef(a);d.useEffect(()=>{E.current=i},[i]),d.useEffect(()=>{b.current=a},[a]);const[k,T]=d.useState(()=>{try{const j=JSON.parse(sessionStorage.getItem("captureItems")||"null");if(Array.isArray(j)&&j.length>0){const B=j.filter(M=>!M.status||M.status==="idle");if(B.length>0)return B.forEach(M=>{M.id>=xs&&(xs=M.id+1)}),B.map(M=>({...Wn(M.locator),...M}))}}catch{}return[Wn()]});d.useEffect(()=>{sessionStorage.setItem("captureItems",JSON.stringify(k.filter(j=>j.kind!=="file")))},[k]),d.useEffect(()=>{p.current=k},[k]);const[L,q]=d.useState(!1),[F,X]=d.useState(null),[Z,ue]=d.useState(null),[Ae,ge]=d.useState(!0),[D,P]=d.useState(!0),[H,te]=d.useState(!0);d.useEffect(()=>{so().then(j=>{ue(j),ge(j.cookie_ext_enabled??!0),P(j.modal_closer_enabled??!0)}).catch(()=>ue({}))},[]);const ee=F!==null?F:(Z==null?void 0:Z.ublock_enabled)??!0,[Re,Y]=d.useState(!1);d.useEffect(()=>{["captureDialogLocator","captureDialogError","captureDialogBusy","captureDialogJobStatus","captureDialogJobUid"].forEach(j=>sessionStorage.removeItem(j)),o.forEach(j=>{j.jobUid&&!y.current.has(j.jobUid)&&ye(j.id,j.jobUid,j.locator,j.archiveId,null)})},[]),d.useEffect(()=>{const j=u.current;if(!j)return;const B=()=>{if(g.current.forEach(M=>clearTimeout(M)),g.current.clear(),!f.current){const M=v.current;p.current.forEach(A=>{var W;A.kind==="file"&&(A.uploadStatus==="uploading"?((W=m.current.get(A.id))==null||W(),m.current.delete(A.id)):A.uploadStatus==="done"&&A.uploadLocator&&hi(M,A.uploadLocator).catch(()=>{}))})}f.current=!1,n()};return j.addEventListener("close",B),()=>j.removeEventListener("close",B)},[n]),d.useEffect(()=>{const j=u.current;j&&(e?(c.current||T([Wn()]),c.current=!1,j.open||j.showModal()):(g.current.forEach(B=>clearTimeout(B)),g.current.clear(),j.open&&j.close()))},[e]),d.useEffect(()=>()=>{y.current.forEach(j=>clearInterval(j)),g.current.forEach(j=>clearTimeout(j))},[]);function ye(j,B,M,A,W=null){if(y.current.has(B))return;const V=setInterval(async()=>{var pe,ae,xe,ie;try{const Qe=await Xd(A,B);if(Qe.status==="completed"){clearInterval(y.current.get(B)),y.current.delete(B),await Promise.resolve((pe=w.current)==null?void 0:pe.call(w)),(ae=b.current)==null||ae.call(b,j);try{const we=Qe.notes_json?JSON.parse(Qe.notes_json):null;if(we!=null&&we.ublock_skipped||we!=null&&we.cookie_ext_skipped){const xt=we.ublock_skipped&&we.cookie_ext_skipped?"Captured without ad-blocking or cookie-consent extension. Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config.":we.ublock_skipped?"Captured without ad-blocking. ARCHIVR_UBLOCK=true but ARCHIVR_UBLOCK_EXT is not set or the path is invalid.":"Captured without cookie-consent extension. ARCHIVR_COOKIE_EXT is not set or the path is invalid.";C.current(xt,M,"warning"),ce(W,"warning",M)}else W||C.current(null,M,"success"),ce(W,"archived")}catch{W||C.current(null,M,"success"),ce(W,"archived")}}else if(Qe.status==="failed"){clearInterval(y.current.get(B)),y.current.delete(B),(xe=b.current)==null||xe.call(b,j);const we=Qe.error_text||"Capture failed.";C.current(we,M),ce(W,"failed",M)}}catch(Qe){clearInterval(y.current.get(B)),y.current.delete(B),(ie=b.current)==null||ie.call(b,j);const we=Qe.message||"Network error";C.current(we,M),ce(W,"failed",M)}},500);y.current.set(B,V)}function ce(j,B,M=null){if(!j)return;const A=h.current.get(j);if(!A||(B==="archived"||B==="warning"?(A.archived++,B==="warning"&&(A.warnings++,M&&A.warningLocators.push(M))):(A.failed++,M&&A.failedLocators.push(M)),A.archived+A.failed0?`${W} archived (${V} with warnings)`:`${W} archived`;ie=pe>0?`${xt}, ${pe} failed`:xt}const Qe=W===0?"error":pe>0||V>0?"warning":"success",we=[];ae.length>0&&we.push(`Failed: -${ae.map(xt=>` ${xt}`).join(` -`)}`),xe.length>0&&we.push(`With warnings: -${xe.map(xt=>` ${xt}`).join(` -`)}`);const Un=we.length>0?we.join(` -`):null;C.current(Un,null,Qe,ie)}async function Ee(j,B,M,A={}){var ae,xe;const W=v.current,V=((ae=crypto.randomUUID)==null?void 0:ae.call(crypto))??`job-${Date.now()}-${Math.random()}`,pe={ublock_enabled:ee,reader_mode:Re,cookie_ext_enabled:Ae,modal_closer_enabled:D,via_freedium:H,...A};try{const ie=await Qh(W,j,B,pe);(xe=E.current)==null||xe.call(E,{id:V,jobUid:ie.job_uid,locator:j,archiveId:W}),ye(V,ie.job_uid,j,W,M)}catch(ie){const Qe=ie.message||"Submission failed.";C.current(Qe,j),ce(M,"failed",j),j.startsWith("file://")&&ie.status&&hi(W,j).catch(()=>{})}}function Ye(){var A,W;if(k.some(V=>V.kind==="file"&&V.uploadStatus==="uploading"))return;const j=k.filter(V=>V.kind==="file"?V.uploadStatus==="done"&&V.uploadLocator:V.locator.trim());if(j.length===0||j.some(V=>V.kind!=="file"&&Eu(V))||j.some(V=>V.kind!=="file"&&(V.probeState==="probing"||Pn(V.locator)&&V.playlistProbeState!=="done"))||j.some(V=>V.kind!=="file"&&Array.isArray(V.playlistItems)&&V.playlistItems.length===0))return;const B=j.length>1?((A=crypto.randomUUID)==null?void 0:A.call(crypto))??`batch-${Date.now()}`:null;B&&h.current.set(B,{total:j.length,archived:0,warnings:0,failed:0,failedLocators:[],warningLocators:[]});const M=j.map(V=>V.kind==="file"?{locator:V.uploadLocator,quality:"best",extraExtensions:{}}:{locator:V.locator.trim(),quality:V.playlistItems!==null?null:V.quality||"best",extraExtensions:V.playlistItems!==null?{per_item_quality:Object.fromEntries(V.playlistItems.map(pe=>[pe.id,pe.quality])),sync:V.syncEnabled}:{}});f.current=!0,T([Wn()]),(W=u.current)==null||W.close(),M.forEach(({locator:V,quality:pe,extraExtensions:ae})=>Ee(V,pe,B,ae))}function Ct(){T(j=>[...j,Wn()])}function yt(j){var M;clearTimeout(g.current.get(j)),g.current.delete(j);const B=p.current.find(A=>A.id===j);(B==null?void 0:B.kind)==="file"&&(B.uploadStatus==="uploading"?((M=m.current.get(j))==null||M(),m.current.delete(j)):B.uploadStatus==="done"&&B.uploadLocator&&hi(v.current,B.uploadLocator).catch(()=>{})),T(A=>{const W=A.filter(V=>V.id!==j);return W.length===0?[Wn()]:W})}function Ht(j,B){if(clearTimeout(g.current.get(j)),T(M=>M.map(A=>A.id===j?{...A,locator:B,probeState:"idle",probeQualities:null,probeHasAudio:!1,quality:"best",playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1}:A)),Jd(B)){const M=setTimeout(async()=>{g.current.delete(j),T(A=>A.map(W=>W.id===j?{...W,probeState:"probing"}:W));try{const A=await Kh(v.current,B.trim());T(W=>W.map(V=>{if(V.id!==j||V.locator!==B)return V;const pe=A.qualities??[],ae=A.has_audio??!1,xe=pe.length===0&&ae?"audio":"best";return{...V,probeState:"done",probeQualities:pe,probeHasAudio:ae,quality:xe}}))}catch{T(A=>A.map(W=>W.id===j?{...W,probeState:"idle",probeQualities:null}:W))}},600);g.current.set(j,M)}else if(Pn(B)){const M=setTimeout(async()=>{g.current.delete(j),T(A=>A.map(W=>W.id===j?{...W,playlistProbeState:"probing"}:W));try{const A=await qh(v.current,B.trim());T(W=>W.map(V=>V.id!==j||V.locator!==B?V:{...V,playlistProbeState:"done",playlistInfo:A,playlistItems:A.items.map(pe=>({...pe,quality:null})),playlistQuality:null}))}catch{T(A=>A.map(W=>W.id===j?{...W,playlistProbeState:"error"}:W))}},800);g.current.set(j,M)}}function ut(j,B){T(M=>M.map(A=>A.id===j?{...A,quality:B}:A))}function rt(j,B){T(M=>M.map(A=>{if(A.id!==j)return A;const W=Pm(B,A.playlistItems);return{...A,playlistQuality:B,playlistItems:W}}))}function vt(j,B,M){T(A=>A.map(W=>W.id!==j?W:{...W,playlistItems:W.playlistItems.map(V=>V.id===B?{...V,quality:M}:V)}))}function Et(j){T(B=>B.map(M=>M.id===j?{...M,playlistExpanded:!M.playlistExpanded}:M))}function O(j,B){T(M=>M.map(A=>A.id===j?{...A,syncEnabled:B}:A))}function K(j,B){T(M=>M.map(A=>A.id!==j?A:{...A,playlistItems:A.playlistItems.filter(W=>W.id!==B)}))}function de(j){const B=Array.from(j);B.length!==0&&B.forEach(M=>{const A=Tm(M.name);T(ae=>ae.length===1&&ae[0].kind!=="file"&&!ae[0].locator.trim()?[A]:[...ae,A]);const W=v.current,{promise:V,abort:pe}=Nm(W,M,ae=>{T(xe=>xe.map(ie=>ie.id===A.id?{...ie,uploadProgress:ae}:ie))});m.current.set(A.id,pe),V.then(ae=>{m.current.delete(A.id),T(xe=>xe.map(ie=>ie.id===A.id?{...ie,uploadStatus:"done",uploadLocator:ae.locator,uploadProgress:100}:ie))}).catch(ae=>{m.current.delete(A.id),ae.message!=="Upload cancelled"&&T(xe=>xe.map(ie=>ie.id===A.id?{...ie,uploadStatus:"error",uploadError:ae.message}:ie))})})}function Be(j){j.preventDefault(),j.stopPropagation(),j.dataTransfer.types.includes("Files")&&N(!0)}function Dt(j){j.currentTarget.contains(j.relatedTarget)||N(!1)}function ze(j){j.preventDefault(),j.stopPropagation(),N(!1),de(j.dataTransfer.files)}function Fn(j){de(j.target.files),j.target.value=""}const Nn=k.some(j=>j.kind==="file"&&j.uploadStatus==="uploading"),tn=k.filter(j=>j.kind==="file"?j.uploadStatus==="done"&&j.uploadLocator:j.locator.trim()).length,Ve=k.some(j=>j.kind!=="file"&&Eu(j)),wr=k.some(j=>j.kind!=="file"&&Array.isArray(j.playlistItems)&&j.playlistItems.length===0),Bn=k.some(j=>j.kind!=="file"&&(j.probeState==="probing"||Pn(j.locator)&&j.playlistProbeState!=="done"));return s.jsx("dialog",{ref:u,className:`capture-dialog${S?" capture-dialog--dragover":""}`,onDragOver:Be,onDragLeave:Dt,onDrop:ze,children:s.jsxs("div",{className:"capture-dialog-inner",children:[s.jsxs("div",{className:"capture-dialog-header",children:[s.jsx("h2",{className:"capture-dialog-title",children:"Capture"}),s.jsx("button",{type:"button",className:"capture-dialog-close",onClick:()=>{var j;return(j=u.current)==null?void 0:j.close()},"aria-label":"Close",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),s.jsx("div",{className:"capture-rows",children:k.map((j,B)=>j.kind==="file"?s.jsx(zm,{item:j,onRemove:()=>yt(j.id)},j.id):s.jsx(Rm,{item:j,autoFocus:B===k.length-1,onLocatorChange:M=>Ht(j.id,M),onQualityChange:M=>ut(j.id,M),onRemove:()=>yt(j.id),onSubmit:Ye,onPlaylistQualityChange:M=>rt(j.id,M),onPlaylistItemQualityChange:(M,A)=>vt(j.id,M,A),onPlaylistToggle:()=>Et(j.id),onSyncChange:M=>O(j.id,M),onPlaylistItemDelete:M=>K(j.id,M)},j.id))}),s.jsx("input",{ref:x,type:"file",multiple:!0,hidden:!0,onChange:Fn,"aria-hidden":"true",tabIndex:-1}),s.jsxs("div",{className:"capture-add-row-group",children:[s.jsxs("button",{type:"button",className:"capture-add-row",onClick:Ct,children:[s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"8",y1:"2",x2:"8",y2:"14"}),s.jsx("line",{x1:"2",y1:"8",x2:"14",y2:"8"})]}),"Add URL"]}),s.jsxs("button",{type:"button",className:"capture-add-row capture-add-file",onClick:()=>{var j;return(j=x.current)==null?void 0:j.click()},children:[s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{x:"3",y:"1",width:"10",height:"14",rx:"1.5"}),s.jsx("line",{x1:"5.5",y1:"5.5",x2:"10.5",y2:"5.5"}),s.jsx("line",{x1:"5.5",y1:"8",x2:"10.5",y2:"8"}),s.jsx("line",{x1:"5.5",y1:"10.5",x2:"8.5",y2:"10.5"})]}),"Upload file"]})]}),s.jsxs("div",{className:"capture-advanced",children:[s.jsxs("button",{type:"button",className:"capture-advanced-toggle",onClick:()=>q(j=>!j),"aria-expanded":L,children:[s.jsx("svg",{className:`capture-chevron${L?" capture-chevron--open":""}`,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("polyline",{points:"4 6 8 10 12 6"})}),"Advanced options"]}),L&&s.jsxs("div",{className:"capture-advanced-panel",children:[s.jsxs("label",{className:"capture-ext-row",children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"uBlock Origin Lite"}),s.jsx("span",{className:"capture-ext-desc",children:"Block ads during this capture"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":ee,className:`ext-toggle ext-toggle--sm${ee?" ext-toggle--on":""}`,onClick:()=>X(j=>j===null?!ee:!j),"aria-label":"Toggle uBlock for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Block cookie banners"}),s.jsx("span",{className:"capture-ext-desc",children:"Dismiss cookie consent banners during this capture"}),!(Z!=null&&Z.cookie_ext_available)&&s.jsxs("span",{className:"capture-ext-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":Ae,className:`ext-toggle ext-toggle--sm${Ae?" ext-toggle--on":""}`,onClick:()=>ge(j=>!j),"aria-label":"Toggle cookie banner blocking for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Reader mode"}),s.jsx("span",{className:"capture-ext-desc",children:"Distil to article text via Readability (off by default)"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":Re,className:`ext-toggle ext-toggle--sm${Re?" ext-toggle--on":""}`,onClick:()=>Y(j=>!j),"aria-label":"Toggle reader mode for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Close modals and dialogs"}),s.jsx("span",{className:"capture-ext-desc",children:"Auto-dismiss cookie banners and overlays during this capture"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":D,className:`ext-toggle ext-toggle--sm${D?" ext-toggle--on":""}`,onClick:()=>P(j=>!j),"aria-label":"Toggle modal closer for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]}),s.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[s.jsxs("span",{className:"capture-ext-label",children:[s.jsx("span",{className:"capture-ext-name",children:"Freedium mirror"}),s.jsx("span",{className:"capture-ext-desc",children:"Route paywalled articles through a Freedium mirror (Medium, NYT, WaPo, etc.)"})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":H,className:`ext-toggle ext-toggle--sm${H?" ext-toggle--on":""}`,onClick:()=>te(j=>!j),"aria-label":"Toggle Freedium mirror for this capture",children:s.jsx("span",{className:"ext-toggle-knob"})})]})]})]}),s.jsxs("div",{className:"capture-actions",children:[s.jsx("button",{type:"button",className:"capture-submit",onClick:Ye,disabled:tn===0||Ve||Bn||wr||Nn,children:tn>1?`Archive ${tn}`:"Archive"}),s.jsx("button",{type:"button",className:"capture-cancel",onClick:()=>{var j;return(j=u.current)==null?void 0:j.close()},children:"Cancel"})]})]})})}function Rm({item:e,autoFocus:t,onLocatorChange:n,onQualityChange:r,onRemove:l,onSubmit:i,onPlaylistQualityChange:a,onPlaylistItemQualityChange:o,onPlaylistToggle:u,onSyncChange:c,onPlaylistItemDelete:y}){const g=d.useRef(null);d.useEffect(()=>{var x;t&&((x=g.current)==null||x.focus())},[t]);const h=(()=>{if(Pn(e.locator)){if(e.playlistProbeState==="probing")return s.jsx("span",{className:"capture-quality-probing","aria-label":"Probing playlist…",children:"…"});if(e.playlistProbeState==="done"){const x=[...new Set(e.playlistItems.flatMap(p=>p.qualities.map(f=>parseInt(f))))].sort((p,f)=>f-p),S=e.playlistItems.every(p=>p.has_audio),N=e.playlistItems.filter(p=>p.quality===null).length;return s.jsxs(s.Fragment,{children:[s.jsxs("select",{className:"capture-quality",value:e.playlistQuality??"",onChange:p=>a(p.target.value),"aria-label":"Playlist quality",children:[!e.playlistQuality&&s.jsx("option",{value:"",disabled:!0,children:"Select quality…"}),s.jsx("option",{value:"best",children:"Best quality"}),x.map(p=>s.jsxs("option",{value:`${p}p`,children:[p,"p"]},p)),S&&s.jsx("option",{value:"audio",children:"Audio only"})]}),N>0&&s.jsxs("span",{className:"capture-conflict-badge",children:[N," need selection"]})]})}return e.playlistProbeState==="error"?s.jsx("span",{className:"capture-quality-hint capture-quality-hint--error",children:"Probe failed — edit URL to retry"}):null}if(!Jd(e.locator))return null;if(e.probeState==="probing")return s.jsx("span",{className:"capture-quality-probing","aria-label":"Checking available qualities",children:"…"});if(e.probeState==="done"){const x=e.probeQualities??[],S=e.probeHasAudio??!1;return x.length===0&&!S?s.jsx("span",{className:"capture-quality-hint",children:"No media detected"}):x.length===0&&S?s.jsx("select",{className:"capture-quality",value:"audio",onChange:N=>r(N.target.value),"aria-label":"Video quality",children:s.jsx("option",{value:"audio",children:"Audio only"})}):s.jsxs("select",{className:"capture-quality",value:e.quality||"best",onChange:N=>r(N.target.value),"aria-label":"Video quality",children:[s.jsx("option",{value:"best",children:"Best quality"}),x.map(N=>s.jsx("option",{value:N,children:N},N)),S&&s.jsx("option",{value:"audio",children:"Audio only"})]})}return null})(),v=Pn(e.locator)&&e.playlistProbeState==="done"?s.jsxs("label",{className:"capture-sync-row",children:[s.jsx("input",{type:"checkbox",checked:e.syncEnabled,onChange:x=>c(x.target.checked)}),s.jsx("span",{children:"Sync — skip already-archived videos"})]}):null;return s.jsxs("div",{className:"capture-row",children:[s.jsxs("div",{className:"capture-row-main",children:[Pn(e.locator)&&e.playlistProbeState==="done"?s.jsx("button",{type:"button",className:"capture-playlist-toggle capture-playlist-toggle--left",onClick:u,"aria-label":e.playlistExpanded?"Collapse video list":"Expand video list","aria-expanded":e.playlistExpanded,children:e.playlistExpanded?"▲":"▼"}):null,s.jsx("input",{ref:g,className:"capture-input",type:"text",placeholder:"https://… · yt:ID · ytm:ID · tweet:ID · x:ID",value:e.locator,onChange:x=>n(x.target.value),onKeyDown:x=>{x.key==="Enter"&&i()},autoComplete:"off",spellCheck:!1}),h,s.jsx("button",{type:"button",className:"capture-row-action capture-row-remove",onClick:l,"aria-label":"Remove",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),e.error&&s.jsx("p",{className:"capture-row-error",children:e.error}),Pn(e.locator)&&e.playlistProbeState==="done"&&e.playlistExpanded?s.jsxs("div",{className:"capture-playlist-items",children:[e.playlistItems.map(x=>s.jsxs("div",{className:`capture-playlist-item${x.quality===null?" capture-playlist-item--conflict":""}`,children:[s.jsx("span",{className:"capture-playlist-item-title",children:x.title||x.url}),s.jsxs("select",{className:"capture-item-quality",value:x.quality??"",onChange:S=>o(x.id,S.target.value),"aria-label":`Quality for ${x.title||x.url}`,children:[x.quality===null&&s.jsx("option",{value:"",disabled:!0,children:"Choose…"}),s.jsx("option",{value:"best",children:"Best quality"}),x.qualities.map(S=>s.jsx("option",{value:S,children:S},S)),x.has_audio&&s.jsx("option",{value:"audio",children:"Audio only"})]}),x.quality===null&&s.jsx("span",{className:"capture-playlist-conflict-badge",children:"Choose quality"}),s.jsx("button",{type:"button",className:"capture-playlist-item-remove","aria-label":`Remove ${x.title||x.url}`,onClick:()=>y(x.id),children:"×"})]},x.id)),v]}):v]})}function zm({item:e,onRemove:t}){const n=e.uploadStatus==="uploading",r=e.uploadStatus==="done",l=e.uploadStatus==="error";return s.jsxs("div",{className:"capture-row",children:[s.jsxs("div",{className:"capture-row-main",children:[s.jsx("span",{className:"capture-file-icon","aria-hidden":"true",children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",style:{width:14,height:14},children:[s.jsx("rect",{x:"3",y:"1",width:"10",height:"14",rx:"1.5"}),s.jsx("line",{x1:"5.5",y1:"5.5",x2:"10.5",y2:"5.5"}),s.jsx("line",{x1:"5.5",y1:"8",x2:"10.5",y2:"8"}),s.jsx("line",{x1:"5.5",y1:"10.5",x2:"8.5",y2:"10.5"})]})}),s.jsx("span",{className:`capture-file-name${l?" capture-file-name--error":""}`,children:e.filename}),n&&s.jsxs("span",{className:"capture-file-progress-wrap","aria-label":`Uploading ${e.uploadProgress}%`,children:[s.jsx("span",{className:"capture-file-progress-bar",children:s.jsx("span",{className:"capture-file-progress-fill",style:{width:`${e.uploadProgress}%`}})}),s.jsxs("span",{className:"capture-file-progress-pct",children:[e.uploadProgress,"%"]})]}),r&&s.jsx("span",{className:"capture-file-badge capture-file-badge--done","aria-label":"Upload complete",children:s.jsx("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{width:11,height:11},children:s.jsx("polyline",{points:"3 8.5 6.5 12 13 5"})})}),l&&s.jsx("span",{className:"capture-file-badge capture-file-badge--error",children:"!"}),s.jsx("button",{type:"button",className:"capture-row-action capture-row-remove",onClick:t,"aria-label":"Remove",disabled:n,children:s.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),s.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),l&&s.jsx("p",{className:"capture-row-error",children:e.uploadError||"Upload failed"})]})}function Im(){return s.jsxs("div",{className:"skeleton-row",children:[s.jsx("div",{className:"col-check","aria-hidden":"true"}),s.jsx("div",{className:"col-added",children:s.jsx("span",{className:"skeleton-cell",style:{width:108,height:13}})}),s.jsxs("div",{className:"col-title",style:{gap:"0.42em",display:"flex",alignItems:"center"},children:[s.jsx("span",{className:"skeleton-cell",style:{width:14,height:14,borderRadius:"50%",flexShrink:0}}),s.jsx("span",{className:"skeleton-cell",style:{width:"58%",height:13}})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"skeleton-cell",style:{width:58,height:20,borderRadius:99}})}),s.jsx("div",{className:"col-size",children:s.jsx("span",{className:"skeleton-cell",style:{width:44,height:12}})}),s.jsx("div",{className:"col-url",children:s.jsx("span",{className:"skeleton-cell",style:{width:"65%",height:12}})})]})}function cl(e){if(!e)return"0 B";const t=["B","KB","MB","GB"];let n=e,r=0;for(;n>=1024&&r").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}function dt(e){return Dm(e)??""}function ao(e){if(!e)return"";const t=new Date(e);if(isNaN(t))return e;const n=r=>String(r).padStart(2,"0");return`${t.getUTCFullYear()}-${n(t.getUTCMonth()+1)}-${n(t.getUTCDate())} ${n(t.getUTCHours())}:${n(t.getUTCMinutes())}`}const bu={youtube:'',youtube_music:'',spotify:'',x:'',instagram:'',facebook:'',tiktok:'',reddit:'',snapchat:'',local:'',web:'',other:'?'};function Os(e){return bu[e]??bu.other}function Gd(e){return e.split("/").map(t=>t?t.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"").join("/")}function $m({entry:e,index:t,onRowClick:n,selectedUids:r}){const l=(r==null?void 0:r.size)===1&&r.has(e.entry_uid),i=(r==null?void 0:r.size)>=2&&r.has(e.entry_uid),a=["child-entry-row",t%2===0?"child-entry-row--light":"child-entry-row--dark",l&&"is-selected",i&&"is-multi-selected"].filter(Boolean).join(" ");return s.jsxs("div",{className:a,tabIndex:0,"data-entry-uid":e.entry_uid,onMouseDown:o=>{o.shiftKey&&o.preventDefault()},onClick:o=>n(e,o),onKeyDown:o=>{o.key==="Enter"&&n(e,o)},children:[s.jsx("div",{className:"col-check","aria-hidden":"true"}),s.jsx("div",{className:"col-added",children:ao(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[s.jsx("span",{className:"source-icon",children:s.jsx("span",{dangerouslySetInnerHTML:{__html:Os(e.source_kind)}})}),s.jsx("span",{className:"entry-title",children:dt(e.title)||dt(e.entry_uid)})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"type-pill",children:dt(e.entity_kind)})}),s.jsx("div",{className:"col-size",children:s.jsx("span",{className:"size-total",children:cl(e.total_artifact_bytes)})}),s.jsx("div",{className:"url-cell col-url",children:dt(e.original_url)})]})}function Om({entry:e,archiveId:t,rowIndex:n,isSelected:r,isMultiSelected:l,onRowClick:i,selectedUids:a,deletedUids:o,isPublicSession:u}){const[c,y]=d.useState(!1),[g,h]=d.useState(!1),[v,x]=d.useState(null),[S,N]=d.useState(!1),f=e.source_kind==="web"&&e.entity_kind==="page"&&e.has_favicon&&t&&!c?s.jsx("img",{src:`/api/archives/${t}/entries/${e.entry_uid}/favicon`,width:"16",height:"16",alt:"",onError:()=>y(!0),style:{objectFit:"contain"}}):s.jsx("span",{dangerouslySetInnerHTML:{__html:Os(e.source_kind)}}),m=r||l,w=e.child_count>0&&!u;function C(k){k.stopPropagation(),i(e,{ctrlKey:!0,metaKey:!1,shiftKey:!1,preventDefault(){}})}async function E(k){if(k.stopPropagation(),g){h(!1);return}if(h(!0),v===null&&!S){N(!0);try{const T=await Oh(t,e.entry_uid);x(T)}catch{x([])}finally{N(!1)}}}const b=["entry-row-outer",n%2===0?"entry-row-outer--light":"entry-row-outer--dark",r&&"is-selected",l&&"is-multi-selected"].filter(Boolean).join(" ");return s.jsxs("div",{className:b,"data-entry-uid":e.entry_uid,children:[s.jsxs("div",{className:"entry-row-main",tabIndex:0,onMouseDown:k=>{k.shiftKey&&k.preventDefault()},onClick:k=>i(e,k),onKeyDown:k=>{k.key==="Enter"&&i(e,k)},children:[s.jsx("div",{className:"col-check",children:s.jsx("button",{type:"button",className:`row-checkbox${m?" is-checked":""}`,"aria-pressed":m,"aria-label":m?"Deselect entry":"Select entry",onClick:C,onKeyDown:k=>k.stopPropagation()})}),s.jsx("div",{className:"col-added",children:ao(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[w&&s.jsx("button",{type:"button",className:`entry-expand-btn${g?" is-expanded":""}`,"aria-label":g?"Collapse children":`Expand ${e.child_count} items`,"aria-expanded":g,onClick:E,onKeyDown:k=>k.stopPropagation()}),s.jsx("span",{className:"source-icon",children:f}),s.jsx("span",{className:"entry-title",children:dt(e.title)||dt(e.entry_uid)}),w&&s.jsx("span",{className:"child-count-badge","aria-hidden":"true",children:e.child_count})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"type-pill",children:dt(e.entity_kind)})}),s.jsxs("div",{className:"col-size",children:[s.jsx("span",{className:"size-total",children:cl(e.total_artifact_bytes)}),e.cached_bytes>0&&e.cacheable_bytes>0&&s.jsxs("span",{className:"size-cached-pct",title:`${cl(e.cached_bytes)} already on disk from an earlier entry`,children:[Math.round(e.cached_bytes/e.cacheable_bytes*100),"% cached"]})]}),s.jsx("div",{className:"url-cell col-url",children:dt(e.original_url)})]}),g&&s.jsxs(s.Fragment,{children:[S&&s.jsx("div",{className:"child-entries-loading",children:"Loading…"}),s.jsx("div",{className:"child-entries","aria-label":`${e.child_count} child entries`,children:v&&v.filter(k=>!(o!=null&&o.has(k.entry_uid))).map((k,T)=>s.jsx($m,{entry:k,index:T,onRowClick:i,selectedUids:a},k.entry_uid))})]})]})}function Am({entries:e,selectedUids:t,onRowClick:n,archiveId:r,pendingCaptures:l=[],deletedUids:i,isPublicSession:a}){return s.jsx("section",{id:"archive-view",className:"view is-active",children:s.jsxs("div",{className:"entry-table",children:[s.jsxs("div",{className:"entry-header-row",children:[s.jsx("div",{className:"col-check","aria-hidden":"true"}),s.jsx("div",{className:"col-added",children:"Added"}),s.jsx("div",{className:"col-title",children:"Title"}),s.jsx("div",{className:"col-type",children:"Type"}),s.jsx("div",{className:"col-size",children:"Size"}),s.jsx("div",{className:"col-url",children:"Original URL"})]}),s.jsxs("div",{id:"entries-body",children:[l.filter(o=>o.archiveId===r).reverse().map(o=>s.jsx(Im,{},o.id)),e.map((o,u)=>s.jsx(Om,{entry:o,rowIndex:u,archiveId:r,isSelected:t.size===1&&t.has(o.entry_uid),isMultiSelected:t.size>=2&&t.has(o.entry_uid),onRowClick:n,selectedUids:t,deletedUids:i,isPublicSession:a},o.entry_uid))]})]})})}function Mm(e){if(!e)return"—";try{return new Date(e).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return e}}function Fm({status:e}){const t=e==="completed"?"run-status--completed":e==="failed"?"run-status--failed":e==="in_progress"?"run-status--in-progress":"",n=e?e.replace(/_/g," "):"—";return s.jsx("span",{className:`run-status ${t}`,children:n})}function Bm({runs:e}){const[t,n]=d.useState(null);function r(l){n(i=>i===l?null:l)}return s.jsx("section",{id:"runs-view",className:"view is-active",children:s.jsxs("table",{className:"entry-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Started"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Requested"}),s.jsx("th",{children:"Completed"}),s.jsx("th",{children:"Failed"})]})}),s.jsx("tbody",{children:e.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:5,style:{color:"var(--muted)",padding:"24px 16px",textAlign:"center"},children:"No runs yet."})}):e.map(l=>{const i=l.status==="failed"&&l.error_summary,a=t===l.run_uid;return[s.jsxs("tr",{className:i?"run-row run-row--failed":"run-row",onClick:i?()=>r(l.run_uid):void 0,title:i?a?"Click to hide error":"Click to view error":void 0,children:[s.jsx("td",{children:Mm(l.started_at)}),s.jsxs("td",{children:[s.jsx(Fm,{status:l.status}),i&&s.jsx("span",{className:"run-expand-hint","aria-hidden":"true",children:a?"▴":"▾"})]}),s.jsx("td",{children:l.requested_count??"—"}),s.jsx("td",{children:l.completed_count??"—"}),s.jsx("td",{children:l.failed_count??"—"})]},l.run_uid),i&&a&&s.jsx("tr",{className:"run-error-row",children:s.jsx("td",{colSpan:5,children:s.jsx("pre",{className:"run-error-detail",children:l.error_summary})})},`${l.run_uid}-detail`)]})})]})})}const Um=4;function Hm({archives:e}){const{currentUser:t}=d.useContext(As)??{},n=t&&(t.role_bits&Um)!==0,[r,l]=d.useState("users"),[i,a]=d.useState([]),[o,u]=d.useState([]),[c,y]=d.useState(!1),[g,h]=d.useState(null),[v,x]=d.useState(""),[S,N]=d.useState(""),[p,f]=d.useState(""),[m,w]=d.useState(null),[C,E]=d.useState(!1),[b,k]=d.useState(""),[T,L]=d.useState(""),[q,F]=d.useState(null),[X,Z]=d.useState(!1),ue=d.useCallback(async()=>{if(n){y(!0),h(null);try{const[P,H]=await Promise.all([im(),um()]);a(P),u(H)}catch(P){h(P.message)}finally{y(!1)}}},[n]);d.useEffect(()=>{ue()},[ue]);async function Ae(P){const H=P.status==="active"?"disabled":"active";try{await om(P.user_uid,H),a(te=>te.map(ee=>ee.user_uid===P.user_uid?{...ee,status:H}:ee))}catch(te){h(te.message)}}async function ge(P){if(P.preventDefault(),!v.trim()||!S){w("Username and password required");return}E(!0),w(null);try{await am(v.trim(),S,p.trim()||void 0),x(""),N(""),f(""),await ue()}catch(H){w(H.message)}finally{E(!1)}}async function D(P){if(P.preventDefault(),!b.trim()||!T.trim()){F("Slug and name required");return}Z(!0),F(null);try{await cm(b.trim(),T.trim()),k(""),L(""),await ue()}catch(H){F(H.message)}finally{Z(!1)}}return n?s.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[s.jsx("h1",{children:"Admin"}),s.jsxs("div",{className:"view-tabs",children:[s.jsx("button",{className:`view-tab${r==="users"?" is-active":""}`,onClick:()=>l("users"),children:"Users"}),s.jsx("button",{className:`view-tab${r==="roles"?" is-active":""}`,onClick:()=>l("roles"),children:"Roles"}),s.jsx("button",{className:`view-tab${r==="archives"?" is-active":""}`,onClick:()=>l("archives"),children:"Archives"})]}),g&&s.jsx("div",{className:"form-msg form-msg--err",children:g}),r==="users"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Users"}),c?s.jsx("p",{className:"muted",children:"Loading…"}):s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Username"}),s.jsx("th",{children:"Email"}),s.jsx("th",{children:"Roles"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:i.map(P=>s.jsxs("tr",{className:P.status==="disabled"?"admin-row-disabled":"",children:[s.jsx("td",{children:P.username}),s.jsx("td",{className:"muted",children:P.email||"—"}),s.jsx("td",{children:P.role_slugs.join(", ")||"—"}),s.jsx("td",{children:s.jsx("span",{className:`status-badge status-${P.status}`,children:P.status})}),s.jsx("td",{children:s.jsx("button",{className:"admin-action-btn",onClick:()=>Ae(P),children:P.status==="active"?"Ban":"Unban"})})]},P.user_uid))})]}),s.jsx("h3",{children:"Create User"}),s.jsxs("form",{className:"admin-form",onSubmit:ge,children:[s.jsx("input",{className:"admin-input",placeholder:"Username",value:v,onChange:P=>x(P.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"password",placeholder:"Password (min 8 chars)",value:S,onChange:P=>N(P.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"email",placeholder:"Email (optional)",value:p,onChange:P=>f(P.target.value)}),m&&s.jsx("div",{className:"form-msg form-msg--err",children:m}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:C,children:C?"Creating…":"Create User"})]})]}),r==="roles"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Roles"}),c?s.jsx("p",{className:"muted",children:"Loading…"}):s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Slug"}),s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Level"}),s.jsx("th",{children:"Bit"}),s.jsx("th",{children:"Built-in"})]})}),s.jsx("tbody",{children:o.map(P=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:P.slug})}),s.jsx("td",{children:P.name}),s.jsx("td",{children:P.level}),s.jsx("td",{children:P.bit_position}),s.jsx("td",{children:P.is_builtin?"✓":""})]},P.role_uid))})]}),s.jsx("h3",{children:"Create Custom Role"}),s.jsxs("form",{className:"admin-form",onSubmit:D,children:[s.jsx("input",{className:"admin-input",placeholder:"Slug (e.g. moderator)",value:b,onChange:P=>k(P.target.value),required:!0}),s.jsx("input",{className:"admin-input",placeholder:"Display Name (e.g. Moderator)",value:T,onChange:P=>L(P.target.value),required:!0}),q&&s.jsx("div",{className:"form-msg form-msg--err",children:q}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:X,children:X?"Creating…":"Create Role"})]})]}),r==="archives"&&s.jsxs("div",{className:"admin-section",children:[s.jsx("h2",{children:"Mounted Archives"}),s.jsx("div",{className:"admin-list",children:e.map(P=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:P.label}),s.jsx("div",{className:"muted",children:P.archive_path})]},P.id))})]})]}):s.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[s.jsx("h1",{children:"Admin"}),s.jsx("p",{className:"muted",children:"You need admin privileges to access this panel."}),s.jsx("h2",{children:"Mounted Archives"}),s.jsx("div",{className:"admin-list",children:e.map(P=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:P.label}),s.jsx("div",{className:"muted",children:P.archive_path})]},P.id))})]})}function Yd({node:e,onPick:t}){var n;return s.jsxs("li",{children:[s.jsx("button",{className:"tag-picker-node-btn",title:e.tag.full_path,onClick:()=>t(e.tag),children:e.tag.slug}),((n=e.children)==null?void 0:n.length)>0&&s.jsx("div",{className:"tag-children",children:s.jsx("ul",{className:"tag-tree-list",children:e.children.map(r=>s.jsx(Yd,{node:r,onPick:t},r.tag.tag_uid))})})]})}function Tu({title:e,tagNodes:t,excludeUid:n,onPick:r,onCancel:l}){d.useEffect(()=>{function o(u){u.key==="Escape"&&(u.preventDefault(),u.stopPropagation(),l())}return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[l]);function i(o){return o.filter(u=>u.tag.tag_uid!==n).map(u=>({...u,children:i(u.children)}))}const a=n?i(t):t;return s.jsx("div",{className:"tag-picker-backdrop",onClick:o=>{o.target===o.currentTarget&&l()},children:s.jsxs("div",{className:"tag-picker-modal",role:"dialog","aria-modal":"true",children:[s.jsxs("div",{className:"tag-picker-header",children:[s.jsx("span",{className:"tag-picker-title",children:e}),s.jsx("button",{className:"tag-picker-close",onClick:l,title:"Cancel","aria-label":"Cancel",children:"×"})]}),s.jsxs("div",{className:"tag-picker-body",children:[s.jsx("button",{className:"tag-picker-root-btn",onClick:()=>r(null),title:"Place at root level (no parent)",children:"↑ Root tag (no parent)"}),a.length>0?s.jsx("ul",{className:"tag-tree-list tag-picker-tree",children:a.map(o=>s.jsx(Yd,{node:o,onPick:r},o.tag.tag_uid))}):s.jsx("p",{className:"tag-picker-empty",children:"No other tags available."})]})]})})}function Zd({parentPath:e,archiveId:t,onDone:n,onCancel:r}){const[l,i]=d.useState(""),a=d.useRef(!1);async function o(){const u=l.trim();if(!u){r();return}const c=e?`${e}/${u}`:`/${u}`;try{await Wh(t,c),n()}catch(y){alert(y.message||"Create failed"),r()}}return s.jsx("input",{className:"tag-rename-input",autoFocus:!0,placeholder:"tag name",value:l,onChange:u=>i(u.target.value),onKeyDown:u=>{u.key==="Enter"&&u.currentTarget.blur(),u.key==="Escape"&&(a.current=!0,u.currentTarget.blur())},onBlur:()=>{a.current?(a.current=!1,r()):o()}})}function ef({node:e,archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:c,onMoveSourceSelect:y,pendingCreateParentUid:g,onCreateDone:h,onCreateCancel:v}){var q;const x=n===e.tag.full_path,[S,N]=d.useState(!1),[p,f]=d.useState(""),m=d.useRef(!1);function w(){if(S)return;if(c){y(e);return}const F=x?null:e.tag.full_path;r(F),l("archive")}function C(F){F.stopPropagation(),!c&&(f(e.tag.slug),N(!0))}async function E(){const F=p.trim();if(!F||F===e.tag.slug){N(!1);return}try{const X=await Uh(t,e.tag.tag_uid,F);i(e.tag.full_path,X.full_path),o()}catch{}finally{N(!1)}}async function b(F){var Z;F.stopPropagation();const X=((Z=e.children)==null?void 0:Z.length)>0?`Delete tag "${e.tag.full_path}" and all its child tags? This cannot be undone.`:`Delete tag "${e.tag.full_path}"? This cannot be undone.`;if(window.confirm(X))try{await Hh(t,e.tag.tag_uid),a(e.tag.full_path),o()}catch{}}const k={archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:c,onMoveSourceSelect:y,pendingCreateParentUid:g,onCreateDone:h,onCreateCancel:v},T=g===e.tag.tag_uid,L=((q=e.children)==null?void 0:q.length)>0;return s.jsxs("li",{children:[s.jsxs("div",{className:`tag-node-row${c?" tag-node-row--move-select":""}`,children:[S?s.jsx("input",{className:"tag-rename-input",autoFocus:!0,value:p,onChange:F=>f(F.target.value),onKeyDown:F=>{F.key==="Enter"&&F.currentTarget.blur(),F.key==="Escape"&&(m.current=!0,F.currentTarget.blur())},onBlur:()=>{m.current?(m.current=!1,N(!1)):E()}}):s.jsxs("button",{className:`tag-node-btn${x?" is-active":""}${c?" tag-node-btn--move-select":""}`,title:c?`Select "${e.tag.full_path}" to move`:e.tag.full_path,onClick:w,onDoubleClick:c?void 0:C,children:[s.jsx("span",{className:"tag-node-label",children:u?e.tag.name:e.tag.slug}),s.jsx("span",{className:"tag-node-count",children:e.children.length===0?`(${e.entry_count})`:`(${e.entry_count}) (${e.subtree_count} Total)`}),!c&&s.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",title:"Rename tag",onClick:F=>{F.stopPropagation(),C(F)},children:s.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),!S&&!c&&s.jsx("button",{className:"remove tag-node-delete",title:`Delete "${e.tag.full_path}"`,onClick:b,"aria-label":`Delete "${e.tag.full_path}"`,children:"×"})]}),(L||T)&&s.jsx("div",{className:"tag-children",children:s.jsxs("ul",{className:"tag-tree-list",children:[e.children.map(F=>s.jsx(ef,{node:F,...k},F.tag.tag_uid)),T&&s.jsx("li",{children:s.jsx(Zd,{parentPath:e.tag.full_path,archiveId:t,onDone:h,onCancel:v})})]})})]})}function Wm({archiveId:e,tagNodes:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u}){const[c,y]=d.useState(null),[g,h]=d.useState(null);function v(){y("select-source"),h(null)}function x(){y(null),h(null)}d.useEffect(()=>{if(c!=="select-source")return;function X(Z){Z.key==="Escape"&&(Z.preventDefault(),Z.stopPropagation(),x())}return document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[c]);function S(X){h(X),y("select-dest")}async function N(X){const Z=g.tag.full_path,ue=g.tag.tag_uid,Ae=(X==null?void 0:X.tag_uid)??null;x();try{const ge=await Vh(e,ue,Ae);i(Z,ge.full_path),o()}catch(ge){alert(ge.message||"Move failed")}}const[p,f]=d.useState(null),[m,w]=d.useState(void 0);function C(){f("select-parent"),w(void 0)}function E(){f(null),w(void 0)}function b(X){w(X??null),f("input")}function k(){f(null),w(void 0),o()}const T=c==="select-source",L=p==="input"?m?m.tag_uid:"__root__":void 0,q={archiveId:e,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:T,onMoveSourceSelect:S,pendingCreateParentUid:L,onCreateDone:k,onCreateCancel:E},F=L==="__root__";return s.jsxs("section",{id:"tags-view",className:"view is-active",children:[s.jsxs("div",{className:"tag-tree",children:[s.jsx("div",{className:"tag-tree-header",children:T?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"tag-tree-title tag-tree-title--move",children:"Select a tag to move"}),s.jsx("button",{className:"tag-tree-action-btn tag-tree-action-btn--cancel",onClick:x,children:"Cancel"})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"tag-tree-title",children:"Tags"}),n&&s.jsxs("span",{className:"tag-tree-active",title:n,children:["Filtering: ",n]}),s.jsxs("div",{className:"tag-tree-actions",children:[s.jsx("button",{className:"tag-tree-action-btn",onClick:C,title:"Create a new tag",disabled:!!p||!!c,children:"+ New"}),s.jsx("button",{className:"tag-tree-action-btn",onClick:v,title:"Move a tag to a different parent",disabled:!!p||!!c||t.length===0,children:"Move"})]})]})}),t.length===0&&!F?s.jsx("p",{className:"muted",style:{padding:"8px 0"},children:"No tags yet."}):s.jsxs("ul",{className:"tag-tree-list",children:[t.map(X=>s.jsx(ef,{node:X,...q},X.tag.tag_uid)),F&&s.jsx("li",{children:s.jsx(Zd,{parentPath:null,archiveId:e,onDone:k,onCancel:E})})]})]}),p==="select-parent"&&s.jsx(Tu,{title:"Create tag under…",tagNodes:t,excludeUid:null,onPick:b,onCancel:E}),c==="select-dest"&&g&&s.jsx(Tu,{title:`Move "${g.tag.slug}" under…`,tagNodes:t,excludeUid:g.tag.tag_uid,onPick:N,onCancel:x})]})}const Or=[{value:0,label:"Private"},{value:2,label:"Users only"},{value:3,label:"Public"}],Vm=e=>{var t;return((t=Or.find(n=>n.value===e))==null?void 0:t.label)??String(e)};function Qm({archiveId:e}){const[t,n]=d.useState([]),[r,l]=d.useState(!1),[i,a]=d.useState(null),[o,u]=d.useState(null),[c,y]=d.useState(null),[g,h]=d.useState(!1),[v,x]=d.useState(null),[S,N]=d.useState(""),[p,f]=d.useState(""),[m,w]=d.useState(2),[C,E]=d.useState(!1),[b,k]=d.useState(!0),[T,L]=d.useState(null),[q,F]=d.useState(""),[X,Z]=d.useState(2),[ue,Ae]=d.useState(!1),[ge,D]=d.useState(null),[P,H]=d.useState(!1),[te,ee]=d.useState(""),Re=d.useRef(null),Y=t.find(O=>O.collection_uid===o)??null,ye=(Y==null?void 0:Y.slug)==="_default_",ce=d.useCallback(async()=>{if(e){l(!0),a(null);try{const O=await io(e);n(O)}catch(O){a(O.message)}finally{l(!1)}}},[e]),Ee=d.useCallback(async O=>{if(!O){y(null);return}h(!0),x(null);try{const K=await fm(e,O);y(K)}catch(K){x(K.message)}finally{h(!1)}},[e]);d.useEffect(()=>{ce()},[ce]),d.useEffect(()=>{Ee(o)},[o,Ee]),d.useEffect(()=>{P&&Re.current&&Re.current.focus()},[P]),d.useEffect(()=>{c!=null&&Z(c.default_visibility_bits)},[c]);async function Ye(O){O.preventDefault();const K=S.trim(),de=p.trim();if(!(!K||!de)){E(!0),L(null);try{const Be=await dm(e,K,de,m,b);N(""),f(""),w(2),k(!0),await ce(),u(Be.collection_uid)}catch(Be){L(Be.message)}finally{E(!1)}}}async function Ct(){const O=te.trim();if(!O||!Y){H(!1);return}try{await pi(e,Y.collection_uid,{name:O}),await ce(),y(K=>K&&{...K,name:O})}catch(K){a(K.message)}finally{H(!1)}}async function yt(O){if(Y)try{await pi(e,Y.collection_uid,{default_visibility_bits:O}),await ce(),y(K=>K&&{...K,default_visibility_bits:O})}catch(K){a(K.message)}}async function Ht(O){if(Y)try{await pi(e,Y.collection_uid,{requires_auth:O}),await ce(),y(K=>K&&{...K,requires_auth:O})}catch(K){a(K.message)}}async function ut(){if(Y&&window.confirm(`Delete collection "${Y.name}"? Entries will not be deleted.`))try{await mm(e,Y.collection_uid),u(null),y(null),await ce()}catch(O){a(O.message)}}async function rt(O){O.preventDefault();const K=q.trim();if(!(!K||!Y)){Ae(!0),D(null);try{await ca(e,Y.collection_uid,K,X),F(""),await Ee(Y.collection_uid)}catch(de){D(de.message)}finally{Ae(!1)}}}async function vt(O){if(Y)try{await pm(e,Y.collection_uid,O),await Ee(Y.collection_uid)}catch(K){x(K.message)}}async function Et(O,K){if(Y)try{await hm(e,Y.collection_uid,O,K),y(de=>de&&{...de,entries:de.entries.map(Be=>Be.entry_uid===O?{...Be,collection_visibility_bits:K}:Be)})}catch(de){x(de.message)}}return e?s.jsxs("div",{className:"collections-view",children:[s.jsx("h2",{className:"collections-heading",children:"Collections"}),r&&s.jsx("div",{className:"muted",children:"Loading…"}),i&&s.jsxs("div",{className:"collections-error",children:[i," ",s.jsx("button",{onClick:()=>a(null),className:"coll-dismiss",children:"×"})]}),s.jsxs("div",{className:"collections-layout",children:[s.jsxs("div",{className:"collections-sidebar",children:[t.map(O=>s.jsxs("button",{className:`coll-sidebar-row${o===O.collection_uid?" is-active":""}`,onClick:()=>u(O.collection_uid),children:[s.jsx("span",{className:"coll-row-name",children:O.name}),s.jsx("span",{className:"coll-row-meta",children:Vm(O.default_visibility_bits)})]},O.collection_uid)),t.length===0&&!r&&s.jsx("div",{className:"muted",style:{padding:"8px 12px"},children:"No collections yet."})]}),Y?s.jsxs("div",{className:"coll-detail",children:[s.jsxs("div",{className:"coll-detail-header",children:[P?s.jsx("input",{ref:Re,className:"coll-rename-input",value:te,onChange:O=>ee(O.target.value),onBlur:Ct,onKeyDown:O=>{O.key==="Enter"&&Ct(),O.key==="Escape"&&H(!1)}}):s.jsxs("h3",{className:`coll-detail-name${ye?"":" coll-detail-name--editable"}`,title:ye?void 0:"Click to rename",onClick:()=>{ye||(ee(Y.name),H(!0))},children:[(c==null?void 0:c.name)??Y.name,!ye&&s.jsx("span",{className:"coll-edit-hint",children:" ✎"})]}),!ye&&s.jsx("button",{className:"coll-delete-btn",onClick:ut,title:"Delete collection",children:"Delete"})]}),s.jsxs("div",{className:"coll-detail-vis",children:[s.jsx("span",{className:"coll-vis-label",children:"Entries' default visibility"}),s.jsx("select",{className:"coll-vis-select",value:(c==null?void 0:c.default_visibility_bits)??Y.default_visibility_bits,onChange:O=>yt(Number(O.target.value)),children:Or.map(O=>s.jsx("option",{value:O.value,children:O.label},O.value))})]}),s.jsxs("div",{className:"coll-detail-vis",children:[s.jsx("span",{className:"coll-vis-label",children:"Collection access"}),s.jsxs("label",{className:"coll-auth-label",children:[s.jsx("input",{type:"checkbox",checked:!!((c==null?void 0:c.requires_auth)??Y.requires_auth),onChange:O=>Ht(O.target.checked)})," Require authentication to view"]})]}),s.jsxs("div",{className:"coll-entries-section",children:[s.jsx("div",{className:"coll-section-heading",children:"Entries"}),g&&s.jsx("div",{className:"muted",children:"Loading…"}),v&&s.jsx("div",{className:"collections-error",children:v}),!g&&c&&(c.entries.length===0?s.jsx("div",{className:"muted",children:"No entries in this collection."}):s.jsx("ul",{className:"coll-entries-list",children:c.entries.map(O=>s.jsxs("li",{className:"coll-entry-row",children:[s.jsxs("div",{className:"coll-entry-info",children:[s.jsx("span",{className:"coll-entry-title",children:O.title||O.entry_uid}),s.jsx("span",{className:"coll-entry-kind muted",children:O.source_kind})]}),s.jsxs("div",{className:"coll-entry-actions",children:[s.jsx("select",{className:"coll-entry-vis-select",value:O.collection_visibility_bits,onChange:K=>Et(O.entry_uid,Number(K.target.value)),children:Or.map(K=>s.jsx("option",{value:K.value,children:K.label},K.value))}),!ye&&s.jsx("button",{className:"coll-entry-remove",onClick:()=>vt(O.entry_uid),title:"Remove from collection",children:"×"})]})]},O.entry_uid))}))]}),!ye&&s.jsxs("form",{className:"coll-add-entry-form",onSubmit:rt,children:[s.jsx("div",{className:"coll-section-heading",children:"Add entry"}),s.jsxs("div",{className:"coll-add-entry-row",children:[s.jsx("input",{className:"coll-add-entry-input",type:"text",value:q,onChange:O=>F(O.target.value),placeholder:"entry_uid",required:!0}),s.jsx("select",{className:"coll-vis-select",value:X,onChange:O=>Z(Number(O.target.value)),children:Or.map(O=>s.jsx("option",{value:O.value,children:O.label},O.value))}),s.jsx("button",{className:"coll-add-btn",type:"submit",disabled:ue,children:ue?"…":"Add"})]}),ge&&s.jsx("div",{className:"collections-error",style:{marginTop:4},children:ge})]})]}):s.jsx("div",{className:"coll-detail coll-detail--empty",children:s.jsx("div",{className:"muted",children:"Select a collection to view details."})})]}),s.jsxs("details",{className:"coll-create-details",children:[s.jsx("summary",{children:"+ Create collection"}),s.jsxs("form",{className:"coll-create-form",onSubmit:Ye,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-name",children:"Name"}),s.jsx("input",{className:"capture-input",id:"coll-name",type:"text",value:S,onChange:O=>{N(O.target.value),p||f(O.target.value.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""))},placeholder:"My Collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-slug",children:"Slug"}),s.jsx("input",{className:"capture-input",id:"coll-slug",type:"text",value:p,onChange:O=>f(O.target.value),placeholder:"my-collection",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"coll-vis",children:"Entries' default visibility"}),s.jsx("select",{className:"capture-input",id:"coll-vis",style:{height:42},value:m,onChange:O=>w(Number(O.target.value)),children:Or.map(O=>s.jsx("option",{value:O.value,children:O.label},O.value))})]}),s.jsx("div",{className:"form-field",children:s.jsxs("label",{className:"form-label",children:[s.jsx("input",{type:"checkbox",checked:b,onChange:O=>k(O.target.checked)})," Require authentication to view"]})}),T&&s.jsx("div",{className:"collections-error",children:T}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:C,children:C?"Creating…":"Create collection"})]})]})]}):s.jsx("div",{className:"view-placeholder",children:"Select an archive."})}const Km=4;function qm({tab:e,onTabChange:t,archiveId:n}){const{currentUser:r,setCurrentUser:l}=d.useContext(As)??{},i=r&&(r.role_bits&Km)!==0,a=["profile","tokens",...i?["instance","cookies","extensions","storage"]:[]],o={profile:"Profile",tokens:"API Tokens",instance:"Instance",cookies:"Cookies",extensions:"Extensions",storage:"Storage"};return s.jsxs("section",{className:"admin-view",children:[s.jsx("h1",{children:"Settings"}),s.jsx("div",{className:"view-tabs",children:a.map(u=>s.jsx("button",{className:`view-tab${e===u?" is-active":""}`,onClick:()=>t(u),children:o[u]},u))}),e==="profile"&&s.jsx(Xm,{currentUser:r,setCurrentUser:l}),e==="tokens"&&s.jsx(Jm,{}),e==="instance"&&i&&s.jsx(Gm,{}),e==="cookies"&&i&&s.jsx(Zm,{}),e==="extensions"&&i&&s.jsx(eg,{}),e==="storage"&&i&&s.jsx(Ym,{archiveId:n})]})}function Xm({currentUser:e,setCurrentUser:t}){const[n,r]=d.useState((e==null?void 0:e.display_name)??""),[l,i]=d.useState(!1),[a,o]=d.useState(null),[u,c]=d.useState(""),[y,g]=d.useState(""),[h,v]=d.useState(""),[x,S]=d.useState(!1),[N,p]=d.useState(null);async function f(w){w.preventDefault(),i(!0),o(null);try{await em(n),t(C=>({...C,display_name:n||null})),o({ok:!0,text:"Saved."})}catch(C){o({ok:!1,text:C.message})}finally{i(!1)}}async function m(w){if(w.preventDefault(),y!==h){p({ok:!1,text:"Passwords do not match."});return}S(!0),p(null);try{await nm(u,y),c(""),g(""),v(""),p({ok:!0,text:"Password changed."})}catch(C){p({ok:!1,text:C.message})}finally{S(!1)}}return s.jsxs("div",{style:{maxWidth:440},children:[s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Display Name"}),s.jsxs("form",{onSubmit:f,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"display-name",children:"Name shown in the UI"}),s.jsx("input",{className:"field-input",id:"display-name",placeholder:(e==null?void 0:e.username)??"",value:n,onChange:w=>r(w.target.value)})]}),a&&s.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:l,children:l?"Saving…":"Save"})]})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Display Preferences"}),s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:(e==null?void 0:e.humanize_slugs)??!1,onChange:async w=>{const C=w.target.checked;try{await tm({humanize_slugs:C}),t(E=>({...E,humanize_slugs:C}))}catch{}}}),s.jsx("span",{className:"form-label",style:{margin:0},children:"Humanize tag display"})]}),s.jsx("p",{className:"muted",style:{fontSize:13,margin:"4px 0 0"},children:'When on, tag paths show as "X / Articles" instead of "x/articles".'})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Change Password"}),s.jsxs("form",{onSubmit:m,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"cur-pw",children:"Current password"}),s.jsx("input",{className:"field-input",id:"cur-pw",type:"password",value:u,onChange:w=>c(w.target.value),required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"new-pw",children:"New password"}),s.jsx("input",{className:"field-input",id:"new-pw",type:"password",value:y,onChange:w=>g(w.target.value),required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",htmlFor:"confirm-pw",children:"Confirm new password"}),s.jsx("input",{className:"field-input",id:"confirm-pw",type:"password",value:h,onChange:w=>v(w.target.value),required:!0})]}),N&&s.jsx("div",{className:`form-msg form-msg--${N.ok?"ok":"err"}`,children:N.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:x,children:x?"Changing…":"Change Password"})]})]})]})}function Jm(){const[e,t]=d.useState([]),[n,r]=d.useState(!0),[l,i]=d.useState(null),[a,o]=d.useState(""),[u,c]=d.useState(!1),[y,g]=d.useState(null),h=d.useCallback(async()=>{r(!0),i(null);try{t(await rm())}catch(S){i(S.message)}finally{r(!1)}},[]);d.useEffect(()=>{h()},[h]);async function v(S){if(S.preventDefault(),!!a.trim()){c(!0);try{const N=await lm(a.trim());g(N),o(""),h()}catch(N){i(N.message)}finally{c(!1)}}}async function x(S){try{await sm(S),t(N=>N.filter(p=>p.token_uid!==S))}catch(N){i(N.message)}}return s.jsx("div",{style:{maxWidth:600},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"API Tokens"}),y&&s.jsxs("div",{className:"token-banner",children:[s.jsx("strong",{children:"Token created."})," Copy it now — it won't be shown again.",s.jsx("code",{children:y.raw_token}),s.jsx("button",{className:"token-dismiss",onClick:()=>g(null),children:"Dismiss"})]}),s.jsxs("form",{className:"token-create-row",onSubmit:v,children:[s.jsx("input",{className:"field-input field-input--flex",placeholder:"Token name",value:a,onChange:S=>o(S.target.value),required:!0}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:u,children:u?"Creating…":"Create token"})]}),l&&s.jsx("div",{className:"form-msg form-msg--err",children:l}),n?s.jsx("div",{className:"muted",children:"Loading…"}):s.jsxs("div",{children:[e.length===0&&s.jsx("div",{className:"muted",children:"No tokens yet."}),e.map(S=>s.jsxs("div",{className:"token-row",children:[s.jsxs("div",{className:"token-row-info",children:[s.jsx("strong",{children:S.name}),s.jsxs("div",{className:"muted",children:["Created ",S.created_at.slice(0,10),S.last_used_at&&` · Last used ${S.last_used_at.slice(0,10)}`]})]}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"4px 10px"},onClick:()=>x(S.token_uid),children:"Revoke"})]},S.token_uid))]})]})})}function Gm(){const[e,t]=d.useState(null),[n,r]=d.useState(!0),[l,i]=d.useState(null),[a,o]=d.useState(!1),[u,c]=d.useState(null);d.useEffect(()=>{(async()=>{try{t(await so())}catch(g){i(g.message)}finally{r(!1)}})()},[]);async function y(g){g.preventDefault(),o(!0),c(null);try{await ql(e),c({ok:!0,text:"Saved."})}catch(h){c({ok:!1,text:h.message})}finally{o(!1)}}return n?s.jsx("div",{className:"muted",children:"Loading…"}):l?s.jsx("div",{className:"form-msg form-msg--err",children:l}):e?s.jsx("div",{style:{maxWidth:440},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Instance Settings"}),s.jsxs("form",{onSubmit:y,children:[[["public_index_enabled","Public index (unauthenticated browsing)"],["public_entry_content_enabled","Public entry content"],["open_registration_enabled","Open registration"]].map(([g,h])=>s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:!!e[g],onChange:v=>t(x=>({...x,[g]:v.target.checked}))}),h]},g)),s.jsxs("div",{className:"form-field",style:{marginTop:4},children:[s.jsx("label",{className:"form-label",children:"Default entry visibility"}),s.jsxs("select",{className:"field-input",value:e.default_entry_visibility,onChange:g=>t(h=>({...h,default_entry_visibility:Number(g.target.value)})),children:[s.jsx("option",{value:0,children:"Private"}),s.jsx("option",{value:2,children:"Unlisted"}),s.jsx("option",{value:3,children:"Public"})]})]}),u&&s.jsx("div",{className:`form-msg form-msg--${u.ok?"ok":"err"}`,children:u.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:a,children:a?"Saving…":"Save Settings"})]})]})}):null}function mi(e){if(e===0)return"0 B";const t=["B","KB","MB","GB","TB"],n=Math.floor(Math.log(e)/Math.log(1024));return`${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`}function Ym({archiveId:e}){const[t,n]=d.useState("idle"),[r,l]=d.useState(null),[i,a]=d.useState(null),[o,u]=d.useState(null);function c(){n("idle"),l(null),a(null),u(null)}async function y(){n("scanning"),u(null),l(null);try{const v=await gm(e);l(v),n("scanned")}catch(v){u(v.message),n("error")}}async function g(){n("deleting"),u(null);try{const v=await ym(e);a(v),n("done")}catch(v){u(v.message),n("error")}}const h=r&&r.deletable_files===0&&r.orphaned_blob_rows===0;return s.jsx("div",{style:{maxWidth:440},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Orphan Cleanup"}),s.jsxs("p",{className:"muted",style:{marginBottom:16},children:["Scan for blob files and database records that are no longer referenced by any archive entry and safely delete them."," ",s.jsx("strong",{children:"Cleanup is blocked while captures are running."})]}),!e&&s.jsx("div",{className:"muted",children:"No archive selected."}),e&&t==="idle"&&s.jsx("button",{className:"btn-ghost",onClick:y,children:"Scan for orphaned blobs"}),t==="scanning"&&s.jsx("div",{className:"muted",children:"Scanning…"}),t==="scanned"&&r&&h&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"form-msg form-msg--ok",children:"Archive is clean — nothing to remove."}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Done"})]}),t==="scanned"&&r&&!h&&s.jsxs("div",{children:[s.jsxs("div",{style:{marginBottom:14,lineHeight:1.6},children:["Found ",s.jsx("strong",{children:r.deletable_files})," unreferenced file",r.deletable_files!==1?"s":""," ","and ",s.jsx("strong",{children:r.orphaned_blob_rows})," orphaned DB record",r.orphaned_blob_rows!==1?"s":""," ","— ",s.jsx("strong",{children:mi(r.total_bytes)})," recoverable."]}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsxs("button",{className:"btn-danger",onClick:g,children:["Delete (",mi(r.total_bytes),")"]}),s.jsx("button",{className:"btn-ghost",onClick:c,children:"Cancel"})]})]}),t==="deleting"&&s.jsx("div",{className:"muted",children:"Deleting…"}),t==="done"&&i&&s.jsxs("div",{children:[s.jsxs("div",{className:"form-msg form-msg--ok",children:["Freed ",s.jsx("strong",{children:mi(i.freed_bytes)})," ","— removed ",i.deleted_files," file",i.deleted_files!==1?"s":""," ","and ",i.deleted_blob_rows," DB record",i.deleted_blob_rows!==1?"s":"","."]}),i.errors&&i.errors.length>0&&s.jsxs("div",{className:"form-msg form-msg--err",style:{marginTop:6},children:[i.errors.length," file",i.errors.length!==1?"s":""," could not be deleted."]}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Scan again"})]}),t==="error"&&s.jsxs("div",{children:[s.jsx("div",{className:"form-msg form-msg--err",children:o}),s.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Try again"})]})]})})}function Zm(){const[e,t]=d.useState(null),[n,r]=d.useState(!0),[l,i]=d.useState(null),[a,o]=d.useState("global"),[u,c]=d.useState(""),[y,g]=d.useState("{}"),[h,v]=d.useState(null),[x,S]=d.useState(!1),[N,p]=d.useState({});d.useEffect(()=>{f()},[]);async function f(){r(!0),i(null);try{t(await wm())}catch(k){i(k.message)}finally{r(!1)}}async function m(k){k.preventDefault();try{JSON.parse(y)}catch{v({ok:!1,text:'cookies must be valid JSON, e.g. {"session": "abc"}'});return}S(!0),v(null);try{await km(a==="global"?null:u.trim(),a,y),c(""),g("{}"),o("global"),v({ok:!0,text:"Rule added."}),await f()}catch(T){v({ok:!1,text:T.message})}finally{S(!1)}}async function w(k){try{await Sm(k),await f()}catch(T){i(T.message)}}function C(k){p(T=>({...T,[k.rule_uid]:{cookiesInput:k.cookies_json,saving:!1,msg:null}}))}function E(k){p(T=>{const L={...T};return delete L[k],L})}async function b(k){const T=N[k.rule_uid];try{JSON.parse(T.cookiesInput)}catch{p(L=>({...L,[k.rule_uid]:{...L[k.rule_uid],msg:{ok:!1,text:"Invalid JSON"}}}));return}p(L=>({...L,[k.rule_uid]:{...L[k.rule_uid],saving:!0,msg:null}}));try{await jm(k.rule_uid,{cookies_json:T.cookiesInput}),E(k.rule_uid),await f()}catch(L){p(q=>({...q,[k.rule_uid]:{...q[k.rule_uid],saving:!1,msg:{ok:!1,text:L.message}}}))}}return n?s.jsx("div",{className:"muted",children:"Loading…"}):l?s.jsx("div",{className:"form-msg form-msg--err",children:l}):s.jsx("div",{style:{maxWidth:560},children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Cookie Rules"}),s.jsx("p",{className:"muted",style:{marginBottom:12},children:"Cookies are injected into every capture network request (yt-dlp, HTTP downloads, web-page snapshots). Global rules apply to all URLs; wildcard and regex rules apply only to matching URLs."}),e&&e.length>0?s.jsxs("table",{className:"data-table",style:{width:"100%",marginBottom:16},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Pattern"}),s.jsx("th",{children:"Cookies"}),s.jsx("th",{style:{width:100},children:"Actions"})]})}),s.jsx("tbody",{children:e.map(k=>{const T=N[k.rule_uid],L=k.url_pattern?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"muted",children:[k.pattern_kind,":"]})," ",s.jsx("code",{children:k.url_pattern})]}):s.jsx("span",{className:"muted",children:"global (all URLs)"});return s.jsxs("tr",{children:[s.jsx("td",{children:L}),s.jsx("td",{children:T?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:12,width:"100%",minHeight:60},value:T.cookiesInput,onChange:q=>p(F=>({...F,[k.rule_uid]:{...F[k.rule_uid],cookiesInput:q.target.value}}))}),T.msg&&s.jsx("div",{className:`form-msg form-msg--${T.msg.ok?"ok":"err"}`,children:T.msg.text}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[s.jsx("button",{className:"btn-primary",style:{fontSize:12,padding:"2px 8px"},disabled:T.saving,onClick:()=>b(k),children:T.saving?"Saving…":"Save"}),s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>E(k.rule_uid),children:"Cancel"})]})]}):s.jsx("code",{style:{fontSize:12,wordBreak:"break-all"},children:k.cookies_json})}),s.jsx("td",{children:!T&&s.jsxs("div",{style:{display:"flex",gap:6},children:[s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>C(k),children:"Edit"}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"2px 8px"},onClick:()=>w(k.rule_uid),children:"Del"})]})})]},k.rule_uid)})})]}):s.jsx("p",{className:"muted",style:{marginBottom:16},children:"No cookie rules defined."}),s.jsx("h3",{style:{marginBottom:8},children:"Add Rule"}),s.jsxs("form",{onSubmit:m,children:[s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:"Pattern type"}),s.jsxs("select",{className:"field-input",value:a,onChange:k=>o(k.target.value),children:[s.jsx("option",{value:"global",children:"Global (all URLs)"}),s.jsx("option",{value:"wildcard",children:"Wildcard (e.g. *.youtube.com)"}),s.jsx("option",{value:"regex",children:"Regex (matched against full URL)"})]})]}),a!=="global"&&s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:a==="wildcard"?"URL/hostname pattern":"Regex pattern"}),s.jsx("input",{className:"field-input",type:"text",value:u,onChange:k=>c(k.target.value),placeholder:a==="wildcard"?"*.youtube.com or https://example.com/*":".*\\.youtube\\.com.*",required:!0})]}),s.jsxs("div",{className:"form-field",children:[s.jsx("label",{className:"form-label",children:"Cookies (JSON object)"}),s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:13,minHeight:70},value:y,onChange:k=>g(k.target.value),placeholder:'{"SESSION": "abc123", "token": "xyz"}',required:!0})]}),h&&s.jsx("div",{className:`form-msg form-msg--${h.ok?"ok":"err"}`,children:h.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:x,children:x?"Adding…":"Add Rule"})]})]})})}function eg(){const[e,t]=d.useState(null),[n,r]=d.useState(!0),[l,i]=d.useState(!1),[a,o]=d.useState(null);d.useEffect(()=>{(async()=>{try{t(await so())}catch(N){o({ok:!1,text:N.message})}finally{r(!1)}})()},[]);async function u(N){i(!0),o(null);try{await ql({ublock_enabled:N}),t(p=>({...p,ublock_enabled:N})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function c(N){i(!0),o(null);try{await ql({cookie_ext_enabled:N}),t(p=>({...p,cookie_ext_enabled:N})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function y(N){i(!0),o(null);try{await ql({modal_closer_enabled:N}),t(p=>({...p,modal_closer_enabled:N})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}if(n)return s.jsx("div",{className:"muted",children:"Loading\\u2026"});const g=(e==null?void 0:e.ublock_ext_available)??!1,h=(e==null?void 0:e.ublock_enabled)??!0,v=(e==null?void 0:e.cookie_ext_available)??!1,x=(e==null?void 0:e.cookie_ext_enabled)??!0,S=(e==null?void 0:e.modal_closer_enabled)??!0;return s.jsx("div",{children:s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Extensions"}),s.jsx("p",{className:"form-hint",style:{marginBottom:20},children:"Extensions run inside the browser during WebPage captures and can block ads, accept cookie banners, and more. Changes take effect on the next capture."}),s.jsxs("div",{className:"ext-grid",children:[s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"uBlock Origin Lite"}),s.jsx("span",{className:"ext-card-desc",children:"Blocks ads, trackers, and other page clutter during archiving via Chrome’s declarativeNetRequest API (Manifest V3)."}),!g&&s.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_UBLOCK_EXT"})," to the unpacked extension directory to enable."]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":h,className:`ext-toggle${h?" ext-toggle--on":""}`,onClick:()=>u(!h),disabled:l,"aria-label":"Toggle uBlock Origin Lite",children:s.jsx("span",{className:"ext-toggle-knob"})})]})}),s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"I Still Don’t Care About Cookies"}),s.jsx("span",{className:"ext-card-desc",children:"Dismiss cookie consent banners during archiving."}),!v&&s.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",s.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})," to the unpacked extension directory to enable."]})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":x,className:`ext-toggle${x?" ext-toggle--on":""}`,onClick:()=>c(!x),disabled:l,"aria-label":"Toggle I Still Don't Care About Cookies",children:s.jsx("span",{className:"ext-toggle-knob"})})]})}),s.jsx("div",{className:"ext-card",children:s.jsxs("div",{className:"ext-card-header",children:[s.jsxs("div",{className:"ext-card-info",children:[s.jsx("span",{className:"ext-card-name",children:"Modal & Dialog Closer"}),s.jsx("span",{className:"ext-card-desc",children:"Auto-dismiss cookie banners, consent overlays, and other modal dialogs before a WebPage capture is taken. Implemented as an injected browser script; no external extension required."})]}),s.jsx("button",{type:"button",role:"switch","aria-checked":S,className:`ext-toggle${S?" ext-toggle--on":""}`,onClick:()=>y(!S),disabled:l,"aria-label":"Toggle Modal and Dialog Closer",children:s.jsx("span",{className:"ext-toggle-knob"})})]})})]}),a&&s.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text})]})})}const Pu={0:"Private",1:"Public",2:"Users only",3:"Public"},tg=()=>s.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M7 17 17 7M9 7h8v8"})});function ng({archiveId:e,selectedEntry:t,selectedUids:n,selectedEntries:r,detail:l,onTagFilterSet:i,tagNodes:a,onTagsRefresh:o,onEntryTitleChange:u,onEntryDeleted:c,onBulkDeleted:y,humanizeTags:g,onDetailRefresh:h,onOpenPreview:v,onPlay:x,isPublicSession:S}){var gl;const[N,p]=d.useState([]),[f,m]=d.useState(""),[w,C]=d.useState([]),[E,b]=d.useState(""),k=d.useRef(0),T=d.useRef(!1),[L,q]=d.useState(!1),[F,X]=d.useState(""),[Z,ue]=d.useState("idle"),[Ae,ge]=d.useState(""),D=d.useRef(null),[P,H]=d.useState(!1);d.useEffect(()=>{H(!1)},[(gl=l==null?void 0:l.summary)==null?void 0:gl.entry_uid]);const te=(n==null?void 0:n.size)>=2,[ee,Re]=d.useState(""),[Y,ye]=d.useState("idle"),[ce,Ee]=d.useState(""),[Ye,Ct]=d.useState([]),[yt,Ht]=d.useState(""),[ut,rt]=d.useState("idle"),[vt,Et]=d.useState(""),[O,K]=d.useState("idle"),[de,Be]=d.useState(""),[Dt,ze]=d.useState("idle"),[Fn,Nn]=d.useState("");d.useEffect(()=>{const z=++k.current;if(D.current&&(clearInterval(D.current),D.current=null),ue("idle"),ge(""),!t||!e){p([]),C([]);return}if(S){p([]),C([]);return}q(!1),X(""),T.current=!1,p([]),Promise.all([Il(e,t.entry_uid),Cu(e,t.entry_uid)]).then(([re,be])=>{z===k.current&&(p(re),C(be))}).catch(()=>{})},[t,e,S]),d.useEffect(()=>()=>{clearInterval(D.current)},[]),d.useEffect(()=>{if(!e){Ct([]);return}io(e).then(Ct).catch(()=>Ct([]))},[e]),d.useEffect(()=>{Re(""),ye("idle"),Ee(""),Ht(""),rt("idle"),Et(""),K("idle"),Be(""),ze("idle"),Nn("")},[n]);async function tn(){const z=n.size;if(!window.confirm(`Delete ${z} entr${z===1?"y":"ies"}? This cannot be undone.`))return;K("running");const re=new Set;for(const be of n)try{await _u(e,be),re.add(be)}catch{}K("idle"),y==null||y(re)}async function Ve(){const z=ee.trim();if(z){ye("running"),Ee("");try{for(const re of n)await Nu(e,re,z);Re(""),ye("done"),o==null||o(),setTimeout(()=>ye("idle"),1800)}catch(re){Ee(re.message),ye("error")}}}async function wr(){if(!yt)return;rt("running"),Et("");const z=[],re=Ye.find(be=>be.collection_uid===yt);for(const be of n)try{await ca(e,yt,be,(re==null?void 0:re.default_visibility_bits)??2)}catch{z.push(be)}z.length>0?(Et(`Failed for ${z.length} entr${z.length===1?"y":"ies"}.`),rt("error")):(rt("done"),setTimeout(()=>rt("idle"),1800))}async function Bn(){if(!de||!t)return;ze("running"),Nn("");const z=Ye.find(re=>re.collection_uid===de);try{await ca(e,de,t.entry_uid,(z==null?void 0:z.default_visibility_bits)??2),ze("done"),Be("");const re=await Cu(e,t.entry_uid);C(re),setTimeout(()=>ze("idle"),1800)}catch(re){Nn(re.message),ze("error")}}async function j(){const z=F.trim()||null;try{await Fh(e,t.entry_uid,z),u==null||u(t.entry_uid,z)}catch{}finally{q(!1)}}async function B(){const z=f.trim();if(!(!z||!t))try{await Nu(e,t.entry_uid,z),m(""),b("");const re=await Il(e,t.entry_uid);p(re),o()}catch(re){b(re.message)}}async function M(z){try{await Bh(e,t.entry_uid,z);const re=await Il(e,t.entry_uid);p(re),o()}catch{}}async function A(){if(!(!t||!e)&&window.confirm("Delete this entry? This cannot be undone."))try{await _u(e,t.entry_uid),c==null||c(t.entry_uid)}catch{}}async function W(){if(!t||!e||Z==="running")return;const z=k.current,re=t.entry_uid;ue("running"),ge("");try{const{job_uid:be}=await vm(e,re);if(k.current!==z)return;D.current=setInterval(async()=>{try{const $t=await Xd(e,be);if($t.status==="completed"){if(clearInterval(D.current),D.current=null,k.current!==z)return;ue("done");const Wt=await Il(e,re);if(k.current!==z)return;p(Wt),h==null||h()}else if($t.status==="failed"){if(clearInterval(D.current),D.current=null,k.current!==z)return;ue("error"),ge($t.error_text||"Re-archive failed.")}}catch{if(clearInterval(D.current),D.current=null,k.current!==z)return;ue("error"),ge("Network error while polling.")}},500)}catch(be){if(k.current!==z)return;ue("error"),ge(be.message||"Failed to start re-archive.")}}const V=l?[["Added",ao(l.summary.archived_at)],["Source",l.summary.source_kind],["Type",l.summary.entity_kind],["Visibility",Pu[l.summary.visibility]??l.summary.visibility],["Root",l.structured_root_relpath]]:[],pe=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),ae=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv","pdf","html","htm","jpg","jpeg","png","gif","webp","avif","svg","bmp"]),xe=l?l.artifacts.findIndex(z=>z.artifact_role==="primary_media"):-1,ie=xe>=0?l.artifacts[xe]:null,Qe=ie?ie.relpath.split(".").pop().toLowerCase():"",we=ie&&pe.has(Qe),Un=xe>=0&&t?`/api/archives/${e}/entries/${t.entry_uid}/artifacts/${xe}`:null,xt=l&&!we&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread"||ie&&ae.has(Qe));return s.jsxs("aside",{className:"context-rail",children:[s.jsx("div",{className:"rail-eyebrow",children:"Context"}),te?S?s.jsxs("p",{className:"bulk-count",children:[s.jsx("span",{className:"bulk-count-num",children:n.size})," entries selected"]}):s.jsxs("div",{className:"bulk-panel",children:[s.jsxs("p",{className:"bulk-count",children:[s.jsx("span",{className:"bulk-count-num",children:n.size})," entries selected"]}),s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Assign tag"}),ce&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:ce}),s.jsxs("div",{className:"tag-input-wrap",children:[s.jsx("span",{className:"hash",children:"/"}),s.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:ee,onChange:z=>Re(z.target.value),onKeyDown:z=>{z.key==="Enter"&&Ve()}}),s.jsx("button",{className:"tag-add-btn",onClick:Ve,disabled:Y==="running"||!ee.trim(),children:Y==="running"?"…":Y==="done"?"✓":"Add"})]})]}),Ye.length>0&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Add to collection"}),s.jsxs("div",{className:"bulk-coll-row",children:[s.jsxs("select",{className:"bulk-coll-select",value:yt,onChange:z=>Ht(z.target.value),children:[s.jsx("option",{value:"",children:"Pick a collection…"}),Ye.filter(z=>z.slug!=="_default_").map(z=>s.jsx("option",{value:z.collection_uid,children:z.name},z.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:wr,disabled:!yt||ut==="running",children:ut==="running"?"…":ut==="done"?"✓":ut==="error"?"!":"Add"})]}),vt&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"6px 0 0"},children:vt})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:tn,disabled:O==="running",children:O==="running"?"Deleting…":`Delete ${n.size} entr${n.size===1?"y":"ies"}`})})]}):t?l?s.jsxs(s.Fragment,{children:[S?s.jsx("h2",{className:"rail-title",children:dt(l.summary.title)||dt(l.summary.entry_uid)}):L?s.jsx("input",{className:"rail-title-input",autoFocus:!0,value:F,onChange:z=>X(z.target.value),onKeyDown:z=>{z.key==="Enter"&&z.currentTarget.blur(),z.key==="Escape"&&(T.current=!0,z.currentTarget.blur())},onBlur:()=>{T.current?q(!1):j(),T.current=!1}}):s.jsxs("h2",{className:"rail-title rail-title--editable",title:"Click to rename",onClick:()=>{X(l.summary.title??""),q(!0)},children:[dt(l.summary.title)||dt(l.summary.entry_uid),s.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),l.summary.original_url&&s.jsxs("a",{className:"url-tile",href:l.summary.original_url,target:"_blank",rel:"noopener noreferrer",children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:Os(l.summary.source_kind)}}),s.jsx("span",{className:"u-text",children:l.summary.original_url}),s.jsx("span",{className:"ext",children:s.jsx(tg,{})})]}),we&&x&&s.jsx("button",{className:"rail-preview-btn",onClick:()=>x(Un,t),children:"▶ Play"}),xt&&v&&s.jsx("button",{className:"rail-preview-btn",onClick:v,children:"Preview"}),s.jsx("div",{className:"meta-list",children:V.filter(([,z])=>z!=null&&z!=="").map(([z,re])=>s.jsxs("div",{className:"meta-item",children:[s.jsx("span",{className:"meta-k",children:z}),s.jsx("span",{className:`meta-v${z==="Root"?" mono":""}`,children:dt(re)})]},z))}),l.artifacts.length>0&&(()=>{const z=l.artifacts.map((Ie,jr)=>({...Ie,_idx:jr})),re=z.filter(Ie=>Ie.artifact_role==="font"),be=z.filter(Ie=>Ie.artifact_role!=="font"),$t=re.reduce((Ie,jr)=>Ie+(jr.byte_size||0),0),Wt=l.summary.entry_uid,kr=Ie=>s.jsx("li",{children:s.jsxs("a",{href:`/api/archives/${e}/entries/${Wt}/artifacts/${Ie._idx}`,target:"_blank",rel:"noopener noreferrer",className:"artifact-link",children:[s.jsx("span",{className:"artifact-name",children:Ie.artifact_role==="font"?Ie.relpath.split("/").pop():Ie.artifact_role.replace(/_/g," ")}),s.jsx("span",{className:"artifact-size",children:Ie.byte_size!=null?cl(Ie.byte_size):"—"})]})},Ie._idx);return s.jsxs("div",{className:"rail-section",children:[s.jsxs("div",{className:"rail-section-heading",children:["Artifacts ",s.jsx("span",{className:"num",children:l.artifacts.length})]}),s.jsxs("ul",{className:"artifact-list",children:[be.map(kr),re.length>0&&s.jsxs("li",{className:"artifact-group",children:[s.jsxs("button",{type:"button",className:"artifact-group-header artifact-link","aria-expanded":P,onClick:()=>H(Ie=>!Ie),children:[s.jsxs("span",{className:"artifact-name",children:[s.jsx("span",{"aria-hidden":"true",className:`artifact-group-chevron${P?" open":""}`,children:"›"}),` fonts (${re.length})`]}),s.jsx("span",{className:"artifact-size",children:cl($t)})]}),P&&s.jsx("ul",{className:"artifact-list artifact-group-body",children:re.map(kr)})]})]})]})})()]}):s.jsx("p",{className:"tags-empty",children:"Loading\\u2026"}):s.jsx("p",{className:"tags-empty",children:"Select an entry."}),t&&!te&&!S&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Tags"}),N.length===0?s.jsx("p",{className:"tags-empty",children:"No tags yet."}):s.jsx("div",{className:"tags-wrap",children:N.map(z=>s.jsxs("span",{className:"tag-pill",title:z.full_path,children:[g?Gd(z.full_path):z.full_path,s.jsx("button",{className:"remove",title:`Remove tag ${z.full_path}`,onClick:()=>M(z.tag_uid),children:"×"})]},z.tag_uid))}),E&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:E}),s.jsxs("div",{className:"tag-input-wrap",children:[s.jsx("span",{className:"hash",children:"/"}),s.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:f,onChange:z=>m(z.target.value),onKeyDown:z=>{z.key==="Enter"&&B()}}),s.jsx("button",{className:"tag-add-btn",onClick:B,children:"Add"})]})]}),(w.length>0||Ye.filter(z=>z.slug!=="_default_").length>0)&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Collections"}),w.map(z=>s.jsxs("div",{className:"coll-row",children:[s.jsx("span",{className:"coll-name",children:z.name}),s.jsx("span",{className:"vis-badge",children:Pu[z.visibility_bits]??`bits:${z.visibility_bits}`})]},z.collection_uid)),Ye.filter(z=>z.slug!=="_default_").length>0&&s.jsxs("div",{className:"bulk-coll-row",style:{marginTop:8},children:[s.jsxs("select",{className:"bulk-coll-select",value:de,onChange:z=>Be(z.target.value),children:[s.jsx("option",{value:"",children:"Add to collection…"}),Ye.filter(z=>z.slug!=="_default_").map(z=>s.jsx("option",{value:z.collection_uid,children:z.name},z.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:Bn,disabled:!de||Dt==="running",children:Dt==="running"?"…":Dt==="done"?"✓":Dt==="error"?"!":"Add"})]}),Fn&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"4px 0 0"},children:Fn})]}),l&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread")&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Actions"}),s.jsx("button",{className:"rail-rearchive-btn",onClick:W,disabled:Z==="running",children:Z==="running"?"Re-archiving…":"Re-archive"}),Z==="done"&&s.jsx("p",{className:"form-msg form-msg--ok",style:{marginTop:"6px"},children:"Re-archived successfully."}),Z==="error"&&s.jsx("p",{className:"form-msg form-msg--err",style:{marginTop:"6px"},children:Ae})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:A,children:"Delete entry"})})]})]})}const rg=/\/api\/archives\/([^/]+)\/entries\/([^/]+)\/artifacts\/(\d+)/;function lg(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M5 17H3a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h18a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-2"}),s.jsx("polygon",{points:"12 15 17 21 7 21 12 15"})]})}function sg({src:e,contentType:t="video/mp4"}){const n=d.useRef(null),[r,l]=d.useState(null),[i,a]=d.useState(!1),[o,u]=d.useState(!1);d.useEffect(()=>{if(!e){l(null);return}const g=e.match(rg);if(!g){l(e);return}let h=!1;return l(null),xm(g[1],g[2],parseInt(g[3],10)).then(({url:v})=>{h||l(v)}).catch(()=>{h||l(e)}),()=>{h=!0}},[e]),d.useEffect(()=>{n.current&&n.current.load()},[r]),d.useEffect(()=>{u(typeof HTMLVideoElement<"u"&&"webkitShowPlaybackTargetPicker"in HTMLVideoElement.prototype)},[]),d.useEffect(()=>{var h;const g=v=>{if(v)try{cast.framework.CastContext.getInstance().setOptions({receiverApplicationId:chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,autoJoinPolicy:chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}),a(!0)}catch{}};if((h=window.cast)!=null&&h.framework)g(!0);else if(window.__onGCastApiAvailable=g,!document.querySelector('script[src*="cast_sender"]')){const v=document.createElement("script");v.src="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1",document.head.appendChild(v)}},[]),d.useEffect(()=>{if(!i||!r)return;const g=cast.framework.CastContext.getInstance(),{CastContextEventType:h,SessionState:v}=cast.framework,x=N=>{if(!N)return;const p=new chrome.cast.media.MediaInfo(window.location.origin+r,t);N.loadMedia(new chrome.cast.media.LoadRequest(p)).catch(()=>{})};x(g.getCurrentSession());const S=N=>{(N.sessionState===v.SESSION_STARTED||N.sessionState===v.SESSION_RESUMED)&&x(g.getCurrentSession())};return g.addEventListener(h.SESSION_STATE_CHANGED,S),()=>g.removeEventListener(h.SESSION_STATE_CHANGED,S)},[i,r,t]);const c=()=>{var g,h;(h=(g=n.current)==null?void 0:g.webkitShowPlaybackTargetPicker)==null||h.call(g)},y=i||o;return s.jsx("div",{className:"preview-video-wrap",style:{position:"relative"},children:e?s.jsxs(s.Fragment,{children:[r?s.jsxs("video",{ref:n,controls:!0,autoPlay:!1,playsInline:!0,"x-webkit-airplay":"allow",style:{width:"100%",maxHeight:"100%",display:"block"},children:[s.jsx("source",{src:r}),"Your browser does not support the video element."]}):s.jsx("div",{className:"video-tv-loading","aria-label":"Loading video…"}),y&&r&&s.jsxs("div",{className:"video-tv-controls",children:[o&&s.jsx("button",{className:"video-tv-btn",title:"AirPlay to device","aria-label":"AirPlay to device",onClick:c,children:s.jsx(lg,{})}),i&&s.jsx("google-cast-launcher",{className:"video-tv-btn",title:"Cast to TV"})]})]}):s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No video available"})})}function Lu({src:e,type:t,title:n,originalUrl:r}){const l=r||e,i=n||null;return s.jsxs("div",{className:"preview-iframe-wrap",style:{flex:1,minHeight:0,display:"flex",flexDirection:"column"},children:[s.jsxs("div",{className:"preview-iframe-toolbar",style:{display:"flex",flexDirection:"column",gap:"2px",padding:"6px 12px",borderBottom:"1px solid var(--line-soft)",background:"var(--paper-2)",flexShrink:0},children:[i&&s.jsx("span",{style:{fontSize:"0.85rem",fontWeight:600,color:"var(--ink)",fontFamily:"var(--sans)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.78rem",color:"var(--muted)",fontFamily:"var(--sans)"},children:l}),s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",style:{fontSize:"0.78rem",color:"var(--accent)",textDecoration:"none",whiteSpace:"nowrap",fontFamily:"var(--sans)",flexShrink:0},children:t==="pdf"?"Open PDF ↗":"Open in new tab ↗"})]})]}),s.jsx("iframe",{src:e,sandbox:"allow-same-origin allow-popups",allow:"autoplay 'none'",referrerPolicy:"no-referrer",style:{flex:1,border:"none",width:"100%",minHeight:0},title:i||(t==="pdf"?"PDF preview":"Page preview")})]})}function ig({src:e,alt:t}){return s.jsx("div",{className:"preview-image-wrap",style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",background:"var(--paper-2)",overflow:"hidden"},children:s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",style:{display:"contents"},children:s.jsx("img",{src:e,alt:t||"",style:{objectFit:"contain",maxHeight:"100%",maxWidth:"100%",display:"block",cursor:"pointer"}})})})}function tf(e){return e?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(new Date(e*1e3)):""}function Ru(e){return!e||!e.includes("&")?e:e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}const G={card:{background:"var(--paper)",border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",maxWidth:"560px",margin:"0 auto",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},threadOuter:{border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",maxWidth:"560px",margin:"0 auto",background:"var(--paper)",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},tweetRow:{display:"flex",gap:"10px",padding:"10px 12px"},tweetRowThread:{display:"flex",gap:"10px",padding:"10px 12px 0"},leftCol:{display:"flex",flexDirection:"column",alignItems:"center",flexShrink:0,width:"36px"},rightCol:{flex:1,minWidth:0,paddingBottom:"8px"},avatar:{width:"36px",height:"36px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},avatarPh:{width:"36px",height:"36px",borderRadius:"50%",background:"var(--line)",flexShrink:0},threadLine:{flex:1,width:"2px",background:"var(--line-soft, var(--line))",margin:"4px 0",minHeight:"12px",borderRadius:"1px"},authorRow:{display:"flex",alignItems:"baseline",gap:"4px",flexWrap:"wrap",marginBottom:"4px",lineHeight:"1.3"},authorName:{fontWeight:"700",fontSize:"14px",color:"var(--ink)"},authorHandle:{fontSize:"13px",color:"var(--muted)"},datePart:{fontSize:"13px",color:"var(--muted)"},tweetText:{fontSize:"14px",lineHeight:"1.5",color:"var(--ink)",whiteSpace:"pre-line",marginBottom:"8px",wordBreak:"break-word"},stats:{display:"flex",gap:"12px",fontSize:"13px",color:"var(--muted)"},link:{color:"var(--accent)",textDecoration:"none"},loading:{padding:"24px 16px",textAlign:"center",color:"var(--muted)",fontSize:"14px"},error:{padding:"24px 16px",textAlign:"center",color:"var(--alert)",fontSize:"14px"},mediaGrid:{marginBottom:"8px",borderRadius:"10px",overflow:"hidden",border:"1px solid var(--line)"},mediaImg:{display:"block",width:"100%",objectFit:"cover",maxHeight:"260px"},mediaVideo:{display:"block",width:"100%",maxHeight:"260px",background:"#000"},article:{maxWidth:"560px",margin:"0 auto",border:"1px solid var(--line)",borderRadius:"12px",overflow:"hidden",background:"var(--paper)",fontFamily:'var(--sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif)'},aCover:{width:"100%",display:"block",objectFit:"cover",maxHeight:"280px"},aMeta:{padding:"10px 14px 0"},aTweetTitle:{fontSize:"20px",fontWeight:"800",letterSpacing:"-0.3px",color:"var(--ink)",lineHeight:"1.3",marginBottom:"8px"},aAuthorRow:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},aAvatar:{width:"36px",height:"36px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},aAvatarPh:{width:"36px",height:"36px",borderRadius:"50%",background:"var(--line)",flexShrink:0},aAuthorName:{fontSize:"14px",fontWeight:"700",color:"var(--ink)",lineHeight:"1.3"},aAuthorSub:{fontSize:"13px",color:"var(--muted)",lineHeight:"1.3"},aDivider:{border:"none",borderTop:"1px solid var(--line)",margin:"0"},aBody:{padding:"4px 14px 16px"},bH1:{fontSize:"22px",fontWeight:"800",letterSpacing:"-0.4px",color:"var(--ink)",lineHeight:"1.25",margin:"16px 0 6px"},bH2:{fontSize:"18px",fontWeight:"700",letterSpacing:"-0.2px",color:"var(--ink)",lineHeight:"1.3",margin:"14px 0 4px"},bP:{fontSize:"15px",color:"var(--ink)",lineHeight:"1.65",marginBottom:"12px",marginTop:"0"},bSpacer:{height:"4px",display:"block"},bQuote:{borderLeft:"3px solid var(--line)",padding:"2px 12px",margin:"12px 0",color:"var(--muted)",fontSize:"15px",lineHeight:"1.6"},bHr:{border:"none",borderTop:"1px solid var(--line)",margin:"14px 0"},bImg:{width:"100%",display:"block",borderRadius:"8px",margin:"12px 0"},bUl:{margin:"8px 0 12px",paddingLeft:"24px"},bOl:{margin:"8px 0 12px",paddingLeft:"24px"},bLi:{fontSize:"15px",color:"var(--ink)",lineHeight:"1.6",marginBottom:"4px"},bTweet:{display:"flex",alignItems:"center",gap:"10px",border:"1px solid var(--line)",borderRadius:"10px",padding:"10px 14px",margin:"12px 0",color:"var(--muted)",fontSize:"14px",textDecoration:"none"},bMdPre:{borderRadius:"8px",margin:"10px 0",overflow:"auto",background:"var(--paper-3, var(--field))",padding:"12px 14px"},bMdCode:{fontFamily:"ui-monospace, 'Cascadia Code', 'Fira Code', Menlo, Consolas, monospace",fontSize:"12px",lineHeight:"1.6",color:"var(--ink)",background:"transparent",display:"block"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:"var(--paper-3, var(--field))",padding:"1px 5px",borderRadius:"4px",color:"var(--ink)"},qtBadge:{fontSize:"11px",color:"var(--muted)",display:"inline-flex",alignItems:"center",gap:"2px",marginLeft:"4px",letterSpacing:"0.03em",flexShrink:0},lightboxBackdrop:{position:"fixed",inset:0,zIndex:500,background:"rgba(0,0,0,0.92)",display:"flex",alignItems:"center",justifyContent:"center",padding:"20px"},lightboxContent:{display:"flex",flexDirection:"column",alignItems:"center",gap:"10px",maxWidth:"90vw",maxHeight:"90vh"},lightboxToolbar:{display:"flex",alignItems:"center",gap:"10px",alignSelf:"flex-end"},lightboxImg:{maxWidth:"88vw",maxHeight:"80vh",objectFit:"contain",borderRadius:"6px",display:"block"},lightboxNav:{display:"flex",gap:"12px",alignItems:"center"},lightboxNavBtn:{background:"rgba(255,255,255,0.18)",border:"none",color:"#fff",fontSize:"20px",cursor:"pointer",borderRadius:"50%",width:"36px",height:"36px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,flexShrink:0},lightboxBtn:{background:"rgba(255,255,255,0.18)",border:"none",color:"#fff",fontSize:"16px",cursor:"pointer",borderRadius:"50%",width:"30px",height:"30px",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,flexShrink:0},lightboxLink:{color:"rgba(255,255,255,0.7)",textDecoration:"none",fontSize:"14px"},lightboxCounter:{color:"rgba(255,255,255,0.6)",fontSize:"13px"}},De={bg:"#000000",border:"#2f3336",text:"#e7e9ea",dim:"#71767b",accent:"#1d9bf0",codeBg:"#16181c"},gi={article:{background:De.bg,color:De.text,minHeight:"100%",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif'},articleInner:{maxWidth:"598px",margin:"0 auto",paddingBottom:"80px"},aCover:{width:"100%",display:"block",objectFit:"cover",maxHeight:"420px"},aMeta:{padding:"20px 16px 0"},aTweetTitle:{fontSize:"34px",fontWeight:"800",letterSpacing:"-0.5px",color:De.text,lineHeight:"44px",marginBottom:"16px"},aAuthorRow:{display:"flex",alignItems:"center",gap:"12px",marginBottom:"16px"},aAvatar:{width:"40px",height:"40px",borderRadius:"50%",objectFit:"cover",flexShrink:0,display:"block"},aAvatarPh:{width:"40px",height:"40px",borderRadius:"50%",background:De.border,flexShrink:0},aAuthorName:{fontSize:"15px",fontWeight:"700",color:De.text,lineHeight:"1.3"},aAuthorSub:{fontSize:"15px",color:De.dim,lineHeight:"1.3"},aDivider:{border:"none",borderTop:`1px solid ${De.border}`,margin:"0"},aBody:{padding:"4px 16px 0"},bH1:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:De.text,lineHeight:"36px",margin:"24px 0 10px"},bH2:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:De.text,lineHeight:"36px",margin:"24px 0 10px"},bP:{fontSize:"17px",color:De.text,lineHeight:"1.5",marginBottom:"16px",marginTop:"0"},bSpacer:{height:"6px",display:"block"},bQuote:{borderLeft:`3px solid ${De.border}`,padding:"2px 14px",margin:"14px 0",color:De.dim,fontSize:"17px",lineHeight:"1.5"},bHr:{border:"none",borderTop:`1px solid ${De.border}`,margin:"28px 0"},bImg:{width:"100%",display:"block",borderRadius:"12px",margin:"16px 0"},bUl:{margin:"10px 0 16px",paddingLeft:"28px"},bOl:{margin:"10px 0 16px",paddingLeft:"28px"},bLi:{fontSize:"17px",color:De.text,lineHeight:"1.5",marginBottom:"6px"},bTweet:{display:"flex",alignItems:"center",gap:"12px",border:`1px solid ${De.border}`,borderRadius:"12px",padding:"14px 16px",margin:"14px 0",color:De.dim,fontSize:"15px",textDecoration:"none"},bMdPre:{borderRadius:"12px",margin:"12px 0",overflow:"auto",background:"#1e2029"},bMdCode:{fontFamily:"ui-monospace, 'Cascadia Code', 'Fira Code', Menlo, Consolas, monospace",fontSize:"13px",lineHeight:"1.65",padding:"18px 20px",display:"block",color:De.text,background:"transparent"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:De.codeBg,padding:"2px 6px",borderRadius:"4px",color:"#e6edf3"},link:{color:De.accent,textDecoration:"none"}};function ag(e,t,n){const r={};return n&&n.forEach((l,i)=>{l.relpath&&(r[l.relpath]=`/api/archives/${e}/entries/${t}/artifacts/${i}`)}),r}function ur(e,t,n){return e&&n[e]?n[e]:t||null}function nf(){return s.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",style:{flexShrink:0,color:"var(--ink)"},children:s.jsx("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.748l7.73-8.835L1.254 2.25H8.08l4.259 5.63L18.244 2.25zm-1.161 17.52h1.833L7.084 4.126H5.117L17.083 19.77z"})})}function oo(e,t,...n){var r;if(e.fromIndex!=null&&e.toIndex!=null)return{s:e.fromIndex,e:e.toIndex};if(((r=e.indices)==null?void 0:r.length)===2)return{s:e.indices[0],e:e.indices[1]};if(t)for(const l of n){if(!l)continue;const i=t.indexOf(l);if(i!==-1)return{s:i,e:i+l.length}}return null}function rf(e,t){const n=e.expanded_url||e.url||e.text||"",r=e.display_url||e.expanded_url||e.url||e.text||"",l=oo(e,t,e.url,e.text,e.display_url,e.expanded_url);return!l||!n?null:{...l,kind:"url",href:n,display:r}}function lf(e,t){const n=e.screen_name||e.name||e.text||"",r=n?`@${n}`:null,l=oo(e,t,r);return!l||!n?null:{...l,kind:"mention",screen_name:n}}const zu=/https?:\/\/[^\s<>"'\])]+/g,og=/[.,;:!?)()]+$/;function ws(e,t){const n=[];let r=0,l;for(zu.lastIndex=0;(l=zu.exec(e))!==null;){l.index>r&&n.push(e.slice(r,l.index));let i=l[0].replace(og,"");n.push(s.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",style:t,children:i},l.index));const a=l[0].slice(i.length);a&&n.push(a),r=l.index+l[0].length}return r===0?e:(rrf(o,e)).filter(Boolean),...(t.user_mentions||[]).map(o=>lf(o,e)).filter(Boolean)];if(r.length===0&&n.length===0)return ws(Ru(e),G.link);const l=new Set([0,e.length]);for(const o of r)o.s>=0&&o.s<=e.length&&l.add(o.s),o.e>=0&&o.e<=e.length&&l.add(o.e);for(const[o,u]of n)o>=0&&o<=e.length&&l.add(o),u>=0&&u<=e.length&&l.add(u);const i=(o,u)=>n.some(([c,y])=>c<=o&&y>=u),a=[...l].sort((o,u)=>o-u);return a.slice(0,-1).map((o,u)=>{const c=a[u+1];if(i(o,c))return null;const y=e.slice(o,c),g=r.filter(x=>x.s<=o&&x.e>=c),h=g.find(x=>x.kind==="url");if(h)return s.jsx("a",{href:h.href,target:"_blank",rel:"noopener noreferrer",style:G.link,children:h.display||y},u);const v=g.find(x=>x.kind==="mention");return v?s.jsx("a",{href:`https://x.com/${v.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:G.link,children:y},u):s.jsx("span",{children:ws(Ru(y),G.link)},u)}).filter(o=>o!==null)}function cg(e,t,n,r,l=G){if(!e)return null;t=t||[],n=n||[],r=r||[];const i=[];for(const u of t)u.length>0&&i.push({s:u.offset,e:u.offset+u.length,kind:"style",style:u.style});for(const u of n){const c=rf(u,e);c&&i.push(c)}for(const u of r){const c=lf(u,e);c&&i.push(c)}if(i.length===0)return ws(e,l.link);const a=new Set([0,e.length]);for(const u of i)u.s>=0&&u.s<=e.length&&a.add(u.s),u.e>=0&&u.e<=e.length&&a.add(u.e);const o=[...a].sort((u,c)=>u-c);return o.slice(0,-1).map((u,c)=>{const y=o[c+1],g=i.filter(N=>N.s<=u&&N.e>=y),h=e.slice(u,y);let v;if(h.includes(` -`)){const N=h.split(` -`);v=N.flatMap((p,f)=>fN.kind==="style"&&N.style==="Code")&&(v=s.jsx("code",{style:l.iCode,children:v})),g.some(N=>N.kind==="style"&&N.style==="Bold")&&(v=s.jsx("strong",{children:v})),g.some(N=>N.kind==="style"&&N.style==="Italic")&&(v=s.jsx("em",{children:v})),g.some(N=>N.kind==="style"&&N.style==="Underline")&&(v=s.jsx("u",{children:v})),g.some(N=>N.kind==="style"&&N.style==="Strikethrough")&&(v=s.jsx("s",{children:v}));const x=g.find(N=>N.kind==="url");if(x){const N=/^https?:\/\/t\.co\//i.test(v);v=s.jsx("a",{href:x.href,target:"_blank",rel:"noopener noreferrer",style:l.link,children:N?x.display:v})}const S=g.find(N=>N.kind==="mention");return S&&(v=s.jsx("a",{href:`https://x.com/${S.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:l.link,children:v})),s.jsx("span",{children:typeof v=="string"?ws(v,l.link):v},c)})}function dg(e,t,n){const r=(n==null?void 0:n.st)||G,l=e.resolved_entities||[];return l.length===0?null:l.map((i,a)=>{var o;switch(i.type){case"divider":return s.jsx("hr",{style:r.bHr},a);case"media":{const u=ur(i.local_path,i.url,t);return u?s.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:c=>{var y;!c.metaKey&&!c.ctrlKey&&(c.preventDefault(),(y=n==null?void 0:n.onImgClick)==null||y.call(n,u))},children:s.jsx("img",{src:u,style:r.bImg,loading:"lazy",alt:""})},a):null}case"tweet":return i.tweet_id?s.jsxs("a",{href:`https://x.com/i/status/${i.tweet_id}`,target:"_blank",rel:"noopener noreferrer",style:r.bTweet,children:[s.jsx(nf,{}),"View post on X"]},a):null;case"link":return i.url?s.jsx("p",{style:r.bP,children:s.jsx("a",{href:i.url,target:"_blank",rel:"noopener noreferrer",style:r.link,children:i.url})},a):null;case"markdown":{const u=i.markdown??((o=i.data)==null?void 0:o.markdown)??"";return s.jsx("pre",{style:r.bMdPre,children:s.jsx("code",{style:r.bMdCode,children:u})},a)}case"emoji":return i.url?s.jsx("img",{src:i.url,alt:"",style:{height:"1.2em",verticalAlign:"middle",margin:"0 1px"}},a):null;default:return null}})}function yi(e,t,n,r){const l=(r==null?void 0:r.st)||G,i=e.type||"",a=e.text||"",o=e.inline_style_ranges||[],u=e.data||{},c=cg(a,o,u.urls||[],u.mentions||[],l);switch(i){case"header-one":return s.jsx("h1",{style:l.bH1,children:c},t);case"header-two":{const y=a.match(/(?:x\.com|twitter\.com)\/i\/status\/(\d+)/);return y?s.jsxs("a",{href:`https://x.com/i/status/${y[1]}`,target:"_blank",rel:"noopener noreferrer",style:l.bTweet,children:[s.jsx(nf,{}),"View post on X"]},t):s.jsx("h2",{style:l.bH2,children:c},t)}case"unstyled":return a.trim()?s.jsx("p",{style:l.bP,children:c},t):s.jsx("span",{style:l.bSpacer},t);case"blockquote":return s.jsx("blockquote",{style:l.bQuote,children:c},t);case"unordered-list-item":case"ordered-list-item":return s.jsx("li",{style:l.bLi,children:c},t);case"atomic":return s.jsx("span",{children:dg(e,n,r)},t);default:return a?s.jsx("p",{style:l.bP,children:c},t):null}}function fg(e,t,n){const r=(n==null?void 0:n.st)||G,l=[];let i=0;for(;i{r&&(l==null||l(!0))},[r,l]);const o=r?gi:G,u=e.cover_media||{},c=e.author||t||{},y=e.first_published_at_secs?tf(e.first_published_at_secs):"",h=[c.screen_name?`@${c.screen_name}`:"",y].filter(Boolean).join(" · "),v=ur(u.local_path,u.url,n),x=ur(c.avatar_local_path,c.avatar_url,n),S=s.jsxs(s.Fragment,{children:[i&&s.jsx(sf,{items:[{src:i,alt:""}],startIndex:0,onClose:()=>a(null)}),v&&s.jsx("a",{href:v,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:N=>{!N.metaKey&&!N.ctrlKey&&(N.preventDefault(),a(v))},children:s.jsx("img",{src:v,style:o.aCover,alt:"Article cover"})}),s.jsxs("div",{style:o.aMeta,children:[e.title&&s.jsx("div",{style:o.aTweetTitle,children:e.title}),s.jsxs("div",{style:o.aAuthorRow,children:[x?s.jsx("img",{src:x,style:o.aAvatar,alt:c.name||""}):s.jsx("div",{style:o.aAvatarPh}),s.jsxs("div",{children:[s.jsx("div",{style:o.aAuthorName,children:c.name||c.screen_name||"Unknown"}),h&&s.jsx("div",{style:o.aAuthorSub,children:h})]})]})]}),s.jsx("hr",{style:o.aDivider}),s.jsx("div",{style:o.aBody,children:fg(e.blocks||[],n,{onImgClick:a,st:o})})]});return r?s.jsx("div",{style:gi.article,children:s.jsx("div",{style:gi.articleInner,children:S})}):s.jsx("div",{style:G.article,children:S})}function hg({photos:e,onOpen:t}){const n=e.length;if(n===0)return null;if(n===1)return s.jsx("a",{href:e[0].src,target:"_blank",rel:"noopener noreferrer",style:{display:"block"},onClick:l=>{!l.metaKey&&!l.ctrlKey&&(l.preventDefault(),t(0))},children:s.jsx("img",{src:e[0].src,alt:e[0].alt||"",style:G.mediaImg,loading:"lazy"})});const r=n<=2?"180px":"140px";return s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gridTemplateRows:n===2?r:`${r} ${r}`,gap:"2px"},children:e.map((l,i)=>s.jsx("a",{href:l.src,target:"_blank",rel:"noopener noreferrer",style:{display:"block",overflow:"hidden",gridRow:n===3&&i===0?"span 2":void 0},onClick:a=>{!a.metaKey&&!a.ctrlKey&&(a.preventDefault(),t(i))},children:s.jsx("img",{src:l.src,alt:l.alt||"",loading:"lazy",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}})},i))})}function sf({items:e,startIndex:t,onClose:n}){const[r,l]=d.useState(t);d.useEffect(()=>{const a=o=>{(o.key==="Escape"||o.key==="ArrowLeft"||o.key==="ArrowRight")&&(o.stopPropagation(),o.preventDefault()),o.key==="Escape"&&n(),o.key==="ArrowRight"&&l(u=>Math.min(u+1,e.length-1)),o.key==="ArrowLeft"&&l(u=>Math.max(u-1,0))};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[n,e.length]);const i=e[r];return s.jsx("div",{style:G.lightboxBackdrop,onClick:n,children:s.jsxs("div",{style:G.lightboxContent,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{style:G.lightboxToolbar,children:[e.length>1&&s.jsxs("span",{style:G.lightboxCounter,children:[r+1," / ",e.length]}),s.jsx("a",{href:i.src,target:"_blank",rel:"noopener noreferrer",style:G.lightboxLink,title:"Open in new tab",children:"↗"}),s.jsx("button",{style:G.lightboxBtn,onClick:n,"aria-label":"Close",children:"×"})]}),s.jsx("img",{src:i.src,alt:i.alt||"",style:G.lightboxImg}),e.length>1&&s.jsxs("div",{style:G.lightboxNav,children:[s.jsx("button",{style:G.lightboxNavBtn,onClick:()=>l(a=>Math.max(a-1,0)),disabled:r===0,children:"‹"}),s.jsx("button",{style:G.lightboxNavBtn,onClick:()=>l(a=>Math.min(a+1,e.length-1)),disabled:r===e.length-1,children:"›"})]})]})})}function Iu({tweet:e,isInThread:t,isLast:n,artifactMap:r}){var f,m;const[l,i]=d.useState(null),a=e.author||{},o=e.created_at_secs?tf(e.created_at_secs):"",u=e.entities||{},c=ur(a.avatar_local_path,a.avatar_url,r),y=t&&!n,g=e.is_quote_status===!0,h=t?G.tweetRowThread:G.tweetRow,v=e.full_text||"",x=((m=(f=e.extended_entities)==null?void 0:f.media)!=null&&m.length?e.extended_entities.media:u.media)||[],S=[],N=[];for(const w of x)if(w.type==="photo"){const C=ur(w.local_path,w.media_url_https,r);C&&S.push({kind:"photo",src:C,alt:w.alt_text||""})}else if(w.type==="video"||w.type==="animated_gif"){const C=w.local_path&&r[w.local_path]||(()=>{var b,k;return(k=(((b=w.video_info)==null?void 0:b.variants)||[]).filter(T=>T.content_type==="video/mp4").sort((T,L)=>(L.bitrate||0)-(T.bitrate||0))[0])==null?void 0:k.url})();C&&N.push({kind:w.type==="animated_gif"?"gif":"video",src:C})}const p=[];for(const w of x){if(!w.url||!(w.type==="photo"?S.some(b=>b.src===ur(w.local_path,w.media_url_https,r)):N.length>0))continue;const E=oo(w,v,w.url);E&&p.push([E.s,E.e])}return s.jsxs(s.Fragment,{children:[l!==null&&s.jsx(sf,{items:S,startIndex:l,onClose:()=>i(null)}),s.jsxs("div",{style:h,children:[s.jsxs("div",{style:G.leftCol,children:[c?s.jsx("img",{src:c,style:G.avatar,alt:a.name||""}):s.jsx("div",{style:G.avatarPh}),y&&s.jsx("div",{style:G.threadLine})]}),s.jsxs("div",{style:G.rightCol,children:[s.jsxs("div",{style:G.authorRow,children:[s.jsx("span",{style:G.authorName,children:a.name||a.screen_name||"Unknown"}),a.screen_name&&s.jsxs("span",{style:G.authorHandle,children:["@",a.screen_name]}),o&&s.jsxs("span",{style:G.datePart,children:["· ",o]}),g&&s.jsx("span",{style:G.qtBadge,title:"Quote tweet",children:"↻ QT"})]}),s.jsx("div",{style:G.tweetText,children:ug(v,u,p)}),S.length>0&&s.jsx("div",{style:G.mediaGrid,children:s.jsx(hg,{photos:S,onOpen:w=>i(w)})}),N.map((w,C)=>s.jsx("div",{style:G.mediaGrid,children:s.jsx("video",{src:w.src,style:G.mediaVideo,controls:!0,loop:w.kind==="gif",muted:w.kind==="gif",autoPlay:w.kind==="gif"})},C)),(e.retweet_count>0||e.favorite_count>0)&&s.jsxs("div",{style:G.stats,children:[e.favorite_count>0&&s.jsxs("span",{children:["❤️ ",e.favorite_count.toLocaleString()]}),e.retweet_count>0&&s.jsxs("span",{children:["🔁 ",e.retweet_count.toLocaleString()]})]})]})]})]})}function mg({archiveId:e,entryUid:t,artifacts:n,entityKind:r,fullPage:l,onXArticle:i}){const[a,o]=d.useState(!0),[u,c]=d.useState(null),[y,g]=d.useState([]);if(d.useEffect(()=>{if(o(!0),c(null),g([]),!n||!e||!t){o(!1);return}const x=n.map((N,p)=>({...N,index:p})).filter(N=>N.artifact_role==="raw_tweet_json");if(x.length===0){c("No tweet data found."),o(!1);return}let S=!1;return Ah(e,t,x.map(N=>N.index)).then(async N=>{if(S)return;const p=/https?:\/\/t\.co\/[A-Za-z0-9]+/g,f=b=>{var T;const k=b.full_text||"";return(((T=b.entities)==null?void 0:T.urls)||[]).map(L=>{var q;if(L.fromIndex!=null&&L.toIndex!=null)return[L.fromIndex,L.toIndex];if(((q=L.indices)==null?void 0:q.length)===2)return[L.indices[0],L.indices[1]];if(L.url){const F=k.indexOf(L.url);if(F!==-1)return[F,F+L.url.length]}return null}).filter(Boolean)},m=(b,k,T)=>b.some(([L,q])=>L<=k&&q>=T),w=new Set;for(const b of N){const k=b.full_text||"",T=f(b);let L;for(p.lastIndex=0;(L=p.exec(k))!==null;)m(T,L.index,L.index+L[0].length)||w.add(L[0])}const C=w.size>0?await Mh([...w]).catch(()=>({})):{},E=N.map(b=>{var F;const k=b.full_text||"",T=f(b),L=[];let q;for(p.lastIndex=0;(q=p.exec(k))!==null;){const X=q[0],Z=C[X];Z&&Z!==X&&!m(T,q.index,q.index+X.length)&&L.push({url:X,expanded_url:Z,display_url:(()=>{try{const ue=new URL(Z);return ue.hostname+(ue.pathname.length>1?"/…":"")}catch{return Z}})(),fromIndex:q.index,toIndex:q.index+X.length})}return L.length===0?b:{...b,entities:{...b.entities||{},urls:[...((F=b.entities)==null?void 0:F.urls)||[],...L]}}});S||g(E)}).catch(N=>{S||c(N.message||"Failed to load tweet.")}).finally(()=>{S||o(!1)}),()=>{S=!0}},[e,t,n]),a)return s.jsx("div",{style:G.loading,children:"Loading…"});if(u)return s.jsxs("div",{style:G.error,children:["Error: ",u]});if(y.length===0)return null;const h=ag(e,t,n);if(r==="tweet_thread")return s.jsx("div",{style:G.threadOuter,children:y.map((x,S)=>s.jsx(Iu,{tweet:x,isInThread:!0,isLast:S===y.length-1,artifactMap:h},x.id||S))});const v=y[0];return v.is_article&&v.article?s.jsx(pg,{article:v.article,tweetAuthor:v.author,artifactMap:h,fullPage:l,onXArticle:i}):s.jsx("div",{style:G.card,children:s.jsx(Iu,{tweet:v,isInThread:!1,isLast:!0,artifactMap:h})})}const gg=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv"]),yg=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),vg=new Set(["jpg","jpeg","png","gif","webp","avif","svg","bmp"]),xg={mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo",m4v:"video/mp4",ogv:"video/ogg"};function af({archiveId:e,entry:t,detail:n,fullPage:r,onXArticle:l}){if(!t)return s.jsx("div",{className:"preview-panel preview-panel--empty",children:s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"Select an entry to preview"})});if(!n)return s.jsx("div",{className:"preview-panel preview-panel--loading",children:s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"Loading…"})});const{summary:i,artifacts:a}=n,o=i.entry_uid,u=i.entity_kind;if(u==="tweet"||u==="tweet_thread"){const v=s.jsx(mg,{archiveId:e,entryUid:o,artifacts:a,entityKind:u,fullPage:r,onXArticle:l});return r?v:s.jsx("div",{className:"preview-tweet-wrap",children:v})}const c=a.findIndex(v=>v.artifact_role==="primary_media");if(c===-1)return s.jsxs("div",{className:"preview-panel preview-panel--no-preview",children:[s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No preview available"}),a.length>0&&s.jsx("ul",{style:{marginTop:"12px",paddingLeft:"20px",fontSize:"0.8rem",color:"var(--muted-2)",fontFamily:"var(--sans)"},children:a.map((v,x)=>s.jsxs("li",{children:[v.artifact_role,": ",v.relpath]},x))})]});const y=a[c],g=`/api/archives/${e}/entries/${o}/artifacts/${c}`,h=y.relpath.split(".").pop().toLowerCase();return gg.has(h)?s.jsx("div",{className:"preview-panel",children:s.jsx(sg,{src:g,contentType:xg[h]||"video/mp4"})}):yg.has(h)?s.jsxs("div",{className:"preview-panel preview-panel--audio",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"12px",padding:"24px",fontFamily:"var(--sans)"},children:[s.jsx("span",{style:{fontSize:"2rem"},children:"🎵"}),s.jsx("span",{style:{color:"var(--ink)",fontSize:"0.95rem",fontWeight:600},children:i.title||o}),s.jsx("audio",{src:g,controls:!0,style:{marginTop:"8px",width:"100%",maxWidth:"400px"}})]}):h==="pdf"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(Lu,{src:g,type:"pdf",title:i.title,originalUrl:i.original_url})}):h==="html"||h==="htm"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(Lu,{src:g,type:"page",title:i.title,originalUrl:i.original_url})}):vg.has(h)?s.jsx("div",{className:"preview-panel",style:{height:"100%"},children:s.jsx(ig,{src:g,alt:i.title||"Image"})}):s.jsxs("div",{className:"preview-panel preview-panel--no-preview",children:[s.jsx("span",{style:{color:"var(--muted)",fontFamily:"var(--sans)",fontSize:"0.9rem"},children:"No preview available"}),s.jsx("ul",{style:{marginTop:"12px",paddingLeft:"20px",fontSize:"0.8rem",color:"var(--muted-2)",fontFamily:"var(--sans)"},children:a.map((v,x)=>s.jsxs("li",{children:[v.artifact_role,": ",v.relpath]},x))})]})}function wg({archiveId:e,entry:t,detail:n,onClose:r}){var l,i;return d.useEffect(()=>{const a=o=>{o.key==="Escape"&&r()};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[r]),s.jsx("div",{className:"preview-modal-backdrop",onClick:r,children:s.jsxs("div",{className:`preview-modal${((l=n==null?void 0:n.summary)==null?void 0:l.entity_kind)==="tweet"||((i=n==null?void 0:n.summary)==null?void 0:i.entity_kind)==="tweet_thread"?"":" preview-modal--full"}`,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{className:"preview-modal-header",children:[s.jsx("span",{className:"preview-modal-title",children:(t==null?void 0:t.title)||(t==null?void 0:t.entry_uid)||"Preview"}),s.jsx("a",{className:"preview-modal-newtab",href:`/preview/${e}/${t==null?void 0:t.entry_uid}`,target:"_blank",rel:"noopener noreferrer",title:"Open in new tab",children:"↗"}),s.jsx("button",{className:"preview-modal-close",onClick:r,"aria-label":"Close preview",children:"×"})]}),s.jsx("div",{className:"preview-modal-body",children:s.jsx(af,{archiveId:e,entry:t,detail:n})})]})})}function Du(e){if(!isFinite(e)||isNaN(e))return"--:--";const t=Math.floor(e/60),n=Math.floor(e%60);return`${t}:${String(n).padStart(2,"0")}`}function kg({entry:e,src:t,archiveId:n,onClose:r}){const l=d.useRef(null),[i,a]=d.useState(!1),[o,u]=d.useState(0),[c,y]=d.useState(NaN),[g,h]=d.useState(1);d.useEffect(()=>{!l.current||!t||(l.current.load(),u(0),y(NaN),a(!1))},[t]),d.useEffect(()=>{l.current&&(l.current.volume=g)},[g]);function v(){const f=l.current;f&&(i?f.pause():f.play().catch(()=>{}))}function x(f){const m=l.current;if(!m||!isFinite(c))return;const w=Number(f.target.value);m.currentTime=w,u(w)}function S(f){h(Number(f.target.value))}const N=(e==null?void 0:e.title)||(e==null?void 0:e.entry_uid)||"Unknown",p=(e==null?void 0:e.source_kind)||"other";return s.jsxs(s.Fragment,{children:[s.jsx("audio",{ref:l,src:t||void 0,preload:"auto",onPlay:()=>a(!0),onPause:()=>a(!1),onEnded:()=>a(!1),onTimeUpdate:()=>{var f;return u(((f=l.current)==null?void 0:f.currentTime)??0)},onLoadedMetadata:()=>{var f;return y(((f=l.current)==null?void 0:f.duration)??NaN)},onDurationChange:()=>{var f;return y(((f=l.current)==null?void 0:f.duration)??NaN)},style:{display:"none"}}),s.jsxs("div",{className:"audio-bar",style:{position:"fixed",bottom:0,left:0,right:0,zIndex:100,background:"var(--paper-3)",borderTop:"1px solid var(--line)",display:"flex",alignItems:"center",gap:"16px",padding:"0 16px",height:"56px",fontFamily:"var(--sans)"},children:[s.jsxs("div",{className:"audio-bar-info",style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0,flex:"0 1 220px",overflow:"hidden"},children:[s.jsx("span",{className:"source-icon",style:{flexShrink:0,width:"18px",height:"18px",display:"flex",alignItems:"center"},dangerouslySetInnerHTML:{__html:Os(p)}}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.85rem",color:"var(--ink)"},title:N,children:N})]}),s.jsxs("div",{className:"audio-bar-controls",style:{display:"flex",alignItems:"center",gap:"10px",flex:"1 1 0",minWidth:0},children:[s.jsx("button",{onClick:v,"aria-label":i?"Pause":"Play",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"var(--ink)",flexShrink:0,fontSize:"1.2rem",lineHeight:1},children:i?"⏸":"▶"}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--muted)",whiteSpace:"nowrap",flexShrink:0},children:Du(o)}),s.jsx("input",{type:"range",min:0,max:isFinite(c)?c:0,step:.1,value:isFinite(o)?o:0,onChange:x,"aria-label":"Seek",style:{flex:1,minWidth:0,accentColor:"var(--accent)"}}),s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--muted)",whiteSpace:"nowrap",flexShrink:0},children:Du(c)})]}),s.jsxs("div",{className:"audio-bar-right",style:{display:"flex",alignItems:"center",gap:"8px",flex:"0 1 160px"},children:[s.jsx("span",{style:{fontSize:"0.85rem",color:"var(--muted)",flexShrink:0},children:"🔊"}),s.jsx("input",{type:"range",min:0,max:1,step:.01,value:g,onChange:S,"aria-label":"Volume",style:{width:"80px",accentColor:"var(--accent)"}}),s.jsx("button",{onClick:r,"aria-label":"Close audio player",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",color:"var(--muted)",fontSize:"1rem",lineHeight:1,marginLeft:"4px"},children:"✕"})]})]})]})}function jg({archiveId:e,entryUid:t}){var h,v;const[n,r]=d.useState(null),[l,i]=d.useState(!0),[a,o]=d.useState(null),[u,c]=d.useState(!1);d.useEffect(()=>{if(!u)return;const x=document.documentElement,S=document.body,N=x.style.colorScheme,p=S.style.background;return x.style.colorScheme="dark",S.style.background="#000",()=>{x.style.colorScheme=N,S.style.background=p}},[u]),d.useEffect(()=>{c(!1),$r(e,t).then(x=>{r(x),i(!1)}).catch(x=>{o((x==null?void 0:x.message)||"Failed to load entry"),i(!1)})},[e,t]);const y=((h=n==null?void 0:n.summary)==null?void 0:h.title)||t,g=(v=n==null?void 0:n.summary)==null?void 0:v.original_url;return s.jsxs("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column",background:u?"#000":"var(--paper)",fontFamily:"var(--sans)"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px",padding:u?"8px 12px":"10px 16px",borderBottom:u?"none":"1px solid var(--line)",flexShrink:0,position:u?"sticky":"relative",top:0,zIndex:20,background:u?"rgba(0,0,0,0.82)":"var(--paper-2)",backdropFilter:u?"blur(12px)":"none",WebkitBackdropFilter:u?"blur(12px)":"none"},children:[s.jsx("a",{href:"/",style:{color:u?"#1d9bf0":"var(--accent)",textDecoration:"none",fontSize:"13px",flexShrink:0},children:"← Archive"}),s.jsx("span",{style:{flex:1,fontSize:"14px",fontWeight:600,color:u?"#e7e9ea":"var(--ink)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:y}),g&&s.jsx("a",{href:g,target:"_blank",rel:"noopener noreferrer",style:{color:u?"#71767b":"var(--muted)",textDecoration:"none",fontSize:"13px",flexShrink:0},children:"Original ↗"})]}),s.jsxs("div",{style:u?{flex:1}:{flex:1,minHeight:0,overflow:"auto",display:"flex",flexDirection:"column"},children:[l&&s.jsx("div",{style:{padding:"48px",textAlign:"center",color:"var(--muted)",fontSize:"14px"},children:"Loading…"}),a&&s.jsx("div",{style:{padding:"48px",textAlign:"center",color:"var(--alert)",fontSize:"14px"},children:a}),n&&s.jsx(af,{archiveId:e,entry:n.summary,detail:n,fullPage:!0,onXArticle:c})]})]})}const Sg=7e3;function Ng({toasts:e,onDismiss:t,onIgnoreUblock:n}){return e.length?s.jsx("div",{className:"toast-stack",role:"log","aria-live":"polite","aria-label":"Notifications",children:e.map(r=>s.jsx(Cg,{toast:r,onDismiss:t,onIgnoreUblock:n},r.id))}):null}function _g(e){if(!e)return null;if(e.length<=52)return e;try{const{hostname:t,pathname:n,search:r}=new URL(e),l=n.split("/").filter(Boolean),i=(l[l.length-1]??"")+r,a=i?`${t}/…/${i}`:t;return a.length<=56?a:a.slice(0,53)+"…"}catch{return"…"+e.slice(-51)}}function Cg({toast:e,onDismiss:t,onIgnoreUblock:n}){const[r,l]=d.useState(!1),i=e.type==="warning",a=e.type==="success";d.useEffect(()=>{if(r)return;const u=setTimeout(()=>t(e.id),Sg);return()=>clearTimeout(u)},[r,e.id,t]);const o=_g(e.locator);return a?s.jsx("div",{className:"toast toast--success",role:"alert","aria-atomic":"true",children:s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✓"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Archived"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsx("div",{className:"toast-btns",children:s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})})]})}):i?s.jsxs("div",{className:"toast toast--warning",role:"alert","aria-atomic":"true",children:[s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"⚠"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Archived with warnings"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsxs("div",{className:"toast-btns",children:[e.text&&s.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(u=>!u),"aria-expanded":r,children:r?"Hide":"Details"}),e.locator&&s.jsx("button",{type:"button",className:"toast-view-btn toast-ignore-btn",onClick:()=>{n==null||n(),t(e.id)},children:"Ignore"}),s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&s.jsx("p",{className:"toast-warning-detail",children:e.text||"The page was captured but one or more browser extensions were unavailable (ad-blocking or cookie-consent). Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config."})]}):s.jsxs("div",{className:"toast toast--error",role:"alert","aria-atomic":"true",children:[s.jsxs("div",{className:"toast-top",children:[s.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✕"}),s.jsxs("div",{className:"toast-body",children:[s.jsx("span",{className:"toast-headline",children:e.headline||"Capture failed"}),o&&s.jsx("span",{className:"toast-locator",title:e.locator,children:o})]}),s.jsxs("div",{className:"toast-btns",children:[e.text&&s.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(u=>!u),children:r?"Hide":"View error"}),s.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&e.text&&s.jsx("pre",{className:"toast-error-detail",children:e.text})]})}const As=d.createContext(null),Eg=["archive","tags","collections","runs","admin","settings"],bg=["profile","tokens","instance","cookies","extensions","storage"],Lr=(()=>{const e=window.location.pathname.match(/^\/preview\/([^/]+)\/([^/]+)/);return e?{archiveId:e[1],entryUid:e[2]}:null})();function At(){const e=window.location.pathname.split("/").filter(Boolean),t=Eg.includes(e[0])?e[0]:"archive",n=t==="settings"&&bg.includes(e[1])?e[1]:"profile",r=new URLSearchParams(window.location.search),l=r.get("q")??"",i=t==="archive"?r.get("tag")??null:null,a=t==="archive"?r.get("entry")??null:null,o=t==="archive"?r.get("collection")??null:null,u=o==="main"?null:o,c=r.get("archive")??null;return{view:t,settingsTab:n,q:l,tag:i,entry:a,collection:u,archive:c}}function Tg(e,t){return e==="archive"?"/":e==="settings"?`/settings/${t}`:`/${e}`}function Pg(){const[e,t]=d.useState("loading"),[n,r]=d.useState(null);d.useEffect(()=>{(async()=>{var $,Q,J;if(await Xh()){t("setup");return}const I=await Zh();if(!I){const{collection:le,archive:Te}=At();try{const Ke=await ju(),Ne=Te?(($=Ke.find(Ms=>Ms.id===Te))==null?void 0:$.id)??((Q=Ke[0])==null?void 0:Q.id):(J=Ke[0])==null?void 0:J.id;if(Ne){await Su(Ne,le),i(Ke),o(Ne),c(le),t("authenticated");return}}catch{}t("login");return}r(I),t("authenticated")})()},[]),d.useEffect(()=>{const _=()=>{n&&(r(null),t("login"))};return window.addEventListener("auth:expired",_),()=>window.removeEventListener("auth:expired",_)},[n]),d.useEffect(()=>{const _=()=>{const{view:I,settingsTab:$,q:Q,tag:J,entry:le,collection:Te}=At();T(I),q($),X(Q),b(J),p(le),m(null),C(le?new Set([le]):new Set),c(Te)};return window.addEventListener("popstate",_),()=>window.removeEventListener("popstate",_)},[]);const[l,i]=d.useState([]),[a,o]=d.useState(null),[u,c]=d.useState(()=>At().collection),[y,g]=d.useState([]),[h,v]=d.useState([]),[x,S]=d.useState(()=>new Set),[N,p]=d.useState(()=>At().entry),[f,m]=d.useState(null),[w,C]=d.useState(()=>{const _=At().entry;return _?new Set([_]):new Set}),[E,b]=d.useState(()=>At().tag),[k,T]=d.useState(()=>At().view),[L,q]=d.useState(()=>At().settingsTab),[F,X]=d.useState(()=>At().q),[Z,ue]=d.useState(""),[Ae,ge]=d.useState(!1),[D,P]=d.useState([]),[H,te]=d.useState([]),[ee,Re]=d.useState(()=>sessionStorage.getItem("captureDialogOpen")==="true"),[Y,ye]=d.useState([]),ce=d.useRef(0),[Ee,Ye]=d.useState(()=>{try{const _=JSON.parse(sessionStorage.getItem("pendingCaptures")||"[]");if(Array.isArray(_))return _}catch{}return[]});d.useEffect(()=>{sessionStorage.setItem("pendingCaptures",JSON.stringify(Ee))},[Ee]);const[Ct,yt]=d.useState(()=>sessionStorage.getItem("ublockWarningIgnored")==="true"),[Ht,ut]=d.useState(null),rt=d.useRef(0),vt=d.useRef(null),Et=d.useRef(!1),O=d.useRef(!0),K=d.useRef(null),de=d.useRef(0),Be=d.useRef(new Map),Dt=(n==null?void 0:n.humanize_slugs)??!1;d.useEffect(()=>{const _=++rt.current;ut(null),!(!f||!a)&&$r(a,f.entry_uid).then(I=>{_===rt.current&&ut(I)}).catch(()=>{})},[f,a]),d.useEffect(()=>{sessionStorage.setItem("captureDialogOpen",ee)},[ee]);const ze=d.useCallback(async(_,I,$,Q)=>{if(_){ge(!0);try{let J;I||$?J=await $h(_,I,$,Q):J=await Su(_,Q),v(J),C(le=>{if(le.size<2)return le;const Te=new Set(J.map(Ne=>Ne.entry_uid)),Ke=new Set([...le].filter(Ne=>Te.has(Ne)));return Ke.size===le.size?le:Ke}),ue(J.length===0?"No results":`${J.length} result${J.length===1?"":"s"}`)}catch{v([]),ue("Search failed. Try again.")}finally{ge(!1)}}},[]);d.useEffect(()=>{e==="authenticated"&&(a||ju().then(_=>{if(i(_),_.length>0){const{archive:I}=At(),$=I?_.find(Q=>Q.id===I):null;o(($==null?void 0:$.id)??_[0].id)}}))},[e,a]),d.useEffect(()=>{if(!a)return;const _=!n;if(O.current){O.current=!1;const $=[];_||($.push(fi(a).then(P)),$.push(Dl(a).then(te))),$.length&&Promise.all($);return}b(null),m(null),p(null),C(new Set),c(null);const I=[ze(a,"",null,null)];_||(I.push(fi(a).then(P)),I.push(Dl(a).then(te))),Promise.all(I)},[a,n]),d.useEffect(()=>{if(a===null)return;const _=setTimeout(()=>{ze(a,F,E,u)},300);return()=>clearTimeout(_)},[F,a,u]),d.useEffect(()=>{a!==null&&(E!==null&&T("archive"),ze(a,F,E,u))},[E,a,u]);const Fn=d.useCallback(_=>{o(_),c(null);const I=new URLSearchParams(window.location.search);I.set("archive",_),I.delete("collection");const $=I.toString();history.replaceState(null,"",window.location.pathname+($?"?"+$:""))},[]);d.useEffect(()=>{if(!a){g([]);return}io(a).then(g).catch(()=>g([]))},[a]);const Nn=d.useCallback(_=>{if(!n){const Q=_?y.find(J=>J.collection_uid===_):y.find(J=>J.slug==="_default_");if(Q!=null&&Q.requires_auth){t("login");return}}c(_),m(null),p(null),C(new Set),ze(a,F,E,_);const I=new URLSearchParams(window.location.search);_?(I.set("collection",_),I.set("archive",a)):(I.delete("collection"),a&&I.set("archive",a));const $=I.toString();history.replaceState(null,"",window.location.pathname+($?"?"+$:""))},[a,F,E,n,y,ze]),tn=d.useCallback(_=>{T(_),_==="tags"&&a&&Dl(a).then(te)},[a]);d.useEffect(()=>{if(Lr)return;const _=Tg(k,L);window.location.pathname!==_&&history.pushState(null,"",_+window.location.search)},[k,L]);const Ve=d.useCallback(_=>{p(_?_.entry_uid:null),m(_)},[]),wr=d.useCallback((_,I)=>{if(Be.current.set(_.entry_uid,_),++de.current,I.shiftKey&&K.current!==null){I.preventDefault();const $=[...document.querySelectorAll("#entries-body [data-entry-uid]")],Q=$.findIndex(Ne=>Ne.dataset.entryUid===K.current),J=$.findIndex(Ne=>Ne.dataset.entryUid===_.entry_uid);if(Q===-1||J===-1){K.current=_.entry_uid,C(new Set([_.entry_uid])),Ve(_);return}const le=Math.min(Q,J),Te=Math.max(Q,J),Ke=new Set($.slice(le,Te+1).map(Ne=>Ne.dataset.entryUid));C(Ke),Ke.size===1&&Ve(_)}else if(I.ctrlKey||I.metaKey){K.current=_.entry_uid;const $=new Set(w);if($.has(_.entry_uid)?$.delete(_.entry_uid):$.add(_.entry_uid),C($),$.size===0)Ve(null);else if($.size===1){const[Q]=$,J=Be.current.get(Q)??h.find(le=>le.entry_uid===Q)??null;if(J)Ve(J);else{const le=++de.current;$r(a,Q).then(Te=>{le===de.current&&(Te!=null&&Te.summary)&&Ve(Te.summary)}).catch(()=>{})}}else Ve(null)}else K.current=_.entry_uid,C(new Set([_.entry_uid])),Ve(_)},[h,w,Ve,a]),Bn=d.useCallback(_=>{b(_)},[]),j=d.useCallback(()=>{b(null)},[]),B=d.useCallback(()=>{a&&Dl(a).then(te)},[a]),M=d.useCallback((_,I)=>{E===_?b(I):E!=null&&E.startsWith(_+"/")&&b(I+E.slice(_.length))},[E]),A=d.useCallback(_=>{(E===_||E!=null&&E.startsWith(_+"/"))&&b(null)},[E]),W=d.useCallback((_,I)=>{v($=>$.map(Q=>Q.entry_uid===_?{...Q,title:I}:Q)),m($=>$&&$.entry_uid===_?{...$,title:I}:$),ut($=>$&&$.summary.entry_uid===_?{...$,summary:{...$.summary,title:I}}:$)},[]),V=d.useCallback(()=>{if(!a||!f)return;const _=++rt.current;$r(a,f.entry_uid).then(I=>{_===rt.current&&ut(I)}).catch(()=>{})},[a,f]),pe=d.useCallback(_=>{const I=h.some($=>$.entry_uid===_);S($=>{const Q=new Set($);return Q.add(_),Q}),v($=>$.filter(Q=>Q.entry_uid!==_)),m($=>($==null?void 0:$.entry_uid)===_?null:$),p($=>$===_?null:$),C($=>{const Q=new Set($);return Q.delete(_),Q}),I||ze(a,F,E,u)},[h,a,F,E,u,ze]),ae=d.useCallback(_=>{const I=new Set(h.map(Q=>Q.entry_uid)),$=[..._].some(Q=>!I.has(Q));S(Q=>{const J=new Set(Q);return _.forEach(le=>J.add(le)),J}),v(Q=>Q.filter(J=>!_.has(J.entry_uid))),C(new Set),m(null),p(null),$&&ze(a,F,E,u)},[h,a,F,E,u,ze]);d.useEffect(()=>{if(w.size>=2)p(null),m(null);else if(w.size===1){const[_]=w;p(_)}else p(null),m(null)},[w]);const xe=d.useMemo(()=>h.filter(_=>w.has(_.entry_uid)),[h,w]);d.useEffect(()=>{if(!N||f)return;const _=h.find(I=>I.entry_uid===N);_&&m(_)},[h,N,f]),d.useEffect(()=>{if(Lr)return;const _=new URLSearchParams(window.location.search).get("archive"),I=new URLSearchParams;F&&I.set("q",F),k==="archive"&&E&&I.set("tag",E),k==="archive"&&N&&I.set("entry",N),k==="archive"&&u?(I.set("collection",u),a&&I.set("archive",a)):_&&a&&I.set("archive",a);const $=I.toString(),Q=window.location.pathname+($?"?"+$:"");window.location.pathname+window.location.search!==Q&&history.replaceState(null,"",Q)},[F,E,N,u,a,k]),d.useEffect(()=>{const _=I=>{var le,Te,Ke,Ne;const $=I.key==="/"&&!I.metaKey&&!I.ctrlKey&&!I.altKey,Q=(I.metaKey||I.ctrlKey)&&I.key==="k";if(!$&&!Q)return;const J=(le=document.activeElement)==null?void 0:le.tagName;$&&(J==="INPUT"||J==="TEXTAREA"||J==="SELECT")||$&&((Te=document.activeElement)!=null&&Te.isContentEditable)||(I.preventDefault(),k==="archive"?((Ke=vt.current)==null||Ke.focus(),(Ne=vt.current)==null||Ne.select()):(Et.current=!0,T("archive")))};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[k]),d.useEffect(()=>{const _=I=>{var co,fo;if(I.metaKey||I.ctrlKey||I.altKey||I.key!=="j"&&I.key!=="k")return;const $=(co=document.activeElement)==null?void 0:co.tagName;if($==="INPUT"||$==="TEXTAREA"||$==="SELECT"||(fo=document.activeElement)!=null&&fo.isContentEditable)return;const Q=[...document.querySelectorAll("#entries-body [data-entry-uid]")];if(Q.length===0)return;const[J]=w.size===1?w:[null],le=J?Q.findIndex(nn=>nn.dataset.entryUid===J):-1,Te=I.key==="j"?Math.min(le+1,Q.length-1):Math.max(le-1,0);if(Te===le&&le!==-1)return;const Ke=Q[Te<0?0:Te],Ne=Ke.dataset.entryUid;K.current=Ne;const Ms=++de.current;C(new Set([Ne]));const uo=Be.current.get(Ne)??h.find(nn=>nn.entry_uid===Ne)??null;uo?Ve(uo):$r(a,Ne).then(nn=>{Ms===de.current&&(nn!=null&&nn.summary)&&Ve(nn.summary)}).catch(()=>{}),Ke.scrollIntoView({block:"nearest"}),I.preventDefault()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[w,h,Ve,a]),d.useEffect(()=>{k==="archive"&&Et.current&&(Et.current=!1,requestAnimationFrame(()=>{var _,I;(_=vt.current)==null||_.focus(),(I=vt.current)==null||I.select()}))},[k]);const ie=d.useCallback(()=>{Re(!0)},[]),Qe=d.useCallback(()=>{Re(!1)},[]),we=d.useCallback(()=>{if(a)return Promise.allSettled([ze(a,F,E,u),fi(a).then(P)])},[a,F,E,u,ze]),Un=d.useCallback((_,I,$="error",Q=null)=>{if($==="warning"&&Ct&&I)return;const J=++ce.current;ye(le=>[...le,{id:J,text:_,locator:I,type:$,headline:Q}])},[Ct]),xt=d.useCallback(_=>{ye(I=>I.filter($=>$.id!==_))},[]),gl=d.useCallback(()=>{sessionStorage.setItem("ublockWarningIgnored","true"),yt(!0),ye(_=>_.filter(I=>!(I.type==="warning"&&I.locator)))},[]),z=d.useCallback(_=>{Ye(I=>[...I,_])},[]),re=d.useCallback(_=>{Ye(I=>I.filter($=>$.id!==_))},[]),[be,$t]=d.useState(null),[Wt,kr]=d.useState(null),Ie=d.useCallback(()=>{f&&$t(f.entry_uid)},[f]),jr=d.useCallback(()=>$t(null),[]),of=d.useCallback((_,I)=>{kr({src:_,entry:I})},[]),uf=d.useCallback(()=>kr(null),[]);return d.useEffect(()=>{$t(null)},[f]),d.useEffect(()=>{const _=I=>{var Q,J,le;if(I.key!=="Escape"||ee||be)return;const $=(Q=document.activeElement)==null?void 0:Q.tagName;$==="INPUT"||$==="TEXTAREA"||$==="SELECT"||w.size>0&&(I.preventDefault(),C(new Set),(le=(J=document.activeElement)==null?void 0:J.blur)==null||le.call(J))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[ee,be,w]),d.useEffect(()=>(document.body.classList.toggle("has-audio-bar",!!Wt),()=>document.body.classList.remove("has-audio-bar")),[Wt]),Lr?s.jsx(jg,{archiveId:Lr.archiveId,entryUid:Lr.entryUid}):e==="loading"?s.jsx("div",{className:"auth-loading",children:"Loading\\u2026"}):e==="setup"?s.jsx(Em,{onComplete:()=>t("login")}):e==="login"?s.jsx(Cm,{onLogin:_=>{r(_),t("authenticated")}}):s.jsx(As.Provider,{value:{currentUser:n,setCurrentUser:r},children:s.jsxs(s.Fragment,{children:[s.jsx(bm,{archives:l,archiveId:a,onArchiveChange:Fn,view:k,onViewChange:tn,onCaptureClick:ie,collections:y,selectedCollectionUid:u,onCollectionChange:Nn,isPublicSession:!n,onSignInClick:()=>t("login")}),s.jsxs("main",{className:"app-shell",children:[s.jsxs("div",{className:"workspace",children:[k==="archive"&&s.jsxs("div",{className:"toolbar",children:[s.jsxs("div",{className:"search-field",children:[s.jsx("span",{className:"ico","aria-hidden":"true",children:s.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("circle",{cx:"11",cy:"11",r:"7"}),s.jsx("line",{x1:"16.5",y1:"16.5",x2:"21",y2:"21"})]})}),s.jsx("input",{ref:vt,className:"search-input",type:"search","aria-label":"Search archive","aria-busy":Ae,placeholder:"Search titles, URLs, types, tags…",value:F,onChange:_=>X(_.target.value)}),s.jsx("span",{className:"kbd",children:"⌘K"})]}),s.jsxs("span",{className:"result-count",children:[Z&&s.jsxs(s.Fragment,{children:[s.jsx("b",{children:Z.split(" ")[0]})," ",Z.split(" ").slice(1).join(" ")]}),E&&s.jsxs("button",{className:"tag-filter-badge",onClick:j,children:["× ",Dt?Gd(E):E]})]})]}),k==="archive"&&s.jsx(Am,{entries:h,selectedUids:w,onRowClick:wr,archiveId:a,pendingCaptures:Ee,deletedUids:x,isPublicSession:!n}),k==="runs"&&s.jsx(Bm,{runs:D}),k==="admin"&&s.jsx(Hm,{archives:l}),k==="tags"&&s.jsx(Wm,{archiveId:a,tagNodes:H,tagFilter:E,onTagFilterSet:Bn,onViewChange:tn,onTagRenamed:M,onTagDeleted:A,onTagsRefresh:B,humanizeTags:Dt}),k==="collections"&&s.jsx(Qm,{archiveId:a}),k==="settings"&&s.jsx(qm,{tab:L,onTabChange:q,archiveId:a})]}),s.jsx(ng,{archiveId:a,selectedEntry:f,selectedUids:w,selectedEntries:xe,detail:Ht,onTagFilterSet:Bn,tagNodes:H,onTagsRefresh:B,onEntryTitleChange:W,onEntryDeleted:pe,onBulkDeleted:ae,humanizeTags:Dt,onDetailRefresh:V,onOpenPreview:Ie,onPlay:of,isPublicSession:!n})]}),be&&f&&f.entry_uid===be&&s.jsx(wg,{archiveId:a,entry:f,detail:Ht,onClose:jr}),Wt&&s.jsx(kg,{entry:Wt.entry,src:Wt.src,archiveId:a,onClose:uf}),s.jsx(Lm,{open:ee,archiveId:a,onClose:Qe,onCaptured:we,onToast:Un,activeJobs:Ee,onJobStarted:z,onJobSettled:re}),s.jsx(Ng,{toasts:Y,onDismiss:xt,onIgnoreUblock:gl})]})})}qd(document.getElementById("root")).render(s.jsx(d.StrictMode,{children:s.jsx(Pg,{})})); diff --git a/crates/archivr-server/static/assets/index-DicH9MNh.css b/crates/archivr-server/static/assets/index-DicH9MNh.css deleted file mode 100644 index 8ca8c49..0000000 --- a/crates/archivr-server/static/assets/index-DicH9MNh.css +++ /dev/null @@ -1 +0,0 @@ -@import"https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@500;600&family=Spectral:wght@500;600&display=swap";:root{color-scheme:light;--ink: #20251f;--muted: #6b6f66;--muted-2: #8a8d83;--paper: #f5f0e7;--paper-2: #e9e1d2;--paper-3: #fffaf0;--line: #d2c6b5;--line-soft: #e5dccd;--accent: #8d3f30;--accent-2: #b78342;--link: #245f72;--top: #141d18;--field: #fffdf7;--r: 3px;--r2: 6px;--r3: 10px;--sans: "Helvetica Neue", Helvetica, Arial, sans-serif;--serif: "Spectral", Georgia, "Times New Roman", serif;--display: "Cormorant Garamond", Georgia, serif}*{box-sizing:border-box}body{margin:0;min-height:100vh;background:var(--paper);color:var(--ink);font-family:var(--sans);font-size:14px;-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}button,input,select{font:inherit}.workspace,.context-rail{scrollbar-width:thin;scrollbar-color:var(--line) transparent}.workspace::-webkit-scrollbar,.context-rail::-webkit-scrollbar{width:11px;height:11px}.workspace::-webkit-scrollbar-track,.context-rail::-webkit-scrollbar-track{background:transparent}.workspace::-webkit-scrollbar-thumb,.context-rail::-webkit-scrollbar-thumb{background:var(--line);border-radius:999px;border:3px solid transparent;background-clip:padding-box}.workspace::-webkit-scrollbar-thumb:hover,.context-rail::-webkit-scrollbar-thumb:hover{background:var(--muted-2);background-clip:padding-box;border:3px solid transparent}.topbar{height:58px;display:grid;grid-template-columns:auto auto 1fr auto auto;align-items:center;gap:26px;padding:0 22px;background:var(--top);color:#efe6d6;border-bottom:3px solid var(--accent)}.brand{font-family:var(--display);font-weight:600;font-size:30px;line-height:1;letter-spacing:.01em;color:#f4ead8}.switcher{position:relative;display:inline-flex;align-items:center}.switcher select{-moz-appearance:none;appearance:none;-webkit-appearance:none;border:1px solid rgba(247,238,223,.2);background:#f7eedf0f;color:#f1e8d8;font-family:var(--sans);font-weight:550;font-size:13.5px;letter-spacing:.04em;padding:8px 32px 8px 15px;cursor:pointer;border-radius:6px;transition:background .15s ease,border-color .15s ease}.switcher select:hover{background:#f7eedf1c;border-color:#f7eedf57}.switcher:after{content:"";position:absolute;right:15px;top:50%;width:6px;height:6px;margin-top:-5px;border-right:1.2px solid #b6ab98;border-bottom:1.2px solid #b6ab98;transform:rotate(45deg);pointer-events:none}.switchers{display:flex;gap:8px;align-items:center;min-width:0}.nav{display:flex;gap:22px;justify-content:flex-end;min-width:0}.nav-link{border:0;background:transparent;color:#cdc1ad;cursor:pointer;padding:6px 0;font-size:12.5px;font-weight:600;letter-spacing:.1em;text-transform:uppercase;position:relative}.nav-link:hover,.nav-link.is-active{color:#f4ead8}.nav-link.is-active:after{content:"";position:absolute;left:0;right:0;bottom:-2px;height:1px;background:var(--accent-2)}.capture-button{display:inline-flex;align-items:center;gap:8px;position:relative;overflow:hidden;border:0;background:linear-gradient(180deg,color-mix(in srgb,var(--accent) 88%,#fff) 0%,var(--accent) 55%);color:#f7eddd;padding:10px 18px;cursor:pointer;font-size:12px;font-weight:600;letter-spacing:.15em;text-transform:uppercase;border-radius:var(--r);box-shadow:inset 0 1px #fff5e629,0 1px 2px #141d184d;transition:filter .18s ease,box-shadow .18s ease}.capture-button:hover{filter:brightness(.93);box-shadow:inset 0 1px #fff5e61f,0 2px 6px #141d1857}.capture-button:before{content:"";position:absolute;top:0;bottom:0;left:0;width:45%;background:linear-gradient(100deg,transparent 0%,rgba(255,246,232,.45) 50%,transparent 100%);transform:translate(-180%) skew(-18deg);pointer-events:none}@media (prefers-reduced-motion: no-preference){.capture-button:hover:before{animation:cap-sheen .7s ease}}@keyframes cap-sheen{0%{transform:translate(-180%) skew(-18deg)}to{transform:translate(340%) skew(-18deg)}}.app-shell{height:calc(100vh - 58px);display:grid;grid-template-columns:minmax(0,1fr) 340px}.workspace{min-width:0;overflow:auto;display:flex;flex-direction:column}.view{display:none}.view.is-active{display:block}.toolbar{position:sticky;top:0;z-index:3;display:flex;align-items:center;gap:16px;padding:12px 22px;background:color-mix(in srgb,var(--paper) 88%,white);border-bottom:1px solid var(--line-soft)}.search-field{position:relative;flex:1 1 auto;min-width:0;display:flex;align-items:center;height:42px;background:var(--field);border:1px solid var(--line);border-radius:20px;transition:border-color .15s ease,box-shadow .15s ease}.search-field:focus-within{border-color:var(--accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 14%,transparent)}.search-field .ico{display:grid;place-items:center;width:46px;height:100%;color:var(--muted-2);flex-shrink:0}.search-field .ico svg{width:16px;height:16px}.search-input{flex:1;min-width:0;height:100%;border:0;background:transparent;color:var(--ink);padding:0 6px 0 0;font-size:14px;letter-spacing:.01em;outline:none}.search-input::placeholder{color:var(--muted-2)}.search-field .kbd{margin-right:12px;display:inline-flex;align-items:center;padding:3px 7px;font-size:11px;color:var(--muted);background:var(--paper-2);border:1px solid var(--line-soft);border-radius:var(--r);flex-shrink:0}.result-count{flex-shrink:0;font-size:13px;color:var(--muted);letter-spacing:.02em;white-space:nowrap}.result-count b{color:var(--ink);font-weight:600;font-variant-numeric:tabular-nums}.tag-filter-badge{display:inline-flex;align-items:center;gap:4px;background:var(--accent);color:#fff;border:0;border-radius:var(--r);font-size:12px;padding:2px 8px;cursor:pointer;margin-left:8px}.tag-filter-badge:hover{opacity:.85}.entry-table{width:100%;font-size:12.5px}.entry-header-row{display:flex;align-items:stretch;position:sticky;top:67px;z-index:2;background:color-mix(in srgb,var(--paper) 92%,white);border-bottom:1px solid var(--line-soft);color:var(--muted);font-size:10.5px;text-transform:uppercase;letter-spacing:.08em}.entry-header-row>div{padding:9px 10px;flex-shrink:0;font-weight:600;display:flex;align-items:center}#entries-body>div{display:flex;align-items:center;cursor:default;border-bottom:1px solid var(--line-soft)}#entries-body>div>div{padding:7px 10px;flex-shrink:0;overflow:hidden}#entries-body>div:not(.entry-row-outer):nth-child(2n){background:#f2ede5}#entries-body>div:not(.entry-row-outer):nth-child(odd){background:var(--paper-3)}#entries-body>.entry-row-outer--light{background:var(--paper-3)}#entries-body>.entry-row-outer--dark{background:#f2ede5}#entries-body>div.is-selected{background:#eee2d2;box-shadow:inset 0 0 0 2px var(--accent)}#entries-body>div.is-multi-selected{background:#eee2d2;box-shadow:inset 0 0 0 2px var(--accent)}.col-added{width:162px;color:var(--muted)}.col-title{flex:1 1 0;min-width:0;overflow:hidden;display:flex;align-items:center;gap:.42em}.col-type{width:116px}.col-size{width:100px;display:flex;flex-direction:column;justify-content:center;gap:1px}.size-total{font-variant-numeric:tabular-nums}.size-cached-pct{font-size:10px;color:var(--muted);opacity:.8;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.col-url{flex:0 0 30%;min-width:0;overflow:hidden}.entry-header-row .col-added,#entries-body>div .col-added{padding-left:22px}.entry-header-row>div:last-child,#entries-body>div>div:last-child{padding-right:22px}.entry-title{color:var(--link);font-weight:700;min-width:0}.entry-header-row>div{padding:9px 10px;flex-shrink:0;font-weight:600}.source-icon{display:flex;align-items:center;justify-content:center;width:1.05em;height:1.05em;flex-shrink:0}.source-icon>*{width:100%;height:100%;display:flex;align-items:center;justify-content:center}.source-icon svg{width:100%;height:100%}.url-cell{color:#555b55;white-space:nowrap;text-overflow:ellipsis;word-break:break-all}#entries-body .url-cell:hover{overflow:visible;white-space:normal}.type-pill{display:inline-block;padding:2px 6px;background:#d8e3df;color:#275a5f;border:1px solid #bfd0ca;border-radius:var(--r)}.col-check{display:none;width:40px;flex-shrink:0;align-items:center;justify-content:center;padding:0!important;cursor:pointer}.row-checkbox{-webkit-appearance:none;-moz-appearance:none;appearance:none;padding:0;border:1.5px solid var(--line);cursor:pointer;display:block;width:17px;height:17px;border-radius:4px;background:var(--paper-3);transition:border-color .15s ease,background .15s ease;position:relative;flex-shrink:0}.row-checkbox.is-checked{background:var(--accent);border-color:var(--accent)}.row-checkbox.is-checked:after{content:"";position:absolute;left:4px;top:2px;width:5px;height:8px;border:2px solid #fff;border-top:none;border-left:none;transform:rotate(45deg)}@media (pointer: coarse){.col-check{display:flex}.entry-header-row .col-added,#entries-body>div .col-added{padding-left:10px}}#runs-view .entry-table{border-collapse:collapse;table-layout:auto}#runs-view .entry-table th{position:sticky;top:0;z-index:1;text-align:left;padding:10px;background:color-mix(in srgb,var(--paper) 92%,white);color:var(--muted);border-bottom:1px solid var(--line-soft);font-size:10.5px;text-transform:uppercase;letter-spacing:.08em}#runs-view .entry-table td{padding:10px;border-bottom:1px solid var(--line-soft);vertical-align:top}#runs-view .entry-table tr:nth-child(2n) td{background:#f2ede5}#runs-view .entry-table tr:nth-child(odd) td{background:var(--paper-3)}.context-rail{border-left:1px solid var(--line);background:var(--paper);padding:20px 20px 32px;overflow:auto}.rail-eyebrow{font-size:10.5px;font-weight:600;letter-spacing:.16em;text-transform:uppercase;color:var(--muted-2);margin-bottom:16px}.rail-title{display:block;font-family:var(--sans);font-weight:700;font-size:15.5px;line-height:1.4;color:var(--ink);margin:0 0 16px;word-break:break-word}.url-tile{display:flex;align-items:center;gap:9px;padding:10px 12px;background:var(--paper-3);border:1px solid var(--line);border-radius:var(--r3);margin-bottom:20px;text-decoration:none}.url-tile:hover{background:var(--field);border-color:var(--accent)}.url-tile .ico{color:var(--ink);flex-shrink:0;display:grid;place-items:center}.url-tile .ico svg{width:15px;height:15px}.url-tile .u-text{min-width:0;flex:1;font-size:12.5px;color:var(--link);font-family:ui-monospace,SF Mono,Menlo,monospace;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.url-tile .ext{color:var(--muted-2);flex-shrink:0}.url-tile .ext svg{width:13px;height:13px;display:block}.meta-list{margin-bottom:24px;border-top:1px solid var(--line-soft)}.meta-item{display:grid;grid-template-columns:92px 1fr;gap:14px;align-items:baseline;padding:9px 0;border-bottom:1px solid var(--line-soft)}.meta-k{font-size:10.5px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--muted-2)}.meta-v{font-size:13.5px;color:var(--ink);word-break:break-word;line-height:1.4}.meta-v.mono{font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:12px;color:var(--muted)}.rail-section{margin-bottom:24px}.rail-section-heading{display:flex;align-items:baseline;gap:8px;font-size:10.5px;font-weight:600;text-transform:uppercase;letter-spacing:.12em;color:var(--muted-2);margin-bottom:9px;padding-bottom:8px;border-bottom:1px solid var(--line)}.rail-section-heading .num{color:var(--muted-2);font-weight:600}.artifact-list{list-style:none;margin:0;padding:0}.artifact-link{display:flex;align-items:baseline;justify-content:space-between;gap:12px;padding:7px 2px;border-bottom:1px solid var(--line-soft);text-decoration:none}.artifact-link:last-child{border-bottom:0}.artifact-name{font-size:13px;color:var(--link);min-width:0;word-break:break-word}.artifact-link:hover .artifact-name{text-decoration:underline}.artifact-size{font-size:11.5px;color:var(--muted-2);flex-shrink:0;font-variant-numeric:tabular-nums}.artifact-group{list-style:none}.artifact-group-header{width:100%;background:none;border:none;border-bottom:1px solid var(--line-soft);cursor:pointer;text-align:left;color:inherit;font:inherit}.artifact-group-header:hover .artifact-name{text-decoration:underline}.artifact-group-chevron{display:inline-block;font-style:normal;transition:transform .15s ease;transform:rotate(0);transform-origin:45% 50%;margin-right:3px}.artifact-group-chevron.open{transform:rotate(90deg)}.artifact-group-body{padding-left:14px}.tags-wrap{display:flex;flex-wrap:wrap;gap:7px;margin:0 0 12px}.tag-pill{display:inline-flex;align-items:center;gap:7px;background:var(--paper-2);border:1px solid var(--line);border-radius:var(--r);font-size:12px;padding:4px 7px 4px 10px;color:var(--ink)}.tag-pill .remove{border:0;background:transparent;cursor:pointer;color:var(--muted-2);width:15px;height:15px;display:grid;place-items:center;font-size:13px;line-height:1}.tag-pill .remove:hover{color:var(--accent)}.tags-empty{font-size:13px;color:var(--muted);margin:0 0 11px}.tag-input-wrap{display:flex;align-items:center;gap:8px;background:var(--field);border:1px solid var(--line);border-radius:var(--r2);padding:2px 2px 2px 11px;transition:border-color .15s ease,box-shadow .15s ease}.tag-input-wrap:focus-within{border-color:var(--accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 12%,transparent)}.tag-input-wrap .hash{color:var(--muted-2);font-size:13px}.tag-input{flex:1;min-width:0;border:0;background:transparent;color:var(--ink);font-size:13px;padding:6px 0;outline:none;font-family:ui-monospace,SF Mono,Menlo,monospace}.tag-add-btn{border:0;background:var(--ink);color:var(--paper-3);padding:6px 13px;font-size:11.5px;letter-spacing:.06em;text-transform:uppercase;border-radius:var(--r);cursor:pointer;white-space:nowrap}.tag-add-btn:hover{background:#2c332b}.coll-row{display:flex;align-items:center;justify-content:space-between;gap:12px;overflow:hidden;padding:9px 13px;background:var(--field);border:1px solid var(--line);border-radius:var(--r2);margin-bottom:6px;transition:border-color .15s ease}.coll-row:hover{border-color:var(--accent)}.coll-name{font-size:13px;color:var(--ink);font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.vis-badge{display:inline-flex;align-items:center;gap:6px;font-size:11px;color:var(--muted);background:var(--paper-2);border:1px solid var(--line-soft);border-radius:999px;padding:3px 10px}.vis-badge:before{content:"";width:6px;height:6px;border-radius:50%;background:var(--accent-2)}.bulk-panel{padding-top:2px}.bulk-count{font-size:13px;color:var(--muted);margin-bottom:22px}.bulk-count-num{font-size:22px;font-weight:700;color:var(--ink);line-height:1;margin-right:4px}.bulk-coll-row{display:flex;align-items:center;gap:8px}.bulk-coll-select{flex:1;min-width:0;height:32px;padding:0 8px;border:1px solid var(--line);border-radius:var(--r);background:var(--field);color:var(--ink);font-size:13px;cursor:pointer;outline:none;transition:border-color .15s ease}.bulk-coll-select:focus{border-color:var(--accent)}.tag-add-btn:disabled{opacity:.45;cursor:default}.rail-delete-zone{margin-top:24px;padding-top:20px;border-top:1px solid var(--line-soft)}.rail-delete-btn{width:100%;padding:8px 14px;background:none;border:1px solid color-mix(in srgb,var(--accent) 45%,transparent);color:var(--accent);border-radius:var(--r);cursor:pointer;font-size:12.5px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;transition:background .15s ease,border-color .15s ease}.rail-delete-btn:hover{background:color-mix(in srgb,var(--accent) 8%,transparent);border-color:var(--accent)}.rail-rearchive-btn{width:100%;padding:6px 12px;background:var(--surface-2, #2a2a2a);color:var(--text, #e0e0e0);border:1px solid var(--border, #444);border-radius:4px;cursor:pointer;font-size:13px}.rail-rearchive-btn:hover:not(:disabled){background:var(--surface-3, #333)}.rail-rearchive-btn:disabled{opacity:.6;cursor:not-allowed}.capture-dialog{border:1px solid var(--line);background:var(--paper);padding:0;width:min(540px,calc(100vw - 32px));border-radius:var(--r3);box-shadow:0 20px 60px #141d1847}.capture-dialog::backdrop{background:#141d1873}.capture-dialog-inner{padding:28px}.capture-dialog-title{margin:0;font-size:22px;font-family:var(--display);font-weight:600}.capture-label{display:block;font-size:11px;font-weight:600;margin-bottom:6px;color:var(--muted-2);text-transform:uppercase;letter-spacing:.06em}.capture-input{width:100%;height:44px;border:1px solid var(--line);background:var(--field);color:var(--ink);padding:0 14px;font-size:15px;margin-bottom:10px;border-radius:var(--r2);outline:none;transition:border-color .15s ease,box-shadow .15s ease}.capture-input:focus{border-color:var(--accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 14%,transparent)}.form-field .capture-input{margin-bottom:0}.capture-error{color:var(--accent);font-size:13px;margin-bottom:10px;min-height:18px}.capture-actions{display:flex;flex-direction:column;gap:8px;margin-top:18px}.capture-submit{border:0;background:var(--ink);color:var(--paper);padding:13px 20px;border-radius:var(--r2);cursor:pointer;font-weight:600;font-size:15px;width:100%;min-width:220px;letter-spacing:.01em}.capture-submit:hover{opacity:.85}.capture-submit:disabled{opacity:.45;cursor:default}.capture-cancel{border:0;background:none;color:var(--muted);padding:7px 18px;border-radius:var(--r);cursor:pointer;font-size:13px;text-align:center;width:100%}.capture-cancel:hover{color:var(--ink);background:var(--paper-2)}.capture-advanced{margin-top:12px}.capture-advanced-toggle{display:flex;align-items:center;gap:5px;background:none;border:0;cursor:pointer;color:var(--muted);font-size:12.5px;padding:4px 0;border-radius:var(--r)}.capture-advanced-toggle:hover{color:var(--ink)}.capture-chevron{width:14px;height:14px;flex-shrink:0;transition:transform .18s ease}.capture-chevron--open{transform:rotate(180deg)}.capture-advanced-panel{margin-top:8px;padding:10px 12px;border:1px solid var(--line);border-radius:var(--r2);background:var(--paper-2)}.capture-ext-row{display:flex;align-items:center;justify-content:space-between;gap:12px;cursor:default}.capture-ext-label{flex:1;min-width:0}.capture-ext-name{display:block;font-size:13px;font-weight:600;color:var(--ink)}.capture-ext-desc{display:block;font-size:11.5px;color:var(--muted);margin-top:1px}.capture-dialog-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:20px}.capture-dialog-close{flex-shrink:0;background:none;border:0;cursor:pointer;color:var(--muted);width:28px;height:28px;display:grid;place-items:center;border-radius:var(--r);padding:0}.capture-dialog-close svg{width:14px;height:14px}.capture-dialog-close:hover{background:var(--paper-2);color:var(--ink)}.capture-rows{display:flex;flex-direction:column;gap:8px;margin-bottom:8px}.capture-row{display:flex;flex-direction:column;gap:3px}.capture-row-main{display:flex;align-items:center;gap:8px}.capture-row-main .capture-input{margin-bottom:0}.capture-quality{flex-shrink:0;height:32px;padding:0 6px;border:1px solid var(--line);border-radius:var(--r);background:var(--paper);color:var(--ink);font-size:12px;cursor:pointer;outline:none;transition:border-color .15s}.capture-quality:hover{border-color:var(--accent-2)}.capture-quality:focus{border-color:var(--accent)}.capture-quality:disabled{opacity:.5;cursor:default}.capture-quality-probing{flex-shrink:0;font-size:12px;color:var(--muted);padding:0 4px;letter-spacing:.05em}.capture-quality-hint{flex-shrink:0;font-size:12px;color:var(--muted);font-style:italic}.capture-quality-hint--error{color:#c05000;font-style:normal}.cap-dot{flex-shrink:0;width:20px;height:20px;border-radius:50%;display:grid;place-items:center;font-size:10px;font-weight:700;line-height:1}.cap-dot--idle{background:var(--paper-2)}.cap-dot--running{background:#fdefd8;color:#8a4f10}.cap-dot--ok{background:#d8eddf;color:#235c35}.cap-dot--err{background:#f5ddd8;color:#8d3f30}.cap-spinner{display:block;width:10px;height:10px;border:2px solid currentColor;border-top-color:transparent;border-radius:50%;animation:cap-spin .7s linear infinite}@keyframes cap-spin{to{transform:rotate(360deg)}}.capture-row-action{flex-shrink:0;background:none;border:0;cursor:pointer;color:var(--muted);width:28px;height:28px;display:grid;place-items:center;border-radius:var(--r);padding:0}.capture-row-action svg{width:12px;height:12px}.capture-row-action:hover{color:var(--accent);background:var(--paper-2)}.capture-row-remove:hover{color:var(--accent)}.capture-row-error{margin:0;padding-left:28px;font-size:12px;color:var(--accent);line-height:1.45}.capture-add-row{display:flex;align-items:center;gap:7px;width:100%;background:none;border:1px dashed var(--line);border-radius:var(--r);color:var(--muted);font-size:13px;cursor:pointer;padding:7px 12px;margin-top:4px;margin-bottom:18px;transition:border-color .15s,color .15s,background .15s}.capture-add-row svg{width:13px;height:13px;flex-shrink:0}.capture-add-row:hover{border-color:var(--accent-2);color:var(--ink);background:var(--paper-2)}.capture-add-row-group{display:flex;gap:8px;margin-top:4px;margin-bottom:18px}.capture-add-row-group .capture-add-row{margin-top:0;margin-bottom:0;flex:1}.capture-dialog--dragover .capture-dialog-inner{outline:2px dashed var(--accent);outline-offset:-6px;border-radius:var(--r3)}.capture-file-icon{flex-shrink:0;color:var(--muted);display:flex;align-items:center}.capture-file-name{flex:1;min-width:0;font-size:13.5px;color:var(--ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.capture-file-name--error{color:var(--accent)}.capture-file-progress-wrap{flex-shrink:0;display:flex;align-items:center;gap:6px}.capture-file-progress-bar{width:80px;height:4px;border-radius:2px;background:var(--paper-2);overflow:hidden;border:1px solid var(--line)}.capture-file-progress-fill{display:block;height:100%;background:var(--ink);border-radius:2px;transition:width .1s ease}.capture-file-progress-pct{font-size:11px;color:var(--muted);min-width:28px;text-align:right}.capture-file-badge{flex-shrink:0;width:18px;height:18px;border-radius:50%;display:grid;place-items:center;font-size:11px;font-weight:700;line-height:1}.capture-file-badge--done{background:#d8eddf;color:#235c35}.capture-file-badge--error{background:#f5ddd8;color:#8d3f30}.toast-stack{position:fixed;bottom:24px;right:24px;z-index:9000;display:flex;flex-direction:column;gap:10px;width:340px;max-width:calc(100vw - 32px);pointer-events:none}.toast{pointer-events:auto;background:var(--paper);border:1px solid var(--line);border-radius:var(--r2);box-shadow:0 6px 24px #141d182e,0 1px 4px #141d181a;overflow:hidden;animation:toast-slide-in .22s cubic-bezier(.22,.68,0,1.2)}@keyframes toast-slide-in{0%{opacity:0;transform:translateY(10px) scale(.97)}to{opacity:1;transform:translateY(0) scale(1)}}.toast--error{border-left:3px solid var(--accent)}.toast--warning{border-left:3px solid #e8a000}.toast--success{border-left:3px solid #22a855}.toast-top{display:flex;align-items:flex-start;gap:10px;padding:12px 12px 12px 14px}.toast-icon{flex-shrink:0;font-size:13px;font-weight:700;color:var(--accent);margin-top:2px}.toast--success .toast-icon{color:#22a855}.toast--warning .toast-icon{color:#e8a000}.toast-body{flex:1;min-width:0}.toast-headline{display:block;font-size:13.5px;font-weight:600;color:var(--ink);line-height:1.3}.toast-locator{display:block;font-size:12px;color:var(--muted);margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.toast-btns{display:flex;align-items:center;gap:6px;flex-shrink:0}.toast-view-btn{background:none;border:1px solid var(--line);color:var(--link);font-size:12px;cursor:pointer;padding:3px 9px;border-radius:var(--r);white-space:nowrap}.toast-view-btn:hover{background:var(--paper-2);border-color:var(--link)}.toast-dismiss{background:none;border:0;cursor:pointer;color:var(--muted);font-size:20px;line-height:1;width:24px;height:24px;display:grid;place-items:center;border-radius:var(--r);padding:0}.toast-dismiss:hover{color:var(--ink);background:var(--paper-2)}.toast-error-detail{margin:0;padding:10px 14px 12px;font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:11.5px;line-height:1.55;color:var(--muted);background:var(--paper-2);border-top:1px solid var(--line);white-space:pre-wrap;word-break:break-word;max-height:200px;overflow-y:auto}.toast-warning-detail{margin:0;padding:10px 14px 12px;font-size:12px;line-height:1.55;color:var(--muted);background:var(--paper-2);border-top:1px solid var(--line);white-space:pre-wrap;word-break:break-word}.toast-ignore-btn{color:var(--muted)}.ext-toggle{flex-shrink:0;position:relative;width:44px;height:24px;border-radius:12px;background:var(--line);border:0;cursor:pointer;transition:background .18s ease;padding:0}.ext-toggle--sm{width:36px;height:20px;border-radius:10px}.ext-toggle--on{background:var(--ink)}.ext-toggle:disabled{opacity:.4;cursor:default}.ext-toggle-knob{position:absolute;top:3px;left:3px;width:18px;height:18px;border-radius:50%;background:var(--paper);transition:transform .18s ease;display:block;box-shadow:0 1px 3px #0003}.ext-toggle--sm .ext-toggle-knob{width:14px;height:14px;top:3px;left:3px}.ext-toggle--on .ext-toggle-knob{transform:translate(20px)}.ext-toggle--sm.ext-toggle--on .ext-toggle-knob{transform:translate(16px)}.ext-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:12px}.ext-card{border:1px solid var(--line);border-radius:var(--r2);padding:16px 18px;background:var(--paper)}.ext-card-header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px}.ext-card-info{flex:1;min-width:0}.ext-card-name{display:block;font-weight:600;font-size:14px;margin-bottom:4px}.ext-card-desc{display:block;font-size:13px;color:var(--muted);line-height:1.5}.ext-card-hint{display:block;font-size:12px;color:#e8a000;margin-top:6px}.ext-card-hint code{font-size:11.5px}.form-hint{font-size:13px;color:var(--muted);line-height:1.55;margin:0}.muted{color:var(--muted)}.admin-view{padding:22px}.admin-list{display:grid;gap:10px;max-width:780px}.admin-archive{border:1px solid var(--line);background:var(--paper-3);padding:12px;border-radius:var(--r2)}.tag-tree{padding:20px 22px;max-width:320px}.tag-tree-header{display:flex;align-items:baseline;gap:10px;margin-bottom:14px;border-bottom:1px solid var(--line-soft);padding-bottom:10px}.tag-tree-title{font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.07em}.tag-tree-active{font-size:12px;color:var(--muted-2);font-style:italic}.tag-tree-list{list-style:none;margin:0;padding:0}.tag-children{padding-left:16px}.tag-node-btn{border:0;background:transparent;color:var(--link);cursor:pointer;padding:3px 0;text-align:left;font-size:13px;display:block;width:100%}.tag-node-btn:hover{text-decoration:underline}.tag-node-btn.is-active{font-weight:600;color:var(--ink)}.tag-node-row{display:flex;align-items:center;gap:4px}.tag-node-row .tag-node-btn{flex:1 1 0;min-width:0;display:flex;align-items:center;gap:4px;width:auto}.tag-node-btn .edit-icon{width:.75em;height:.75em;flex-shrink:0;vertical-align:-.1em;opacity:.35}.tag-node-btn:hover .edit-icon{opacity:.65}.tag-node-delete{flex-shrink:0;border:0;background:transparent;color:var(--muted-2);cursor:pointer;padding:0 3px;font-size:14px;line-height:1;opacity:0}.tag-node-row:hover .tag-node-delete{opacity:1}.tag-node-delete:hover{color:var(--accent)}.tag-rename-input{font-size:13px;flex:1 1 0;min-width:0;padding:2px 5px;border:1px solid var(--accent);border-radius:var(--r);background:var(--field);color:var(--ink);outline:none}.tag-node-label{flex-shrink:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tag-node-count{font-size:11px;color:var(--muted-2);font-weight:400;flex-shrink:0;margin-left:3px}.tag-tree-header{align-items:center}.tag-tree-actions{margin-left:auto;display:flex;gap:4px}.tag-tree-action-btn{font-size:11px;padding:2px 7px;border:1px solid var(--line);border-radius:var(--r);background:transparent;color:var(--muted);cursor:pointer;line-height:1.5;white-space:nowrap;transition:background .1s,color .1s}.tag-tree-action-btn:hover:not(:disabled){background:var(--paper-2);color:var(--ink)}.tag-tree-action-btn:disabled{opacity:.4;cursor:default}.tag-tree-action-btn--cancel{border-color:var(--accent);color:var(--accent)}.tag-tree-action-btn--cancel:hover{background:color-mix(in srgb,var(--accent) 8%,transparent)}.tag-tree-title--move{font-style:italic;color:var(--accent-2)}.tag-node-row--move-select .tag-node-btn{cursor:crosshair;color:var(--ink)}.tag-node-row--move-select .tag-node-btn:hover{background:color-mix(in srgb,var(--link) 10%,transparent);text-decoration:none;border-radius:var(--r)}.tag-picker-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:200;background:#00000073;display:flex;align-items:center;justify-content:center;padding:20px}.tag-picker-modal{background:var(--paper);border-radius:var(--r3);box-shadow:0 16px 56px #0000003d;width:300px;max-width:100%;display:flex;flex-direction:column;max-height:60vh}.tag-picker-header{display:flex;align-items:center;padding:12px 14px;border-bottom:1px solid var(--line);flex-shrink:0;gap:8px}.tag-picker-title{flex:1;font-size:13px;font-weight:600;color:var(--ink);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tag-picker-close{width:26px;height:26px;border-radius:50%;border:none;background:transparent;color:var(--muted-2);font-size:18px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0}.tag-picker-close:hover{background:var(--paper-2);color:var(--ink)}.tag-picker-body{flex:1;min-height:0;overflow-y:auto;padding:8px 12px 12px}.tag-picker-root-btn{display:block;width:100%;text-align:left;padding:5px 8px;margin-bottom:6px;border:1px dashed var(--line);border-radius:var(--r);background:transparent;color:var(--muted);font-size:12px;cursor:pointer}.tag-picker-root-btn:hover{background:var(--paper-2);color:var(--ink);border-color:var(--muted-2)}.tag-picker-tree{border-top:1px solid var(--line-soft);padding-top:6px;margin-top:2px}.tag-picker-node-btn{border:0;background:transparent;color:var(--link);cursor:pointer;padding:3px 6px;text-align:left;font-size:13px;display:block;width:100%;border-radius:var(--r)}.tag-picker-node-btn:hover{background:var(--paper-2);text-decoration:none}.tag-picker-empty{font-size:13px;color:var(--muted-2);margin:6px 0 0}.collections-view{padding:24px}.collections-heading{margin:0 0 16px;font-size:22px;font-family:var(--display);font-weight:600}.collections-error{color:var(--accent);font-size:13px;margin-bottom:8px}.coll-dismiss{background:none;border:none;cursor:pointer;color:var(--accent);font-size:16px;line-height:1;padding:0 4px}.collections-layout{display:grid;grid-template-columns:220px 1fr;gap:0;border:1px solid var(--line);border-radius:var(--r2);min-height:340px}.collections-sidebar{border-right:1px solid var(--line);overflow-y:auto}.coll-sidebar-row{display:flex;flex-direction:column;width:100%;padding:10px 14px;border:none;border-bottom:1px solid var(--line-soft);background:none;cursor:pointer;text-align:left;gap:2px}.coll-sidebar-row:hover{background:var(--paper-2)}.coll-sidebar-row.is-active{background:var(--paper-2);border-left:3px solid var(--accent)}.coll-row-name{font-size:14px;font-weight:600;color:var(--ink)}.coll-row-meta{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.04em}.coll-detail{padding:20px 24px;display:flex;flex-direction:column;gap:16px}.coll-detail--empty{justify-content:center;align-items:center}.coll-detail-header{display:flex;align-items:center;gap:12px}.coll-detail-name{margin:0;font-size:18px;font-family:var(--display);font-weight:600;flex:1}.coll-detail-name--editable{cursor:pointer}.coll-detail-name--editable:hover{color:var(--link)}.coll-edit-hint{font-size:14px;opacity:.5;margin-left:4px}.coll-rename-input{flex:1;font-size:16px;font-family:var(--display);border:1px solid var(--line);padding:4px 8px;background:var(--field);color:var(--ink);border-radius:var(--r)}.coll-delete-btn{border:1px solid var(--accent);background:none;color:var(--accent);padding:5px 12px;font-size:13px;cursor:pointer;border-radius:var(--r)}.coll-delete-btn:hover{background:var(--accent);color:var(--paper)}.coll-detail-vis{display:flex;align-items:center;gap:10px}.coll-vis-label{font-size:13px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.04em;white-space:nowrap}.coll-vis-select{border:1px solid var(--line);background:var(--paper-3);color:var(--ink);padding:4px 8px;font-size:13px;border-radius:var(--r)}.coll-section-heading{font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.06em;margin-bottom:8px}.coll-entries-section{flex:1}.coll-entries-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:2px}.coll-entry-row{display:flex;align-items:center;gap:10px;padding:7px 0;border-bottom:1px solid var(--line-soft)}.coll-entry-info{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.coll-entry-title{font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.coll-entry-kind{font-size:11px;text-transform:uppercase;letter-spacing:.04em}.coll-entry-actions{display:flex;align-items:center;gap:6px;flex-shrink:0}.coll-entry-vis-select{border:1px solid var(--line);background:var(--paper-3);color:var(--ink);padding:3px 6px;font-size:12px;border-radius:var(--r)}.coll-entry-remove{border:none;background:none;cursor:pointer;color:var(--muted);font-size:18px;line-height:1;padding:0 4px}.coll-entry-remove:hover{color:var(--accent)}.coll-add-entry-form{border-top:1px solid var(--line-soft);padding-top:12px}.coll-add-entry-row{display:flex;gap:8px;align-items:center}.coll-add-entry-input{flex:1;border:1px solid var(--line);background:var(--paper-3);color:var(--ink);padding:6px 10px;font-size:13px;min-width:0;border-radius:var(--r)}.coll-add-btn{border:none;background:var(--ink);color:var(--paper);padding:6px 14px;font-size:13px;font-weight:600;cursor:pointer;white-space:nowrap;border-radius:var(--r)}.coll-add-btn:hover{opacity:.85}.coll-add-btn:disabled{opacity:.45;cursor:default}.rail-public-summary{padding:4px 0}.rail-public-summary .rail-title{margin:0 0 10px}.auth-loading{min-height:100vh;display:flex;align-items:center;justify-content:center;color:var(--muted);font-size:15px;background:var(--paper)}.user-menu{display:flex;align-items:center;gap:14px;padding-left:6px;flex-shrink:0}.user-name{font-size:12.5px;color:var(--muted-2);letter-spacing:.01em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:140px}.logout-btn{border:1px solid rgba(255,255,255,.18);background:transparent;color:#c8bfb0;font-size:12px;padding:4px 11px;border-radius:var(--r);cursor:pointer;white-space:nowrap;transition:background .15s,color .15s}.logout-btn:hover{background:#ffffff1a;color:var(--paper)}.logout-btn:disabled{opacity:.5;cursor:default}.login-page,.setup-page{min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;background:var(--paper)}.login-card,.setup-card{width:100%;max-width:360px;padding:40px 36px 44px;background:var(--paper-3);border:1px solid var(--line);border-radius:var(--r3);box-shadow:0 2px 20px #141d1812}.login-brand,.setup-brand{font-family:var(--display);font-size:32px;font-weight:600;color:var(--ink);letter-spacing:-.01em;margin:0 0 6px}.login-tagline,.setup-tagline{font-size:13px;color:var(--muted);margin:0 0 28px}.login-field,.setup-field{display:flex;flex-direction:column;gap:5px;margin-bottom:14px}.login-label,.setup-label{font-size:11.5px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.06em}.login-input,.setup-input{width:100%;border:1px solid var(--line);background:var(--field);color:var(--ink);padding:9px 11px;font-size:14px;border-radius:var(--r2);outline:none;transition:border-color .15s}.login-input:focus,.setup-input:focus{border-color:var(--accent)}.login-error,.setup-error{font-size:13px;color:var(--accent);margin:4px 0 8px}.login-submit,.setup-submit{width:100%;margin-top:8px;border:none;background:var(--top);color:var(--paper);font-size:14px;font-weight:600;padding:11px 16px;border-radius:var(--r2);cursor:pointer;letter-spacing:.02em;transition:opacity .15s}.login-submit:hover,.setup-submit:hover{opacity:.85}.login-submit:disabled,.setup-submit:disabled{opacity:.45;cursor:default}.view-tabs{display:flex;gap:2px;margin-bottom:22px;border-bottom:1px solid var(--line-soft);padding-bottom:0}.view-tab{border:none;background:none;color:var(--muted);font-size:13px;font-weight:600;padding:7px 14px;cursor:pointer;border-bottom:2px solid transparent;margin-bottom:-1px;letter-spacing:.02em;transition:color .12s;text-transform:uppercase;letter-spacing:.06em;font-size:11.5px}.view-tab:hover{color:var(--ink)}.view-tab.is-active{color:var(--ink);border-bottom-color:var(--accent)}.form-section{margin-bottom:32px}.form-section h2{font-size:14px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.06em;margin:0 0 14px}.form-row{display:flex;gap:8px;margin-bottom:10px}.form-field{display:flex;flex-direction:column;gap:5px;margin-bottom:12px}.form-label{font-size:11.5px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}.field-input{border:1px solid var(--line);background:var(--field);color:var(--ink);padding:8px 10px;font-size:13.5px;border-radius:var(--r);outline:none;transition:border-color .15s;min-width:0}.field-input:focus{border-color:var(--accent)}.field-input--flex{flex:1}.form-msg{font-size:13px;margin:6px 0}.form-msg--ok{color:var(--link)}.form-msg--err{color:var(--accent)}.btn-primary{border:none;background:var(--top);color:var(--paper);font-size:13px;font-weight:600;padding:8px 16px;border-radius:var(--r);cursor:pointer;white-space:nowrap}.btn-primary:hover{opacity:.85}.btn-primary:disabled{opacity:.45;cursor:default}.btn-ghost{border:1px solid var(--line);background:none;color:var(--ink);font-size:13px;padding:7px 14px;border-radius:var(--r);cursor:pointer}.btn-ghost:hover{background:var(--paper-2)}.btn-danger{border:1px solid var(--accent);background:none;color:var(--accent);font-size:13px;padding:7px 14px;border-radius:var(--r);cursor:pointer}.btn-danger:hover{background:var(--accent);color:var(--paper)}.admin-view h1{font-family:var(--display);font-weight:600;font-size:26px;margin:0 0 20px}.admin-table{width:100%;border-collapse:collapse;font-size:13px;margin-bottom:28px}.admin-table th{text-align:left;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:var(--muted);padding:8px 10px;border-bottom:1px solid var(--line);background:var(--paper-2)}.admin-table th:first-child{padding-left:16px}.admin-table td{padding:9px 10px;border-bottom:1px solid var(--line-soft);color:var(--ink);vertical-align:middle}.admin-table td:first-child{padding-left:16px}.admin-table tr:hover td{background:var(--paper-2)}.admin-row-disabled td{opacity:.45}.admin-section{margin-bottom:36px;max-width:860px}.admin-section h2{font-size:14px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.06em;margin:0 0 14px}.admin-section h3{font-size:13px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.05em;margin:22px 0 10px}.admin-form{display:flex;flex-direction:column;gap:8px;max-width:480px}.admin-input{border:1px solid var(--line);background:var(--field);color:var(--ink);padding:8px 10px;font-size:13.5px;border-radius:var(--r);outline:none;transition:border-color .15s}.admin-input:focus{border-color:var(--accent)}.admin-action-btn{border:1px solid var(--line);background:none;color:var(--ink);font-size:12px;padding:4px 10px;border-radius:var(--r);cursor:pointer;white-space:nowrap}.admin-action-btn:hover{border-color:var(--accent);color:var(--accent)}.status-badge{display:inline-block;padding:2px 8px;border-radius:var(--r);font-size:11.5px;font-weight:600;text-transform:uppercase;letter-spacing:.04em}.status-active{background:#d8eddf;color:#235c35;border:1px solid #b4d9be}.status-disabled{background:#ede8e0;color:var(--muted);border:1px solid var(--line)}.run-status{display:inline-block;padding:2px 8px;border-radius:var(--r);font-size:11.5px;font-weight:600;text-transform:uppercase;letter-spacing:.04em}.run-status--completed{background:#d8eddf;color:#235c35;border:1px solid #b4d9be}.run-status--failed{background:#f5ddd8;color:#8d3f30;border:1px solid #e0b8b0}.run-status--in-progress{background:#fdefd8;color:#8a4f10;border:1px solid #f0cfa0}.run-row--failed{cursor:pointer}.run-row--failed:hover td{background:#fdf0ed!important}.run-expand-hint{margin-left:6px;font-size:10px;color:var(--accent);vertical-align:middle}.run-error-row td{padding:0!important;background:var(--paper-2)!important}.run-error-detail{margin:0;padding:10px 16px 12px;font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:11.5px;line-height:1.55;color:var(--muted);white-space:pre-wrap;word-break:break-word;max-height:220px;overflow-y:auto}.token-banner{background:#d8eddf;border:1px solid #b4d9be;padding:12px 14px;margin-bottom:16px;font-size:13px;border-radius:var(--r2)}.token-banner code{word-break:break-all;display:block;margin-top:6px;padding:6px 8px;background:var(--field);border:1px solid var(--line);border-radius:var(--r);font-size:12px;font-family:ui-monospace,SF Mono,Menlo,monospace}.token-dismiss{margin-top:8px;font-size:12px;border:1px solid var(--line);background:none;cursor:pointer;padding:3px 8px;border-radius:var(--r);color:var(--muted)}.token-dismiss:hover{background:var(--paper-2)}.token-row{display:flex;align-items:center;justify-content:space-between;border:1px solid var(--line);background:var(--paper-3);padding:10px 12px;border-radius:var(--r);margin-bottom:6px}.token-row-info strong{font-size:14px;display:block}.token-row-info .muted{font-size:12px;margin-top:2px}.token-create-row{display:flex;gap:8px;margin-bottom:16px}.checkbox-row{display:flex;align-items:center;gap:10px;margin-bottom:12px;cursor:pointer;font-size:14px}.checkbox-row input[type=checkbox]{width:15px;height:15px;accent-color:var(--accent)}.coll-create-details{margin-top:16px}.coll-create-details summary{font-weight:600;cursor:pointer;font-size:13px;color:var(--link);list-style:none;display:flex;align-items:center;gap:6px;padding:8px 12px;border:1px solid var(--line-soft);border-radius:var(--r2);background:var(--paper-3);width:fit-content}.coll-create-details summary:hover{background:var(--paper-2)}.coll-create-details[open] summary{border-bottom-left-radius:0;border-bottom-right-radius:0}.coll-create-form{border:1px solid var(--line-soft);border-top:none;padding:14px;border-radius:0 0 var(--r2) var(--r2);background:var(--paper-3);display:flex;flex-direction:column;gap:10px;max-width:440px}@media (max-width: 900px){.topbar{grid-template-columns:1fr auto;height:auto;min-height:58px;padding:12px}.switcher,.nav{grid-column:1 / -1}.nav{justify-content:flex-start;overflow-x:auto}.app-shell{height:auto;grid-template-columns:1fr}.context-rail{border-left:0;border-top:1px solid var(--line)}.entry-table{min-width:860px}}.rail-title--editable{cursor:pointer}.rail-title--editable:hover{opacity:.75}.rail-title--editable .edit-icon{display:inline-block;width:.75em;height:.75em;margin-left:.35em;vertical-align:middle;opacity:0;transition:opacity .1s;flex-shrink:0}.rail-title--editable:hover .edit-icon{opacity:.5}.rail-title-input{width:100%;font:inherit;font-size:inherit;font-weight:600;background:transparent;border:none;border-bottom:1px solid currentColor;color:inherit;padding:0;margin:0 0 8px;outline:none}.preview-panel{flex:1;display:flex;flex-direction:column;min-height:0}.preview-panel-loading,.preview-panel-empty{flex:1;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:8px;color:var(--muted-2);font-size:14px;text-align:center;padding:24px}.preview-video-wrap{flex:1;display:flex;align-items:center;justify-content:center;background:#0d0d0b;min-height:200px}.preview-video-wrap video{max-width:100%;max-height:100%;width:100%;display:block}.video-tv-controls{position:absolute;top:10px;right:10px;display:flex;gap:6px;z-index:10}.video-tv-btn{display:flex;align-items:center;justify-content:center;width:34px;height:34px;padding:0;border:none;border-radius:6px;background:#00000080;color:#ffffffd1;cursor:pointer;backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px);transition:background .15s,color .15s}.video-tv-btn:hover{background:#000000b8;color:#fff}google-cast-launcher.video-tv-btn{color:#ffffffd1}.video-tv-loading{width:100%;min-height:200px;background:#0d0d0b}.preview-iframe-wrap{flex:1;display:flex;flex-direction:column;min-height:0}.preview-iframe-toolbar{display:flex;flex-direction:column;gap:2px;padding:6px 12px;background:var(--paper-2);border-bottom:1px solid var(--line);flex-shrink:0;text-transform:none;letter-spacing:normal}.preview-iframe-toolbar span{font-size:11px;color:var(--muted-2)}.preview-iframe-toolbar a{margin-left:auto;color:var(--link);font-size:12px;text-decoration:none;padding:3px 8px;border:1px solid var(--line);border-radius:var(--r2);background:var(--field);transition:border-color .12s}.preview-iframe-toolbar a:hover{border-color:var(--accent);text-decoration:none}.preview-iframe-wrap iframe{flex:1;width:100%;border:none;background:#fff;min-height:0}.preview-image-wrap{flex:1;display:flex;align-items:center;justify-content:center;padding:20px;background:var(--paper-2)}.preview-image-wrap img{max-width:100%;max-height:100%;object-fit:contain;border-radius:var(--r3);cursor:zoom-in;display:block;box-shadow:0 4px 24px #0000001a}.preview-tweet-wrap{flex:1;min-height:0;overflow-y:auto;padding:12px 16px;background:var(--paper-2);scrollbar-width:thin;scrollbar-color:var(--line) transparent}.preview-tweet-wrap::-webkit-scrollbar{width:8px}.preview-tweet-wrap::-webkit-scrollbar-track{background:transparent}.preview-tweet-wrap::-webkit-scrollbar-thumb{background:var(--line);border-radius:999px;border:2px solid transparent;background-clip:padding-box}.preview-tweet-wrap::-webkit-scrollbar-thumb:hover{background:var(--muted-2);background-clip:padding-box;border:2px solid transparent}.tw-card{border:1px solid var(--line);border-radius:12px;padding:16px;background:var(--paper);max-width:560px;margin:0 auto 12px}.tw-thread{max-width:560px;margin:0 auto}.tw-thread-item{display:flex;gap:0;margin-bottom:0}.tw-thread-connector{display:flex;flex-direction:column;align-items:center;flex-shrink:0;width:52px;padding-top:2px}.tw-thread-avatar-col{display:flex;flex-direction:column;align-items:center;flex-shrink:0}.tw-thread-line{width:2px;background:var(--line);flex:1;min-height:16px;margin:4px 0}.tw-thread-body{flex:1;min-width:0;padding:0 0 16px 12px}.tw-thread-body:last-child{padding-bottom:0}.tw-avatar{width:40px;height:40px;border-radius:50%;object-fit:cover;flex-shrink:0;display:block}.tw-avatar-ph{width:40px;height:40px;border-radius:50%;background:var(--paper-2);border:1px solid var(--line);flex-shrink:0}.tw-header{display:flex;align-items:baseline;gap:6px;flex-wrap:wrap;margin-bottom:6px}.tw-author-name{font-size:14.5px;font-weight:700;color:var(--ink)}.tw-author-handle{font-size:13px;color:var(--muted-2)}.tw-dot{color:var(--muted-2);font-size:13px}.tw-date{font-size:13px;color:var(--muted-2)}.tw-text{font-size:15px;line-height:1.65;color:var(--ink);white-space:pre-line;word-break:break-word;margin-bottom:10px}.tw-text a{color:var(--link);text-decoration:none}.tw-text a:hover{text-decoration:underline}.tw-stats{display:flex;gap:20px;color:var(--muted-2);font-size:13px;margin-top:10px;padding-top:10px;border-top:1px solid var(--line-soft)}.tw-stats span{display:flex;align-items:center;gap:4px}.tw-article{max-width:598px;margin:0 auto}.tw-article-cover{width:100%;display:block;object-fit:cover;max-height:380px}.tw-article-meta{padding:20px 16px 0}.tw-article-title{font-size:22px;font-weight:800;letter-spacing:-.3px;color:var(--ink);line-height:1.3;margin-bottom:14px}.tw-article-author-row{display:flex;align-items:center;gap:12px;margin-bottom:14px}.tw-article-author-name{font-size:14px;font-weight:700;color:var(--ink)}.tw-article-author-sub{font-size:13px;color:var(--muted-2)}.tw-article-divider{border:none;border-top:1px solid var(--line);margin:0}.tw-article-body{padding:8px 16px 60px}.tw-b-h1{font-size:24px;font-weight:800;letter-spacing:-.3px;color:var(--ink);line-height:1.25;margin:22px 0 10px}.tw-b-h2{font-size:19px;font-weight:700;letter-spacing:-.15px;color:var(--ink);line-height:1.3;margin:20px 0 8px}.tw-b-p{font-size:16px;color:var(--ink);line-height:1.72;margin-bottom:14px}.tw-b-p:empty{display:none}.tw-b-spacer{height:6px;display:block}.tw-b-blockquote{border-left:3px solid var(--line);padding:2px 14px;margin:14px 0;color:var(--muted);font-size:16px;line-height:1.65}.tw-b-hr{border:none;border-top:1px solid var(--line);margin:24px 0}.tw-b-img{width:100%;display:block;border-radius:10px;margin:14px 0}.tw-b-ul,.tw-b-ol{margin:10px 0 14px;padding-left:26px}.tw-b-li{font-size:16px;color:var(--ink);line-height:1.65;margin-bottom:6px}.tw-b-code{font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:.875em;background:var(--paper-2);padding:2px 5px;border-radius:4px;color:var(--ink)}.tw-b-pre{background:var(--paper-2);border:1px solid var(--line);border-radius:8px;padding:14px 16px;overflow-x:auto;margin:12px 0}.tw-b-pre code{font-family:ui-monospace,SF Mono,Menlo,monospace;font-size:13px;line-height:1.6}.tw-b-tweet-link{display:flex;align-items:center;gap:10px;border:1px solid var(--line);border-radius:10px;padding:12px 14px;margin:12px 0;color:var(--muted);font-size:14px;text-decoration:none;background:var(--paper-3);transition:background .12s}.tw-b-tweet-link:hover{background:var(--field)}.tw-b-tweet-link svg{flex-shrink:0;color:var(--ink)}.audio-bar{position:fixed;bottom:0;left:0;right:0;height:72px;background:var(--paper);border-top:1px solid var(--line);display:flex;align-items:center;gap:20px;padding:0 24px;z-index:100;box-shadow:0 -2px 16px #00000014}.audio-bar-info{display:flex;align-items:center;gap:10px;min-width:0;flex:0 0 200px}.audio-bar-icon{flex-shrink:0;width:20px;height:20px;display:flex;align-items:center;justify-content:center}.audio-bar-icon svg{width:20px;height:20px}.audio-bar-title{font-size:13px;color:var(--ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0;font-weight:500}.audio-bar-controls{flex:1;display:flex;align-items:center;gap:12px;min-width:0}.audio-bar-play-btn{width:38px;height:38px;border-radius:50%;background:var(--accent);color:var(--paper);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:background .12s,transform .1s}.audio-bar-play-btn:hover{background:var(--accent-2)}.audio-bar-play-btn:active{transform:scale(.93)}.audio-bar-play-btn svg{width:15px;height:15px}.audio-bar-seek{flex:1;min-width:0;display:flex;align-items:center;gap:8px}.audio-bar-seek input[type=range]{flex:1;accent-color:var(--accent);height:4px;cursor:pointer;min-width:0}.audio-bar-time{font-size:11.5px;color:var(--muted-2);white-space:nowrap;min-width:80px;text-align:right;font-variant-numeric:tabular-nums}.audio-bar-right{flex:0 0 auto;display:flex;align-items:center;gap:10px}.audio-bar-volume{display:flex;align-items:center;gap:6px}.audio-bar-volume svg{width:14px;height:14px;color:var(--muted-2);flex-shrink:0}.audio-bar-volume input[type=range]{width:72px;accent-color:var(--accent);cursor:pointer}.audio-bar-close{width:28px;height:28px;border-radius:50%;border:none;background:transparent;color:var(--muted-2);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:18px;padding:0;line-height:1;transition:background .12s,color .12s}.audio-bar-close:hover{background:var(--field);color:var(--ink)}.preview-modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:200;background:#0000008c;display:flex;align-items:center;justify-content:center;padding:20px}.preview-modal{background:var(--paper);border-radius:12px;box-shadow:0 24px 80px #00000047;width:90vw;max-width:1100px;max-height:88vh;display:flex;flex-direction:column;overflow:hidden}.preview-modal--full{height:88vh}.preview-modal--full .preview-modal-body{max-height:none}.preview-modal-header{display:flex;align-items:center;padding:14px 18px;border-bottom:1px solid var(--line);flex-shrink:0;gap:12px}.preview-modal-title{flex:1;min-width:0;font-size:14px;font-weight:600;color:var(--ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.preview-modal-close{width:30px;height:30px;border-radius:50%;border:none;background:transparent;color:var(--muted-2);font-size:20px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:background .12s,color .12s}.preview-modal-close:hover{background:var(--field);color:var(--ink)}.preview-modal-body{flex:1;min-height:0;overflow:hidden;display:flex;flex-direction:column;max-height:calc(88vh - 52px)}.rail-preview-btn{display:block;width:100%;padding:8px 12px;margin-bottom:16px;background:var(--accent);color:var(--paper);border:none;border-radius:var(--r3);font-size:13px;font-weight:600;cursor:pointer;text-align:center;transition:background .12s}.rail-preview-btn:hover{background:var(--accent-2)}.preview-modal-newtab{display:flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:var(--r2);color:var(--muted-2);text-decoration:none;font-size:16px;flex-shrink:0;transition:background .12s,color .12s}.preview-modal-newtab:hover{background:var(--field);color:var(--ink)}body.has-audio-bar{padding-bottom:56px}@keyframes skeleton-shimmer{0%{background-position:200% center}to{background-position:-200% center}}.skeleton-cell{display:inline-block;border-radius:3px;background:linear-gradient(90deg,var(--paper-2) 25%,var(--line-soft) 50%,var(--paper-2) 75%);background-size:200% 100%;animation:skeleton-shimmer 1.8s ease-in-out infinite}.skeleton-row{display:flex;align-items:center;background:var(--paper-3)}.skeleton-row>div{padding:7px 10px;flex-shrink:0;overflow:hidden}.skeleton-row .col-added{padding-left:22px}.skeleton-row>div:last-child{padding-right:22px}@media (pointer: coarse){.skeleton-row .col-added{padding-left:10px}}#entries-body>.entry-row-outer{display:block;border-bottom:none}#entries-body>.entry-row-outer>.entry-row-main{display:flex;align-items:center;cursor:default;border-bottom:1px solid var(--line-soft);padding:0;flex-shrink:unset;overflow:visible}#entries-body>.entry-row-outer>.entry-row-main>div{padding:7px 10px;flex-shrink:0;overflow:hidden}#entries-body>.entry-row-outer>.entry-row-main>div:last-child{padding-right:22px}#entries-body>.entry-row-outer>.entry-row-main .col-added{padding-left:22px}#entries-body>.entry-row-outer.is-selected{background:unset;outline:none;box-shadow:none}#entries-body>.entry-row-outer.is-multi-selected{background:unset;outline:none;box-shadow:none}#entries-body>.entry-row-outer.is-selected>.entry-row-main{background:#eee2d2;box-shadow:inset 0 0 0 2px var(--accent)}#entries-body>.entry-row-outer.is-multi-selected>.entry-row-main{background:#eee2d2;box-shadow:inset 0 0 0 2px var(--accent)}#entries-body>.entry-row-outer .url-cell:hover{overflow:visible;white-space:normal}#entries-body>.entry-row-outer>.child-entries{display:block;padding:0;flex-shrink:unset;overflow:visible;border-left:2px solid var(--line-soft);margin-left:32px}.child-entry-row{display:flex;align-items:center;cursor:default;border-bottom:1px solid var(--line-soft);opacity:.88}.child-entry-row:hover{opacity:1}.child-entry-row:last-child{border-bottom:none}.child-entry-row--light{background:#fafaf8}.child-entry-row--dark{background:#f2f0ec}.child-entry-row.is-selected,.child-entry-row.is-multi-selected{background:#eee2d2;box-shadow:inset 0 0 0 2px var(--accent);opacity:1}.child-entry-row>div{padding:6px 10px;flex-shrink:0;overflow:hidden}.child-entry-row .col-added{padding-left:22px}.child-entry-row>div:last-child{padding-right:22px}.entry-expand-btn{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;flex-shrink:0;padding:0;margin-right:2px;background:none;border:none;cursor:pointer;opacity:.45;color:inherit;transition:opacity .15s}.entry-expand-btn:focus{outline:none}.entry-expand-btn:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:2px}.entry-expand-btn:before{content:"";display:block;width:0;height:0;border-top:4px solid transparent;border-bottom:4px solid transparent;border-left:6px solid currentColor;transition:transform .15s}.entry-expand-btn:hover{opacity:1}.entry-expand-btn.is-expanded:before{transform:rotate(90deg)}.child-count-badge{display:inline-block;margin-left:5px;padding:0 5px;font-size:.72em;font-weight:600;background:color-mix(in srgb,var(--line-soft) 60%,transparent);border-radius:10px;opacity:.75;vertical-align:middle;line-height:1.6}.child-entries-loading{padding:8px 12px;font-size:.85em;opacity:.55}.capture-playlist-toggle{display:inline-flex;align-items:center;gap:4px;font-size:.75rem;color:var(--muted);background:none;border:none;cursor:pointer;padding:2px 6px}.capture-playlist-toggle:hover{color:var(--text)}.capture-playlist-toggle--left{flex-shrink:0;padding:2px 4px;font-size:.7rem}.capture-conflict-badge{font-size:.7rem;color:#c07000;background:#fff3cd;border:1px solid #e0a000;border-radius:4px;padding:1px 6px;margin-left:6px}.capture-playlist-items{border-top:1px solid var(--line-soft);max-height:320px;overflow-y:auto;scrollbar-width:thin;scrollbar-color:var(--line) transparent}.capture-playlist-item{display:flex;align-items:center;gap:8px;padding:5px 10px 5px 14px;font-size:.8rem;border-bottom:1px solid var(--line-soft);border-left:3px solid transparent}.capture-playlist-item:last-of-type{border-bottom:none}.capture-playlist-item--conflict{border-left-color:#c07000;background:color-mix(in srgb,#c07000 6%,transparent)}.capture-playlist-item-title{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text);opacity:.9}.capture-item-quality{font-size:.73rem;padding:2px 4px;border:1px solid var(--line);border-radius:3px;background:var(--paper-3);color:var(--text);flex-shrink:0}.capture-playlist-conflict-badge{font-size:.68rem;font-weight:600;color:#c07000;white-space:nowrap;flex-shrink:0}.capture-playlist-item-remove{flex-shrink:0;display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;padding:0;border:none;background:none;color:var(--muted);cursor:pointer;border-radius:3px;opacity:.3;transition:opacity .1s,color .1s}.capture-playlist-item:hover .capture-playlist-item-remove,.capture-playlist-item-remove:focus-visible{opacity:1}.capture-playlist-item-remove:hover{color:#c04000;opacity:1}@media (pointer: coarse){.capture-playlist-item-remove{opacity:1}}.capture-playlist-item-remove{font-size:.75rem;line-height:1}.capture-sync-row{display:flex;align-items:center;gap:6px;padding:6px 12px;font-size:.78rem;color:var(--muted);border-top:1px solid var(--line-soft);cursor:pointer}.capture-sync-row input[type=checkbox]{cursor:pointer} diff --git a/crates/archivr-server/static/index.html b/crates/archivr-server/static/index.html index 210c92a..4af5c5f 100644 --- a/crates/archivr-server/static/index.html +++ b/crates/archivr-server/static/index.html @@ -6,8 +6,8 @@ Archivr - - + +
diff --git a/docs/README.md b/docs/README.md index 4866c2b..8e4d3c9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -25,9 +25,12 @@ Archivr is a self-hosted tool for capturing and preserving digital content — Y - [Supported Inputs](#supported-inputs) - [YouTube playlists and channels](#youtube-playlists-and-channels) - [Video quality and audio-only](#video-quality-and-audio-only) + - [Text notes](#text-notes) - [Configuration](#configuration) - [TOML config file](#toml-config-file) - [Environment variables](#environment-variables) + - [LLM providers](#llm-providers) +- [Keeping yt-dlp fresh](#keeping-yt-dlp-fresh) - [Deployment](#deployment) - [Security](#security) - [NixOS](#hosting-on-nixos) @@ -41,10 +44,13 @@ Archivr is a self-hosted tool for capturing and preserving digital content — Y - **Web pages** — full self-contained HTML snapshots via SingleFile + Chromium; optional Freedium mirror for paywalled articles; reader mode - **Local files** — import any file from disk by `file://` path - **Deduplication** — SHA3-256 content-addressed blob store shared across all captures; identical files are stored once -- **Tags and search** — hierarchical tag tree, full-text search, filterable entry list +- **Tags and search** — hierarchical tag tree, full-text search (including the latest completed summary and its generated JSON tags), filterable entry list - **Multiple archives** — the server mounts any number of separate archives from a single TOML config - **Role-based auth** — Guest / User / Admin / Owner roles; session cookies and API tokens; Argon2 passwords - **Quality selection** — choose video quality or audio-only per capture; a live metadata probe populates the selector before download +- **LLM summaries** — regenerable per-entry summary via the Anthropic HTTP API, an OpenAI-compatible HTTP API, a local `claude` CLI, or a local `codex` CLI; triggered manually from the entry rail, never automatically on capture; text-only by default, with an explicit `Include attached images` option +- **Text notes** — capture a plain-text or Markdown note with a title and no URL; the byte-preserving note is stored as a normal deduplicated blob and opens in the usual entry-rail preview +- **In-progress capture indicator** — running captures appear as a compact spinner row in the entries list until they finish, replacing the earlier grey skeleton block ## Quick Start @@ -161,6 +167,18 @@ The `POST /api/archives/:id/captures` endpoint accepts an optional `quality` fie `"audio"` selects the most efficient native audio track without re-encoding (Opus/WebM preferred, then AAC/M4A). Omitting `quality` or passing `"best"` downloads at the highest available quality. +### Text notes + +Not every capture has a URL. **Add text** in the capture dialog takes a title and a body and turns them into a +self-contained entry — useful for a scrap of prose, a quote, or a note attached to the surrounding archive. The +body is stored verbatim; no network fetch happens. + +Two body types are accepted: `text/markdown` (saved as `.md`) and `text/plain` (saved as `.txt`). Anything else is +rejected. The body lands in `store/raw/…` under its SHA3-256 content hash, exactly like every other capture, so an +identical note captured twice is stored once. + +Text notes have no synthetic source URL: the original-URL field stays empty rather than inventing a `text:` locator. + ## Configuration ### TOML config file @@ -191,7 +209,8 @@ See `docker/config.example.toml` for a complete annotated example. |---|---|---| | `ARCHIVR_BIND` | `127.0.0.1:8080` | Bind address; overrides `bind` in TOML | | `ARCHIVR_STATIC_DIR` | `crates/archivr-server/static` | Pre-built frontend asset directory | -| `ARCHIVR_YT_DLP` | `yt-dlp` | yt-dlp binary used for video and social downloads | +| `ARCHIVR_YT_DLP` | `yt-dlp` | yt-dlp binary used for video and social downloads; the Nix wrappers point this at the pinned release | +| `ARCHIVR_YT_DLP_FORCE` | — | Absolute path to a yt-dlp binary that MUST be used, bypassing the resolver. Prefer `ARCHIVR_YT_DLP` unless you are overriding for a specific run | | `ARCHIVR_SINGLE_FILE` | `single-file` | single-file-cli binary for web page archiving | | `ARCHIVR_CHROME` | `chromium` | Chromium executable passed to single-file | | `ARCHIVR_CHROME_ARGS` | — | Extra space-separated Chromium flags (Docker sets `--no-sandbox`) | @@ -201,6 +220,105 @@ See `docker/config.example.toml` for a complete annotated example. The Nix wrapper and Docker image set `ARCHIVR_STATIC_DIR`, `ARCHIVR_SINGLE_FILE`, and `ARCHIVR_CHROME` automatically. +#### LLM providers + +Summaries are manual and provider-agnostic. Only the variables for the provider you actually select are read; the two +HTTP providers refuse to start without their API key. They are text-only by default. Selecting `Include attached images` +explicitly sends eligible archived image data to the chosen provider; it is never attached automatically. + +| Provider | Attached images | +|---|---| +| Anthropic HTTP | Supported | +| OpenAI-compatible HTTP | Supported | +| Codex CLI | Supported | +| Claude CLI | Not supported | + +Image inclusion considers only `media` artifacts with `jpg`, `jpeg`, `png`, `webp`, `gif`, or `avif` files. At most four +images are sent, each no larger than 5 MiB and no more than 12 MiB in total. + +Free-text entry search also matches the latest completed summary text and its generated JSON tags. Entries with no +summary, or only a pending or failed summary, get no summary-derived match. + +Each request is cached under the provider and the **requested** model identifier. If a provider reports a more precise +resolved model (for example, an alias's concrete version), the UI displays that resolved name as attribution without +changing the cache identity. + +Summary attempts move from `pending` to `running` and then to `completed` or `failed`. On server startup, interrupted +pending or running attempts are marked failed. Regenerating does not replace an earlier completed summary until the +replacement succeeds, and public readers receive completed content only—never pending state or diagnostic errors. + +| Variable | Default | Description | +|---|---|---| +| `ARCHIVR_ANTHROPIC_API_KEY` | *(required for `anthropic_http`)* | API key for the Anthropic Messages API | +| `ARCHIVR_ANTHROPIC_URL` | `https://api.anthropic.com/v1/messages` | Endpoint override, e.g. an internal proxy | +| `ARCHIVR_ANTHROPIC_MODEL` | `claude-3-5-sonnet-latest` | Model id used for Anthropic summaries | +| `ARCHIVR_OPENAI_API_KEY` | *(required for `openai_compatible`)* | API key for any OpenAI-compatible endpoint | +| `ARCHIVR_OPENAI_URL` | `https://api.openai.com/v1/chat/completions` | Endpoint override; point this at a local server to run offline | +| `ARCHIVR_OPENAI_MODEL` | `gpt-4o-mini` | Model id used for OpenAI-compatible summaries | +| `ARCHIVR_CLAUDE_CLI` | *(auto-discovered)* | Path to a local `claude` binary | +| `ARCHIVR_CLAUDE_MODEL` | *(the CLI's own default)* | Optional model override for the local Claude CLI | +| `ARCHIVR_CODEX_CLI` | *(auto-discovered)* | Path to a local `codex` binary | +| `ARCHIVR_CODEX_MODEL` | *(the CLI's own default)* | Optional model override for the local Codex CLI | +| `ARCHIVR_SUMMARY_HTTP_TIMEOUT` | `120` | Seconds before an HTTP-provider summary is killed | +| `ARCHIVR_SUMMARY_CLI_TIMEOUT` | `300` | Seconds before a CLI-provider summary is killed | + +When `ARCHIVR_CLAUDE_CLI` / `ARCHIVR_CODEX_CLI` is unset the binary is auto-discovered, in this order: the well-known +absolute paths, then `$HOME/.local/bin/`, then the bare name resolved through `PATH`. Note that `PATH` is +consulted **last** — if a stale binary sits at one of the well-known paths it wins over a newer one on `PATH`, so set +the variable explicitly when you have both. The well-known paths are `/opt/homebrew/bin/claude` and +`/usr/local/bin/claude` for Claude, and `/Applications/ChatGPT.app/Contents/Resources/codex`, +`/opt/homebrew/bin/codex`, and `/usr/local/bin/codex` for Codex. + +## Keeping yt-dlp fresh + +yt-dlp is the download engine behind every video and social capture. YouTube rotates its player-signature and API +surfaces on a days-to-weeks cadence, so a binary that worked last month starts returning HTTP 403 on downloads. Keeping +it current is ordinary maintenance, not an emergency. + +**What ships.** `flake.nix` pins a specific yt-dlp release fetched straight from `github.com/yt-dlp/yt-dlp/releases`, +not from nixpkgs — that channel usually lags months behind. The `archivr-server` and `archivr` wrappers set +`ARCHIVR_YT_DLP` to that pinned binary. + +**How the resolver picks.** At runtime archivr probes `--version` on each candidate — the pinned binary from +`ARCHIVR_YT_DLP` and any user-installed binary at `/yt-dlp/yt-dlp` — and runs the newest. An exact version +tie resolves in favour of your own install. Setting `ARCHIVR_YT_DLP_FORCE=/path/to/yt-dlp` bypasses the comparison +entirely. The state dir is `~/Library/Application Support/archivr` on macOS, and `$XDG_STATE_HOME/archivr` (default +`~/.local/state/archivr`) elsewhere. + +There are three ways to get a fresh version, cheapest first. + +**1. Self-update — no rebuild required.** + +```sh +archivr yt-dlp status # every candidate, its version, and which one wins +archivr yt-dlp update # download the latest zipapp into the state dir +archivr yt-dlp update --version 2026.09.15 # pin a specific release tag +``` + +When `ARCHIVR_YT_DLP_FORCE` applies, `status` shows that forced candidate and selects it as the winner. + +The released artifact is a Python zipapp, so this path needs `python3` on `PATH` at run time. + +**2. Automatic weekly bump.** `.github/workflows/update-ytdlp.yml` runs every Monday at 06:00 UTC, queries GitHub for +the latest release, and opens a PR bumping `version` and `hash` in `flake.nix` via `peter-evans/create-pull-request`. +It also accepts `workflow_dispatch` for an on-demand run. + +**3. Manual bump**, when you need it now and do not want to wait for the weekly: + +```sh +NEW=$(curl -s https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest | jq -r .tag_name) +HASH=$(nix hash file --sri --type sha256 <(curl -sL "https://github.com/yt-dlp/yt-dlp/releases/download/${NEW}/yt-dlp")) + +# In flake.nix, inside the `ytDlp = pkgs.stdenv.mkDerivation { … }` block: +# version = "OLD"; → version = "$NEW"; +# url = ".../download/OLD/yt-dlp"; → .../download/$NEW/yt-dlp +# hash = "sha256-OLD…"; → hash = "$HASH"; + +nix build .#archivr-server +./result/bin/archivr yt-dlp status # the env row should report the new version +git commit -am "chore(nix): yt-dlp OLD → $NEW" +``` + ## Deployment ### Security @@ -286,6 +404,11 @@ The image compiles the Rust binary in a separate build stage; only runtime depen Runtime dependencies beyond Rust and Node: `yt-dlp`, Chromium, `single-file` (Node), Python 3 with `twitter-api-client`, `ffmpeg`. `nix develop` provides the dev subset. +Entry summaries are served by one of four interchangeable providers — `anthropic_http`, `openai_compatible`, +`claude_cli`, or `codex_cli` — each configured entirely through the environment; see +[LLM providers](#llm-providers) for the full variable list. The `archivr` CLI itself exposes `archive`, `init`, and +`yt-dlp status` / `yt-dlp update`; summaries are triggered from the web UI rather than the command line. + ```sh # Rust (workspace root) cargo build @@ -307,3 +430,4 @@ nix build .#archivr-server ## License MIT — see [LICENSE](../LICENSE.md). +\n diff --git a/docs/superpowers/plans/2026-08-23-x-article-vision-search.md b/docs/superpowers/plans/2026-08-23-x-article-vision-search.md new file mode 100644 index 0000000..db40265 --- /dev/null +++ b/docs/superpowers/plans/2026-08-23-x-article-vision-search.md @@ -0,0 +1,474 @@ +# X Article, Vision Summaries, and Summary Search Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make X Articles summarize their archived article text, let a user explicitly attach eligible archived images to a requested summary, and search the latest completed summary text (including its JSON tags). + +**Architecture:** Keep `archivr-core` synchronous and make the summary input the single carrier of both reduced text and an opt-in, bounded list of image descriptors. The image-selection policy is serialized into the existing `input_sha256` preimage, preserving the existing `entry_summaries` uniqueness key without a migration. Extend the existing server-side entry search query with a correlated latest-completed-summary predicate; the endpoint response and frontend search transport stay unchanged. + +**Tech Stack:** Rust 2024, `anyhow`, `rusqlite`, `reqwest` blocking HTTP, `serde_json`, Axum, React JSX, and plain CSS. + +--- + +## File map and interfaces + +| File | Responsibility | +| --- | --- | +| `crates/archivr-core/src/summarizer.rs` | X Article reducer, image candidate policy, `SummaryBuildOptions`, `SummaryImage`, cache digest preimage, provider request payloads, Codex invocation, and unit tests. | +| `crates/archivr-server/src/routes.rs` | Parse `include_images`, reject an unsupported Claude CLI vision request before a job is created, and pass build options to both cache lookup and the background worker. | +| `frontend/src/api.js` | Send the explicit `include_images` boolean in the existing summary POST. | +| `frontend/src/components/ContextRail.jsx` | Per-generation checkbox, provider-specific disabled Claude state, privacy/cap warning, and request wiring. | +| `frontend/src/styles.css` | Dedicated summary-image option layout and disabled-note treatment. | +| `crates/archivr-core/src/archive.rs` | Correlated SQL predicate for the latest completed summary and search tests. | +| `docs/README.md`, `AGENTS.md`, `ARCHIVR-MENTAL-MODEL.md` | User, contributor, and architectural documentation after the implementation is complete. | + +Define the following core interfaces before server or UI tasks use them. `archive_file` is an absolute local path derived from `ArchivePaths.store_path` plus the stored artifact `relpath`; it is never returned from an API. + +```rust +pub const MAX_SUMMARY_IMAGES: usize = 4; +pub const MAX_SUMMARY_IMAGE_BYTES: u64 = 5 * 1024 * 1024; +pub const MAX_SUMMARY_IMAGE_TOTAL_BYTES: u64 = 12 * 1024 * 1024; + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct SummaryBuildOptions { + pub include_images: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SummaryImage { + pub sha256: String, + pub mime_type: String, + pub byte_size: u64, + pub archive_file: PathBuf, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SummaryRequest { + pub entry_uid: String, + pub title: Option, + pub source_kind: String, + pub entity_kind: String, + pub content: String, + pub images: Vec, +} + +pub fn build_summary_input( + paths: &ArchivePaths, + entry_uid: &str, + options: SummaryBuildOptions, +) -> Result; + +pub fn summarize_entry( + archive_paths: &ArchivePaths, + entry_uid: &str, + options: SummaryBuildOptions, + provider: &dyn SummaryProvider, + prompt_version: &str, +) -> Result; +``` + +Use one deterministic digest preimage: `content` bytes, then `"\0images="`, then `include_images` as `"0"` or `"1"`, followed by each selected image in query order as `"\0" + sha256 + "\0" + mime_type + "\0" + byte_size`. Hash that complete byte sequence with the existing `hash::hash_bytes`. This means an unchecked request has no images and a different digest from a checked request even when no candidate qualifies. + +### Task 1: Add the X Article reducer with test-first precedence + +**Files:** + +- Modify: `crates/archivr-core/src/summarizer.rs` +- Test: `crates/archivr-core/src/summarizer.rs` (`#[cfg(test)] mod tests`) + +- [ ] **Step 1: Write failing tests for each per-status X Article precedence rule.** + + Add assertions against `extract_tweet_text` using values that retain a link-only top-level tweet body: + + ```rust + #[test] + fn extract_tweet_text_prefers_x_article_plain_text_over_tco_body() { + let tweet = serde_json::json!({ + "full_text": "https://t.co/article", + "article": { "title": "Skin guide", "plain_text": "Use sunscreen daily." } + }); + assert_eq!(extract_tweet_text(&tweet).as_deref(), + Some("Skin guide\n\nUse sunscreen daily.")); + } + + #[test] + fn extract_tweet_text_uses_article_blocks_when_plain_text_is_empty() { + let tweet = serde_json::json!({"article": { + "title": "Blocks", "plain_text": " ", + "blocks": [{"text": "First"}, {"children": [{"text": "Second"}]}] + }}); + assert_eq!(extract_tweet_text(&tweet).as_deref(), Some("Blocks\n\nFirst\n\nSecond")); + } + + #[test] + fn extract_tweet_text_falls_back_from_article_to_link_only_tweet_body() { + let tweet = serde_json::json!({ + "full_text": "https://t.co/fallback", + "article": {"title": "Preview", "preview_text": "Preview copy", "summary_text": "Later"} + }); + assert_eq!(extract_tweet_text(&tweet).as_deref(), Some("Preview\n\nPreview copy")); + } + ``` + +- [ ] **Step 2: Run the focused test target and observe it fail.** + + Run: `cargo test -p archivr-core extract_tweet_text_` + + Expected: FAIL because the current reducer returns the top-level `full_text` or does not descend into `article.blocks`. + +- [ ] **Step 3: Implement `article_text` and deterministic block flattening.** + + Add private helpers before `extract_tweet_text`: + + ```rust + fn nonempty_string(v: &serde_json::Value, key: &str) -> Option; + fn flatten_article_blocks(v: &serde_json::Value, out: &mut Vec); + fn article_text(status: &serde_json::Value) -> Option; + ``` + + `article_text` must inspect the status's `article` object before ordinary fields. With a nonempty title, format each successful source as `title + "\n\n" + body`; if title is empty, return only `body`. Select the body in this exact order: nonblank `plain_text`; recursive text leaves from `blocks` in JSON array/object encounter order; nonblank `preview_text`; nonblank `summary_text`. `flatten_article_blocks` must collect only textual scalar values from conventional textual keys (`text`, `plain_text`, `content`, `body`, `title`, `heading`) and recursively visit arrays and objects; it must not stringify IDs, URLs, booleans, media metadata, or arbitrary scalar fields. Join block leaves with `"\n\n"`. + +- [ ] **Step 4: Integrate the helper into all tweet-status paths.** + + Make `one(v)` call `article_text(v).or_else(|| normal_tweet_text(v))`, where `normal_tweet_text` preserves the existing `full_text`, `text`, `content`, `body` sequence. Keep support for a top-level `{ "tweet": ... }` wrapper and for embedded `thread`, `tweets`, and `replies` members. + +- [ ] **Step 5: Add the thread-artifact regression test and run the focused tests.** + + Add a fixture archive with two `raw_tweet_json` artifacts, where each JSON status has article text, then assert `build_summary_input(..., SummaryBuildOptions::default())?.request.content` contains both article bodies separated by `"\n\n---\n\n"`. Run: `cargo test -p archivr-core extract_tweet_text_ build_summary_input_` + + Expected: PASS, including the existing wrapped/thread tweet tests. + +- [ ] **Step 6: Commit the atomic reducer change.** + + ```bash + git add crates/archivr-core/src/summarizer.rs + git commit -m "fix: summarize X Article text" + ``` + +### Task 2: Model and select explicit image inputs in core + +**Files:** + +- Modify: `crates/archivr-core/src/summarizer.rs` +- Test: `crates/archivr-core/src/summarizer.rs` (`#[cfg(test)] mod tests`) + +- [ ] **Step 1: Write failing candidate-selection and digest tests.** + + Build a temporary archive entry containing `media` artifacts for valid `jpg`, `png`, `webp`, `gif`, and `avif`, plus `avatar`, `video`, `audio`, unsupported `svg`, one 5 MiB + 1 byte image, and enough valid images to exceed both the four-image and 12 MiB limits. Assert only role `media`, allowed MIME/extension pairs, at most four descriptors, no descriptor over 5 MiB, and total selected bytes at most 12 MiB. Also assert: + + ```rust + let text_only = build_summary_input(&paths, &uid, SummaryBuildOptions { include_images: false })?; + let visual = build_summary_input(&paths, &uid, SummaryBuildOptions { include_images: true })?; + assert!(text_only.request.images.is_empty()); + assert!(!visual.request.images.is_empty()); + assert_ne!(text_only.input_sha256, visual.input_sha256); + ``` + +- [ ] **Step 2: Run the new core tests and observe failure.** + + Run: `cargo test -p archivr-core summary_image_` + + Expected: FAIL because `SummaryRequest` has no images and input construction has no image-selection mode. + +- [ ] **Step 3: Define the shared image model and query candidates from existing blobs.** + + Add the constants and `SummaryBuildOptions`, `SummaryImage`, and `SummaryRequest.images` definitions from the file map. Add a private `load_summary_image_candidates(conn, entry_id) -> Result>` querying `entry_artifacts ea JOIN blobs b` for `ea.entry_id = ?1 AND ea.artifact_role = 'media'`, ordered by `ea.id ASC`, selecting `b.sha256`, `b.mime_type`, `b.extension`, `b.byte_size`, and `ea.relpath`. + + Accept a candidate only when both of the following are true: its extension is one of `jpg`, `jpeg`, `png`, `webp`, `gif`, `avif`, and its MIME is the matching `image/jpeg`, `image/png`, `image/webp`, `image/gif`, or `image/avif` family. Resolve `archive_file` under the configured store path and reject a candidate whose canonicalized/normalized path escapes that store root. Stop at the first candidate that would exceed either image count, per-image, or aggregate byte limit; continue scanning later candidates so a too-large or unsupported early artifact cannot hide a valid later one. + +- [ ] **Step 4: Build options-aware input and a complete cache digest.** + + Change every current `build_summary_input` call to pass `SummaryBuildOptions::default()` until Task 4 changes the server. Populate `request.images` only if `options.include_images` is true; text extraction and `MAX_INPUT_CHARS` handling remain identical. Replace `hash_bytes(content.as_bytes())` with a private `summary_input_digest(content, include_images, images)` implementing the stated NUL-delimited preimage so the existing database uniqueness constraint continues to distinguish all modes. Do not alter `database.rs`: `input_sha256` already participates in the cache key. + +- [ ] **Step 5: Run core regression tests.** + + Run: `cargo test -p archivr-core summary_image_ build_summary_input_` + + Expected: PASS; the text-only request has zero image descriptors, and selection is deterministic by artifact insertion order. + +- [ ] **Step 6: Commit the core input model.** + + ```bash + git add crates/archivr-core/src/summarizer.rs + git commit -m "feat: model opt-in summary images" + ``` + +### Task 3: Make provider transports honor image descriptors + +**Files:** + +- Modify: `crates/archivr-core/src/summarizer.rs` +- Test: `crates/archivr-core/src/summarizer.rs` (`#[cfg(test)] mod tests`) + +- [ ] **Step 1: Write failing payload, command, and capability tests.** + + Construct a `SummaryRequest` with one tiny fixture `SummaryImage` and assert `anthropic_request_body` puts a text block and `{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "..." } }` in `messages[0].content`. Assert `openai_request_body` emits a text content part plus `{ "type": "image_url", "image_url": { "url": "data:image/png;base64,..." } }`. Unit-test a pure Codex argument builder so its primary arguments contain `exec`, `--image`, the fixture path, `--output-last-message`, output path, and final `-`; test its positional fallback also keeps `--image`. Assert `ClaudeCliProvider::summarize` returns an error containing `Claude CLI cannot attach local images` when `request.images` is nonempty. + +- [ ] **Step 2: Run the provider tests and observe failure.** + + Run: `cargo test -p archivr-core "anthropic_request_body|openai_request_body|codex.*image|claude.*images"` + + Expected: FAIL because HTTP bodies are string-only, Codex has no `--image`, and Claude silently accepts the request. + +- [ ] **Step 3: Encode images for each HTTP protocol.** + + Add `read_image_base64(image: &SummaryImage) -> Result` which reads only the already bounded selected file and uses `base64::Engine` with the existing dependency or workspace dependency. Make `anthropic_request_body` and `openai_request_body` return their present text-only JSON shapes when `request.images.is_empty()` and their documented content-part arrays otherwise. Preserve `SYSTEM_PROMPT`, `build_user_prompt`, provider URL, headers, and response parsing. + +- [ ] **Step 4: Extend Codex safely and reject Claude at the provider boundary.** + + Refactor `codex::run` to accept `&[SummaryImage]`; add `--image ` once per selected image before `--output-last-message` in both primary stdin and positional-prompt forms. Keep the existing last-message temporary-file contract and cleanup behavior. Have `ClaudeCliProvider::summarize` `bail!("Claude CLI cannot attach local images; choose an HTTP provider or Codex CLI")` before spawning when images are supplied. + +- [ ] **Step 5: Thread image-aware options through synchronous orchestration.** + + Change `summarize_entry` to accept `SummaryBuildOptions` and call the options-aware builder before provider invocation. This is a synchronous core function; do not introduce Tokio, async traits, or new database fields. + +- [ ] **Step 6: Run provider and existing summary tests.** + + Run: `cargo test -p archivr-core summarizer::tests` + + Expected: PASS, with all four providers retaining their text-only behavior when `images` is empty. + +- [ ] **Step 7: Commit the provider implementation.** + + ```bash + git add crates/archivr-core/src/summarizer.rs + git commit -m "feat: attach opted-in images to summaries" + ``` + +### Task 4: Expose the opt-in flag through the server API + +**Files:** + +- Modify: `crates/archivr-server/src/routes.rs` +- Test: `crates/archivr-server/src/routes.rs` (`#[cfg(test)] mod tests`) + +- [ ] **Step 1: Write failing route tests.** + + Add authenticated POST tests that deserialize a request without `include_images` and assert it takes the text-only build path, and with `{ "provider": "claude_cli", "include_images": true }` assert status `400 BAD_REQUEST` and an error containing `Claude CLI cannot attach local images`. Add a successful non-Claude request test with `include_images: true` using a configured test provider and assert the returned cache key differs from the equivalent text-only request. Keep GET assertions unchanged: it remains `{ "entry_uid", "summary" }`. + +- [ ] **Step 2: Run the focused route tests and observe failure.** + + Run: `cargo test -p archivr-server "summary.*include_images|claude.*images"` + + Expected: FAIL because the request body does not accept the field and no capability check occurs. + +- [ ] **Step 3: Add the backward-compatible request field and capability guard.** + + Extend `SummaryRequestBody` exactly as follows: + + ```rust + #[derive(Debug, serde::Deserialize)] + struct SummaryRequestBody { + provider: String, + #[serde(default)] + force: bool, + #[serde(default)] + include_images: bool, + } + ``` + + After resolving `provider_cfg` and before cache lookup/upsert/spawn, return `ApiError::bad_request("Claude CLI cannot attach local images; choose an HTTP provider or Codex CLI")` when `body.include_images && matches!(provider_cfg, ProviderConfig::ClaudeCli(_))`. Construct `SummaryBuildOptions { include_images: body.include_images }` once and pass it to the preflight builder and cloned into `spawn_blocking` for `summarize_entry`. + +- [ ] **Step 4: Verify cache and lifecycle consistency.** + + Ensure preflight `build_summary_input` and background `summarize_entry` receive the same options, so `find_entry_summary` and `upsert_pending_entry_summary` use the same digest. Do not change `entry_summaries`, `latest_entry_summary`, or the GET route; the existing input-hash uniqueness constraint is sufficient. + +- [ ] **Step 5: Run the focused server tests.** + + Run: `cargo test -p archivr-server "summary.*include_images|claude.*images"` + + Expected: PASS; omitting the new field is text-only and a Claude image request produces no pending summary row. + +- [ ] **Step 6: Commit the API wiring.** + + ```bash + git add crates/archivr-server/src/routes.rs + git commit -m "feat: accept image summary requests" + ``` + +### Task 5: Add the explicit, provider-aware image consent control + +**Files:** + +- Modify: `frontend/src/api.js` +- Modify: `frontend/src/components/ContextRail.jsx` +- Modify: `frontend/src/styles.css` +- Test: manual browser smoke test (no frontend test harness exists) + +- [ ] **Step 1: Inspect the existing provider selector and write the manual failure script.** + + In a locally authenticated entry detail, select an HTTP provider and verify the Summary section currently has no `Include attached images` checkbox; select Claude CLI and verify there is no capability explanation. Record this as the observed pre-implementation failure. Do not add a frontend test framework. + +- [ ] **Step 2: Change the API client contract.** + + Change the function signature and POST body only: + + ```js + export async function requestEntrySummary( + archiveId, entryUid, { provider, force = false, includeImages = false } = {} + ) { + // existing fetch and error parsing + body: JSON.stringify({ provider, force, include_images: includeImages }) + } + ``` + + Keep all `fetch` calls inside `frontend/src/api.js`; do not add an inline fetch in the component. + +- [ ] **Step 3: Implement the local per-generation control.** + + Add `const [includeSummaryImages, setIncludeSummaryImages] = useState(false)` beside the summary provider state. In `handleGenerateSummary`, pass `includeImages: includeSummaryImages`. Reset this state to `false` whenever `detail?.summary?.entry_uid` changes, so a consent choice cannot carry to another entry. Do not persist the checkbox in `sessionStorage`; the consent is per generation and defaults off. + +- [ ] **Step 4: Render clear consent, scope, and Claude capability states.** + + In `.rail-summary-controls`, below the provider ` onTitleChange(e.target.value)} + maxLength={500} + /> +