From 64ef4ca3136d3e966d863b4976724a42b4b12c6f Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Mon, 12 Oct 2026 15:54:58 +0200 Subject: [PATCH 01/14] feat: show in-progress captures to all authorized users Store the locator in notes_json immediately on job creation so other users have a display label. Add list_active_capture_jobs (no creator scoping) and a status=active shorthand on the job list endpoint so any ROLE_USER can poll pending+running jobs for the current archive. Frontend polls GET /api/archives/:id/capture_jobs?status=active every 3 s, injects SkeletonEntryRow for foreign jobs (not in local pendingCaptures), and refreshes the entry list when a foreign job settles. --- crates/archivr-core/src/capture_jobs.rs | 28 +++++++++++++ crates/archivr-core/src/database.rs | 10 +++++ crates/archivr-server/src/jobs.rs | 53 ++++++++++++++++++++++++- crates/archivr-server/src/routes.rs | 4 ++ frontend/src/App.jsx | 46 ++++++++++++++++++++- frontend/src/api.js | 4 ++ frontend/src/components/EntriesView.jsx | 5 ++- 7 files changed, 147 insertions(+), 3 deletions(-) diff --git a/crates/archivr-core/src/capture_jobs.rs b/crates/archivr-core/src/capture_jobs.rs index 1cd1ffa..d6e4271 100644 --- a/crates/archivr-core/src/capture_jobs.rs +++ b/crates/archivr-core/src/capture_jobs.rs @@ -53,6 +53,34 @@ pub fn list_capture_jobs( Ok(rows) } +/// Lists all `pending` and `running` capture jobs for an archive, ordered oldest-first. +/// No creator scoping: any authorized user can see active jobs for cross-user skeleton display. +pub fn list_active_capture_jobs(conn: &Connection) -> Result> { + let mut stmt = conn.prepare( + "SELECT job_uid, archive_id, run_uid, status, error_text, notes_json, + created_at, updated_at, created_by + FROM capture_jobs + WHERE status IN ('pending', 'running') + ORDER BY created_at ASC, id ASC", + )?; + let rows = stmt + .query_map([], |row| { + Ok(CaptureJobSummary { + job_uid: row.get(0)?, + archive_id: row.get(1)?, + run_uid: row.get(2)?, + status: row.get(3)?, + error_text: row.get(4)?, + notes_json: row.get(5)?, + created_at: row.get(6)?, + updated_at: row.get(7)?, + created_by: row.get(8)?, + }) + })? + .collect::>>()?; + Ok(rows) +} + /// One `archive_run_items` row of a job's run. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] pub struct JobItem { diff --git a/crates/archivr-core/src/database.rs b/crates/archivr-core/src/database.rs index 6f73c6c..a74ceb2 100644 --- a/crates/archivr-core/src/database.rs +++ b/crates/archivr-core/src/database.rs @@ -1789,6 +1789,16 @@ pub fn link_capture_job_run(conn: &Connection, job_uid: &str, run_uid: &str) -> Ok(()) } +/// Sets (or overwrites) the `notes_json` field of a capture job. +/// Used to store a display locator immediately after job creation. +pub fn update_capture_job_notes(conn: &Connection, job_uid: &str, notes_json: &str) -> Result<()> { + conn.execute( + "UPDATE capture_jobs SET notes_json = ?1, updated_at = ?2 WHERE job_uid = ?3", + params![notes_json, now_timestamp(), job_uid], + )?; + Ok(()) +} + /// Returns a capture job by uid. pub fn get_capture_job(conn: &Connection, job_uid: &str) -> Result> { conn.query_row( diff --git a/crates/archivr-server/src/jobs.rs b/crates/archivr-server/src/jobs.rs index eab359a..283b2d2 100644 --- a/crates/archivr-server/src/jobs.rs +++ b/crates/archivr-server/src/jobs.rs @@ -67,11 +67,18 @@ async fn list_capture_jobs_handler( Query(q): Query, ) -> Result>, ApiError> { auth.require_role(ROLE_USER)?; + // `status=active` is a special value meaning all pending+running jobs, visible to every + // authorized user (no creator scoping). Used by other users to render in-progress skeletons. + if q.status.as_deref() == Some("active") { + let mounted = mounted_archive(&state, &archive_id)?; + let conn = database::open_or_initialize(&mounted.archive_path)?; + return Ok(Json(capture_jobs::list_active_capture_jobs(&conn)?)); + } if let Some(status) = q.status.as_deref() && !capture_jobs::JOB_STATUSES.contains(&status) { return Err(ApiError::bad_request( - "invalid status: must be pending, running, completed, or failed", + "invalid status: must be pending, running, completed, failed, or active", )); } let limit = parse_int_param("limit", q.limit.as_deref())? @@ -725,4 +732,48 @@ mod tests { .unwrap(); assert_eq!(body_json(resp).await[0]["archive_path"], expected.as_str()); } + + #[tokio::test] + async fn active_status_shows_pending_and_running_jobs_from_all_users() { + let f = fixture(); + let alice = make_role_session(&f.auth_path, "alice", &["user"]); + let bob = make_role_session(&f.auth_path, "bob", &["user"]); + let alice_uid = user_uid(&f.auth_path, "alice"); + let bob_uid = user_uid(&f.auth_path, "bob"); + let base = "/api/archives/test/capture_jobs"; + + // Create pending jobs for alice and bob; set one running and one completed. + let (alice_pending, bob_running, alice_completed) = { + let conn = database::open_or_initialize(&f.archive_path).unwrap(); + let a = database::create_capture_job_as(&conn, "test", Some(&alice_uid)).unwrap(); + let b = database::create_capture_job_as(&conn, "test", Some(&bob_uid)).unwrap(); + let c = database::create_capture_job_as(&conn, "test", Some(&alice_uid)).unwrap(); + database::update_capture_job_status(&conn, &b, "running", None, None, None).unwrap(); + database::update_capture_job_status(&conn, &c, "completed", Some("run-x"), None, None).unwrap(); + (a, b, c) + }; + + // Alice using status=active sees both the pending (own) and running (bob's) jobs, + // but not the completed one. + let (s, list) = get(&f.router, &format!("{base}?status=active"), Some(&alice)).await; + assert_eq!(s, StatusCode::OK); + let visible = uids(&list); + assert!(visible.contains(&alice_pending), "alice_pending should be visible"); + assert!(visible.contains(&bob_running), "bob_running should be visible"); + assert!(!visible.contains(&alice_completed), "completed should not appear"); + + // Bob also sees both active jobs (including alice's pending). + let (_, list) = get(&f.router, &format!("{base}?status=active"), Some(&bob)).await; + let visible = uids(&list); + assert!(visible.contains(&alice_pending)); + assert!(visible.contains(&bob_running)); + + // Regular (non-active) status=pending still scopes to own jobs only. + let (_, list) = get(&f.router, &format!("{base}?status=pending"), Some(&alice)).await; + assert_eq!(uids(&list), vec![alice_pending]); + + // Regular listing without status filter still scopes to own jobs only. + let (_, list) = get(&f.router, base, Some(&bob)).await; + assert_eq!(uids(&list), vec![bob_running]); + } } diff --git a/crates/archivr-server/src/routes.rs b/crates/archivr-server/src/routes.rs index 4188bf8..6612472 100644 --- a/crates/archivr-server/src/routes.rs +++ b/crates/archivr-server/src/routes.rs @@ -1720,6 +1720,8 @@ async fn capture_handler( let conn = database::open_or_initialize(&mounted.archive_path)?; let created_by = jobs::caller_user_uid(&state, &auth_user)?; let job_uid = database::create_capture_job_as(&conn, &archive_id, created_by.as_deref())?; + let locator_notes = serde_json::json!({"locator": locator}).to_string(); + database::update_capture_job_notes(&conn, &job_uid, &locator_notes).ok(); drop(conn); // Load cookie rules and global uBlock / cookie-ext settings from the auth DB. let (cookie_rules, global_ublock, global_cookie_ext, global_modal_closer) = { @@ -1887,6 +1889,8 @@ async fn capture_text_handler( let conn = database::open_or_initialize(&mounted.archive_path)?; let created_by = jobs::caller_user_uid(&state, &auth_user)?; let job_uid = database::create_capture_job_as(&conn, &archive_id, created_by.as_deref())?; + let text_notes = serde_json::json!({"locator": format!("text:{}", body.title.trim())}).to_string(); + database::update_capture_job_notes(&conn, &job_uid, &text_notes).ok(); drop(conn); // Spawn background text capture. diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 8829191..ec7319f 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -1,5 +1,5 @@ import { useState, useEffect, useCallback, useRef, useMemo, createContext } from 'react' -import { fetchArchives, fetchEntries, searchEntries, fetchRuns, fetchTags, checkSetup, fetchMe, fetchEntryDetail, listCollections } from './api' +import { fetchArchives, fetchEntries, searchEntries, fetchRuns, fetchTags, checkSetup, fetchMe, fetchEntryDetail, listCollections, listActiveCaptureJobs } from './api' import LoginPage from './components/LoginPage.jsx' import SetupPage from './components/SetupPage.jsx' @@ -167,6 +167,48 @@ export default function App() { sessionStorage.setItem('pendingCaptures', JSON.stringify(pendingCaptures)) }, [pendingCaptures]) + // Foreign captures: active jobs started by other users (or other tabs) that this session + // didn't submit. Polled every 3 s so all authorized viewers see in-progress skeletons. + const [foreignCaptures, setForeignCaptures] = useState([]) + const pendingCapturesRef = useRef(pendingCaptures) + useEffect(() => { pendingCapturesRef.current = pendingCaptures }, [pendingCaptures]) + const handleCapturedRef = useRef(null) + + useEffect(() => { + if (!archiveId || !currentUser) { + setForeignCaptures([]) + return + } + // Track which foreign job UIDs were active on the last successful poll so we can + // detect when they settle (disappear from the active list) and refresh entries. + let prevForeignUids = new Set() + + const poll = async () => { + try { + const activeJobs = await listActiveCaptureJobs(archiveId) + // Exclude jobs the current session is already tracking locally. + const ownJobUids = new Set(pendingCapturesRef.current.map(c => c.jobUid)) + const foreign = activeJobs + .filter(job => !ownJobUids.has(job.job_uid)) + .map(job => { + let locator = '' + try { locator = JSON.parse(job.notes_json || '{}').locator || '' } catch {} + return { id: job.job_uid, jobUid: job.job_uid, locator, archiveId: job.archive_id } + }) + setForeignCaptures(foreign) + // If any previously-active foreign job no longer appears → it settled; refresh. + const newUids = new Set(foreign.map(j => j.jobUid)) + const hadSettled = [...prevForeignUids].some(uid => !newUids.has(uid)) + if (hadSettled) handleCapturedRef.current?.() + prevForeignUids = newUids + } catch {} + } + + poll() + const timer = setInterval(poll, 3000) + return () => { clearInterval(timer); setForeignCaptures([]) } + }, [archiveId, currentUser]) + const [ublockWarningIgnored, setUblockWarningIgnored] = useState( () => sessionStorage.getItem('ublockWarningIgnored') === 'true' ) @@ -647,6 +689,7 @@ export default function App() { fetchRuns(archiveId).then(setRuns), ]) }, [archiveId, searchQuery, tagFilter, selectedCollectionUid, loadEntries]) + useEffect(() => { handleCapturedRef.current = handleCaptured }, [handleCaptured]) const handleToast = useCallback((text, locator, type = 'error', headline = null) => { // Only suppress per-item ublock/cookie warnings (those carry a locator). @@ -798,6 +841,7 @@ export default function App() { onRowClick={handleRowClick} archiveId={archiveId} pendingCaptures={pendingCaptures} + foreignCaptures={foreignCaptures} deletedUids={deletedUids} renamedTitles={renamedTitles} isPublicSession={!currentUser} diff --git a/frontend/src/api.js b/frontend/src/api.js index 2efe474..42a6f31 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -334,6 +334,10 @@ export async function pollCaptureJob(archiveId, jobUid) { return getJson(`/api/archives/${archiveId}/capture_jobs/${jobUid}`); } +export async function listActiveCaptureJobs(archiveId) { + return getJson(`/api/archives/${archiveId}/capture_jobs?status=active`); +} + // ── Auth helpers ───────────────────────────────────────────────────────────── export async function checkSetup() { diff --git a/frontend/src/components/EntriesView.jsx b/frontend/src/components/EntriesView.jsx index 89bdb9d..97c4345 100644 --- a/frontend/src/components/EntriesView.jsx +++ b/frontend/src/components/EntriesView.jsx @@ -2,7 +2,7 @@ import SkeletonEntryRow from './SkeletonEntryRow'; import EntryRow from './EntryRow'; -export default function EntriesView({ entries, selectedUids, onRowClick, archiveId, pendingCaptures = [], deletedUids, renamedTitles, isPublicSession, canReorder = false, onChildReorderError }) { +export default function EntriesView({ entries, selectedUids, onRowClick, archiveId, pendingCaptures = [], foreignCaptures = [], deletedUids, renamedTitles, isPublicSession, canReorder = false, onChildReorderError }) { return (
@@ -18,6 +18,9 @@ export default function EntriesView({ entries, selectedUids, onRowClick, archive {pendingCaptures.filter(c => c.archiveId === archiveId).reverse().map(cap => ( ))} + {foreignCaptures.filter(c => c.archiveId === archiveId).map(cap => ( + + ))} {entries.map((entry, idx) => ( Date: Mon, 12 Oct 2026 19:51:15 +0200 Subject: [PATCH 02/14] feat: entry export (HTML / PDF / Markdown) with quiet Archivr credit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a self-contained export feature across core, server, CLI, and frontend. Users can export one or more archived entries as a shareable bundle without exposing the Archivr instance. A small 'Preserved with archivr' credit is included by default and can be toggled off per export. Core (crates/archivr-core/src/export/): - brand.rs — export CSS (palette from style-guide), CREDIT_HTML, CREDIT_INLINE_HTML (for snapshot injection) - model.rs — ExportEntry / ExportBody / Asset loading; tweet thread reconstruction (reply-graph DFS, sibling ordering) - html.rs — full HTML document renderer: all body kinds, AssetMode Bundle vs Print, render_cover for PDF cover pages - markdown.rs — Markdown renderer with poster-linked video, blockquoted quote tweets, credit sub-tag - bundle.rs — ZIP writer (Deflated for text, Stored for binary, large_file for >= 4 GiB assets) - pdf.rs — print_pdf (headless Chrome), merge_documents (lopdf ID-offset merge), entry_pdf (snapshot injection, PDF-merge, HTML fallback) - mod.rs — export_entries, prune_stale_export_dirs, ExportFile, ffmpeg poster generation, full assembly dispatch summarizer.rs: extract pub(crate) article_parts so the export module reuses the article title/body logic without duplication. Server (crates/archivr-server/src/exports.rs): - GET /api/archives/:archive_id/export?entries=&format=&layout=&credit= - Auth required (guests -> 401); per-UID ensure_entry_visible check - Blocking spawn_blocking task; streaming response via ReaderStream - ARCHIVR_EXPORT_PDF_TIMEOUT added to ENV_VARS (default 120 s) - ARCHIVR_CHROME description updated to mention PDF export - prune_stale_export_dirs called at startup (6 h TTL) CLI (crates/archivr-cli/src/main.rs): archivr export [--format html|pdf|markdown] [--separate] [--no-credit] [-o DIR] Frontend: - api.js: downloadEntryExport (blob + filename from Content-Disposition) - ExportDialog.jsx: native ; format selector; Combine toggle (>= 2 entries); credit toggle (on by default); error display - ContextRail.jsx: single-entry Export... button after Preview; bulk Export N entries... section before delete zone; orderedSelection helper for DOM-order UIDs; ExportDialog mounted once per rail - styles.css: .rail-export-btn, .export-dialog .export-format rules Tests: - 9 new cargo tests in export/mod.rs (HTML, Markdown, PDF merge, parent-child dedupe, separate layout, credit on/off, validation) - 4 new cargo tests in exports.rs (401 no-auth, 200 ZIP, 400 bad format, 400 too many entries) - 4 new bun tests in ExportDialog.test.jsx (single/multi uid, credit default, closed state) - 2 new bun tests in api.test.js (query string, error propagation) All 247 Rust tests and 50 frontend tests pass. MCP follow-up: archivr-mcp export_entries tool (GET /api/.../export, read-scope tokens accepted) — not built here. --- Cargo.lock | 409 ++++++- Cargo.toml | 2 + crates/archivr-cli/src/main.rs | 60 +- crates/archivr-core/Cargo.toml | 3 +- crates/archivr-core/src/export/brand.rs | 56 + crates/archivr-core/src/export/bundle.rs | 190 +++ crates/archivr-core/src/export/html.rs | 705 +++++++++++ crates/archivr-core/src/export/markdown.rs | 281 +++++ crates/archivr-core/src/export/mod.rs | 1075 +++++++++++++++++ crates/archivr-core/src/export/model.rs | 720 +++++++++++ crates/archivr-core/src/export/pdf.rs | 395 ++++++ crates/archivr-core/src/lib.rs | 1 + crates/archivr-core/src/summarizer.rs | 13 +- crates/archivr-server/Cargo.toml | 3 + crates/archivr-server/src/effective_config.rs | 3 +- crates/archivr-server/src/exports.rs | 247 ++++ crates/archivr-server/src/main.rs | 5 + crates/archivr-server/src/routes.rs | 1 + frontend/src/api.js | 28 + frontend/src/api.test.js | 24 + frontend/src/components/ContextRail.jsx | 44 + frontend/src/components/ExportDialog.jsx | 176 +++ frontend/src/components/ExportDialog.test.jsx | 42 + frontend/src/styles.css | 4 + 24 files changed, 4453 insertions(+), 34 deletions(-) create mode 100644 crates/archivr-core/src/export/brand.rs create mode 100644 crates/archivr-core/src/export/bundle.rs create mode 100644 crates/archivr-core/src/export/html.rs create mode 100644 crates/archivr-core/src/export/markdown.rs create mode 100644 crates/archivr-core/src/export/mod.rs create mode 100644 crates/archivr-core/src/export/model.rs create mode 100644 crates/archivr-core/src/export/pdf.rs create mode 100644 crates/archivr-server/src/exports.rs create mode 100644 frontend/src/components/ExportDialog.jsx create mode 100644 frontend/src/components/ExportDialog.test.jsx diff --git a/Cargo.lock b/Cargo.lock index 8c2a54d..12a76a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,23 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aes" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures 0.3.1", +] + [[package]] name = "ahash" version = "0.8.12" @@ -23,6 +40,21 @@ dependencies = [ "memchr", ] +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "android_system_properties" version = "0.1.5" @@ -110,6 +142,7 @@ dependencies = [ "chrono", "hex", "libc", + "lopdf", "regex", "reqwest", "rusqlite", @@ -133,7 +166,7 @@ dependencies = [ "base64", "chrono", "parking_lot", - "rand", + "rand 0.8.6", "regex", "reqwest", "rusqlite", @@ -141,10 +174,12 @@ dependencies = [ "serde_json", "tempfile", "tokio", + "tokio-util", "toml", "tower", "tower-http", "uuid", + "zip", ] [[package]] @@ -155,7 +190,7 @@ checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" dependencies = [ "base64ct", "blake2", - "cpufeatures", + "cpufeatures 0.2.17", "password-hash", ] @@ -167,7 +202,7 @@ checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -276,9 +311,9 @@ checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" [[package]] name = "bitflags" -version = "2.11.1" +version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] name = "blake2" @@ -286,7 +321,7 @@ version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" dependencies = [ - "digest", + "digest 0.10.7", ] [[package]] @@ -298,6 +333,34 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "bumpalo" version = "3.19.0" @@ -310,6 +373,15 @@ version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher", +] + [[package]] name = "cc" version = "1.2.41" @@ -326,6 +398,17 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9" +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + [[package]] name = "chrono" version = "0.4.42" @@ -339,6 +422,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common 0.2.2", + "inout", +] + [[package]] name = "clap" version = "4.5.48" @@ -370,7 +463,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -385,6 +478,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "cookie" version = "0.18.1" @@ -422,6 +521,12 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -431,6 +536,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -450,6 +564,15 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "deranged" version = "0.5.8" @@ -462,11 +585,22 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.6", "subtle", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", +] + [[package]] name = "displaydoc" version = "0.2.6" @@ -475,7 +609,16 @@ checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", +] + +[[package]] +name = "ecb" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26f2a8b3e564eba0877223dc343703ad0385794e882e6d13f3a4dd5c6b1f41ac" +dependencies = [ + "cipher", ] [[package]] @@ -533,6 +676,8 @@ version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" dependencies = [ + "crc32fast", + "miniz_oxide", "zlib-rs", ] @@ -644,10 +789,22 @@ checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" dependencies = [ "cfg-if", "libc", - "r-efi", + "r-efi 5.3.0", "wasi 0.14.7+wasi-0.2.4", ] +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", +] + [[package]] name = "h2" version = "0.4.15" @@ -754,6 +911,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3944cf8cf766b40e2a1a333ee5e9b563f854d5fa49d6a8ca2764e97c6eddb214" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.10.1" @@ -968,6 +1134,16 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "inout" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" +dependencies = [ + "block-padding", + "hybrid-array", +] + [[package]] name = "ipnet" version = "2.12.0" @@ -1002,7 +1178,7 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ecc2af9a1119c51f12a14607e783cb977bde58bc069ff0c3da1095e635d70654" dependencies = [ - "cpufeatures", + "cpufeatures 0.2.17", ] [[package]] @@ -1049,12 +1225,49 @@ version = "0.4.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" +[[package]] +name = "lopdf" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfffda0fe1ab0157e1a13c14bebd3f28671f2fccb7922f0722ec53926e6922d3" +dependencies = [ + "aes", + "bitflags", + "brotli-decompressor", + "cbc", + "ecb", + "encoding_rs", + "flate2", + "getrandom 0.4.3", + "indexmap", + "itoa", + "log", + "md-5", + "nom", + "rand 0.10.3", + "rangemap", + "sha2", + "stringprep", + "thiserror", + "weezl", +] + [[package]] name = "matchit" version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest 0.11.3", +] + [[package]] name = "memchr" version = "2.7.6" @@ -1077,6 +1290,16 @@ dependencies = [ "unicase", ] +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.1" @@ -1122,6 +1345,15 @@ dependencies = [ "tempfile", ] +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -1171,7 +1403,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -1222,7 +1454,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" dependencies = [ "base64ct", - "rand_core", + "rand_core 0.6.4", "subtle", ] @@ -1292,6 +1524,12 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + [[package]] name = "rand" version = "0.8.6" @@ -1300,7 +1538,18 @@ checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" dependencies = [ "libc", "rand_chacha", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", ] [[package]] @@ -1310,7 +1559,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -1322,6 +1571,18 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rangemap" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" + [[package]] name = "redox_syscall" version = "0.5.18" @@ -1553,7 +1814,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -1602,13 +1863,24 @@ dependencies = [ "serde", ] +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + [[package]] name = "sha3" version = "0.10.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75872d278a8f37ef87fa0ddbda7802605cb18344497949862c0d4dcb291eba60" dependencies = [ - "digest", + "digest 0.10.7", "keccak", ] @@ -1618,6 +1890,12 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "slab" version = "0.4.12" @@ -1652,6 +1930,17 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + [[package]] name = "strsim" version = "0.11.1" @@ -1675,6 +1964,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sync_wrapper" version = "1.0.2" @@ -1692,7 +1992,7 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -1729,6 +2029,26 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "time" version = "0.3.51" @@ -1769,6 +2089,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" version = "1.52.3" @@ -1792,7 +2118,7 @@ checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -1969,12 +2295,33 @@ version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + [[package]] name = "unicode-ident" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d" +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + [[package]] name = "untrusted" version = "0.9.0" @@ -2084,7 +2431,7 @@ dependencies = [ "log", "proc-macro2", "quote", - "syn", + "syn 2.0.106", "wasm-bindgen-shared", ] @@ -2119,7 +2466,7 @@ checksum = "9f07d2f20d4da7b26400c9f4a0511e6e0345b040694e8a75bd41d578fa4421d7" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -2143,6 +2490,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "weezl" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ca08e5ef825b65b056d9efbd95c8750683f0a6d0466d02e96dc2e4e360f3d2" + [[package]] name = "windows-core" version = "0.62.2" @@ -2164,7 +2517,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -2175,7 +2528,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -2409,7 +2762,7 @@ checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", "synstructure", ] @@ -2430,7 +2783,7 @@ checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -2450,7 +2803,7 @@ checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", "synstructure", ] @@ -2490,7 +2843,7 @@ checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 9efe770..03c7f8d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,3 +35,5 @@ axum-extra = { version = "0.9", features = ["cookie"] } parking_lot = "0.12" zip = { version = "8.6", default-features = false, features = ["deflate-flate2-zlib-rs"] } libc = "0.2" +lopdf = { version = "0.45", default-features = false } +tokio-util = { version = "0.7", features = ["io"] } diff --git a/crates/archivr-cli/src/main.rs b/crates/archivr-cli/src/main.rs index fe82d5b..fc5a90f 100644 --- a/crates/archivr-cli/src/main.rs +++ b/crates/archivr-cli/src/main.rs @@ -3,6 +3,7 @@ use archivr_core::{ archive, capture::CaptureConfig, downloader::ytdlp_tools::{tools_status, update_tools, ToolCandidate}, + export::{self, ExportFormat, ExportLayout, ExportOptions}, }; use clap::{Parser, Subcommand}; use std::{env, path::Path, process}; @@ -51,7 +52,24 @@ enum Command { #[arg(long = "force-with-info-removal")] force_with_info_removal: bool, }, - + /// Export entries as a shareable HTML/Markdown bundle or PDF + Export { + /// Entry UIDs to export, in output order + #[arg(required = true)] + entries: Vec, + /// Output format + #[arg(long, value_enum, default_value_t = ExportFormatArg::Html)] + format: ExportFormatArg, + /// Export each entry as its own file instead of one combined document + #[arg(long)] + separate: bool, + /// Omit the "Preserved with archivr" credit + #[arg(long)] + no_credit: bool, + /// Directory to write the export into + #[arg(short, long, default_value = ".")] + output_dir: String, + }, /// Inspect or update the yt-dlp binary and the JavaScript runtime (Deno) archivr runs #[command(name = "yt-dlp")] YtDlp { @@ -60,6 +78,23 @@ enum Command { }, } +#[derive(clap::ValueEnum, Debug, Clone, Copy)] +enum ExportFormatArg { + Html, + Pdf, + Markdown, +} + +impl From for ExportFormat { + fn from(a: ExportFormatArg) -> Self { + match a { + ExportFormatArg::Html => ExportFormat::Html, + ExportFormatArg::Pdf => ExportFormat::Pdf, + ExportFormatArg::Markdown => ExportFormat::Markdown, + } + } +} + #[derive(Subcommand, Debug)] enum YtDlpCmd { /// Download the latest yt-dlp zipapp and Deno into archivr's state directory @@ -125,6 +160,29 @@ fn main() -> Result<()> { Ok(()) } + + Command::Export { entries, format, separate, no_credit, output_dir } => { + let archive_path = match archive::find_archive_path()? { + Some(p) => p, + None => { + eprintln!("Not in an archive. Use 'archivr init' to create one."); + process::exit(1); + } + }; + let paths = archive::read_archive_paths(&archive_path)?; + let options = ExportOptions { + format: ExportFormat::from(format), + layout: if separate { ExportLayout::Separate } else { ExportLayout::Together }, + include_credit: !no_credit, + caller_bits: u32::MAX, + }; + let dest = std::path::Path::new(&output_dir); + let export_file = export::export_entries(&paths, &entries, &options)?; + let dest_path = export_file.persist_into(dest)?; + println!("Exported: {}", dest_path.display()); + Ok(()) + } + Command::YtDlp { subcmd } => match subcmd { YtDlpCmd::Update { version } => yt_dlp_update(version.as_deref()), YtDlpCmd::Status => yt_dlp_status(), diff --git a/crates/archivr-core/Cargo.toml b/crates/archivr-core/Cargo.toml index 888189a..b84a614 100644 --- a/crates/archivr-core/Cargo.toml +++ b/crates/archivr-core/Cargo.toml @@ -16,9 +16,10 @@ uuid.workspace = true reqwest = { workspace = true } base64.workspace = true zip.workspace = true +tempfile.workspace = true +lopdf.workspace = true [target.'cfg(unix)'.dependencies] libc.workspace = true [dev-dependencies] -tempfile = "3" diff --git a/crates/archivr-core/src/export/brand.rs b/crates/archivr-core/src/export/brand.rs new file mode 100644 index 0000000..05d3fa7 --- /dev/null +++ b/crates/archivr-core/src/export/brand.rs @@ -0,0 +1,56 @@ +//! Branding constants: export stylesheet and "Preserved with archivr" credit. + +/// Stylesheet embedded in every HTML export. +/// +/// Palette comes from `docs/branding/style-guide.html`. No web fonts are +/// loaded; the stacks fall back to Georgia. +pub(crate) const EXPORT_CSS: &str = r#":root{--ink:#20251f;--paper:#f5f0e7;--line:#d2c6b5;--line-soft:#e5dccd;--accent:#8d3f30;--link:#245f72;--muted:#6b6f66;--brand-text:#f4ead8; +--display:'Cormorant Garamond','Cormorant',Georgia,serif;--serif:'Spectral',Georgia,serif;--sans:'Helvetica Neue',Helvetica,Arial,sans-serif} +*{box-sizing:border-box}html{background:var(--paper);color:var(--ink)} +body{margin:0;font:17px/1.65 var(--serif);-webkit-font-smoothing:antialiased} +.ax-doc{max-width:760px;margin:0 auto;padding:64px 28px 32px} +a{color:var(--link);text-decoration-thickness:1px;text-underline-offset:2px} +.ax-eyebrow{margin:0 0 10px;font:500 10.5px/1 var(--sans);letter-spacing:.16em;text-transform:uppercase;color:var(--muted)} +.ax-title{margin:0;font:600 38px/1.12 var(--display);letter-spacing:.005em} +h2.ax-title{font-size:30px}h3.ax-title{font-size:23px} +.ax-meta{margin:12px 0 0;font:13px/1.5 var(--sans);color:var(--muted)}.ax-meta a{color:inherit} +.ax-masthead{padding-bottom:22px;margin-bottom:28px;border-bottom:1px solid var(--line)} +.ax-entry+.ax-entry{margin-top:72px;padding-top:56px;border-top:1px solid var(--line)} +.ax-collection{margin-bottom:56px}.ax-toc{margin:20px 0 0;padding-left:1.2em;font-size:16px}.ax-toc li{margin:4px 0} +.ax-muted{color:var(--muted);font:13px var(--sans)} +.ax-media{margin:0}.ax-media img,.ax-media video{display:block;max-width:100%;height:auto;border-radius:3px;background:var(--line-soft)} +.ax-media figcaption,.ax-aside{margin:10px 0 0;font:13px var(--sans);color:var(--muted)} +.ax-frame{display:block;width:100%;height:80vh;border:1px solid var(--line);border-radius:3px;background:#fff} +.ax-text{white-space:pre-wrap;overflow-wrap:anywhere} +.ax-placeholder{padding:28px;border:1px solid var(--line);border-radius:3px;font:13px var(--sans);color:var(--muted);text-align:center} +.ax-empty{color:var(--muted);font-style:italic} +.ax-children{list-style:none;margin:0;padding:0}.ax-entry--child{margin-top:40px} +.ax-post{padding:18px 0;border-bottom:1px solid var(--line-soft)}.ax-post:last-child{border-bottom:0} +.ax-post-head{display:flex;align-items:center;gap:10px;margin-bottom:8px} +.ax-avatar{width:36px;height:36px;border-radius:50%}.ax-post-name{font:600 15px var(--sans)} +.ax-post-text{white-space:pre-wrap;overflow-wrap:anywhere} +.ax-post-media{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:6px;margin-top:12px} +.ax-post-media img,.ax-post-media video{width:100%;border-radius:3px} +.ax-quote{margin:14px 0 0;padding:4px 16px;border-left:2px solid var(--line)} +.ax-post-link{display:inline-block;margin-top:10px;font:12px var(--sans);color:var(--muted)} +.ax-article-title{font:600 26px/1.2 var(--display);margin:6px 0 12px}.ax-article-cover{max-width:100%;border-radius:3px} +.ax-colophon{max-width:760px;margin:48px auto 0;padding:22px 28px 56px;border-top:1px solid var(--line);text-align:center} +.ax-credit{display:inline-flex;align-items:center;gap:8px;font:11px var(--sans);letter-spacing:.08em;color:var(--muted);text-decoration:none} +.ax-mark{display:inline-grid;place-items:center;width:16px;height:16px;border-radius:2.5px;background:var(--accent);color:var(--brand-text);font:600 12px/1 var(--display)} +.ax-wordmark{font:600 15px var(--display);letter-spacing:.01em;color:var(--ink)} +.ax-credit:hover .ax-wordmark{color:var(--accent)} +@media print{body{font-size:11.5pt}.ax-doc{padding:0;max-width:none}.ax-entry+.ax-entry{break-before:page;border-top:0;margin-top:0;padding-top:0} +.ax-post,.ax-media,.ax-quote{break-inside:avoid}.ax-colophon{margin-top:32px}} +@page{margin:18mm 16mm}"#; + +/// The "Preserved with archivr" footer element. Included verbatim when +/// `include_credit` is set; omitted entirely otherwise (no Archivr mention). +pub(crate) const CREDIT_HTML: &str = r#""#; + +/// Inline-style credit div injected into SingleFile snapshots for PDF export. +/// The wrapper uses `all:initial` so the host page cannot restyle it. +pub(crate) const CREDIT_INLINE_HTML: &str = r#""#; diff --git a/crates/archivr-core/src/export/bundle.rs b/crates/archivr-core/src/export/bundle.rs new file mode 100644 index 0000000..c819ff7 --- /dev/null +++ b/crates/archivr-core/src/export/bundle.rs @@ -0,0 +1,190 @@ +//! ZIP bundle assembly for HTML and Markdown exports. + +use std::collections::HashSet; +use std::io; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use zip::write::SimpleFileOptions; +use zip::{CompressionMethod, ZipWriter}; + +use crate::export::model::Asset; + +// Extensions that should be compressed (text-like formats). +const COMPRESSED_EXTS: &[&str] = &[ + "html", "htm", "md", "txt", "css", "svg", "vtt", "srt", "json", +]; + +/// Build a ZIP at `zip_path` containing multiple entry folders. +/// +/// `folders` is a list of `(folder_name, html_or_md_content, assets)`. +/// Each folder becomes `/index.{ext}` plus +/// `/assets/` per asset. +/// `ext` is `"html"` or `"md"`. +pub(crate) fn write_zip_multi( + zip_path: &Path, + folders: &[(String, String, Vec)], + ext: &str, +) -> Result<()> { + let file = std::fs::File::create(zip_path) + .with_context(|| format!("failed to create zip: {}", zip_path.display()))?; + let mut zip = ZipWriter::new(file); + let mut seen_assets: HashSet = HashSet::new(); + + for (folder, content, assets) in folders { + let index_path = format!("{folder}/index.{ext}"); + zip.start_file(&index_path, text_options(ext)) + .with_context(|| format!("failed to start {index_path}"))?; + io::copy(&mut content.as_bytes(), &mut zip)?; + + for asset in assets { + let entry_path = format!("{folder}/assets/{}", asset.name); + // Deduplicate: same name in same folder is skipped. + if !seen_assets.insert(entry_path.clone()) { + continue; + } + let opts = asset_options(&asset.name, asset.byte_size); + zip.start_file(&entry_path, opts) + .with_context(|| format!("failed to start {entry_path}"))?; + let mut f = std::fs::File::open(&asset.source) + .with_context(|| format!("failed to open asset: {}", asset.source.display()))?; + io::copy(&mut f, &mut zip)?; + } + } + + zip.finish().context("failed to finish zip")?; + Ok(()) +} + +/// Build a ZIP for a single entry. +/// +/// `(content, assets)` — `assets` may include poster files. +pub(crate) fn write_zip_single( + zip_path: &Path, + slug: &str, + content: &str, + ext: &str, + assets: &[Asset], + extra_assets: &[PathBuf], // poster paths etc. (not an Asset with source+name) +) -> Result<()> { + let folders = vec![(slug.to_string(), content.to_string(), assets.to_vec())]; + write_zip_multi_with_extra(zip_path, &folders, ext, extra_assets) +} + +/// Variant that also writes caller-supplied extra paths (e.g. poster JPEGs +/// generated in the work dir) into `/assets/`. +pub(crate) fn write_zip_multi_with_extra( + zip_path: &Path, + folders: &[(String, String, Vec)], + ext: &str, + extra_assets: &[PathBuf], +) -> Result<()> { + let file = std::fs::File::create(zip_path) + .with_context(|| format!("failed to create zip: {}", zip_path.display()))?; + let mut zip = ZipWriter::new(file); + let mut seen_assets: HashSet = HashSet::new(); + + for (folder, content, assets) in folders { + let index_path = format!("{folder}/index.{ext}"); + zip.start_file(&index_path, text_options(ext)) + .with_context(|| format!("failed to start {index_path}"))?; + io::copy(&mut content.as_bytes(), &mut zip)?; + + for asset in assets { + let entry_path = format!("{folder}/assets/{}", asset.name); + if !seen_assets.insert(entry_path.clone()) { + continue; + } + let opts = asset_options(&asset.name, asset.byte_size); + zip.start_file(&entry_path, opts) + .with_context(|| format!("failed to start {entry_path}"))?; + let mut f = std::fs::File::open(&asset.source) + .with_context(|| format!("failed to open asset: {}", asset.source.display()))?; + io::copy(&mut f, &mut zip)?; + } + + // Extra assets (posters, etc.) for the first folder only — or the folder + // that owns the extra assets is determined by the caller. + // Here we write them under the last folder; callers that need per-folder + // placement should call write_zip_multi instead. + for extra in extra_assets { + let name = extra + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let entry_path = format!("{folder}/assets/{name}"); + if !seen_assets.insert(entry_path.clone()) { + continue; + } + let size = extra.metadata().map(|m| m.len()).unwrap_or(0); + let opts = asset_options(&name, size); + zip.start_file(&entry_path, opts) + .with_context(|| format!("failed to start extra {entry_path}"))?; + let mut f = std::fs::File::open(extra) + .with_context(|| format!("failed to open extra asset: {}", extra.display()))?; + io::copy(&mut f, &mut zip)?; + } + } + + zip.finish().context("failed to finish zip")?; + Ok(()) +} + +/// Build a ZIP that holds multiple PDFs: `/-.pdf`. +pub(crate) fn write_pdf_zip( + zip_path: &Path, + folder: &str, + pdfs: &[(String, PathBuf)], // (name_in_zip, source_path) +) -> Result<()> { + let file = std::fs::File::create(zip_path) + .with_context(|| format!("failed to create zip: {}", zip_path.display()))?; + let mut zip = ZipWriter::new(file); + + for (name, source) in pdfs { + let entry_path = format!("{folder}/{name}"); + let size = source.metadata().map(|m| m.len()).unwrap_or(0); + let opts = asset_options(name, size); + zip.start_file(&entry_path, opts) + .with_context(|| format!("failed to start {entry_path}"))?; + let mut f = std::fs::File::open(source) + .with_context(|| format!("failed to open pdf: {}", source.display()))?; + io::copy(&mut f, &mut zip)?; + } + + zip.finish().context("failed to finish pdf zip")?; + Ok(()) +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +fn text_options(_ext: &str) -> SimpleFileOptions { + SimpleFileOptions::default().compression_method(CompressionMethod::Deflated) + // Deflated for text content + // (ext check is implicit for index.html / index.md) + .compression_level(Some(6)) +} + +fn asset_options(name: &str, byte_size: u64) -> SimpleFileOptions { + let ext = std::path::Path::new(name) + .extension() + .and_then(|e| e.to_str()) + .map(|e| e.to_lowercase()) + .unwrap_or_default(); + + let method = if COMPRESSED_EXTS.contains(&ext.as_str()) { + CompressionMethod::Deflated + } else { + CompressionMethod::Stored + }; + + let mut opts = SimpleFileOptions::default().compression_method(method); + if COMPRESSED_EXTS.contains(&ext.as_str()) { + opts = opts.compression_level(Some(6)); + } + if byte_size >= 4 * 1024 * 1024 * 1024 { + opts = opts.large_file(true); + } + opts +} diff --git a/crates/archivr-core/src/export/html.rs b/crates/archivr-core/src/export/html.rs new file mode 100644 index 0000000..ef49e93 --- /dev/null +++ b/crates/archivr-core/src/export/html.rs @@ -0,0 +1,705 @@ +//! HTML rendering for entry exports. + +use std::path::PathBuf; + +use crate::export::brand; +use crate::export::model::{Asset, ExportBody, ExportEntry, Post, Span, ext_of_s}; + +// --------------------------------------------------------------------------- +// Asset reference mode +// --------------------------------------------------------------------------- + +/// How asset `src` / `href` values are built. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum AssetMode { + /// `assets/` — for ZIP bundles. + Bundle, + /// `file://` — for Chrome PDF printing. + Print, +} + +pub(crate) fn asset_src(mode: AssetMode, asset: &Asset) -> String { + match mode { + AssetMode::Bundle => format!("assets/{}", asset.name), + AssetMode::Print => file_url(&asset.source), + } +} + +pub(crate) fn asset_src_path(mode: AssetMode, path: &std::path::Path) -> String { + match mode { + AssetMode::Bundle => { + // Fallback: use the file name. + path.file_name() + .map(|n| format!("assets/{}", n.to_string_lossy())) + .unwrap_or_default() + } + AssetMode::Print => file_url(path), + } +} + +/// Percent-encodes a file path into a `file://` URL. +fn file_url(path: &std::path::Path) -> String { + let s = path.to_string_lossy(); + let mut out = String::with_capacity(s.len() + 7); + out.push_str("file://"); + for byte in s.as_bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'/' | b'.' | b'_' | b'-' | b'~' => { + out.push(*byte as char) + } + b => out.push_str(&format!("%{b:02X}")), + } + } + out +} + +// --------------------------------------------------------------------------- +// Shared helpers +// --------------------------------------------------------------------------- + +/// HTML-escape `& < > " '`. +pub(crate) fn esc(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for ch in s.chars() { + match ch { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c => out.push(c), + } + } + out +} + +/// Returns `Some(s)` only for `http://` and `https://` URLs. +fn safe_href(s: &str) -> Option<&str> { + if s.starts_with("http://") || s.starts_with("https://") { + Some(s) + } else { + None + } +} + +/// Format `archived_at` (RFC 3339) as `"%-d %B %Y"`. +fn fmt_date(archived_at: &str) -> String { + use chrono::DateTime; + if let Ok(dt) = DateTime::parse_from_rfc3339(archived_at) { + dt.format("%-d %B %Y").to_string() + } else { + archived_at.to_string() + } +} + +/// Format Unix seconds as `"%-d %B %Y"`. +fn fmt_timestamp(secs: i64) -> String { + use chrono::{DateTime, Utc}; + let dt = DateTime::::from_timestamp(secs, 0) + .unwrap_or_else(|| DateTime::::from_timestamp(0, 0).unwrap()); + dt.format("%-d %B %Y").to_string() +} + +/// `"{Source} · {Kind}"`, or just `"{Source}"` when the kind is empty/unknown. +pub(crate) fn source_label(source_kind: &str, entity_kind: &str) -> String { + let src = match source_kind { + "youtube" => "YouTube", + "youtube_music" => "YouTube Music", + "spotify" => "Spotify", + "x" | "twitter" => "X", + "instagram" => "Instagram", + "facebook" => "Facebook", + "tiktok" => "TikTok", + "reddit" => "Reddit", + "snapchat" => "Snapchat", + "web" => "Web", + "local" => "File", + "text" => "Note", + other => { + // Capitalize first letter. + let mut c = other.chars(); + return match c.next() { + None => String::new(), + Some(f) => { + let mut s = f.to_uppercase().to_string(); + s.push_str(c.as_str()); + let kind_part = kind_label(entity_kind); + if kind_part.is_empty() { + s + } else { + format!("{s} · {kind_part}") + } + } + }; + } + }; + let kind_part = kind_label(entity_kind); + if kind_part.is_empty() { + src.to_string() + } else { + format!("{src} · {kind_part}") + } +} + +fn kind_label(entity_kind: &str) -> &str { + match entity_kind { + "video" => "Video", + "playlist" => "Playlist", + "channel" => "Channel", + "music" => "Track", + "album" => "Album", + "post" | "tweet" => "Post", + "tweet_thread" => "Thread", + "story" => "Story", + "page" => "Page", + "file" => "File", + "document" | "unknown" | "" => "", + other => other, + } +} + +/// Display title: `summary.title`, else `original_url`, else `"Untitled entry"`. +pub(crate) fn entry_title(entry: &ExportEntry) -> String { + entry + .summary + .title + .as_deref() + .filter(|t| !t.is_empty()) + .map(str::to_string) + .or_else(|| entry.summary.original_url.clone()) + .unwrap_or_else(|| "Untitled entry".to_string()) +} + +/// Strip a leading `www.` from a hostname. +fn strip_www(host: &str) -> &str { + host.strip_prefix("www.").unwrap_or(host) +} + +/// Return the host of an HTTP(S) URL, or `None`. +fn url_host(url: &str) -> Option { + // Very minimal: find `://` then take up to the next `/`. + let after = url.strip_prefix("http://").or_else(|| url.strip_prefix("https://"))?; + let host = after.split('/').next()?; + Some(strip_www(host).to_string()) +} + +/// Return the file size formatted as B / KB / MB / GB (1024-based, 1 decimal). +fn fmt_size(bytes: u64) -> String { + if bytes < 1024 { + return format!("{bytes} B"); + } + let kb = bytes as f64 / 1024.0; + if kb < 1024.0 { + return format!("{kb:.1} KB"); + } + let mb = kb / 1024.0; + if mb < 1024.0 { + return format!("{mb:.1} MB"); + } + format!("{:.1} GB", mb / 1024.0) +} + +// --------------------------------------------------------------------------- +// Document rendering +// --------------------------------------------------------------------------- + +/// Render a complete HTML document for one or more entries. +/// +/// `mode` controls whether asset `src` values use bundle-relative paths +/// (`assets/`) or absolute `file://` URLs for PDF printing. +pub(crate) fn render_document( + entries: &[ExportEntry], + mode: AssetMode, + posters: &std::collections::HashMap, + include_credit: bool, +) -> String { + let together = entries.len() > 1; + let doc_title = if together { + format!("{} archived entries", entries.len()) + } else { + entry_title(&entries[0]) + }; + + let generator_meta = if include_credit { + r#""# + } else { + "" + }; + + let mut html = format!( + r#" + + +{generator_meta} +{title} +
+"#, + title = esc(&doc_title), + css = brand::EXPORT_CSS, + generator_meta = generator_meta, + ); + + if together { + html.push_str(&render_collection_header(entries)); + } + + for (i, entry) in entries.iter().enumerate() { + html.push_str(&render_entry(entry, i, together, mode, posters)); + } + + html.push_str("
"); + if include_credit { + html.push('\n'); + html.push_str(brand::CREDIT_HTML); + html.push('\n'); + } + html.push_str("\n"); + html +} + +/// Render a PDF cover page (collection header + TOC, no anchors per entry). +pub(crate) fn render_cover( + entries: &[ExportEntry], + include_credit: bool, +) -> String { + let generator_meta = if include_credit { + r#""# + } else { + "" + }; + + let mut html = format!( + r#" + + +{generator_meta} +{n} archived entries +
+"#, + n = entries.len(), + css = brand::EXPORT_CSS, + generator_meta = generator_meta, + ); + + html.push_str(&format!( + r#"

Collection

{n} archived entries

+
    "#, + n = entries.len(), + )); + for entry in entries { + let title = entry_title(entry); + let label = source_label(&entry.summary.source_kind, &entry.summary.entity_kind); + html.push_str(&format!( + r#"
  1. {title} {label}
  2. "#, + title = esc(&title), + label = esc(&label), + )); + } + html.push_str("
\n"); + html.push_str("
"); + if include_credit { + html.push('\n'); + html.push_str(brand::CREDIT_HTML); + html.push('\n'); + } + html.push_str("\n"); + html +} + +fn render_collection_header(entries: &[ExportEntry]) -> String { + let mut s = format!( + r#"

Collection

{n} archived entries

+
    "#, + n = entries.len(), + ); + for (i, entry) in entries.iter().enumerate() { + let title = entry_title(entry); + let label = source_label(&entry.summary.source_kind, &entry.summary.entity_kind); + s.push_str(&format!( + "
  1. {title} {label}
  2. ", + title = esc(&title), + label = esc(&label), + )); + } + s.push_str("
\n"); + s +} + +fn render_entry( + entry: &ExportEntry, + index: usize, + together: bool, + mode: AssetMode, + posters: &std::collections::HashMap, +) -> String { + let title = entry_title(entry); + let label = source_label(&entry.summary.source_kind, &entry.summary.entity_kind); + let date = fmt_date(&entry.summary.archived_at); + + let id_attr = format!(r#" id="entry-{index}""#); + let heading = if together { "h2" } else { "h1" }; + + let original_url_part = match &entry.summary.original_url { + Some(url) if safe_href(url).is_some() => { + let host = url_host(url).unwrap_or_else(|| url.clone()); + format!( + r#" · {host}"#, + url = esc(url), + host = esc(&host), + ) + } + _ => String::new(), + }; + + let mut s = format!( + r#"
+

{label}

+<{heading} class="ax-title">{title} +

Archived {url_part}

+
"#, + label = esc(&label), + title = esc(&title), + dt = esc(&entry.summary.archived_at), + url_part = original_url_part, + ); + + s.push_str(&render_body(&entry.body, mode, posters, &entry.subtitles, &title, 0)); + s.push_str("
\n"); + s +} + +fn render_body( + body: &ExportBody, + mode: AssetMode, + posters: &std::collections::HashMap, + subtitles: &[Asset], + entry_title: &str, + depth: usize, +) -> String { + match body { + ExportBody::Video(asset) => render_video(asset, mode, posters, subtitles), + ExportBody::Audio(asset) => render_audio(asset, mode), + ExportBody::Image(asset) => render_image(asset, mode, entry_title), + ExportBody::Pdf(asset) => render_pdf(asset, mode, entry_title), + ExportBody::Page(asset) => render_page(asset, mode, entry_title), + ExportBody::Text { text, .. } => { + format!(r#"
{}
"#, esc(text)) + } + ExportBody::TextTooLarge(asset) => render_download_link(asset, mode), + ExportBody::File(asset) => render_download_link(asset, mode), + ExportBody::Posts(posts) => render_posts(posts, mode, posters), + ExportBody::Container(children) => render_container(children, mode, posters, depth), + ExportBody::Empty => { + r#"

No archived content is available for this entry.

"# + .to_string() + } + } +} + +fn render_video( + asset: &Asset, + mode: AssetMode, + posters: &std::collections::HashMap, + subtitles: &[Asset], +) -> String { + let src = asset_src(mode, asset); + let poster = posters.get(&asset.name); + + match mode { + AssetMode::Bundle => { + let poster_attr = poster + .map(|p| { + let pname = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + format!(r#" poster="assets/{pname}""#) + }) + .unwrap_or_default(); + let tracks: String = subtitles + .iter() + .enumerate() + .map(|(i, sub)| { + let sub_src = asset_src(mode, sub); + let label = sub.name.clone(); + let srclang_attr = label + .split('-') + .next() + .map(|l| format!(r#" srclang="{l}""#)) + .unwrap_or_default(); + let default_attr = if i == 0 { r#" default"# } else { "" }; + format!( + r#""#, + label = esc(&label), + ) + }) + .collect(); + format!( + r#"
"#, + src = esc(&src), + ) + } + AssetMode::Print => { + if let Some(poster_path) = poster { + let poster_src = asset_src_path(mode, poster_path); + let name = asset.name.clone(); + format!( + r#"
Video · {name}
"#, + poster_src = esc(&poster_src), + name = esc(&name), + ) + } else { + format!( + r#"
Video · {}
"#, + esc(&asset.name) + ) + } + } + } +} + +fn render_audio(asset: &Asset, mode: AssetMode) -> String { + match mode { + AssetMode::Bundle => { + let src = asset_src(mode, asset); + format!(r#""#, esc(&src)) + } + AssetMode::Print => { + format!( + r#"
Audio · {}
"#, + esc(&asset.name) + ) + } + } +} + +fn render_image(asset: &Asset, mode: AssetMode, title: &str) -> String { + let src = asset_src(mode, asset); + format!( + r#"
{alt}
"#, + src = esc(&src), + alt = esc(title), + ) +} + +fn render_pdf(asset: &Asset, mode: AssetMode, title: &str) -> String { + match mode { + AssetMode::Bundle => { + let src = asset_src(mode, asset); + format!( + r#" +

Open the PDF

"#, + src = esc(&src), + ) + } + AssetMode::Print => { + // Handled separately in pdf.rs: the PDF asset is merged directly. + format!(r#"

{}

"#, esc(title)) + } + } +} + +fn render_page(asset: &Asset, mode: AssetMode, title: &str) -> String { + match mode { + AssetMode::Bundle => { + let src = asset_src(mode, asset); + format!( + r#" +

Open the archived page on its own

"#, + src = esc(&src), + title = esc(title), + ) + } + AssetMode::Print => { + // Handled in pdf.rs: the snapshot gets masthead/colophon injected. + format!(r#"

{}

"#, esc(title)) + } + } +} + +fn render_download_link(asset: &Asset, mode: AssetMode) -> String { + let src = asset_src(mode, asset); + let ext = ext_of_s(&asset.name).to_uppercase(); + let size = fmt_size(asset.byte_size); + format!( + r#"

Download {ext} file · {size}

"#, + src = esc(&src), + ext = esc(&ext), + ) +} + +fn render_posts( + posts: &[Post], + mode: AssetMode, + posters: &std::collections::HashMap, +) -> String { + let mut s = String::from(r#"
"#); + for post in posts { + s.push_str(&render_post(post, mode, posters, false)); + } + s.push_str("
"); + s +} + +fn render_post( + post: &Post, + mode: AssetMode, + posters: &std::collections::HashMap, + is_quote: bool, +) -> String { + let tag = if is_quote { "blockquote" } else { "section" }; + let class = if is_quote { "ax-quote" } else { "ax-post" }; + + let date = post + .created_at_secs + .map(fmt_timestamp) + .unwrap_or_default(); + + let avatar_html = post + .avatar + .as_ref() + .map(|a| { + let src = asset_src(mode, a); + format!(r#""#, src = esc(&src)) + }) + .unwrap_or_default(); + + let handle_html = post + .handle + .as_deref() + .map(|h| format!(" @{h} · {date}", h = esc(h))) + .unwrap_or_else(|| if date.is_empty() { String::new() } else { format!(" · {date}") }); + + let mut s = format!( + r#"<{tag} class="{class}"> +
{avatar_html}{name} {handle_html}
+"#, + name = esc(&post.name), + ); + + // Body: article or text. + if let Some((title, body, cover)) = &post.article { + if let Some(title) = title { + s.push_str(&format!( + r#"

{}

"#, + esc(title) + )); + } + if let Some(cover) = cover { + let src = asset_src(mode, cover); + s.push_str(&format!( + r#""#, + esc(&src) + )); + } + for para in body.split("\n\n") { + let trimmed = para.trim(); + if !trimmed.is_empty() { + s.push_str(&format!("

{}

", esc(trimmed))); + } + } + } else if !post.spans.is_empty() { + s.push_str(r#"
"#); + for span in &post.spans { + match span { + Span::Text(t) => s.push_str(&esc(t)), + Span::Link { text, href } => { + if let Some(h) = safe_href(href) { + s.push_str(&format!( + r#"{text}"#, + h = esc(h), + text = esc(text), + )); + } else { + s.push_str(&esc(text)); + } + } + } + } + s.push_str("
"); + } + + // Photos and videos. + if !post.photos.is_empty() || !post.videos.is_empty() { + s.push_str(r#"
"#); + for photo in &post.photos { + let src = asset_src(mode, photo); + s.push_str(&format!( + r#""#, + src = esc(&src) + )); + } + for (video, is_gif) in &post.videos { + match mode { + AssetMode::Bundle => { + let src = asset_src(mode, video); + if *is_gif { + s.push_str(&format!( + r#""#, + src = esc(&src) + )); + } else { + s.push_str(&format!( + r#""#, + src = esc(&src) + )); + } + } + AssetMode::Print => { + let poster = posters.get(&video.name); + if let Some(poster_path) = poster { + let poster_src = asset_src_path(mode, poster_path); + s.push_str(&format!( + r#""#, + poster_src = esc(&poster_src) + )); + } else { + s.push_str(&format!( + r#"
Video · {}
"#, + esc(&video.name) + )); + } + } + } + } + s.push_str("
"); + } + + // Quote. + if let Some(quote) = &post.quote { + s.push_str(&render_post(quote, mode, posters, true)); + } + + // Status link. + if let Some(url) = &post.status_url { + s.push_str(&format!( + r#"View on X"#, + url = esc(url) + )); + } + + s.push_str(&format!("")); + s +} + +fn render_container( + children: &[ExportEntry], + mode: AssetMode, + posters: &std::collections::HashMap, + depth: usize, +) -> String { + let mut s = String::from(r#"
    "#); + for child in children { + let title = entry_title(child); + let date = fmt_date(&child.summary.archived_at); + let child_body = render_body(&child.body, mode, posters, &child.subtitles, &title, depth + 1); + s.push_str(&format!( + r#"
  1. +

    {title}

    +

    +
    {child_body}
    +
  2. "#, + title = esc(&title), + dt = esc(&child.summary.archived_at), + )); + } + s.push_str("
"); + s +} diff --git a/crates/archivr-core/src/export/markdown.rs b/crates/archivr-core/src/export/markdown.rs new file mode 100644 index 0000000..ea823d9 --- /dev/null +++ b/crates/archivr-core/src/export/markdown.rs @@ -0,0 +1,281 @@ +//! Markdown rendering for entry exports. + +use std::path::PathBuf; + +use crate::export::model::{Asset, ExportBody, ExportEntry, Post, Span, ext_of_s}; +use crate::export::html::{entry_title, source_label}; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +fn fmt_date(archived_at: &str) -> String { + use chrono::DateTime; + if let Ok(dt) = DateTime::parse_from_rfc3339(archived_at) { + dt.format("%-d %B %Y").to_string() + } else { + archived_at.to_string() + } +} + +fn fmt_timestamp(secs: i64) -> String { + use chrono::{DateTime, Utc}; + let dt = DateTime::::from_timestamp(secs, 0) + .unwrap_or_else(|| DateTime::::from_timestamp(0, 0).unwrap()); + dt.format("%-d %B %Y").to_string() +} + +/// Escape `[` and `]` in link text. +fn esc_link(s: &str) -> String { + s.replace('[', "\\[").replace(']', "\\]") +} + +/// Normalise a title for headings (no newlines). +fn normalise_title(s: &str) -> String { + s.replace('\n', " ").replace('\r', "") +} + +/// URL hostname (no www.). +fn url_host(url: &str) -> Option { + let after = url.strip_prefix("http://").or_else(|| url.strip_prefix("https://"))?; + let host = after.split('/').next()?; + Some(host.strip_prefix("www.").unwrap_or(host).to_string()) +} + +/// Asset src: `assets/`. +fn asset_ref(asset: &Asset) -> String { + format!("assets/{}", asset.name) +} + +/// Poster src. +fn poster_ref(poster: &std::path::Path) -> String { + poster + .file_name() + .map(|n| format!("assets/{}", n.to_string_lossy())) + .unwrap_or_default() +} + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +/// Render a Markdown document for one or more entries. +pub(crate) fn render_markdown( + entries: &[ExportEntry], + posters: &std::collections::HashMap, + include_credit: bool, +) -> String { + let together = entries.len() > 1; + let mut out = String::new(); + + if together { + out.push_str(&format!("# {} archived entries\n\n", entries.len())); + for (i, entry) in entries.iter().enumerate() { + let title = normalise_title(&entry_title(entry)); + out.push_str(&format!("- [{title}](#{anchor})\n", anchor = entry_anchor(i))); + } + out.push('\n'); + for (i, entry) in entries.iter().enumerate() { + out.push_str(&format!( + "\n\n", + entry_anchor(i) + )); + out.push_str(&render_entry_body(entry, 2, posters)); + } + } else { + out.push_str(&render_entry_body(&entries[0], 1, posters)); + } + + if include_credit { + out.push_str("\n\n---\n\nPreserved with [archivr](https://github.com/thegeneralist01/archivr)\n"); + } + + out +} + +fn entry_anchor(index: usize) -> String { + format!("entry-{index}") +} + +/// Render a single entry as Markdown, starting with a heading at `level`. +fn render_entry_body( + entry: &ExportEntry, + level: usize, + posters: &std::collections::HashMap, +) -> String { + let title = normalise_title(&entry_title(entry)); + let label = source_label(&entry.summary.source_kind, &entry.summary.entity_kind); + let date = fmt_date(&entry.summary.archived_at); + + let heading = "#".repeat(level); + + let url_part = entry + .summary + .original_url + .as_deref() + .filter(|u| u.starts_with("http://") || u.starts_with("https://")) + .map(|url| { + let host = url_host(url).unwrap_or_else(|| url.to_string()); + format!(" · [{host}]({url})") + }) + .unwrap_or_default(); + + let mut out = format!( + "{heading} {title}\n\n*{label} · Archived {date}{url_part}*\n\n", + heading = heading, + title = esc_link(&title), + label = esc_link(&label), + url_part = url_part, + ); + + out.push_str(&render_body_md(&entry.body, level + 1, posters, &title)); + out.push('\n'); + out +} + +fn render_body_md( + body: &ExportBody, + child_level: usize, + posters: &std::collections::HashMap, + entry_title: &str, +) -> String { + match body { + ExportBody::Video(asset) => { + let video_ref = asset_ref(asset); + if let Some(poster) = posters.get(&asset.name) { + let p = poster_ref(poster); + format!("[![Video]({p})]({video_ref})\n") + } else { + format!("[Video file]({video_ref})\n") + } + } + ExportBody::Audio(asset) => format!("[Audio file]({})\n", asset_ref(asset)), + ExportBody::Image(asset) => { + format!("![{title}]({src})\n", title = esc_link(entry_title), src = asset_ref(asset)) + } + ExportBody::Pdf(asset) => format!("[PDF document]({})\n", asset_ref(asset)), + ExportBody::Page(asset) => format!("[Archived page snapshot]({})\n", asset_ref(asset)), + ExportBody::Text { text, .. } => { + // Verbatim text. + format!("{}\n", text) + } + ExportBody::TextTooLarge(asset) | ExportBody::File(asset) => { + let ext = ext_of_s(&asset.name).to_uppercase(); + format!("[Download {ext} file]({})\n", asset_ref(asset)) + } + ExportBody::Posts(posts) => render_posts_md(posts, posters), + ExportBody::Container(children) => { + render_container_md(children, child_level, posters) + } + ExportBody::Empty => "*No archived content is available for this entry.*\n".to_string(), + } +} + +fn render_posts_md( + posts: &[Post], + posters: &std::collections::HashMap, +) -> String { + let mut parts: Vec = Vec::new(); + for post in posts { + parts.push(render_post_md(post, posters)); + } + parts.join("\n\n---\n\n") +} + +fn render_post_md( + post: &Post, + posters: &std::collections::HashMap, +) -> String { + let mut out = String::new(); + + let date = post + .created_at_secs + .map(fmt_timestamp) + .unwrap_or_default(); + + let handle_part = post + .handle + .as_deref() + .map(|h| format!(" @{h}")) + .unwrap_or_default(); + let date_part = if date.is_empty() { String::new() } else { format!(" · {date}") }; + + out.push_str(&format!( + "**{name}**{handle_part}{date_part}\n\n", + name = post.name, + )); + + // Body. + if let Some((title, body, cover)) = &post.article { + if let Some(t) = title { + out.push_str(&format!("**{t}**\n\n")); + } + if let Some(c) = cover { + out.push_str(&format!("![]({})\n\n", asset_ref(c))); + } + out.push_str(body); + out.push('\n'); + } else if !post.spans.is_empty() { + for span in &post.spans { + match span { + Span::Text(t) => out.push_str(t), + Span::Link { text, href } + if href.starts_with("http://") || href.starts_with("https://") => + { + out.push_str(&format!("[{text}]({href})")); + } + Span::Link { text, .. } => out.push_str(text), + } + } + out.push('\n'); + } + + // Photos. + for photo in &post.photos { + out.push_str(&format!("\n![]({})", asset_ref(photo))); + } + + // Videos. + for (video, _) in &post.videos { + let video_ref = asset_ref(video); + if let Some(poster) = posters.get(&video.name) { + let p = poster_ref(poster); + out.push_str(&format!("\n[![Video]({p})]({video_ref})")); + } else { + out.push_str(&format!("\n[Video]({video_ref})")); + } + } + + // Quote. + if let Some(quote) = &post.quote { + let quoted = render_post_md(quote, posters); + for line in quoted.lines() { + out.push_str(&format!("\n> {line}")); + } + out.push('\n'); + } + + // Status link. + if let Some(url) = &post.status_url { + out.push_str(&format!("\n[View on X]({url})\n")); + } + + out +} + +fn render_container_md( + children: &[ExportEntry], + level: usize, + posters: &std::collections::HashMap, +) -> String { + let mut out = String::new(); + for child in children { + let title = normalise_title(&entry_title(child)); + let date = fmt_date(&child.summary.archived_at); + let heading = "#".repeat(level); + out.push_str(&format!("{heading} {title}\n\n*Archived {date}*\n\n")); + out.push_str(&render_body_md(&child.body, level + 1, posters, &title)); + out.push('\n'); + } + out +} diff --git a/crates/archivr-core/src/export/mod.rs b/crates/archivr-core/src/export/mod.rs new file mode 100644 index 0000000..0687701 --- /dev/null +++ b/crates/archivr-core/src/export/mod.rs @@ -0,0 +1,1075 @@ +//! Entry export: HTML ZIP, PDF, Markdown ZIP. +//! +//! The public entry point is [`export_entries`]. + +mod brand; +mod bundle; +mod html; +mod markdown; +mod model; +mod pdf; + +use std::collections::HashMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use chrono::Utc; +use tempfile::TempDir; + +use crate::archive::{self, ArchivePaths, EntrySummary}; +use crate::database; +use crate::env_config::env_or; +use crate::process; + + +// --------------------------------------------------------------------------- +// Public API types +// --------------------------------------------------------------------------- + +/// The supported output formats. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ExportFormat { + Html, + Pdf, + Markdown, +} + +impl ExportFormat { + pub fn parse(s: &str) -> Option { + match s.to_lowercase().as_str() { + "html" => Some(Self::Html), + "pdf" => Some(Self::Pdf), + "markdown" => Some(Self::Markdown), + _ => None, + } + } +} + +/// Whether multiple entries are combined into one document or each gets its own file. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ExportLayout { + Together, + Separate, +} + +impl ExportLayout { + pub fn parse(s: &str) -> Option { + match s.to_lowercase().as_str() { + "together" => Some(Self::Together), + "separate" => Some(Self::Separate), + _ => None, + } + } +} + +/// Options controlling the export. +#[derive(Debug, Clone)] +pub struct ExportOptions { + pub format: ExportFormat, + pub layout: ExportLayout, + pub include_credit: bool, + /// Visibility bits for child (container) enumeration; CLI passes `u32::MAX`. + pub caller_bits: u32, +} + +/// Maximum number of entries per export request. +pub const MAX_EXPORT_ENTRIES: usize = 100; + +/// A completed export file inside a temporary work directory. +/// +/// Call [`ExportFile::open`] to get a readable file handle or +/// [`ExportFile::persist_into`] to move the file to a permanent location. +#[derive(Debug)] +pub struct ExportFile { + /// Absolute path to the output file inside `work_dir`. + pub path: PathBuf, + /// ASCII file name suitable for `Content-Disposition`. + pub filename: String, + pub content_type: &'static str, + work_dir: TempDir, +} + +impl ExportFile { + /// Open the file, then drop the work dir (unix unlink keeps the handle + /// alive for reading). Returns `(file, len, filename, content_type)`. + pub fn open(self) -> Result<(fs::File, u64, String, &'static str)> { + let file = fs::File::open(&self.path) + .with_context(|| format!("failed to open export file: {}", self.path.display()))?; + let len = file.metadata().map(|m| m.len()).unwrap_or(0); + let filename = self.filename.clone(); + let ct = self.content_type; + drop(self.work_dir); // unlinks temp dir; the open handle survives on unix + Ok((file, len, filename, ct)) + } + + /// Move the output file to `dest_dir/`. Errors if the + /// destination already exists. + pub fn persist_into(self, dest_dir: &Path) -> Result { + let dest = dest_dir.join(&self.filename); + if dest.exists() { + bail!("{} already exists", dest.display()); + } + // Try rename first (same device); fall back to copy+remove. + if fs::rename(&self.path, &dest).is_err() { + fs::copy(&self.path, &dest) + .with_context(|| format!("failed to copy export to {}", dest.display()))?; + let _ = fs::remove_file(&self.path); + } + drop(self.work_dir); + Ok(dest) + } +} + +// --------------------------------------------------------------------------- +// Main entry point +// --------------------------------------------------------------------------- + +/// Export the given entries. +/// +/// Returns an [`ExportFile`] inside a temporary directory; call +/// `open()` or `persist_into()` to retrieve the result. +pub fn export_entries( + paths: &ArchivePaths, + entry_uids: &[String], + options: &ExportOptions, +) -> Result { + // 1. Validate + if entry_uids.is_empty() { + bail!("entries must not be empty"); + } + if entry_uids.len() > MAX_EXPORT_ENTRIES { + bail!("select at most 100 entries"); + } + + // Deduplicate UIDs while preserving first-occurrence order. + let mut seen = std::collections::HashSet::new(); + let uids: Vec = entry_uids + .iter() + .filter(|uid| seen.insert((*uid).clone())) + .cloned() + .collect(); + + // 2. Open DB and load entries. + let conn = database::open_or_initialize(&paths.archive_path)?; + let mut summaries: Vec = Vec::new(); + for uid in &uids { + let detail = archive::get_entry_detail(&conn, uid)?; + match detail { + Some(d) => summaries.push(d.summary), + None => bail!("entry not found: {uid}"), + } + } + + // 3. Remove entries whose parent is also in the set. + let uid_set: std::collections::HashSet = uids.iter().cloned().collect(); + let summaries: Vec = summaries + .into_iter() + .filter(|s| { + s.parent_entry_uid + .as_ref() + .map_or(true, |p| !uid_set.contains(p)) + }) + .collect(); + + if summaries.is_empty() { + bail!("no entries to export after filtering"); + } + + // 4. Create work directory. + let exports_temp = paths.store_path.join("temp").join("exports"); + fs::create_dir_all(&exports_temp)?; + let work_dir = tempfile::Builder::new() + .prefix("export-") + .tempdir_in(&exports_temp) + .context("failed to create export work dir")?; + let wpath = work_dir.path().to_path_buf(); + + // 5. Load all entries. + let entries: Vec = summaries + .into_iter() + .map(|s| model::load_entry(&conn, &paths.store_path, s, options.caller_bits, 0)) + .collect::>>()?; + + // 6. Generate posters when format requires them. + let posters: HashMap = if options.format != ExportFormat::Markdown { + generate_posters(&entries, &wpath) + } else { + // Still generate for markdown (poster images as video links). + generate_posters(&entries, &wpath) + }; + + // 7. Dispatch. + let (out_path, filename, content_type) = + assemble(&entries, options, &wpath, &posters, &paths.store_path)?; + + Ok(ExportFile { + path: out_path, + filename, + content_type, + work_dir, + }) +} + +// --------------------------------------------------------------------------- +// Poster generation +// --------------------------------------------------------------------------- + +fn collect_video_names(entries: &[model::ExportEntry]) -> Vec<(PathBuf, String)> { + let mut out: Vec<(PathBuf, String)> = Vec::new(); + for entry in entries { + collect_videos_from_body(&entry.body, &mut out); + } + out +} + +fn collect_videos_from_body(body: &model::ExportBody, out: &mut Vec<(PathBuf, String)>) { + match body { + model::ExportBody::Video(a) => out.push((a.source.clone(), a.name.clone())), + model::ExportBody::Container(children) => { + for child in children { + collect_videos_from_body(&child.body, out); + } + } + model::ExportBody::Posts(posts) => { + for post in posts { + collect_post_videos(post, out); + } + } + _ => {} + } +} + +fn collect_post_videos(post: &model::Post, out: &mut Vec<(PathBuf, String)>) { + for (video, _) in &post.videos { + out.push((video.source.clone(), video.name.clone())); + } + if let Some(quote) = &post.quote { + collect_post_videos(quote, out); + } +} + +/// Run ffmpeg to generate poster images for all video assets. +/// Returns a map of video name → poster path. +fn generate_posters(entries: &[model::ExportEntry], work_dir: &Path) -> HashMap { + let ffmpeg_path = PathBuf::from(env_or("ARCHIVR_FFMPEG", "ffmpeg")); + let videos = collect_video_names(entries); + if videos.is_empty() { + return HashMap::new(); + } + + let poster_dir = work_dir.join("posters"); + if let Err(e) = fs::create_dir_all(&poster_dir) { + eprintln!("warn: export: failed to create poster dir: {e:#}"); + return HashMap::new(); + } + + let mut posters: HashMap = HashMap::new(); + let mut ffmpeg_missing = false; + + for (src, name) in &videos { + if ffmpeg_missing { + break; + } + let stem = Path::new(name) + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_else(|| name.clone()); + let poster_path = poster_dir.join(format!("{stem}-poster.jpg")); + + if let Some(p) = try_poster(&ffmpeg_path, src, &poster_path, &mut ffmpeg_missing) { + posters.insert(name.clone(), p); + } + } + posters +} + +/// Attempt to generate a poster for one video. Returns `Some(path)` on success. +fn try_poster( + ffmpeg: &Path, + src: &Path, + out: &Path, + ffmpeg_missing: &mut bool, +) -> Option { + let args: Vec = vec![ + "-nostdin".into(), + "-hide_banner".into(), + "-loglevel".into(), + "error".into(), + "-ss".into(), + "1".into(), + "-i".into(), + src.into(), + "-frames:v".into(), + "1".into(), + "-vf".into(), + "scale='min(1280,iw)':-2".into(), + "-q:v".into(), + "3".into(), + "-y".into(), + out.into(), + ]; + + let run = process::run_with_timeout(ffmpeg, &args, None, Duration::from_secs(60)); + match run { + Ok(_) if out.exists() && out.metadata().map(|m| m.len()).unwrap_or(0) > 0 => { + return Some(out.to_path_buf()); + } + Err(e) if is_not_found(&e) => { + eprintln!("warn: export: ffmpeg not found; skipping posters"); + *ffmpeg_missing = true; + return None; + } + _ => {} + } + + // Retry with -ss 0. + let args_retry: Vec = vec![ + "-nostdin".into(), + "-hide_banner".into(), + "-loglevel".into(), + "error".into(), + "-ss".into(), + "0".into(), + "-i".into(), + src.into(), + "-frames:v".into(), + "1".into(), + "-vf".into(), + "scale='min(1280,iw)':-2".into(), + "-q:v".into(), + "3".into(), + "-y".into(), + out.into(), + ]; + match process::run_with_timeout(ffmpeg, &args_retry, None, Duration::from_secs(60)) { + Ok(_) if out.exists() && out.metadata().map(|m| m.len()).unwrap_or(0) > 0 => { + Some(out.to_path_buf()) + } + Err(e) => { + let src_name = src.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + eprintln!("warn: export: poster for {src_name}: {e:#}"); + None + } + Ok(_) => None, + } +} + +fn is_not_found(err: &anyhow::Error) -> bool { + err.chain() + .any(|e| { + e.downcast_ref::() + .map_or(false, |io| io.kind() == std::io::ErrorKind::NotFound) + }) +} + +// --------------------------------------------------------------------------- +// Assembly dispatch +// --------------------------------------------------------------------------- + +/// Returns `(out_path, filename, content_type)`. +fn assemble( + entries: &[model::ExportEntry], + options: &ExportOptions, + work_dir: &Path, + posters: &HashMap, + store_path: &Path, +) -> Result<(PathBuf, String, &'static str)> { + let date = Utc::now().format("%Y-%m-%d").to_string(); + let n = entries.len(); + + match options.format { + ExportFormat::Html => assemble_html(entries, options, work_dir, posters, &date, n), + ExportFormat::Markdown => { + assemble_markdown(entries, options, work_dir, posters, &date, n) + } + ExportFormat::Pdf => assemble_pdf(entries, options, work_dir, posters, store_path, &date, n), + } +} + +// --------------------------------------------------------------------------- +// HTML assembly +// --------------------------------------------------------------------------- + +fn assemble_html( + entries: &[model::ExportEntry], + options: &ExportOptions, + work_dir: &Path, + posters: &HashMap, + date: &str, + n: usize, +) -> Result<(PathBuf, String, &'static str)> { + let all_assets = collect_all_assets(entries, posters); + + if n == 1 || options.layout == ExportLayout::Together { + // Single document: one folder. + let slug = if n == 1 { + entry_slug(entries[0].summary.title.as_deref().unwrap_or("")) + } else { + format!("export-{date}") + }; + let filename = if n == 1 { + format!("{slug}.zip") + } else { + format!("export-{n}-entries-{date}.zip") + }; + let html = html::render_document(entries, html::AssetMode::Bundle, posters, options.include_credit); + let zip_path = work_dir.join(&filename); + bundle::write_zip_single(&zip_path, &slug, &html, "html", &all_assets, &[])?; + Ok((zip_path, filename, "application/zip")) + } else { + // Separate: one folder per entry. + let outer = format!("export-{date}"); + let filename = format!("export-{n}-entries-{date}.zip"); + let zip_path = work_dir.join(&filename); + + let folders: Vec<(String, String, Vec)> = entries + .iter() + .enumerate() + .map(|(i, entry)| { + let nn = format!("{:02}", i + 1); + let slug = entry_slug(entry.summary.title.as_deref().unwrap_or("")); + let folder = format!("{outer}/{nn}-{slug}"); + let html = html::render_document( + std::slice::from_ref(entry), + html::AssetMode::Bundle, + posters, + options.include_credit, + ); + let assets = collect_entry_assets(entry, posters); + (folder, html, assets) + }) + .collect(); + + bundle::write_zip_multi(&zip_path, &folders, "html")?; + Ok((zip_path, filename, "application/zip")) + } +} + +// --------------------------------------------------------------------------- +// Markdown assembly +// --------------------------------------------------------------------------- + +fn assemble_markdown( + entries: &[model::ExportEntry], + options: &ExportOptions, + work_dir: &Path, + posters: &HashMap, + date: &str, + n: usize, +) -> Result<(PathBuf, String, &'static str)> { + let all_assets = collect_all_assets(entries, posters); + + if n == 1 || options.layout == ExportLayout::Together { + let slug = if n == 1 { + entry_slug(entries[0].summary.title.as_deref().unwrap_or("")) + } else { + format!("export-{date}") + }; + let filename = if n == 1 { + format!("{slug}.zip") + } else { + format!("export-{n}-entries-{date}.zip") + }; + let md = markdown::render_markdown(entries, posters, options.include_credit); + let zip_path = work_dir.join(&filename); + bundle::write_zip_single(&zip_path, &slug, &md, "md", &all_assets, &[])?; + Ok((zip_path, filename, "application/zip")) + } else { + let outer = format!("export-{date}"); + let filename = format!("export-{n}-entries-{date}.zip"); + let zip_path = work_dir.join(&filename); + + let folders: Vec<(String, String, Vec)> = entries + .iter() + .enumerate() + .map(|(i, entry)| { + let nn = format!("{:02}", i + 1); + let slug = entry_slug(entry.summary.title.as_deref().unwrap_or("")); + let folder = format!("{outer}/{nn}-{slug}"); + let md = markdown::render_markdown( + std::slice::from_ref(entry), + posters, + options.include_credit, + ); + let assets = collect_entry_assets(entry, posters); + (folder, md, assets) + }) + .collect(); + + bundle::write_zip_multi(&zip_path, &folders, "md")?; + Ok((zip_path, filename, "application/zip")) + } +} + +// --------------------------------------------------------------------------- +// PDF assembly +// --------------------------------------------------------------------------- + +fn assemble_pdf( + entries: &[model::ExportEntry], + options: &ExportOptions, + work_dir: &Path, + posters: &HashMap, + _store_path: &Path, + date: &str, + n: usize, +) -> Result<(PathBuf, String, &'static str)> { + if n == 1 { + let slug = entry_slug(entries[0].summary.title.as_deref().unwrap_or("")); + let filename = format!("{slug}.pdf"); + let pdf_path = work_dir.join(&filename); + let entry_path = + pdf::entry_pdf(&entries[0], 0, options.include_credit, work_dir, posters)?; + fs::rename(&entry_path, &pdf_path) + .or_else(|_| fs::copy(&entry_path, &pdf_path).map(|_| ()))?; + return Ok((pdf_path, filename, "application/pdf")); + } + + match options.layout { + ExportLayout::Together => { + let filename = format!("export-{n}-entries-{date}.pdf"); + let out = work_dir.join(&filename); + + // Cover page. + let cover_html = html::render_cover(entries, options.include_credit); + let cover_html_path = work_dir.join("cover.html"); + fs::write(&cover_html_path, &cover_html)?; + let cover_pdf_path = work_dir.join("cover.pdf"); + let profile_dir = work_dir.join("chrome-profile"); + fs::create_dir_all(&profile_dir)?; + pdf::print_pdf(&cover_html_path, &cover_pdf_path, &profile_dir)?; + + // Per-entry PDFs (no credit: it's on the cover). + let mut pdf_paths: Vec = vec![cover_pdf_path]; + for (i, entry) in entries.iter().enumerate() { + let p = pdf::entry_pdf(entry, i, false, work_dir, posters)?; + pdf_paths.push(p); + } + + pdf::merge_pdf_files(&pdf_paths, &out)?; + Ok((out, filename, "application/pdf")) + } + ExportLayout::Separate => { + // A ZIP of individual PDFs. + let outer = format!("export-{date}"); + let filename = format!("export-{n}-entries-{date}.zip"); + let zip_path = work_dir.join(&filename); + + let mut pdf_names: Vec<(String, PathBuf)> = Vec::new(); + for (i, entry) in entries.iter().enumerate() { + let nn = format!("{:02}", i + 1); + let slug = entry_slug(entry.summary.title.as_deref().unwrap_or("")); + let pdf_path = pdf::entry_pdf(entry, i, options.include_credit, work_dir, posters)?; + let name_in_zip = format!("{nn}-{slug}.pdf"); + pdf_names.push((name_in_zip, pdf_path)); + } + + bundle::write_pdf_zip(&zip_path, &outer, &pdf_names)?; + Ok((zip_path, filename, "application/zip")) + } + } +} + +// --------------------------------------------------------------------------- +// Asset collection +// --------------------------------------------------------------------------- + +/// Collect all assets referenced across all entries (and posters) without duplicates. +fn collect_all_assets( + entries: &[model::ExportEntry], + posters: &HashMap, +) -> Vec { + let mut seen: std::collections::HashSet = std::collections::HashSet::new(); + let mut out: Vec = Vec::new(); + for entry in entries { + for asset in collect_entry_assets(entry, posters) { + if seen.insert(asset.name.clone()) { + out.push(asset); + } + } + } + out +} + +fn collect_entry_assets( + entry: &model::ExportEntry, + posters: &HashMap, +) -> Vec { + let mut out: Vec = Vec::new(); + collect_body_assets(&entry.body, posters, &mut out); + for sub in &entry.subtitles { + out.push(sub.clone()); + } + out +} + +fn collect_body_assets( + body: &model::ExportBody, + posters: &HashMap, + out: &mut Vec, +) { + match body { + model::ExportBody::Video(a) => { + out.push(a.clone()); + if let Some(poster) = posters.get(&a.name) { + if let Ok(sz) = poster.metadata().map(|m| m.len()) { + out.push(model::Asset { + source: poster.clone(), + name: poster + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(), + byte_size: sz, + }); + } + } + } + model::ExportBody::Audio(a) + | model::ExportBody::Image(a) + | model::ExportBody::Pdf(a) + | model::ExportBody::Page(a) + | model::ExportBody::TextTooLarge(a) + | model::ExportBody::File(a) => out.push(a.clone()), + model::ExportBody::Text { .. } | model::ExportBody::Empty => {} + model::ExportBody::Posts(posts) => { + for post in posts { + collect_post_assets(post, posters, out); + } + } + model::ExportBody::Container(children) => { + for child in children { + collect_entry_assets_into(child, posters, out); + } + } + } +} + +fn collect_post_assets( + post: &model::Post, + posters: &HashMap, + out: &mut Vec, +) { + if let Some(a) = &post.avatar { + out.push(a.clone()); + } + if let Some((_, _, cover)) = &post.article { + if let Some(a) = cover { + out.push(a.clone()); + } + } + for photo in &post.photos { + out.push(photo.clone()); + } + for (video, _) in &post.videos { + out.push(video.clone()); + if let Some(poster) = posters.get(&video.name) { + if let Ok(sz) = poster.metadata().map(|m| m.len()) { + out.push(model::Asset { + source: poster.clone(), + name: poster + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(), + byte_size: sz, + }); + } + } + } + if let Some(quote) = &post.quote { + collect_post_assets(quote, posters, out); + } +} + +fn collect_entry_assets_into( + entry: &model::ExportEntry, + posters: &HashMap, + out: &mut Vec, +) { + collect_body_assets(&entry.body, posters, out); + for sub in &entry.subtitles { + out.push(sub.clone()); + } +} + +// --------------------------------------------------------------------------- +// Naming helpers +// --------------------------------------------------------------------------- + +/// Convert a title to a URL-safe slug (lowercase ASCII-alphanumeric, `-` +/// for other runs, trimmed and capped at 60 bytes). +pub fn entry_slug(title: &str) -> String { + let mut slug = String::new(); + let mut in_sep = true; // start as true to trim leading separators + for ch in title.chars() { + if ch.is_ascii_alphanumeric() { + slug.push(ch.to_ascii_lowercase()); + in_sep = false; + } else if !in_sep { + slug.push('-'); + in_sep = true; + } + } + // Trim trailing `-`. + while slug.ends_with('-') { + slug.pop(); + } + // Cap at 60 bytes. + let mut end = 60.min(slug.len()); + while end > 0 && !slug.is_char_boundary(end) { + end -= 1; + } + slug.truncate(end); + if slug.is_empty() { "entry".to_string() } else { slug } +} + +// --------------------------------------------------------------------------- +// Stale export cleanup +// --------------------------------------------------------------------------- + +/// Remove export temp dirs older than `older_than` from +/// `/temp/exports`. +pub fn prune_stale_export_dirs(store_path: &Path, older_than: Duration) { + let exports_dir = store_path.join("temp").join("exports"); + let dir = match fs::read_dir(&exports_dir) { + Ok(d) => d, + Err(_) => return, + }; + let cutoff = std::time::SystemTime::now() - older_than; + for entry in dir.flatten() { + let meta = match entry.metadata() { + Ok(m) => m, + Err(_) => continue, + }; + let mtime = match meta.modified() { + Ok(t) => t, + Err(_) => continue, + }; + if mtime < cutoff { + let path = entry.path(); + if let Err(e) = fs::remove_dir_all(&path) { + eprintln!("warn: export cleanup: {}: {e:#}", path.display()); + } + } + } +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use super::pdf::merge_documents; + use crate::archive::initialize_archive; + use crate::database; + + struct TestCtx { + _tmp: tempfile::TempDir, + paths: ArchivePaths, + user_id: i64, + run_id: i64, + si_counter: std::cell::Cell, + } + + impl TestCtx { + fn new() -> Self { + let tmp = tempfile::TempDir::new().unwrap(); + let archive_dir = tmp.path().join(".archivr"); + let store_dir = tmp.path().join("store"); + let paths = initialize_archive(&archive_dir, &store_dir, "Test", 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, 10).unwrap(); + TestCtx { _tmp: tmp, paths, user_id, run_id: run.id, si_counter: std::cell::Cell::new(0) } + } + + fn conn(&self) -> rusqlite::Connection { + database::open_or_initialize(&self.paths.archive_path).unwrap() + } + + /// Create a text entry with a .txt primary_media artifact. Returns entry_uid. + fn add_text_entry(&self, title: &str, content: &str) -> String { + let conn = self.conn(); + let n = self.si_counter.get(); + self.si_counter.set(n + 1); + let si_id = database::upsert_source_identity( + &conn, "text", "document", Some(&format!("t-{n}")), None, &format!("text:{n}"), + ).unwrap(); + let entry = database::create_archived_entry( + &conn, + &database::NewEntry { + source_identity_id: si_id, + archive_run_id: self.run_id, + parent_entry_id: None, + root_entry_id: None, + created_by_user_id: self.user_id, + owned_by_user_id: self.user_id, + source_kind: "text".to_string(), + entity_kind: "document".to_string(), + title: Some(title.to_string()), + visibility: "public".to_string(), + representation_kind: "text".to_string(), + source_metadata_json: "{}".to_string(), + display_metadata_json: None, + }, + ).unwrap(); + // Write the file on disk. + let hash = format!("{n:064x}"); + let sub1 = &hash[0..1]; + let sub2 = &hash[1..2]; + let relpath = format!("raw/{sub1}/{sub2}/{hash}.txt"); + let file_path = self.paths.store_path.join(&relpath); + std::fs::create_dir_all(file_path.parent().unwrap()).unwrap(); + std::fs::write(&file_path, content).unwrap(); + database::add_entry_artifact( + &conn, + &database::NewArtifact { + entry_id: entry.id, + artifact_role: "primary_media".to_string(), + storage_area: "raw".to_string(), + relpath, + blob_id: None, + logical_path: None, + metadata_json: None, + }, + ).unwrap(); + entry.entry_uid + } + + /// Create a parent + child entry pair. Returns (parent_uid, child_uid). + fn add_container_entry(&self, parent_title: &str, child_title: &str) -> (String, String) { + let conn = self.conn(); + let n = self.si_counter.get(); + self.si_counter.set(n + 2); + let si_parent = database::upsert_source_identity( + &conn, "youtube", "playlist", Some(&format!("p-{n}")), None, &format!("yt:p:{n}"), + ).unwrap(); + let parent = database::create_archived_entry( + &conn, + &database::NewEntry { + source_identity_id: si_parent, + archive_run_id: self.run_id, + parent_entry_id: None, + root_entry_id: None, + created_by_user_id: self.user_id, + owned_by_user_id: self.user_id, + source_kind: "youtube".to_string(), + entity_kind: "playlist".to_string(), + title: Some(parent_title.to_string()), + visibility: "public".to_string(), + representation_kind: "json".to_string(), + source_metadata_json: "{}".to_string(), + display_metadata_json: None, + }, + ).unwrap(); + let si_child = database::upsert_source_identity( + &conn, "youtube", "video", Some(&format!("c-{n}")), None, &format!("yt:c:{n}"), + ).unwrap(); + let child = database::create_archived_entry( + &conn, + &database::NewEntry { + source_identity_id: si_child, + archive_run_id: self.run_id, + parent_entry_id: Some(parent.id), + root_entry_id: Some(parent.id), + created_by_user_id: self.user_id, + owned_by_user_id: self.user_id, + source_kind: "youtube".to_string(), + entity_kind: "video".to_string(), + title: Some(child_title.to_string()), + visibility: "public".to_string(), + representation_kind: "video".to_string(), + source_metadata_json: "{}".to_string(), + display_metadata_json: None, + }, + ).unwrap(); + (parent.entry_uid, child.entry_uid) + } + } + + fn read_zip_entry(file: std::fs::File, suffix: &str) -> String { + let mut archive = zip::ZipArchive::new(file).unwrap(); + let names: Vec = archive.file_names().map(str::to_string).collect(); + let name = names + .iter() + .find(|n| n.ends_with(suffix)) + .cloned() + .unwrap_or_else(|| panic!("no entry ending with {suffix}; names: {names:?}")); + let mut entry = archive.by_name(&name).unwrap(); + let mut content = String::new(); + std::io::Read::read_to_string(&mut entry, &mut content).unwrap(); + content + } + + #[test] + fn test_html_credit_on() { + let ctx = TestCtx::new(); + let uid = ctx.add_text_entry("&test", "hello world"); + let opts = ExportOptions { + format: ExportFormat::Html, + layout: ExportLayout::Together, + include_credit: true, + caller_bits: u32::MAX, + }; + let export = export_entries(&ctx.paths, &[uid.clone()], &opts).unwrap(); + let (file, _, filename, _) = export.open().unwrap(); + assert!(filename.ends_with(".zip"), "filename: {filename}"); + let html = read_zip_entry(file, "index.html"); + assert!(html.contains("<b>&test"), "title should be HTML-escaped"); + assert!(html.contains("Preserved with"), "credit present"); + assert!(html.contains("github.com/thegeneralist01/archivr")); + assert!(!html.contains("/api/"), "no /api/ paths"); + assert!(!html.contains(&uid), "uid not in output"); + } + + #[test] + fn test_html_credit_off() { + let ctx = TestCtx::new(); + let uid = ctx.add_text_entry("My Entry", "body"); + let opts = ExportOptions { + format: ExportFormat::Html, + layout: ExportLayout::Together, + include_credit: false, + caller_bits: u32::MAX, + }; + let export = export_entries(&ctx.paths, &[uid], &opts).unwrap(); + let (file, _, _, _) = export.open().unwrap(); + let html = read_zip_entry(file, "index.html"); + assert!(!html.to_lowercase().contains("archivr"), "no archivr mention when credit off"); + } + + #[test] + fn test_separate_layout() { + let ctx = TestCtx::new(); + let u1 = ctx.add_text_entry("Alpha", "a"); + let u2 = ctx.add_text_entry("Beta", "b"); + let opts = ExportOptions { + format: ExportFormat::Html, + layout: ExportLayout::Separate, + include_credit: false, + caller_bits: u32::MAX, + }; + let export = export_entries(&ctx.paths, &[u1, u2], &opts).unwrap(); + let (file, _, filename, _) = export.open().unwrap(); + assert!(filename.ends_with(".zip")); + let archive = zip::ZipArchive::new(file).unwrap(); + let names: Vec = archive.file_names().map(str::to_string).collect(); + assert!(names.iter().any(|n| n.contains("01-") && n.ends_with("index.html")), "01 missing; {names:?}"); + assert!(names.iter().any(|n| n.contains("02-") && n.ends_with("index.html")), "02 missing; {names:?}"); + } + + #[test] + fn test_markdown_entry() { + let ctx = TestCtx::new(); + let uid = ctx.add_text_entry("My Note", "# heading\n\nbody text"); + let opts = ExportOptions { + format: ExportFormat::Markdown, + layout: ExportLayout::Together, + include_credit: false, + caller_bits: u32::MAX, + }; + let export = export_entries(&ctx.paths, &[uid], &opts).unwrap(); + let (file, _, _, _) = export.open().unwrap(); + let md = read_zip_entry(file, "index.md"); + assert!(md.starts_with("# My Note"), "heading: {md}"); + assert!(md.contains("# heading\n\nbody text"), "body verbatim"); + } + + #[test] + fn test_parent_child_dedupe() { + let ctx = TestCtx::new(); + let (parent_uid, child_uid) = ctx.add_container_entry("Parent Playlist", "Child Video"); + let opts = ExportOptions { + format: ExportFormat::Html, + layout: ExportLayout::Together, + include_credit: false, + caller_bits: u32::MAX, + }; + // Both UIDs requested; child should be dropped since parent is also selected. + let export = export_entries(&ctx.paths, &[parent_uid, child_uid], &opts).unwrap(); + let (file, _, _, _) = export.open().unwrap(); + let html = read_zip_entry(file, "index.html"); + let count = html.matches("Child Video").count(); + assert!(count <= 1, "child title at most once; found {count}"); + } + + #[test] + fn test_validation_empty() { + let ctx = TestCtx::new(); + let opts = ExportOptions { + format: ExportFormat::Html, + layout: ExportLayout::Together, + include_credit: true, + caller_bits: u32::MAX, + }; + let err = export_entries(&ctx.paths, &[], &opts).unwrap_err(); + assert!(err.to_string().contains("must not be empty")); + } + + #[test] + fn test_validation_too_many() { + let ctx = TestCtx::new(); + let uids: Vec = (0..101).map(|i| format!("uid-{i}")).collect(); + let opts = ExportOptions { + format: ExportFormat::Html, + layout: ExportLayout::Together, + include_credit: true, + caller_bits: u32::MAX, + }; + let err = export_entries(&ctx.paths, &uids, &opts).unwrap_err(); + assert!(err.to_string().contains("100 entries")); + } + + #[test] + fn test_slug() { + assert_eq!(entry_slug("Hello World!"), "hello-world"); + assert_eq!(entry_slug(" "), "entry"); + assert_eq!(entry_slug("日本語"), "entry"); + assert_eq!(entry_slug("my-entry"), "my-entry"); + } + + #[test] + fn test_merge_pdfs_page_count() { + use lopdf::{Dictionary, Document, Object, Stream}; + let make_doc = |content: &[u8]| -> Document { + let mut doc = Document::with_version("1.4"); + let stream_id = doc.add_object(Object::Stream(Stream::new(Dictionary::new(), content.to_vec()))); + let mut page_dict = Dictionary::new(); + page_dict.set("Type", Object::Name(b"Page".to_vec())); + page_dict.set("Contents", Object::Reference(stream_id)); + page_dict.set("MediaBox", Object::Array(vec![ + Object::Integer(0), Object::Integer(0), + Object::Integer(612), Object::Integer(792), + ])); + let page_id = doc.add_object(Object::Dictionary(page_dict)); + let mut pages_dict = Dictionary::new(); + pages_dict.set("Type", Object::Name(b"Pages".to_vec())); + pages_dict.set("Kids", Object::Array(vec![Object::Reference(page_id)])); + pages_dict.set("Count", Object::Integer(1)); + let pages_id = doc.add_object(Object::Dictionary(pages_dict)); + if let Some(Object::Dictionary(pd)) = doc.objects.get_mut(&page_id) { + pd.set("Parent", Object::Reference(pages_id)); + } + let mut catalog = Dictionary::new(); + catalog.set("Type", Object::Name(b"Catalog".to_vec())); + catalog.set("Pages", Object::Reference(pages_id)); + let catalog_id = doc.add_object(Object::Dictionary(catalog)); + doc.trailer.set("Root", Object::Reference(catalog_id)); + doc + }; + + let doc1 = make_doc(b"BT /F1 12 Tf 100 700 Td (Page one) Tj ET"); + let doc2_p1 = make_doc(b"BT /F1 12 Tf 100 700 Td (Page two) Tj ET"); + let doc2_p2 = make_doc(b"BT /F1 12 Tf 100 700 Td (Page three) Tj ET"); + + let doc2 = merge_documents(vec![doc2_p1, doc2_p2]).unwrap(); + let mut merged = merge_documents(vec![doc1, doc2]).unwrap(); + let mut bytes: Vec = Vec::new(); + merged.save_to(&mut bytes).unwrap(); + let reloaded = lopdf::Document::load_mem(&bytes).unwrap(); + assert_eq!(reloaded.get_pages().len(), 3, "merged PDF should have 3 pages"); + } +} diff --git a/crates/archivr-core/src/export/model.rs b/crates/archivr-core/src/export/model.rs new file mode 100644 index 0000000..d4ea2d6 --- /dev/null +++ b/crates/archivr-core/src/export/model.rs @@ -0,0 +1,720 @@ +//! Data model for exports: loaded entries and their bodies. + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; + +use anyhow::Result; +use rusqlite::Connection; + +use crate::archive::{self, EntryArtifactSummary, EntrySummary}; +use crate::summarizer::article_parts; +use crate::twitter::parse_tweet_id; + +// --------------------------------------------------------------------------- +// Public types +// --------------------------------------------------------------------------- + +/// An asset file that will be written into the export bundle. +#[derive(Debug, Clone)] +pub(crate) struct Asset { + /// Absolute on-disk path (canonical store path or a work-dir poster path). + pub source: PathBuf, + /// Bundle-relative file name (e.g. `sha256abc.mp4`, `sha256abc-poster.jpg`). + pub name: String, + pub byte_size: u64, +} + +/// A resolved span in tweet body text. +#[derive(Debug, Clone)] +pub(crate) enum Span { + Text(String), + Link { text: String, href: String }, +} + +/// A single tweet / post. +#[derive(Debug, Clone)] +pub(crate) struct Post { + pub _id: String, + pub name: String, + pub handle: Option, + pub avatar: Option, + pub created_at_secs: Option, + pub spans: Vec, + /// `Some((title, body, cover))` for X article statuses. + pub article: Option<(Option, String, Option)>, + pub photos: Vec, + /// `(asset, animated_gif)`. + pub videos: Vec<(Asset, bool)>, + pub quote: Option>, + /// `https://x.com/{handle|i}/status/{id}`. + pub status_url: Option, +} + +/// The primary content of an exported entry. +#[derive(Debug)] +pub(crate) enum ExportBody { + Video(Asset), + Audio(Asset), + Image(Asset), + Pdf(Asset), + /// An HTML/HTM snapshot (SingleFile page). + Page(Asset), + Text { _mime_markdown: bool, text: String }, + /// Text file > 5 MiB: offer a download link only. + TextTooLarge(Asset), + File(Asset), + Posts(Vec), + Container(Vec), + Empty, +} + +/// A fully loaded entry, ready for rendering. +#[derive(Debug)] +pub(crate) struct ExportEntry { + pub summary: EntrySummary, + /// Subtitle `.vtt` assets in track order. + pub subtitles: Vec, + pub body: ExportBody, +} + +// --------------------------------------------------------------------------- +// Extension helpers +// --------------------------------------------------------------------------- + +const VIDEO_EXTS: &[&str] = &["mp4", "webm", "mov", "mkv", "avi", "m4v", "ogv"]; +const AUDIO_EXTS: &[&str] = &["mp3", "ogg", "m4a", "opus", "wav", "flac", "aac"]; +const IMAGE_EXTS: &[&str] = &["jpg", "jpeg", "png", "gif", "webp", "avif", "svg", "bmp"]; +const TEXT_EXTS: &[&str] = &["md", "markdown", "txt"]; +const TEXT_MAX_BYTES: u64 = 5 * 1024 * 1024; + +/// Extract the file name component of a store-relative path like +/// `raw/A/B/sha256.mp4`. +pub(crate) fn file_name_of(relpath: &str) -> String { + Path::new(relpath) + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| relpath.to_string()) +} + +/// Lowercase file extension without the dot, or `""`. +pub(crate) fn ext_of_s(path: &str) -> String { + Path::new(path) + .extension() + .and_then(|e| e.to_str()) + .map(|e| e.to_lowercase()) + .unwrap_or_default() +} + +// --------------------------------------------------------------------------- +// Loading +// --------------------------------------------------------------------------- + +/// Load a single entry and all its required data from the DB. +/// +/// `depth` limits container recursion: pass `0` for top-level entries. +/// Containers found at depth ≥ 2 become `Empty`. +pub(crate) fn load_entry( + conn: &Connection, + store_path: &Path, + summary: EntrySummary, + caller_bits: u32, + depth: usize, +) -> Result { + let detail = archive::get_entry_detail(conn, &summary.entry_uid)?; + let detail = match detail { + Some(d) => d, + None => { + return Ok(ExportEntry { + summary, + subtitles: vec![], + body: ExportBody::Empty, + }); + } + }; + + // ----- build asset map from artifacts ----- + let mut asset_map: HashMap = HashMap::new(); + let mut primary_media_artifact: Option = None; + let mut subtitle_artifacts: Vec = Vec::new(); + let mut raw_json_artifacts: Vec = Vec::new(); + + for artifact in &detail.artifacts { + match artifact.artifact_role.as_str() { + "primary_media" => { + if artifact.relpath.to_lowercase().ends_with(".json") { + raw_json_artifacts.push(artifact.clone()); + } else { + primary_media_artifact = Some(artifact.clone()); + } + if let Ok(p) = archive::resolve_artifact_path(store_path, artifact) { + asset_map.insert( + artifact.relpath.clone(), + Asset { + byte_size: artifact.byte_size.unwrap_or(0) as u64, + source: p, + name: file_name_of(&artifact.relpath), + }, + ); + } else { + eprintln!("warn: export: artifact not found: {}", artifact.relpath); + } + } + "media" | "avatar" => { + match archive::resolve_artifact_path(store_path, artifact) { + Ok(p) => { + asset_map.insert( + artifact.relpath.clone(), + Asset { + byte_size: artifact.byte_size.unwrap_or(0) as u64, + source: p, + name: file_name_of(&artifact.relpath), + }, + ); + } + Err(e) => eprintln!("warn: export: artifact not found: {e:#}"), + } + } + "raw_tweet_json" => { + raw_json_artifacts.push(artifact.clone()); + if let Ok(p) = archive::resolve_artifact_path(store_path, artifact) { + asset_map.insert( + artifact.relpath.clone(), + Asset { + byte_size: artifact.byte_size.unwrap_or(0) as u64, + source: p, + name: file_name_of(&artifact.relpath), + }, + ); + } + } + "subtitle" => subtitle_artifacts.push(artifact.clone()), + _ => {} // favicon, font, etc. + } + } + + // ----- subtitles (VTT only) ----- + let subtitles: Vec = subtitle_artifacts + .iter() + .filter(|a| a.relpath.to_lowercase().ends_with(".vtt")) + .filter_map(|a| { + archive::resolve_artifact_path(store_path, a) + .map(|p| Asset { + byte_size: a.byte_size.unwrap_or(0) as u64, + source: p, + name: file_name_of(&a.relpath), + }) + .map_err(|e| { + eprintln!("warn: export: subtitle not found: {e:#}"); + e + }) + .ok() + }) + .collect(); + + // ----- determine body ----- + let ek = summary.entity_kind.as_str(); + let sk = summary.source_kind.as_str(); + + let body = if summary.child_count > 0 { + if depth >= 2 { + ExportBody::Empty + } else { + let children = + archive::list_child_entries(conn, &summary.entry_uid, caller_bits)?; + let loaded: Vec = children + .into_iter() + .map(|child| load_entry(conn, store_path, child, caller_bits, depth + 1)) + .collect::>>()?; + ExportBody::Container(loaded) + } + } else if ek == "tweet" + || ek == "tweet_thread" + || (sk == "x" && ek == "post") + || (sk == "twitter" && ek == "post") + { + let posts = load_posts( + &detail.source_metadata_json, + &raw_json_artifacts, + store_path, + &asset_map, + ek, + ); + if posts.is_empty() { + body_from_primary_media(primary_media_artifact.as_ref(), &asset_map) + } else { + ExportBody::Posts(posts) + } + } else { + body_from_primary_media(primary_media_artifact.as_ref(), &asset_map) + }; + + Ok(ExportEntry { + summary, + subtitles, + body, + }) +} + +fn body_from_primary_media( + artifact: Option<&EntryArtifactSummary>, + asset_map: &HashMap, +) -> ExportBody { + let artifact = match artifact { + Some(a) => a, + None => return ExportBody::Empty, + }; + let relpath = &artifact.relpath; + let asset = match asset_map.get(relpath) { + Some(a) => a.clone(), + None => return ExportBody::Empty, + }; + let ext = ext_of_s(relpath); + let ext = ext.as_str(); + if VIDEO_EXTS.contains(&ext) { + ExportBody::Video(asset) + } else if AUDIO_EXTS.contains(&ext) { + ExportBody::Audio(asset) + } else if IMAGE_EXTS.contains(&ext) { + ExportBody::Image(asset) + } else if ext == "pdf" { + ExportBody::Pdf(asset) + } else if ext == "html" || ext == "htm" { + ExportBody::Page(asset) + } else if TEXT_EXTS.contains(&ext) { + if asset.byte_size > TEXT_MAX_BYTES { + ExportBody::TextTooLarge(asset) + } else { + match std::fs::read(&asset.source) { + Ok(bytes) => { + let text = String::from_utf8_lossy(&bytes).into_owned(); + let _mime_markdown = ext == "md" || ext == "markdown"; + ExportBody::Text { _mime_markdown, text } + } + Err(e) => { + eprintln!("warn: export: failed to read text artifact: {e:#}"); + ExportBody::TextTooLarge(asset) + } + } + } + } else { + ExportBody::File(asset) + } +} + +// --------------------------------------------------------------------------- +// Tweet / thread loading +// --------------------------------------------------------------------------- + +fn load_posts( + source_metadata_json: &str, + json_artifacts: &[EntryArtifactSummary], + store_path: &Path, + asset_map: &HashMap, + entity_kind: &str, +) -> Vec { + let seed_id: Option = serde_json::from_str::(source_metadata_json) + .ok() + .and_then(|v| v.get("tweet_id").and_then(|t| t.as_str()).map(str::to_string)); + + let mut statuses: Vec = Vec::new(); + for artifact in json_artifacts { + let path = match archive::resolve_artifact_path(store_path, artifact) { + Ok(p) => p, + Err(_) => continue, + }; + let bytes = match std::fs::read(&path) { + Ok(b) => b, + Err(e) => { + eprintln!( + "warn: export: failed to read tweet JSON {}: {e:#}", + path.display() + ); + continue; + } + }; + let json: serde_json::Value = match serde_json::from_slice(&bytes) { + Ok(v) => v, + Err(_) => continue, + }; + let tweet_obj = json.get("tweet").cloned().unwrap_or(json); + if tweet_obj.get("id").is_some() || tweet_obj.get("id_str").is_some() { + statuses.push(tweet_obj); + } + } + + if statuses.is_empty() { + return vec![]; + } + + let status_map: HashMap = statuses + .iter() + .filter_map(|s| tweet_id(s).map(|id| (id, s.clone()))) + .collect(); + + if entity_kind == "tweet" { + let status = seed_id + .as_deref() + .and_then(|sid| status_map.get(sid)) + .or_else(|| statuses.first()) + .cloned(); + match status { + Some(s) => vec![parse_post(&s, asset_map, None)], + None => vec![], + } + } else { + build_thread(&statuses, &status_map, seed_id.as_deref(), asset_map) + } +} + +fn build_thread( + statuses: &[serde_json::Value], + status_map: &HashMap, + seed_id: Option<&str>, + asset_map: &HashMap, +) -> Vec { + if statuses.is_empty() { + return vec![]; + } + + let start_id = seed_id + .and_then(|id| status_map.get(id).map(|_| id.to_string())) + .or_else(|| statuses.last().and_then(tweet_id)) + .unwrap_or_default(); + + // Walk upward to find the root. + let mut root_id = start_id; + let mut visited: HashSet = HashSet::new(); + visited.insert(root_id.clone()); + loop { + let status = match status_map.get(&root_id) { + Some(s) => s, + None => break, + }; + match in_reply_to_id(status) { + Some(pid) if status_map.contains_key(&pid) && !visited.contains(&pid) => { + visited.insert(pid.clone()); + root_id = pid; + } + _ => break, + } + } + + // Build children map. + let mut children_map: HashMap> = HashMap::new(); + for status in statuses { + let id = match tweet_id(status) { + Some(id) => id, + None => continue, + }; + if let Some(parent) = in_reply_to_id(status) { + if status_map.contains_key(&parent) { + children_map.entry(parent).or_default().push(id); + } + } + } + + // Sort siblings by created_at then by id. + for children in children_map.values_mut() { + children.sort_by(|a, b| { + let ca = status_map + .get(a) + .and_then(|s| created_at_secs(s)) + .unwrap_or(0); + let cb = status_map + .get(b) + .and_then(|s| created_at_secs(s)) + .unwrap_or(0); + ca.cmp(&cb).then(a.cmp(b)) + }); + } + + let mut result = Vec::new(); + let mut conversation_ids: HashSet = HashSet::new(); + dfs( + &root_id, + status_map, + &children_map, + asset_map, + &mut result, + &mut conversation_ids, + ); + result +} + +fn dfs( + id: &str, + status_map: &HashMap, + children_map: &HashMap>, + asset_map: &HashMap, + out: &mut Vec, + conversation_ids: &mut HashSet, +) { + let status = match status_map.get(id) { + Some(s) => s, + None => return, + }; + conversation_ids.insert(id.to_string()); + let post = parse_post(status, asset_map, Some(conversation_ids)); + out.push(post); + if let Some(children) = children_map.get(id) { + for child_id in children.clone() { + dfs(&child_id, status_map, children_map, asset_map, out, conversation_ids); + } + } +} + +// --------------------------------------------------------------------------- +// Tweet parsing helpers +// --------------------------------------------------------------------------- + +fn tweet_id(status: &serde_json::Value) -> Option { + let id = status + .get("id_str") + .and_then(|v| v.as_str()) + .map(str::to_string) + .or_else(|| { + status.get("id").and_then(|v| { + if let Some(s) = v.as_str() { + Some(s.to_string()) + } else { + v.as_u64().map(|n| n.to_string()) + } + }) + })?; + if id.is_empty() { None } else { Some(id) } +} + +fn in_reply_to_id(status: &serde_json::Value) -> Option { + status + .get("in_reply_to_status_id_str") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty() && *s != "null") + .map(str::to_string) + .or_else(|| { + status + .get("in_reply_to_status_id") + .and_then(|v| v.as_u64()) + .map(|n| n.to_string()) + }) +} + +fn created_at_secs(status: &serde_json::Value) -> Option { + if let Some(n) = status.get("created_at_secs").and_then(|v| v.as_i64()) { + return Some(n); + } + if let Some(s) = status.get("created_at").and_then(|v| v.as_str()) { + use chrono::DateTime; + if let Ok(dt) = DateTime::parse_from_str(s, "%a %b %d %T %z %Y") { + return Some(dt.timestamp()); + } + if let Ok(dt) = DateTime::parse_from_rfc3339(s) { + return Some(dt.timestamp()); + } + } + None +} + +fn parse_post( + status: &serde_json::Value, + asset_map: &HashMap, + conversation_ids: Option<&HashSet>, +) -> Post { + let id = tweet_id(status).unwrap_or_default(); + + let author = status.get("author").or_else(|| status.get("user")); + let name = author + .and_then(|a| a.get("name").and_then(|v| v.as_str())) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .or_else(|| { + author + .and_then(|a| a.get("screen_name").and_then(|v| v.as_str())) + .map(str::to_string) + }) + .unwrap_or_else(|| "Unknown".to_string()); + let handle = author + .and_then(|a| a.get("screen_name").and_then(|v| v.as_str())) + .filter(|s| !s.is_empty()) + .map(str::to_string); + + let avatar_local = author + .and_then(|a| a.get("avatar_local_path").and_then(|v| v.as_str())) + .map(str::to_string); + let avatar = avatar_local.as_deref().and_then(|lp| asset_map.get(lp)).cloned(); + + let created_at_secs = created_at_secs(status); + + // Article. + let article = article_parts(status).map(|(title, body)| { + let cover_local = status + .pointer("/article/cover_media/local_path") + .and_then(|v| v.as_str()) + .map(str::to_string); + let cover = cover_local.as_deref().and_then(|lp| asset_map.get(lp)).cloned(); + (title, body, cover) + }); + + // Spans (only when no article). + let raw_spans = if article.is_some() { + vec![] + } else { + build_spans(status) + }; + + // Media. + let media_list = status + .get("extended_entities") + .or_else(|| status.get("entities")) + .and_then(|e| e.get("media")) + .and_then(|m| m.as_array()) + .cloned() + .unwrap_or_default(); + + let media_url_set: HashSet = media_list + .iter() + .filter_map(|m| m.get("url").and_then(|u| u.as_str())) + .map(str::to_string) + .collect(); + let spans = filter_spans(raw_spans, &media_url_set); + + let mut photos: Vec = Vec::new(); + let mut videos: Vec<(Asset, bool)> = Vec::new(); + for m in &media_list { + let local_path = m + .get("local_path") + .and_then(|v| v.as_str()) + .map(str::to_string); + let asset = match local_path.as_deref().and_then(|lp| asset_map.get(lp)).cloned() { + Some(a) => a, + None => continue, + }; + match m.get("type").and_then(|v| v.as_str()).unwrap_or("") { + "photo" => photos.push(asset), + "video" => videos.push((asset, false)), + "animated_gif" => videos.push((asset, true)), + _ => {} + } + } + + // Quote. + let quoted_id = status + .get("quoted_status_id_str") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .map(str::to_string); + let quote = quoted_id.as_deref().and_then(|qid| { + if conversation_ids.map_or(false, |c| c.contains(qid)) { + return None; + } + status + .get("quoted_status") + .map(|qs| Box::new(parse_post(qs, asset_map, None))) + }); + + // Status URL. + let status_url = parse_tweet_id(&id).map(|tid| { + handle + .as_deref() + .map(|h| format!("https://x.com/{h}/status/{tid}")) + .unwrap_or_else(|| format!("https://x.com/i/status/{tid}")) + }); + + Post { + _id: id, + name, + handle, + avatar, + created_at_secs, + spans, + article, + photos, + videos, + quote, + status_url, + } +} + +fn build_spans(status: &serde_json::Value) -> Vec { + let text = status + .get("full_text") + .or_else(|| status.get("text")) + .and_then(|v| v.as_str()) + .unwrap_or(""); + + let url_entities = status + .pointer("/entities/urls") + .and_then(|v| v.as_array()) + .cloned() + .unwrap_or_default(); + + let mut text = decode_html_entities(text); + + let mut replacements: Vec<(String, String, String)> = url_entities + .iter() + .filter_map(|e| { + let short = e.get("url").and_then(|v| v.as_str())?; + let display = e + .get("display_url") + .and_then(|v| v.as_str()) + .unwrap_or(short); + let expanded = e + .get("expanded_url") + .and_then(|v| v.as_str()) + .unwrap_or(short); + if short.is_empty() { + None + } else { + Some((short.to_string(), display.to_string(), expanded.to_string())) + } + }) + .collect(); + + if replacements.is_empty() { + let trimmed = text.trim().to_string(); + return if trimmed.is_empty() { vec![] } else { vec![Span::Text(trimmed)] }; + } + + let mut spans: Vec = Vec::new(); + loop { + let earliest = replacements + .iter() + .enumerate() + .filter_map(|(i, (short, _, _))| text.find(short.as_str()).map(|pos| (pos, i, short.len()))) + .min_by_key(|(pos, _, _)| *pos); + match earliest { + None => break, + Some((pos, idx, len)) => { + let (_, display_url, expanded_url) = replacements[idx].clone(); + if pos > 0 { + spans.push(Span::Text(text[..pos].to_string())); + } + spans.push(Span::Link { text: display_url, href: expanded_url }); + text = text[pos + len..].to_string(); + replacements.remove(idx); + } + } + } + let remainder = text.trim().to_string(); + if !remainder.is_empty() { + spans.push(Span::Text(remainder)); + } + spans +} + +fn filter_spans(spans: Vec, strip_set: &HashSet) -> Vec { + spans + .into_iter() + .filter(|span| match span { + Span::Link { href, .. } => !strip_set.contains(href), + Span::Text(t) => !strip_set.contains(t.as_str()), + }) + .collect() +} + +fn decode_html_entities(s: &str) -> String { + s.replace("&", "&") + .replace("<", "<") + .replace(">", ">") + .replace(""", "\"") + .replace("'", "'") +} diff --git a/crates/archivr-core/src/export/pdf.rs b/crates/archivr-core/src/export/pdf.rs new file mode 100644 index 0000000..39364c7 --- /dev/null +++ b/crates/archivr-core/src/export/pdf.rs @@ -0,0 +1,395 @@ +//! PDF generation via headless Chrome and lopdf merging. + +use std::collections::HashMap; +use std::ffi::OsString; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use lopdf::{Dictionary, Document, Object, ObjectId, Stream}; + +use crate::env_config::{env_or, env_timeout}; +use crate::export::brand; +use crate::export::html::{AssetMode, entry_title, render_document, source_label}; +use crate::export::model::{Asset, ExportBody, ExportEntry}; +use crate::process; + +// --------------------------------------------------------------------------- +// Chrome PDF printing +// --------------------------------------------------------------------------- + +/// Print an HTML file to PDF using headless Chrome. +pub(crate) fn print_pdf(html_path: &Path, out: &Path, profile_dir: &Path) -> Result<()> { + let chrome = env_or("ARCHIVR_CHROME", "chromium"); + let chrome_path = PathBuf::from(&chrome); + + let timeout_secs = env_timeout("ARCHIVR_EXPORT_PDF_TIMEOUT", 120); + + let extra_args: Vec = std::env::var("ARCHIVR_CHROME_ARGS") + .unwrap_or_default() + .split_whitespace() + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect(); + + let html_url = percent_encode_path(html_path); + + let mut args: Vec = vec![ + "--headless=new".into(), + "--disable-gpu".into(), + "--no-first-run".into(), + "--no-default-browser-check".into(), + "--hide-scrollbars".into(), + format!("--user-data-dir={}", profile_dir.display()).into(), + "--no-pdf-header-footer".into(), + "--run-all-compositor-stages-before-draw".into(), + "--virtual-time-budget=15000".into(), + format!("--print-to-pdf={}", out.display()).into(), + ]; + for a in &extra_args { + args.push(a.into()); + } + args.push(html_url.into()); + + process::run_with_timeout(&chrome_path, &args, None, Duration::from_secs(timeout_secs)) + .with_context(|| "PDF export needs Chromium: set ARCHIVR_CHROME")?; + + if !out.exists() || out.metadata().map(|m| m.len()).unwrap_or(0) == 0 { + bail!( + "Chromium produced no PDF (set ARCHIVR_CHROME to a Chromium/Chrome binary); \ + tried: {chrome}" + ); + } + Ok(()) +} + +fn percent_encode_path(path: &Path) -> String { + let s = path.to_string_lossy(); + let mut out = String::with_capacity(s.len() + 7); + out.push_str("file://"); + for byte in s.as_bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'/' | b'.' | b'_' | b'-' | b'~' => { + out.push(*byte as char) + } + b => out.push_str(&format!("%{b:02X}")), + } + } + out +} + +// --------------------------------------------------------------------------- +// lopdf merging +// --------------------------------------------------------------------------- + +/// Merge PDF files on disk into a single output PDF. +pub(crate) fn merge_pdf_files(inputs: &[PathBuf], output: &Path) -> Result<()> { + if inputs.is_empty() { + bail!("merge_pdf_files: no inputs"); + } + if inputs.len() == 1 { + std::fs::copy(&inputs[0], output) + .with_context(|| format!("failed to copy PDF to {}", output.display()))?; + return Ok(()); + } + + let docs: Vec = inputs + .iter() + .map(|p| Document::load(p).with_context(|| format!("failed to load PDF: {}", p.display()))) + .collect::>>()?; + + let mut merged = merge_documents(docs)?; + merged + .save(output) + .with_context(|| format!("failed to save merged PDF to {}", output.display()))?; + Ok(()) +} + +/// Merge multiple `Document` values into one, appending pages in order. +/// +/// Follows the lopdf `examples/merge.rs` pattern: each source document's +/// object IDs are shifted by an offset so they do not collide, then all +/// objects are copied into a fresh document with a new Pages tree and Catalog. +pub(crate) fn merge_documents(docs: Vec) -> Result { + if docs.is_empty() { + bail!("merge_documents: no documents provided"); + } + if docs.len() == 1 { + return Ok(docs.into_iter().next().unwrap()); + } + + let mut merged = Document::with_version("1.5"); + let mut all_page_ids: Vec = Vec::new(); + // next_id tracks the next free object number so we can assign the Pages + // and Catalog objects after all source objects have been copied in. + let mut next_id: u32 = 0; + + for doc in docs { + let offset = next_id; + + // Collect pages in page-number order before we consume the doc. + let pages = doc.get_pages(); // BTreeMap + for (_page_num, page_oid) in &pages { + all_page_ids.push((page_oid.0 + offset, page_oid.1)); + } + + let doc_max = doc.objects.keys().map(|(n, _)| *n).max().unwrap_or(0); + + for (oid, obj) in &doc.objects { + let new_oid: ObjectId = (oid.0 + offset, oid.1); + let remapped = remap_refs(obj, offset); + merged.objects.insert(new_oid, remapped); + } + + next_id += doc_max + 1; + } + + // Build the Pages dictionary. + let pages_oid: ObjectId = (next_id, 0); + next_id += 1; + + // Point every collected page at the new Pages parent. + for page_id in &all_page_ids { + if let Some(Object::Dictionary(dict)) = merged.objects.get_mut(page_id) { + dict.set("Parent", Object::Reference(pages_oid)); + } + } + + let mut pages_dict = Dictionary::new(); + pages_dict.set("Type", Object::Name(b"Pages".to_vec())); + pages_dict.set( + "Kids", + Object::Array(all_page_ids.iter().map(|id| Object::Reference(*id)).collect()), + ); + pages_dict.set("Count", Object::Integer(all_page_ids.len() as i64)); + merged.objects.insert(pages_oid, Object::Dictionary(pages_dict)); + + // Build the Catalog. + let catalog_oid: ObjectId = (next_id, 0); + let mut catalog = Dictionary::new(); + catalog.set("Type", Object::Name(b"Catalog".to_vec())); + catalog.set("Pages", Object::Reference(pages_oid)); + merged.objects.insert(catalog_oid, Object::Dictionary(catalog)); + + merged.trailer.set("Root", Object::Reference(catalog_oid)); + merged.trailer.set("Size", Object::Integer((next_id + 1) as i64)); + merged.max_id = next_id; + + Ok(merged) +} + +/// Recursively remap all `Reference` object IDs by adding `offset` to the +/// object number component. +fn remap_refs(obj: &Object, offset: u32) -> Object { + match obj { + Object::Reference(id) => Object::Reference((id.0 + offset, id.1)), + Object::Array(arr) => Object::Array(arr.iter().map(|o| remap_refs(o, offset)).collect()), + Object::Dictionary(dict) => { + let mut new_dict = Dictionary::new(); + for (k, v) in dict.iter() { + new_dict.set(k.clone(), remap_refs(v, offset)); + } + Object::Dictionary(new_dict) + } + Object::Stream(stream) => { + let mut new_dict = Dictionary::new(); + for (k, v) in stream.dict.iter() { + new_dict.set(k.clone(), remap_refs(v, offset)); + } + Object::Stream(Stream::new(new_dict, stream.content.clone())) + } + other => other.clone(), + } +} + +// --------------------------------------------------------------------------- +// Per-entry PDF generation +// --------------------------------------------------------------------------- + +/// Generate a PDF for a single entry. Returns the path inside `work_dir`. +pub(crate) fn entry_pdf( + entry: &ExportEntry, + index: usize, + with_credit: bool, + work_dir: &Path, + posters: &HashMap, +) -> Result { + let profile_dir = work_dir.join("chrome-profile"); + std::fs::create_dir_all(&profile_dir)?; + + match &entry.body { + ExportBody::Page(asset) => { + entry_pdf_from_page(entry, index, with_credit, work_dir, &profile_dir, asset) + } + ExportBody::Pdf(asset) => { + entry_pdf_from_existing_pdf(entry, index, with_credit, work_dir, &profile_dir, asset) + } + _ => entry_pdf_from_html(entry, index, with_credit, work_dir, &profile_dir, posters), + } +} + +fn entry_pdf_from_html( + entry: &ExportEntry, + index: usize, + with_credit: bool, + work_dir: &Path, + profile_dir: &Path, + posters: &HashMap, +) -> Result { + let html = render_document(std::slice::from_ref(entry), AssetMode::Print, posters, with_credit); + let html_path = work_dir.join(format!("print-{index}.html")); + std::fs::write(&html_path, &html) + .with_context(|| format!("failed to write print HTML: {}", html_path.display()))?; + let out = work_dir.join(format!("entry-{index}.pdf")); + print_pdf(&html_path, &out, profile_dir)?; + Ok(out) +} + +fn entry_pdf_from_page( + entry: &ExportEntry, + index: usize, + with_credit: bool, + work_dir: &Path, + profile_dir: &Path, + asset: &Asset, +) -> Result { + let snapshot_bytes = std::fs::read(&asset.source) + .with_context(|| format!("failed to read snapshot: {}", asset.source.display()))?; + let snapshot = String::from_utf8_lossy(&snapshot_bytes); + + let title = entry_title(entry); + let label = source_label(&entry.summary.source_kind, &entry.summary.entity_kind); + let masthead = build_masthead_div(&title, &label, &entry.summary.archived_at); + + let injected = inject_after_body_open(&snapshot, &masthead); + let injected = if with_credit { + inject_before_body_close(&injected, brand::CREDIT_INLINE_HTML) + } else { + injected + }; + + let html_path = work_dir.join(format!("print-page-{index}.html")); + std::fs::write(&html_path, injected.as_bytes()) + .with_context(|| format!("failed to write page HTML: {}", html_path.display()))?; + let out = work_dir.join(format!("entry-{index}.pdf")); + print_pdf(&html_path, &out, profile_dir)?; + Ok(out) +} + +fn entry_pdf_from_existing_pdf( + entry: &ExportEntry, + index: usize, + with_credit: bool, + work_dir: &Path, + profile_dir: &Path, + asset: &Asset, +) -> Result { + // Print the masthead as its own page. + let title = entry_title(entry); + let label = source_label(&entry.summary.source_kind, &entry.summary.entity_kind); + let mhtml = build_masthead_page(&title, &label, &entry.summary.archived_at, with_credit); + let mhtml_path = work_dir.join(format!("masthead-{index}.html")); + std::fs::write(&mhtml_path, mhtml.as_bytes()).context("failed to write masthead HTML")?; + let mast_pdf_path = work_dir.join(format!("masthead-{index}.pdf")); + print_pdf(&mhtml_path, &mast_pdf_path, profile_dir)?; + + let out = work_dir.join(format!("entry-{index}.pdf")); + + match Document::load(&asset.source) { + Ok(orig_doc) => { + let mast_doc = Document::load(&mast_pdf_path).context("failed to reload masthead PDF")?; + let mut merged = merge_documents(vec![mast_doc, orig_doc])?; + merged.save(&out).context("failed to save merged PDF")?; + Ok(out) + } + Err(e) => { + eprintln!("warn: export: failed to load PDF artifact: {e:#}"); + // Fallback: render a plain HTML page for this entry. + let html = render_document( + std::slice::from_ref(entry), + AssetMode::Print, + &HashMap::new(), + with_credit, + ); + let html_path = work_dir.join(format!("print-{index}.html")); + std::fs::write(&html_path, &html)?; + print_pdf(&html_path, &out, profile_dir)?; + Ok(out) + } + } +} + +// --------------------------------------------------------------------------- +// Masthead injection helpers +// --------------------------------------------------------------------------- + +fn build_masthead_div(title: &str, label: &str, archived_at: &str) -> String { + use chrono::DateTime; + let date = DateTime::parse_from_rfc3339(archived_at) + .map(|dt| dt.format("%-d %B %Y").to_string()) + .unwrap_or_else(|_| archived_at.to_string()); + + format!( + r#"
+

{label}

+

{title}

+

Archived {date}

+
"#, + label = html_esc(label), + title = html_esc(title), + date = html_esc(&date), + ) +} + +fn build_masthead_page(title: &str, label: &str, archived_at: &str, with_credit: bool) -> String { + let masthead = build_masthead_div(title, label, archived_at); + let credit = if with_credit { brand::CREDIT_HTML } else { "" }; + format!( + r#" +
{masthead}
{credit}"#, + ) +} + +fn inject_after_body_open(html: &str, to_inject: &str) -> String { + let lower = html.to_lowercase(); + if let Some(body_start) = lower.find("') { + let insert_at = body_start + rel_end + 1; + let mut out = String::with_capacity(html.len() + to_inject.len() + 1); + out.push_str(&html[..insert_at]); + out.push('\n'); + out.push_str(to_inject); + out.push_str(&html[insert_at..]); + return out; + } + } + let mut out = String::with_capacity(html.len() + to_inject.len() + 1); + out.push_str(to_inject); + out.push('\n'); + out.push_str(html); + out +} + +fn inject_before_body_close(html: &str, to_inject: &str) -> String { + let lower = html.to_lowercase(); + if let Some(close_pos) = lower.rfind("") { + let mut out = String::with_capacity(html.len() + to_inject.len() + 1); + out.push_str(&html[..close_pos]); + out.push('\n'); + out.push_str(to_inject); + out.push_str(&html[close_pos..]); + return out; + } + let mut out = html.to_string(); + out.push('\n'); + out.push_str(to_inject); + out +} + +fn html_esc(s: &str) -> String { + s.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) + .replace('\'', "'") +} diff --git a/crates/archivr-core/src/lib.rs b/crates/archivr-core/src/lib.rs index 55d70c1..340b87c 100644 --- a/crates/archivr-core/src/lib.rs +++ b/crates/archivr-core/src/lib.rs @@ -14,3 +14,4 @@ pub mod text_title; pub mod transcriber; pub(crate) mod env_config; pub(crate) mod process; +pub mod export; diff --git a/crates/archivr-core/src/summarizer.rs b/crates/archivr-core/src/summarizer.rs index 3b9db28..1dc1bd8 100644 --- a/crates/archivr-core/src/summarizer.rs +++ b/crates/archivr-core/src/summarizer.rs @@ -838,7 +838,11 @@ fn flatten_article_blocks(v: &serde_json::Value, out: &mut Vec) { } } -fn article_text(status: &serde_json::Value) -> Option { +/// Extract the article title and body from a tweet status object. +/// +/// Returns `Some((title, body))` when the status has an `article` object with +/// usable body text; `None` otherwise. +pub(crate) fn article_parts(status: &serde_json::Value) -> Option<(Option, String)> { let article = status.get("article")?; article.as_object()?; let title = nonempty_string(article, "title"); @@ -852,9 +856,12 @@ fn article_text(status: &serde_json::Value) -> Option { }) .or_else(|| nonempty_string(article, "preview_text")) .or_else(|| nonempty_string(article, "summary_text"))?; + Some((title, body)) +} - Some(match title.as_deref() { - Some(title) => format!("{title}\n\n{body}"), +fn article_text(status: &serde_json::Value) -> Option { + article_parts(status).map(|(title, body)| match title.as_deref() { + Some(t) => format!("{t}\n\n{body}"), None => body, }) } diff --git a/crates/archivr-server/Cargo.toml b/crates/archivr-server/Cargo.toml index 6371f8a..ac32531 100644 --- a/crates/archivr-server/Cargo.toml +++ b/crates/archivr-server/Cargo.toml @@ -24,6 +24,9 @@ regex.workspace = true reqwest.workspace = true uuid.workspace = true +tokio-util.workspace = true +zip.workspace = true + [dev-dependencies] tempfile.workspace = true tower.workspace = true diff --git a/crates/archivr-server/src/effective_config.rs b/crates/archivr-server/src/effective_config.rs index de10c8e..57f61f0 100644 --- a/crates/archivr-server/src/effective_config.rs +++ b/crates/archivr-server/src/effective_config.rs @@ -69,8 +69,9 @@ pub(crate) static ENV_VARS: &[EnvSpec] = &[ spec("ARCHIVR_DENO", "tools", None, "Pinned Deno binary offered to the JS runtime resolver."), spec("ARCHIVR_JS_RUNTIME", "tools", None, "Forced JS runtime for yt-dlp as RUNTIME[:ABS_PATH] (deno, node, bun, quickjs)."), spec("ARCHIVR_SINGLE_FILE", "tools", Some("single-file"), "single-file-cli binary for web page archiving."), - spec("ARCHIVR_CHROME", "tools", Some("chromium"), "Chromium executable passed to single-file."), + spec("ARCHIVR_CHROME", "tools", Some("chromium"), "Chromium executable used by single-file and PDF export."), spec("ARCHIVR_CHROME_ARGS", "tools", None, "Extra space-separated Chromium flags."), + spec("ARCHIVR_EXPORT_PDF_TIMEOUT", "tools", Some("120"), "Seconds allowed for each Chromium PDF render during entry export."), spec("ARCHIVR_UBLOCK", "tools", Some("true"), "Default for the uBlock extension toggle when no instance setting overrides it (false or 0 disables)."), spec("ARCHIVR_UBLOCK_EXT", "tools", None, "Directory of the unpacked uBlock extension."), spec("ARCHIVR_COOKIE_CONSENT", "tools", Some("true"), "Default for the cookie-consent extension toggle when no instance setting overrides it (false or 0 disables)."), diff --git a/crates/archivr-server/src/exports.rs b/crates/archivr-server/src/exports.rs new file mode 100644 index 0000000..07b5c1c --- /dev/null +++ b/crates/archivr-server/src/exports.rs @@ -0,0 +1,247 @@ +//! `GET /api/archives/:archive_id/export` — generate and stream an entry export. + +use axum::{ + Router, + body::Body, + extract::{Path, Query, State}, + http::{HeaderValue, header}, + response::{IntoResponse, Response}, + routing::get, +}; +use tokio_util::io::ReaderStream; + +use archivr_core::{archive, database, export}; + +use crate::routes::{ApiError, AppState, AuthUser, auth_to_caller_bits, ensure_entry_visible, mounted_archive}; + +pub fn routes() -> Router { + Router::new().route( + "/api/archives/:archive_id/export", + get(export_handler), + ) +} + +#[derive(Debug, serde::Deserialize)] +struct ExportQuery { + entries: String, + format: String, + layout: Option, + credit: Option, +} + +async fn export_handler( + State(state): State, + auth_user: AuthUser, + Path(archive_id): Path, + Query(q): Query, +) -> Result { + // 1. Require authentication. + if matches!(auth_user, AuthUser::Guest) { + return Err(ApiError::unauthorized("login required")); + } + + // 2. Parse format, layout, and credit. + let format = export::ExportFormat::parse(&q.format) + .ok_or_else(|| ApiError::bad_request("format must be html, pdf, or markdown"))?; + + let layout = match q.layout.as_deref().unwrap_or("together") { + "together" => export::ExportLayout::Together, + "separate" => export::ExportLayout::Separate, + _ => return Err(ApiError::bad_request("layout must be together or separate")), + }; + + let include_credit = q.credit.unwrap_or(true); + + // 3. Parse and validate entry UIDs. + let uids: Vec = q + .entries + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect(); + + if uids.is_empty() { + return Err(ApiError::bad_request("entries must not be empty")); + } + if uids.len() > export::MAX_EXPORT_ENTRIES { + return Err(ApiError::bad_request("select at most 100 entries")); + } + + // 4. Resolve archive and verify entry visibility. + let mounted = mounted_archive(&state, &archive_id)?; + let conn = database::open_or_initialize(&mounted.archive_path)?; + for uid in &uids { + ensure_entry_visible(&conn, &auth_user, uid)?; + database::entry_id_for_uid(&conn, uid)? + .ok_or_else(|| ApiError::not_found("entry not found"))?; + } + drop(conn); // don't hold a connection across the blocking task + + let paths = archive::read_archive_paths(&mounted.archive_path)?; + let caller_bits = auth_to_caller_bits(&auth_user); + let options = export::ExportOptions { + format, + layout, + include_credit, + caller_bits, + }; + + // 5. Run the (synchronous) export in a blocking thread. + let export_file = tokio::task::spawn_blocking(move || { + export::export_entries(&paths, &uids, &options) + }) + .await + .map_err(|e| { + eprintln!("warn: export: task panicked: {e:#}"); + ApiError::internal("export task failed") + })? + .map_err(|e| { + eprintln!("warn: export: {e:#}"); + ApiError::internal(&format!("{e:#}")) + })?; + + // 6. Stream the file. + let (std_file, len, filename, content_type) = export_file.open().map_err(|e| { + eprintln!("warn: export: failed to open result: {e:#}"); + ApiError::internal("failed to open export file") + })?; + let async_file = tokio::fs::File::from_std(std_file); + let stream = ReaderStream::new(async_file); + let body = Body::from_stream(stream); + + let disposition = format!("attachment; filename=\"{filename}\""); + let response = Response::builder() + .header(header::CONTENT_TYPE, content_type) + .header(header::CONTENT_LENGTH, len) + .header(header::CACHE_CONTROL, "no-store") + .header( + header::CONTENT_DISPOSITION, + HeaderValue::from_str(&disposition) + .unwrap_or_else(|_| HeaderValue::from_static("attachment")), + ) + .body(body) + .map_err(|_| ApiError::internal("failed to build response"))?; + + Ok(response) +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use archivr_core::{archive, database}; + use axum::http::StatusCode; + + use crate::test_support::{fixture, make_test_session, send}; + + /// Insert a minimal text entry and return its `entry_uid`. + fn seed_entry(archive_path: &std::path::Path) -> String { + let paths = archive::read_archive_paths(archive_path).unwrap(); + let conn = database::open_or_initialize(archive_path).unwrap(); + let user_id = database::ensure_default_user(&conn).unwrap(); + let run = database::create_archive_run(&conn, user_id, 1).unwrap(); + let si = database::upsert_source_identity( + &conn, "text", "document", Some("te1"), None, "text:e:1", + ).unwrap(); + let entry = database::create_archived_entry( + &conn, + &database::NewEntry { + source_identity_id: si, + 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: "text".to_string(), + entity_kind: "document".to_string(), + title: Some("Export Test".to_string()), + visibility: "public".to_string(), + representation_kind: "text".to_string(), + source_metadata_json: "{}".to_string(), + display_metadata_json: None, + }, + ).unwrap(); + let relpath = "raw/e/1/export_test.txt".to_string(); + let fpath = paths.store_path.join(&relpath); + std::fs::create_dir_all(fpath.parent().unwrap()).unwrap(); + std::fs::write(&fpath, b"hello export").unwrap(); + database::add_entry_artifact( + &conn, + &database::NewArtifact { + entry_id: entry.id, + artifact_role: "primary_media".to_string(), + storage_area: "raw".to_string(), + relpath, + blob_id: None, + logical_path: None, + metadata_json: None, + }, + ).unwrap(); + entry.entry_uid + } + + #[tokio::test] + async fn no_cookie_returns_401() { + let f = fixture(); + let uid = seed_entry(&f.archive_path); + let (status, _) = send( + &f.router, + "GET", + &format!("/api/archives/test/export?entries={uid}&format=html"), + None, + None, + ).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + } + + #[tokio::test] + async fn visible_entry_returns_zip() { + let f = fixture(); + let uid = seed_entry(&f.archive_path); + let cookie = make_test_session(&f.auth_path); + let (status, bytes) = send( + &f.router, + "GET", + &format!("/api/archives/test/export?entries={uid}&format=html"), + Some(&cookie), + None, + ).await; + assert_eq!(status, StatusCode::OK, "expected 200; body: {:?}", String::from_utf8_lossy(&bytes)); + let cursor = std::io::Cursor::new(bytes); + zip::ZipArchive::new(cursor).expect("response should be a valid ZIP"); + } + + #[tokio::test] + async fn invalid_format_returns_400() { + let f = fixture(); + let uid = seed_entry(&f.archive_path); + let cookie = make_test_session(&f.auth_path); + let (status, _) = send( + &f.router, + "GET", + &format!("/api/archives/test/export?entries={uid}&format=docx"), + Some(&cookie), + None, + ).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + } + + #[tokio::test] + async fn too_many_entries_returns_400() { + let f = fixture(); + let cookie = make_test_session(&f.auth_path); + let entries: Vec = (0..101).map(|i| format!("uid-{i}")).collect(); + let (status, _) = send( + &f.router, + "GET", + &format!("/api/archives/test/export?entries={}&format=html", entries.join(",")), + Some(&cookie), + None, + ).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + } +} diff --git a/crates/archivr-server/src/main.rs b/crates/archivr-server/src/main.rs index fbdbcf6..d90f46a 100644 --- a/crates/archivr-server/src/main.rs +++ b/crates/archivr-server/src/main.rs @@ -6,6 +6,7 @@ mod effective_config; mod entry_access; mod guards; mod jobs; +mod exports; mod registry; mod routes; #[cfg(test)] @@ -150,6 +151,10 @@ async fn main() -> Result<()> { if let Ok(paths) = archivr_core::archive::read_archive_paths(&archive.archive_path) { let uploads_dir = paths.store_path.join("temp").join("uploads"); prune_stale_upload_dirs(&uploads_dir, prune_cutoff, true); + archivr_core::export::prune_stale_export_dirs( + &paths.store_path, + std::time::Duration::from_secs(6 * 60 * 60), + ); } } diff --git a/crates/archivr-server/src/routes.rs b/crates/archivr-server/src/routes.rs index 6612472..836464f 100644 --- a/crates/archivr-server/src/routes.rs +++ b/crates/archivr-server/src/routes.rs @@ -436,6 +436,7 @@ pub fn app_with_state(state: AppState) -> Router { .merge(crate::admin_users::routes()) .merge(crate::credentials::routes()) .merge(crate::jobs::routes()) + .merge(crate::exports::routes()) .merge(crate::effective_config::routes()) .fallback_service(ServeDir::new(&static_dir).not_found_service(ServeFile::new(static_dir.join("index.html")))) .layer(axum::middleware::from_fn_with_state( diff --git a/frontend/src/api.js b/frontend/src/api.js index 42a6f31..5b97a55 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -737,6 +737,34 @@ export async function deleteUpload(archiveId, locator) { } catch {} } +// Builds the export on the server and returns { blob, filename }. +// Errors carry the server's {error} text. +export async function downloadEntryExport(archiveId, { entryUids, format, layout, credit }) { + const params = new URLSearchParams({ + entries: entryUids.join(','), + format, + layout, + credit: String(credit), + }); + const res = await fetch(`/api/archives/${archiveId}/export?${params}`, { + credentials: 'same-origin', + }); + if (!res.ok) { + const detail = await res.text(); + let message = detail.trim(); + try { + message = JSON.parse(detail).error || message; + } catch { + // non-JSON body + } + throw new Error(message || `Export failed (${res.status} ${res.statusText})`); + } + const disposition = res.headers.get('Content-Disposition') || ''; + const filename = /filename="([^"]+)"/.exec(disposition)?.[1] || 'export'; + return { blob: await res.blob(), filename }; +} + + // ── 401 interceptor ─────────────────────────────────────────────────────────── const _origFetch = window.fetch; window.fetch = async (...args) => { diff --git a/frontend/src/api.test.js b/frontend/src/api.test.js index e889ebb..4d9ea69 100644 --- a/frontend/src/api.test.js +++ b/frontend/src/api.test.js @@ -69,3 +69,27 @@ describe('token and session API calls', () => { expect(calls[0].method).toBe('DELETE') }) }) + +describe('downloadEntryExport', () => { + test('builds correct query string', async () => { + const fakeBlob = new Blob(['zip-content'], { type: 'application/zip' }) + const headers = new Headers({ 'Content-Disposition': 'attachment; filename="my-export.zip"' }) + const calls = mockFetch(new Response(fakeBlob, { status: 200, headers })) + const result = await api.downloadEntryExport('a', { + entryUids: ['u1', 'u2'], + format: 'pdf', + layout: 'separate', + credit: false, + }) + expect(calls).toHaveLength(1) + expect(calls[0].url).toBe('/api/archives/a/export?entries=u1%2Cu2&format=pdf&layout=separate&credit=false') + expect(result.filename).toBe('my-export.zip') + }) + + test('throws the server error text on failure', async () => { + mockFetch(new Response(JSON.stringify({ error: 'select at most 100 entries' }), { status: 400 })) + await expect( + api.downloadEntryExport('a', { entryUids: ['u1'], format: 'html', layout: 'together', credit: true }) + ).rejects.toThrow('select at most 100 entries') + }) +}) diff --git a/frontend/src/components/ContextRail.jsx b/frontend/src/components/ContextRail.jsx index 3bd0efb..3c2f685 100644 --- a/frontend/src/components/ContextRail.jsx +++ b/frontend/src/components/ContextRail.jsx @@ -1,5 +1,6 @@ import { useState, useEffect, useLayoutEffect, useRef } from 'react' import { fetchEntryTags, assignTag, removeTag, listEntryCollections, listCollections, addEntryToCollection, updateEntryTitle, generateThreadTitle, deleteEntry, rearchiveEntry, pollCaptureJob, fetchEntrySummary, requestEntrySummary, fetchTranscriptionEngines } from '../api' +import ExportDialog from './ExportDialog' import { formatTimestamp, formatBytes, valueText, sourceIconSvg, displayPath } from '../utils' const VIS_LABEL = { 0: 'Private', 1: 'Public', 2: 'Users only', 3: 'Public' } @@ -46,8 +47,26 @@ const ExternalIcon = () => ( ) +/// Returns UIDs in the DOM order of `rows`, then any UIDs in `selectedUids` +/// not found in `rows` in Set iteration order. +function orderedSelection(rows, selectedUids) { + const seen = new Set() + const result = [] + for (const uid of rows) { + if (selectedUids.has(uid) && !seen.has(uid)) { + seen.add(uid) + result.push(uid) + } + } + for (const uid of selectedUids) { + if (!seen.has(uid)) result.push(uid) + } + return result +} + export default function ContextRail({ archiveId, selectedEntry, selectedUids, selectedEntries, detail, onTagFilterSet, tagNodes, onTagsRefresh, onEntryTitleChange, onEntryDeleted, onBulkDeleted, humanizeTags, onDetailRefresh, onOpenPreview, onPlay, isPublicSession }) { const [tags, setTags] = useState([]) + const [exportOpen, setExportOpen] = useState(false) const [assignInput, setAssignInput] = useState('') const [entryCollections, setEntryCollections] = useState([]) const [assignError, setAssignError] = useState('') @@ -677,6 +696,16 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se
)} +
+

Export

+ +
+
+ )} {(() => { // Public sessions get read-only treatment: the completed text if the @@ -1058,6 +1092,16 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se
)} + { + if (!isBulk) return detail ? [detail.summary.entry_uid] : [] + const rows = Array.from(document.querySelectorAll('#entries-body [data-entry-uid]')).map(el => el.dataset.entryUid) + return orderedSelection(rows, selectedUids) + })()} + onClose={() => setExportOpen(false)} + /> ) } diff --git a/frontend/src/components/ExportDialog.jsx b/frontend/src/components/ExportDialog.jsx new file mode 100644 index 0000000..236ab75 --- /dev/null +++ b/frontend/src/components/ExportDialog.jsx @@ -0,0 +1,176 @@ +import { useRef, useEffect, useState } from 'react' +import { downloadEntryExport } from '../api' + +export default function ExportDialog({ open, archiveId, entryUids, onClose }) { + const dialogRef = useRef(null) + + const [format, setFormat] = useState('html') + const [together, setTogether] = useState(true) + const [credit, setCredit] = useState(true) + const [status, setStatus] = useState('idle') // 'idle' | 'running' | 'error' + const [error, setError] = useState(null) + + // Sync open state with the native dialog. + useEffect(() => { + const dialog = dialogRef.current + if (!dialog) return + if (open) { + if (!dialog.open) dialog.showModal() + } else { + if (dialog.open) dialog.close() + } + }, [open]) + + // Wire the native close event (Escape key, etc.) back to onClose. + useEffect(() => { + const dialog = dialogRef.current + if (!dialog) return + const handler = () => onClose() + dialog.addEventListener('close', handler) + return () => dialog.removeEventListener('close', handler) + }, [onClose]) + + // Reset state each time the dialog opens. + useEffect(() => { + if (open) { + setFormat('html') + setTogether(true) + setCredit(true) + setStatus('idle') + setError(null) + } + }, [open]) + + const n = entryUids?.length ?? 0 + const title = n === 1 ? 'Export entry' : `Export ${n} entries` + + async function handleSubmit(e) { + e.preventDefault() + setStatus('running') + setError(null) + try { + const { blob, filename } = await downloadEntryExport(archiveId, { + entryUids, + format, + layout: together ? 'together' : 'separate', + credit, + }) + // Trigger browser download via a temporary anchor. + const url = URL.createObjectURL(blob) + const a = document.createElement('a') + a.href = url + a.download = filename + document.body.appendChild(a) + a.click() + document.body.removeChild(a) + setTimeout(() => URL.revokeObjectURL(url), 1000) + dialogRef.current?.close() + } catch (err) { + setStatus('error') + setError(err.message || 'Export failed') + } + } + + return ( + +
+
+

{title}

+ +
+ +
+
+ + {/* Format selector */} + + + {/* Combine toggle — only when ≥2 entries */} + {n >= 2 && ( + + )} + + {/* Credit toggle */} + + +
+ + {status === 'error' && error && ( +

{error}

+ )} + +
+ + +
+
+
+
+ ) +} diff --git a/frontend/src/components/ExportDialog.test.jsx b/frontend/src/components/ExportDialog.test.jsx new file mode 100644 index 0000000..cc19a6e --- /dev/null +++ b/frontend/src/components/ExportDialog.test.jsx @@ -0,0 +1,42 @@ +import { describe, expect, test } from 'bun:test' +import { renderToStaticMarkup } from 'react-dom/server' + +// Shim window.fetch so api.js can install its 401 interceptor at import time. +const originalWindow = globalThis.window +globalThis.window = { fetch: globalThis.fetch } +const { default: ExportDialog } = await import('./ExportDialog') +globalThis.window = originalWindow + +describe('ExportDialog', () => { + test('with one uid, no "Combine" toggle is rendered', () => { + const markup = renderToStaticMarkup( + {}} /> + ) + expect(markup).not.toContain('Combine into one document') + expect(markup).toContain('Export entry') + }) + + test('with two uids, the "Combine" toggle is rendered', () => { + const markup = renderToStaticMarkup( + {}} /> + ) + expect(markup).toContain('Combine into one document') + expect(markup).toContain('Export 2 entries') + }) + + test('"Include Archivr credit" toggle is checked by default', () => { + const markup = renderToStaticMarkup( + {}} /> + ) + expect(markup).toContain('Include Archivr credit') + expect(markup).toContain('aria-checked="true"') + }) + + test('closed dialog does not render modal content', () => { + const markup = renderToStaticMarkup( + {}} /> + ) + // The dialog element is still in the DOM (native dialog hides itself). + expect(markup).toContain('export-dialog') + }) +}) diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 7be7355..51386d0 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -3629,3 +3629,7 @@ body.has-audio-bar { padding-bottom: 56px; } letter-spacing: .04em; text-align: right; } + +/* ── Export ───────────────────────────────────────────────────────────────── */ +.rail-export-btn { margin-top: 6px; } +.export-dialog .export-format { width: 100%; margin: 4px 0 14px; } From 2115a70343563b4598ee25ea02e66d09def69a34 Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Mon, 12 Oct 2026 20:00:06 +0200 Subject: [PATCH 03/14] fix: handle __Host- cookies correctly for single-file captures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Chrome's CDP Network.setCookies rejects __Host- prefixed cookies that carry a domain attribute — the prefix semantically forbids domain binding. The previous Netscape cookie file always emitted a domain column, causing setCookies to fail with "Invalid cookie fields" and the capture to produce no output file. Switch single-file's cookie file to JSON format (single-file tries JSON.parse first, falls back to Netscape text parsing). JSON gives per-cookie field control: - __Host- cookies: {url, path: "/", secure: true}, no domain field. url is the https page URL (synthesised as https://hostname/ when the page URL is non-https, since __Host- requires https anyway). - __Secure- cookies: {domain, path: "/", secure: true}. - All other cookies: {domain, path: "/"} — unchanged behaviour. yt-dlp still receives the existing Netscape file; only the single-file path is affected. Add four unit tests covering __Host-, __Secure-, regular cookies, and the http→https url fallback. --- crates/archivr-core/src/downloader/cookies.rs | 169 ++++++++++++++++++ .../archivr-core/src/downloader/singlefile.rs | 6 +- 2 files changed, 172 insertions(+), 3 deletions(-) diff --git a/crates/archivr-core/src/downloader/cookies.rs b/crates/archivr-core/src/downloader/cookies.rs index 93f8891..579d6ee 100644 --- a/crates/archivr-core/src/downloader/cookies.rs +++ b/crates/archivr-core/src/downloader/cookies.rs @@ -1,4 +1,5 @@ use std::{collections::HashMap, io::Write, path::Path}; +use serde_json::json; /// Writes a Netscape-format HTTP cookie file suitable for yt-dlp `--cookies` and /// single-file `--browser-cookies-file`. The file is created with mode 0o600 @@ -38,6 +39,84 @@ pub fn write_netscape_cookie_file( Ok(()) } +/// Writes a JSON-format cookie file for single-file `--browser-cookies-file`. +/// +/// Single-file accepts both Netscape text and JSON; JSON gives us per-cookie +/// field control, which is required for `__Host-`/`__Secure-` cookies. +/// +/// - `__Host-` cookies: Chrome CDP `Network.setCookies` rejects these when a +/// `domain` attribute is present. They must be set via `url` (no `domain`), +/// `path: "/"`, and `secure: true`. +/// - `__Secure-` cookies: require `secure: true`; `domain` is still fine. +/// - All other cookies: use `domain` as before; `secure` left false because +/// we have no per-cookie scheme information from the user's input map. +/// +/// The file is created 0o600 (owner read/write only) to protect cookie secrets. +pub fn write_json_cookie_file( + cookies: &HashMap, + domain: &str, + page_url: &str, + path: &Path, +) -> std::io::Result<()> { + #[cfg(unix)] + let mut f = { + use std::os::unix::fs::OpenOptionsExt; + std::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .mode(0o600) + .open(path)? + }; + #[cfg(not(unix))] + let mut f = std::fs::File::create(path)?; + + // Build a canonical https root URL for __Host- cookies (must be https). + // If the page_url itself is https we use it directly; otherwise synthesise one. + let host_url = if page_url.starts_with("https://") { + page_url.to_string() + } else { + format!("https://{}/", domain) + }; + + let entries: Vec = cookies + .iter() + .map(|(name, value)| { + if name.starts_with("__Host-") { + // No `domain` field — Chrome rejects __Host- cookies that carry one. + json!({ + "name": name, + "value": value, + "url": host_url, + "path": "/", + "secure": true + }) + } else if name.starts_with("__Secure-") { + json!({ + "name": name, + "value": value, + "domain": domain, + "path": "/", + "secure": true + }) + } else { + json!({ + "name": name, + "value": value, + "domain": domain, + "path": "/" + }) + } + }) + .collect(); + + let json_str = serde_json::to_string(&entries) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?; + f.write_all(json_str.as_bytes())?; + Ok(()) +} + + /// Extracts the exact hostname from a URL, suitable for use as the Netscape /// cookie domain. /// @@ -64,3 +143,93 @@ pub fn cookies_to_header(cookies: &HashMap) -> String { .collect::>() .join("; ") } + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::NamedTempFile; + + fn read_json(f: &NamedTempFile) -> Vec { + let s = std::fs::read_to_string(f.path()).unwrap(); + serde_json::from_str(&s).unwrap() + } + + #[test] + fn host_prefix_cookie_has_no_domain_uses_url() { + let mut cookies = HashMap::new(); + cookies.insert("__Host-session".to_string(), "abc123".to_string()); + let f = NamedTempFile::new().unwrap(); + write_json_cookie_file( + &cookies, + "example.com", + "https://example.com/page", + f.path(), + ) + .unwrap(); + let entries = read_json(&f); + assert_eq!(entries.len(), 1); + let c = &entries[0]; + assert_eq!(c["name"], "__Host-session"); + assert_eq!(c["value"], "abc123"); + assert!(c.get("domain").is_none(), "__Host- must not have domain field"); + assert_eq!(c["url"], "https://example.com/page"); + assert_eq!(c["path"], "/"); + assert_eq!(c["secure"], true); + } + + #[test] + fn secure_prefix_cookie_has_domain_and_secure_true() { + let mut cookies = HashMap::new(); + cookies.insert("__Secure-token".to_string(), "xyz".to_string()); + let f = NamedTempFile::new().unwrap(); + write_json_cookie_file( + &cookies, + "example.com", + "https://example.com/", + f.path(), + ) + .unwrap(); + let entries = read_json(&f); + let c = &entries[0]; + assert_eq!(c["domain"], "example.com"); + assert_eq!(c["secure"], true); + assert!(c.get("url").is_none(), "__Secure- should not carry url field"); + } + + #[test] + fn regular_cookie_uses_domain_no_secure() { + let mut cookies = HashMap::new(); + cookies.insert("cf_bm".to_string(), "val".to_string()); + let f = NamedTempFile::new().unwrap(); + write_json_cookie_file( + &cookies, + "example.com", + "https://example.com/", + f.path(), + ) + .unwrap(); + let entries = read_json(&f); + let c = &entries[0]; + assert_eq!(c["domain"], "example.com"); + assert!(c.get("secure").map(|v| v != true).unwrap_or(true), "regular cookie should not be forced secure"); + assert!(c.get("url").is_none()); + } + + #[test] + fn host_prefix_falls_back_to_https_url_when_page_url_is_http() { + let mut cookies = HashMap::new(); + cookies.insert("__Host-x".to_string(), "1".to_string()); + let f = NamedTempFile::new().unwrap(); + write_json_cookie_file( + &cookies, + "marketing.creativedirector.net", + "http://marketing.creativedirector.net/course", + f.path(), + ) + .unwrap(); + let entries = read_json(&f); + let c = &entries[0]; + assert!(c["url"].as_str().unwrap().starts_with("https://"), "must use https url for __Host- even when page is http"); + assert!(c.get("domain").is_none()); + } +} diff --git a/crates/archivr-core/src/downloader/singlefile.rs b/crates/archivr-core/src/downloader/singlefile.rs index 4fbc1bd..a346d86 100644 --- a/crates/archivr-core/src/downloader/singlefile.rs +++ b/crates/archivr-core/src/downloader/singlefile.rs @@ -10,7 +10,7 @@ use std::{ process::Command, }; -use crate::downloader::cookies::{domain_from_url, write_netscape_cookie_file}; +use crate::downloader::cookies::{domain_from_url, write_json_cookie_file}; use crate::hash::hash_file; /// Combined reader-mode script: Readability.js (Apache 2.0) bundled with the @@ -611,9 +611,9 @@ fn save_with( // Write cookie file (secrets must never appear in process args). let cookie_file: Option = if !cookies.is_empty() { - let cf = temp_dir.join("cookies.txt"); + let cf = temp_dir.join("cookies.json"); let domain = domain_from_url(url); - write_netscape_cookie_file(cookies, &domain, &cf) + write_json_cookie_file(cookies, &domain, url, &cf) .context("failed to write single-file cookie file")?; Some(cf) } else { From f7e9a0ef25b02c46230421232afa4a28687ed83e Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Mon, 12 Oct 2026 21:10:54 +0200 Subject: [PATCH 04/14] fix: move Export to Actions section, fix Export\u2026 text rendering --- .../static/assets/index-CKGxin5o.js | 49 ---------- .../static/assets/index-CQKWq7vB.css | 1 - crates/archivr-server/static/index.html | 4 +- frontend/src/components/ContextRail.jsx | 93 ++++++++++--------- frontend/src/styles.css | 1 - 5 files changed, 51 insertions(+), 97 deletions(-) delete mode 100644 crates/archivr-server/static/assets/index-CKGxin5o.js delete mode 100644 crates/archivr-server/static/assets/index-CQKWq7vB.css diff --git a/crates/archivr-server/static/assets/index-CKGxin5o.js b/crates/archivr-server/static/assets/index-CKGxin5o.js deleted file mode 100644 index 6b965c1..0000000 --- a/crates/archivr-server/static/assets/index-CKGxin5o.js +++ /dev/null @@ -1,49 +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 Xu={exports:{}},Cs={},Ju={exports:{}},oe={};/** - * @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 gl=Symbol.for("react.element"),Nf=Symbol.for("react.portal"),Cf=Symbol.for("react.fragment"),Ef=Symbol.for("react.strict_mode"),bf=Symbol.for("react.profiler"),Tf=Symbol.for("react.provider"),Pf=Symbol.for("react.context"),Lf=Symbol.for("react.forward_ref"),Rf=Symbol.for("react.suspense"),zf=Symbol.for("react.memo"),If=Symbol.for("react.lazy"),So=Symbol.iterator;function $f(e){return e===null||typeof e!="object"?null:(e=So&&e[So]||e["@@iterator"],typeof e=="function"?e:null)}var Gu={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Yu=Object.assign,Zu={};function jr(e,t,n){this.props=e,this.context=t,this.refs=Zu,this.updater=n||Gu}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 ec(){}ec.prototype=jr.prototype;function _a(e,t,n){this.props=e,this.context=t,this.refs=Zu,this.updater=n||Gu}var Na=_a.prototype=new ec;Na.constructor=_a;Yu(Na,jr.prototype);Na.isPureReactComponent=!0;var _o=Array.isArray,tc=Object.prototype.hasOwnProperty,Ca={current:null},nc={key:!0,ref:!0,__self:!0,__source:!0};function rc(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)tc.call(t,r)&&!nc.hasOwnProperty(r)&&(l[r]=t[r]);var o=arguments.length-2;if(o===1)l.children=n;else if(1>>1,se=I[ee];if(0>>1;eel(Ne,K))pel(U,Ne)?(I[ee]=U,I[pe]=K,ee=pe):(I[ee]=Ne,I[Y]=K,ee=Y);else if(pel(U,K))I[ee]=U,I[pe]=K,ee=pe;else break e}}return R}function l(I,R){var K=I.sortIndex-R.sortIndex;return K!==0?K:I.id-R.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,m=3,x=!1,w=!1,S=!1,_=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 h(I){for(var R=n(d);R!==null;){if(R.callback===null)r(d);else if(R.startTime<=I)r(d),R.sortIndex=R.expirationTime,t(u,R);else break;R=n(d)}}function k(I){if(S=!1,h(I),!w)if(n(u)!==null)w=!0,Le(E);else{var R=n(d);R!==null&&ve(k,R.startTime-I)}}function E(I,R){w=!1,S&&(S=!1,p(v),v=-1),x=!0;var K=m;try{for(h(R),g=n(u);g!==null&&(!(g.expirationTime>R)||I&&!X());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,m=g.priorityLevel;var se=ee(g.expirationTime<=R);R=e.unstable_now(),typeof se=="function"?g.callback=se:g===n(u)&&r(u),h(R)}else r(u);g=n(u)}if(g!==null)var ie=!0;else{var Y=n(d);Y!==null&&ve(k,Y.startTime-R),ie=!1}return ie}finally{g=null,m=K,x=!1}}var P=!1,N=null,v=-1,b=5,L=-1;function X(){return!(e.unstable_now()-LI||125ee?(I.sortIndex=K,t(d,I),n(u)===null&&I===n(d)&&(S?(p(v),v=-1):S=!0,ve(k,K-ee))):(I.sortIndex=se,t(u,I),w||x||(w=!0,Le(E))),I},e.unstable_shouldYield=X,e.unstable_wrapCallback=function(I){var R=m;return function(){var K=m;m=R;try{return I.apply(this,arguments)}finally{m=K}}}})(oc);ac.exports=oc;var Kf=ac.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 Qf=c,jt=Kf;function O(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,qf=/^[: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 Xf(e){return Li.call(Eo,e)?!0:Li.call(Co,e)?!1:qf.test(e)?Eo[e]=!0:(Co[e]=!0,!1)}function Jf(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 Gf(e,t,n,r){if(t===null||typeof t>"u"||Jf(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 ct(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 Ye={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Ye[e]=new ct(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Ye[t]=new ct(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Ye[e]=new ct(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Ye[e]=new ct(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){Ye[e]=new ct(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Ye[e]=new ct(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Ye[e]=new ct(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Ye[e]=new ct(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Ye[e]=new ct(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);Ye[t]=new ct(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);Ye[t]=new ct(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);Ye[t]=new ct(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Ye[e]=new ct(e,1,!1,e.toLowerCase(),null,!1,!1)});Ye.xlinkHref=new ct("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Ye[e]=new ct(e,1,!1,e.toLowerCase(),null,!0,!0)});function Pa(e,t,n,r){var l=Ye.hasOwnProperty(t)?Ye[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:"")?$r(e):""}function Yf(e){switch(e.tag){case 5:return $r(e.type);case 16:return $r("Lazy");case 13:return $r("Suspense");case 19:return $r("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 dc:return(e.displayName||"Context")+".Consumer";case cc: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 dn:t=e._payload,e=e._init;try{return $i(e(t))}catch{}}return null}function Zf(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 Nn(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function pc(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function ep(e){var t=pc(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 Nl(e){e._valueTracker||(e._valueTracker=ep(e))}function hc(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=pc(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function ts(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 Pe({},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=Nn(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 mc(e,t){t=t.checked,t!=null&&Pa(e,"checked",t,!1)}function Oi(e,t){mc(e,t);var n=Nn(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,Nn(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"||ts(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Dr=Array.isArray;function or(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=Cl.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Yr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Br={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},tp=["Webkit","ms","Moz","O"];Object.keys(Br).forEach(function(e){tp.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Br[t]=Br[e]})});function xc(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Br.hasOwnProperty(e)&&Br[e]?(""+t).trim():t+"px"}function wc(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=xc(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var np=Pe({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(np[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(O(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(O(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(O(61))}if(t.style!=null&&typeof t.style!="object")throw Error(O(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=xl(e)){if(typeof Wi!="function")throw Error(O(280));var t=e.stateNode;t&&(t=Ls(t),Wi(e.stateNode,e.type,t))}}function kc(e){ur?cr?cr.push(e):cr=[e]:ur=e}function jc(){if(ur){var e=ur,t=cr;if(cr=ur=null,zo(e),t)for(e=0;e>>=0,e===0?32:31-(pp(e)/hp|0)|0}var El=64,bl=4194304;function Or(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 ss(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=Or(o):(i&=a,i!==0&&(r=Or(i)))}else a=n&~l,a!==0?r=Or(a):i!==0&&(r=Or(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 yl(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ft(t),e[t]=n}function vp(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=Hr),Uo=" ",Ho=!1;function Uc(e,t){switch(e){case"keyup":return Kp.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Hc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Yn=!1;function qp(e,t){switch(e){case"compositionend":return Hc(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 Xp(e,t){if(Yn)return e==="compositionend"||!Ua&&Uc(e,t)?(e=Fc(),Vl=Ma=mn=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=ts();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=ts(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 lh(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=qo(n,i);var a=qo(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,Vr=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!==ts(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}),Vr&&ll(Vr,r)||(Vr=r,r=os(Ji,"onSelect"),0nr||(e.current=ra[nr],ra[nr]=null,nr--)}function we(e,t){nr++,ra[nr]=e.current,e.current=t}var Cn={},lt=bn(Cn),ht=bn(!1),Mn=Cn;function gr(e,t){var n=e.type.contextTypes;if(!n)return Cn;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 mt(e){return e=e.childContextTypes,e!=null}function cs(){_e(ht),_e(lt)}function nu(e,t,n){if(lt.current!==Cn)throw Error(O(168));we(lt,t),we(ht,n)}function rd(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(O(108,Zf(e)||"Unknown",l));return Pe({},n,r)}function ds(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Cn,Mn=lt.current,we(lt,e),we(ht,ht.current),!0}function ru(e,t,n){var r=e.stateNode;if(!r)throw Error(O(169));n?(e=rd(e,t,Mn),r.__reactInternalMemoizedMergedChildContext=e,_e(ht),_e(lt),we(lt,e)):_e(ht),we(ht,n)}var Gt=null,Rs=!1,gi=!1;function ld(e){Gt===null?Gt=[e]:Gt.push(e)}function gh(e){Rs=!0,ld(e)}function Tn(){if(!gi&&Gt!==null){gi=!0;var e=0,t=ge;try{var n=Gt;for(ge=1;e>=a,l-=a,Yt=1<<32-Ft(t)+l|n<v?(b=N,N=null):b=N.sibling;var L=m(p,N,h[v],k);if(L===null){N===null&&(N=b);break}e&&N&&L.alternate===null&&t(p,N),f=i(L,f,v),P===null?E=L:P.sibling=L,P=L,N=b}if(v===h.length)return n(p,N),Ce&&Ln(p,v),E;if(N===null){for(;vv?(b=N,N=null):b=N.sibling;var X=m(p,N,L.value,k);if(X===null){N===null&&(N=b);break}e&&N&&X.alternate===null&&t(p,N),f=i(X,f,v),P===null?E=X:P.sibling=X,P=X,N=b}if(L.done)return n(p,N),Ce&&Ln(p,v),E;if(N===null){for(;!L.done;v++,L=h.next())L=g(p,L.value,k),L!==null&&(f=i(L,f,v),P===null?E=L:P.sibling=L,P=L);return Ce&&Ln(p,v),E}for(N=r(p,N);!L.done;v++,L=h.next())L=x(N,p,v,L.value,k),L!==null&&(e&&L.alternate!==null&&N.delete(L.key===null?v:L.key),f=i(L,f,v),P===null?E=L:P.sibling=L,P=L);return e&&N.forEach(function(Q){return t(p,Q)}),Ce&&Ln(p,v),E}function _(p,f,h,k){if(typeof h=="object"&&h!==null&&h.type===Gn&&h.key===null&&(h=h.props.children),typeof h=="object"&&h!==null){switch(h.$$typeof){case _l:e:{for(var E=h.key,P=f;P!==null;){if(P.key===E){if(E=h.type,E===Gn){if(P.tag===7){n(p,P.sibling),f=l(P,h.props.children),f.return=p,p=f;break e}}else if(P.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===dn&&iu(E)===P.type){n(p,P.sibling),f=l(P,h.props),f.ref=Lr(p,P,h),f.return=p,p=f;break e}n(p,P);break}else t(p,P);P=P.sibling}h.type===Gn?(f=An(h.props.children,p.mode,k,h.key),f.return=p,p=f):(k=Zl(h.type,h.key,h.props,null,p.mode,k),k.ref=Lr(p,f,h),k.return=p,p=k)}return a(p);case Jn:e:{for(P=h.key;f!==null;){if(f.key===P)if(f.tag===4&&f.stateNode.containerInfo===h.containerInfo&&f.stateNode.implementation===h.implementation){n(p,f.sibling),f=l(f,h.children||[]),f.return=p,p=f;break e}else{n(p,f);break}else t(p,f);f=f.sibling}f=_i(h,p.mode,k),f.return=p,p=f}return a(p);case dn:return P=h._init,_(p,f,P(h._payload),k)}if(Dr(h))return w(p,f,h,k);if(Cr(h))return S(p,f,h,k);$l(p,h)}return typeof h=="string"&&h!==""||typeof h=="number"?(h=""+h,f!==null&&f.tag===6?(n(p,f.sibling),f=l(f,h),f.return=p,p=f):(n(p,f),f=Si(h,p.mode,k),f.return=p,p=f),a(p)):n(p,f)}return _}var vr=od(!0),ud=od(!1),hs=bn(null),ms=null,sr=null,Qa=null;function qa(){Qa=sr=ms=null}function Xa(e){var t=hs.current;_e(hs),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){ms=e,Qa=sr=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(pt=!0),e.firstContext=null)}function Tt(e){var t=e._currentValue;if(Qa!==e)if(e={context:e,memoizedValue:t,next:null},sr===null){if(ms===null)throw Error(O(308));sr=e,ms.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 cd(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,rn(e,r)}function rn(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 fn=!1;function Ga(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function dd(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 en(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function kn(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,de&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,rn(e,n)}return l=r.interleaved,l===null?(t.next=t,Ja(r)):(t.next=l.next,l.next=t),r.interleaved=t,rn(e,n)}function Ql(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 gs(e,t,n,r){var l=e.updateQueue;fn=!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 m=o.lane,x=o.eventTime;if((r&m)===m){y!==null&&(y=y.next={eventTime:x,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var w=e,S=o;switch(m=t,x=n,S.tag){case 1:if(w=S.payload,typeof w=="function"){g=w.call(x,g,m);break e}g=w;break e;case 3:w.flags=w.flags&-65537|128;case 0:if(w=S.payload,m=typeof w=="function"?w.call(x,g,m):w,m==null)break e;g=Pe({},g,m);break e;case 2:fn=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,m=l.effects,m===null?l.effects=[o]:m.push(o))}else x={eventTime:x,lane:m,tag:o.tag,payload:o.payload,callback:o.callback,next:null},y===null?(d=y=x,u=g):y=y.next=x,a|=m;if(o=o.next,o===null){if(o=l.shared.pending,o===null)break;m=o,o=m.next,m.next=null,l.lastBaseUpdate=m,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{ge=n,vi.transition=r}}function bd(){return Pt().memoizedState}function wh(e,t,n){var r=Sn(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Td(e))Pd(t,n);else if(n=cd(e,t,n,r),n!==null){var l=ot();Bt(n,e,r,l),Ld(n,t,r)}}function kh(e,t,n){var r=Sn(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Td(e))Pd(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,Ut(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=cd(e,t,l,r),n!==null&&(l=ot(),Bt(n,e,r,l),Ld(n,t,r))}}function Td(e){var t=e.alternate;return e===Te||t!==null&&t===Te}function Pd(e,t){Kr=vs=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Ld(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Da(e,n)}}var xs={readContext:Tt,useCallback:tt,useContext:tt,useEffect:tt,useImperativeHandle:tt,useInsertionEffect:tt,useLayoutEffect:tt,useMemo:tt,useReducer:tt,useRef:tt,useState:tt,useDebugValue:tt,useDeferredValue:tt,useTransition:tt,useMutableSource:tt,useSyncExternalStore:tt,useId:tt,unstable_isNewReconciler:!1},jh={readContext:Tt,useCallback:function(e,t){return Vt().memoizedState=[e,t===void 0?null:t],e},useContext:Tt,useEffect:cu,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Xl(4194308,4,Sd.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Xl(4194308,4,e,t)},useInsertionEffect:function(e,t){return Xl(4,2,e,t)},useMemo:function(e,t){var n=Vt();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Vt();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=wh.bind(null,Te,e),[r.memoizedState,e]},useRef:function(e){var t=Vt();return e={current:e},t.memoizedState=e},useState:uu,useDebugValue:so,useDeferredValue:function(e){return Vt().memoizedState=e},useTransition:function(){var e=uu(!1),t=e[0];return e=xh.bind(null,e[1]),Vt().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Te,l=Vt();if(Ce){if(n===void 0)throw Error(O(407));n=n()}else{if(n=t(),Xe===null)throw Error(O(349));Bn&30||md(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,cu(yd.bind(null,r,i,e),[e]),r.flags|=2048,fl(9,gd.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Vt(),t=Xe.identifierPrefix;if(Ce){var n=Zt,r=Yt;n=(r&~(1<<32-Ft(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=cl++,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[Kt]=t,e[al]=r,Bd(e,t,!1,!1),t.stateNode=e;e:{switch(a=Ui(n,r),n){case"dialog":Se("cancel",e),Se("close",e),l=r;break;case"iframe":case"object":case"embed":Se("load",e),l=r;break;case"video":case"audio":for(l=0;lkr&&(t.flags|=128,r=!0,Rr(i,!1),t.lanes=4194304)}else{if(!r)if(e=ys(a),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Rr(i,!0),i.tail===null&&i.tailMode==="hidden"&&!a.alternate&&!Ce)return nt(t),null}else 2*De()-i.renderingStartTime>kr&&n!==1073741824&&(t.flags|=128,r=!0,Rr(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=De(),t.sibling=null,n=be.current,we(be,r?n&1|2:n&1),t):(nt(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?vt&1073741824&&(nt(t),t.subtreeFlags&6&&(t.flags|=8192)):nt(t),null;case 24:return null;case 25:return null}throw Error(O(156,t.tag))}function Ph(e,t){switch(Va(t),t.tag){case 1:return mt(t.type)&&cs(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return xr(),_e(ht),_e(lt),eo(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Za(t),null;case 13:if(_e(be),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(O(340));yr()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return _e(be),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 Ol=!1,rt=!1,Lh=typeof WeakSet=="function"?WeakSet:Set,V=null;function ir(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){ze(e,t,r)}else n.current=null}function ma(e,t,n){try{n()}catch(r){ze(e,t,r)}}var ku=!1;function Rh(e,t){if(Yi=is,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,m=null;t:for(;;){for(var x;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),(x=g.firstChild)!==null;)m=g,g=x;for(;;){if(g===e)break t;if(m===n&&++d===l&&(o=a),m===i&&++y===r&&(u=a),(x=g.nextSibling)!==null)break;g=m,m=g.parentNode}g=x}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},is=!1,V=t;V!==null;)if(t=V,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,V=e;else for(;V!==null;){t=V;try{var w=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(w!==null){var S=w.memoizedProps,_=w.memoizedState,p=t.stateNode,f=p.getSnapshotBeforeUpdate(t.elementType===t.type?S:Ot(t.type,S),_);p.__reactInternalSnapshotBeforeUpdate=f}break;case 3:var h=t.stateNode.containerInfo;h.nodeType===1?h.textContent="":h.nodeType===9&&h.documentElement&&h.removeChild(h.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(O(163))}}catch(k){ze(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,V=e;break}V=t.return}return w=ku,ku=!1,w}function Qr(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 $s(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 Wd(e){var t=e.alternate;t!==null&&(e.alternate=null,Wd(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Kt],delete t[al],delete t[na],delete t[hh],delete t[mh])),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 Vd(e){return e.tag===5||e.tag===3||e.tag===4}function ju(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Vd(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=us));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 Je=null,At=!1;function cn(e,t,n){for(n=n.child;n!==null;)Kd(e,t,n),n=n.sibling}function Kd(e,t,n){if(Qt&&typeof Qt.onCommitFiberUnmount=="function")try{Qt.onCommitFiberUnmount(Es,n)}catch{}switch(n.tag){case 5:rt||ir(n,t);case 6:var r=Je,l=At;Je=null,cn(e,t,n),Je=r,At=l,Je!==null&&(At?(e=Je,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Je.removeChild(n.stateNode));break;case 18:Je!==null&&(At?(e=Je,n=n.stateNode,e.nodeType===8?mi(e.parentNode,n):e.nodeType===1&&mi(e,n),nl(e)):mi(Je,n.stateNode));break;case 4:r=Je,l=At,Je=n.stateNode.containerInfo,At=!0,cn(e,t,n),Je=r,At=l;break;case 0:case 11:case 14:case 15:if(!rt&&(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)}cn(e,t,n);break;case 1:if(!rt&&(ir(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){ze(n,t,o)}cn(e,t,n);break;case 21:cn(e,t,n);break;case 22:n.mode&1?(rt=(r=rt)||n.memoizedState!==null,cn(e,t,n),rt=r):cn(e,t,n);break;default:cn(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 Lh),t.forEach(function(r){var l=Bh.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function Dt(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=a),r&=~i}if(r=l,r=De()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Ih(r/1960))-r,10e?16:e,gn===null)var r=!1;else{if(e=gn,gn=null,js=0,de&6)throw Error(O(331));var l=de;for(de|=4,V=e.current;V!==null;){var i=V,a=i.child;if(V.flags&16){var o=i.deletions;if(o!==null){for(var u=0;uDe()-uo?On(e,0):oo|=n),gt(e,t)}function ef(e,t){t===0&&(e.mode&1?(t=bl,bl<<=1,!(bl&130023424)&&(bl=4194304)):t=1);var n=ot();e=rn(e,t),e!==null&&(yl(e,t,n),gt(e,n))}function Fh(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),ef(e,n)}function Bh(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(O(314))}r!==null&&r.delete(t),ef(e,n)}var tf;tf=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||ht.current)pt=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return pt=!1,bh(e,t,n);pt=!!(e.flags&131072)}else pt=!1,Ce&&t.flags&1048576&&sd(t,ps,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Jl(e,t),e=t.pendingProps;var l=gr(t,lt.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,mt(r)?(i=!0,ds(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,Ga(t),l.updater=Is,t.stateNode=l,l._reactInternals=t,oa(t,r,e,n),t=da(null,t,r,!0,i,n)):(t.tag=0,Ce&&i&&Wa(t),at(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Jl(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=Hh(r),e=Ot(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,Ot(r.type,e),n);break e}throw Error(O(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ot(r,l),ca(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ot(r,l),vu(e,t,r,l,n);case 3:e:{if(Ad(t),e===null)throw Error(O(387));r=t.pendingProps,i=t.memoizedState,l=i.element,dd(e,t),gs(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(O(423)),t),t=xu(e,t,r,n,l);break e}else if(r!==l){l=wr(Error(O(424)),t),t=xu(e,t,r,n,l);break e}else for(wt=wn(t.stateNode.containerInfo.firstChild),kt=t,Ce=!0,Mt=null,n=ud(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(yr(),r===l){t=ln(e,t,n);break e}at(e,t,r,n)}t=t.child}return t;case 5:return fd(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),Od(e,t),at(e,t,a,n),t.child;case 6:return e===null&&sa(t),null;case 13:return Md(e,t,n);case 4:return Ya(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=vr(t,null,r,n):at(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ot(r,l),gu(e,t,r,l,n);case 7:return at(e,t,t.pendingProps,n),t.child;case 8:return at(e,t,t.pendingProps.children,n),t.child;case 12:return at(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,we(hs,r._currentValue),r._currentValue=a,i!==null)if(Ut(i.value,a)){if(i.children===l.children&&!ht.current){t=ln(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=en(-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(O(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}at(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,fr(t,n),l=Tt(l),r=r(l),t.flags|=1,at(e,t,r,n),t.child;case 14:return r=t.type,l=Ot(r,t.pendingProps),l=Ot(r.type,l),yu(e,t,r,l,n);case 15:return $d(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ot(r,l),Jl(e,t),t.tag=1,mt(r)?(e=!0,ds(t)):e=!1,fr(t,n),Rd(t,r,l),oa(t,r,l,n),da(null,t,r,!0,e,n);case 19:return Fd(e,t,n);case 22:return Dd(e,t,n)}throw Error(O(156,t.tag))};function nf(e,t){return Tc(e,t)}function Uh(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 Et(e,t,n,r){return new Uh(e,t,n,r)}function ho(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Hh(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 _n(e,t){var n=e.alternate;return n===null?(n=Et(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 Zl(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=Et(12,n,t,l|2),e.elementType=Ri,e.lanes=i,e;case zi:return e=Et(13,n,t,l),e.elementType=zi,e.lanes=i,e;case Ii:return e=Et(19,n,t,l),e.elementType=Ii,e.lanes=i,e;case fc:return Os(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case cc:a=10;break e;case dc:a=9;break e;case Ra:a=11;break e;case za:a=14;break e;case dn:a=16,r=null;break e}throw Error(O(130,e==null?e:typeof e,""))}return t=Et(a,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function An(e,t,n,r){return e=Et(7,e,r,t),e.lanes=n,e}function Os(e,t,n,r){return e=Et(22,e,r,t),e.elementType=fc,e.lanes=n,e.stateNode={isHidden:!1},e}function Si(e,t,n){return e=Et(6,e,null,t),e.lanes=n,e}function _i(e,t,n){return t=Et(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Wh(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 Wh(e,t,n,o,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Et(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 Vh(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(af)}catch(e){console.error(e)}}af(),ic.exports=St;var Jh=ic.exports,of,Lu=Jh;of=Lu.createRoot,Lu.hydrateRoot;async function Oe(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 Oe("/api/archives")}async function zu(e,t=null){const n=t?`/api/archives/${e}/entries?collection=${encodeURIComponent(t)}`:`/api/archives/${e}/entries`;return Oe(n)}async function Gh(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),Oe(`/api/archives/${e}/entries/search?${l}`)}async function Mr(e,t){return Oe(`/api/archives/${e}/entries/${t}`)}async function Yh(e,t,{signal:n}={}){return Oe(`/api/archives/${e}/entries/${t}/summary`,{signal:n})}async function Zh(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 em(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 Iu(e,t){return Oe(`/api/archives/${e}/entries/${t}/children`)}async function tm(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/children/order`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({child_uids:n})});if(!r.ok){const l=await r.json().catch(()=>({})),i=new Error(l.error||`HTTP ${r.status}`);throw i.status=r.status,i}}function nm(e,t,n){return Promise.all(n.map(r=>Oe(`/api/archives/${e}/entries/${t}/artifacts/${r}`)))}async function rm(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 lm(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 Fl(e,t){return Oe(`/api/archives/${e}/entries/${t}/tags`)}async function $u(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 sm(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 Du(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 im(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 am(e,t){const n=await fetch(`/api/archives/${e}/tags/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(await n.text())}async function om(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 um(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 Ni(e){return Oe(`/api/archives/${e}/runs`)}async function Bl(e){return Oe(`/api/archives/${e}/tags`)}async function cm(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 dm(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 fm(e,t){return Oe(`/api/archives/${e}/captures/probe?locator=${encodeURIComponent(t)}`)}async function pm(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 uf(e,t){return Oe(`/api/archives/${e}/capture_jobs/${t}`)}async function hm(){return(await(await fetch("/api/auth/setup")).json()).setup_required===!0}async function mm(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 gm(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 ym(){await fetch("/api/auth/logout",{method:"POST"})}async function cf(){const e=await fetch("/api/auth/me");return e.status===401?null:e.json()}async function vm(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 xm(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 wm(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 km(){return Oe("/api/auth/tokens")}async function jm(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 xo(){return Oe("/api/admin/instance-settings")}async function Jr(e){const t=await fetch("/api/admin/instance-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error||`HTTP ${t.status}`)}}async function _m(){return Oe("/api/admin/users")}async function Nm(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 Cm(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 df(){return Oe("/api/admin/roles")}async function Em(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 Oe(`/api/archives/${e}/collections`)}async function bm(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 Tm(e,t){return Oe(`/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 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 Lm(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 Ou(e,t){return Oe(`/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 Rm(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 zm(e){return Oe(`/api/archives/${e}/blob-cleanup`)}async function Im(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 $m(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 Dm(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 Om(){return Oe("/api/admin/cookie-rules")}async function Am(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 Mm(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 Fm(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 Bm(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 Um=window.fetch;window.fetch=async(...e)=>{var n;const t=await Um(...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 Hm({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 gm(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 Wm({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(m){if(m.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 mm(t,r),e()}catch(x){u(x.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:m=>n(m.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:m=>l(m.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:m=>a(m.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 Vm({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:m}=c.useContext(Hs)??{},[x,w]=c.useState(!1);async function S(){w(!0),await ym(),m(null),window.location.reload()}const _=a.find(h=>h.slug==="_default_"),p=!d||!!_&&!_.requires_auth,f=a.filter(h=>h.slug!=="_default_").filter(h=>!d||!h.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:h=>n(h.target.value),children:e.map(h=>s.jsx("option",{value:h.id,children:h.label},h.id))})}),f.length>0&&s.jsx("div",{className:"switcher",children:s.jsxs("select",{"aria-label":"Select collection",value:o??"",onChange:h=>u(h.target.value||null),children:[p&&s.jsx("option",{value:"",children:"All entries"}),f.map(h=>s.jsx("option",{value:h.collection_uid,children:h.name},h.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(h=>s.jsx("button",{className:`nav-link${r===h?" is-active":""}`,onClick:()=>l(h),children:h.charAt(0).toUpperCase()+h.slice(1)},h))}),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:x,children:x?"Logging out…":"Log out"})]})]})]})}let hl=1;function ff(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:hl++,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 Km(e){return{id:hl++,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:hl++,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 Au(e){return Array.isArray(e.playlistItems)&&e.playlistItems.some(t=>t.quality===null)}function Xm({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),m=c.useRef(new Map),x=c.useRef(t);c.useEffect(()=>{x.current=t},[t]);const w=c.useRef(null),[S,_]=c.useState(!1),p=c.useRef([]),f=c.useRef(!1),h=c.useRef(new Map),k=c.useRef(r),E=c.useRef(l);c.useEffect(()=>{k.current=r},[r]),c.useEffect(()=>{E.current=l},[l]);const P=c.useRef(i),N=c.useRef(a);c.useEffect(()=>{P.current=i},[i]),c.useEffect(()=>{N.current=a},[a]);const[v,b]=c.useState(()=>{try{const j=JSON.parse(sessionStorage.getItem("captureItems")||"null");if(Array.isArray(j)&&j.length>0){const B=j.filter(A=>!A.status||A.status==="idle");if(B.length>0)return B.forEach(A=>{A.id>=hl&&(hl=A.id+1)}),B.map(A=>({...Xn(A.locator),...A}))}}catch{}return[Xn()]});c.useEffect(()=>{sessionStorage.setItem("captureItems",JSON.stringify(v.filter(j=>j.kind!=="file")))},[v]),c.useEffect(()=>{p.current=v},[v]);const[L,X]=c.useState(!1),[Q,ne]=c.useState(null),[q,fe]=c.useState(null),[Le,ve]=c.useState(!0),[I,R]=c.useState(!0),[K,ee]=c.useState(!0);c.useEffect(()=>{xo().then(j=>{fe(j),ve(j.cookie_ext_enabled??!0),R(j.modal_closer_enabled??!0)}).catch(()=>fe({}))},[]);const se=Q!==null?Q:(q==null?void 0:q.ublock_enabled)??!0,[ie,Y]=c.useState(!1);c.useEffect(()=>{["captureDialogLocator","captureDialogError","captureDialogBusy","captureDialogJobStatus","captureDialogJobUid"].forEach(j=>sessionStorage.removeItem(j)),o.forEach(j=>{j.jobUid&&!y.current.has(j.jobUid)&&Ne(j.id,j.jobUid,j.locator,j.archiveId,null)})},[]),c.useEffect(()=>{const j=u.current;if(!j)return;const B=()=>{if(g.current.forEach(A=>clearTimeout(A)),g.current.clear(),!f.current){const A=x.current;p.current.forEach(D=>{var F;D.kind==="file"&&(D.uploadStatus==="uploading"?((F=h.current.get(D.id))==null||F(),h.current.delete(D.id)):D.uploadStatus==="done"&&D.uploadLocator&&Ei(A,D.uploadLocator).catch(()=>{}))})}f.current=!1,n()};return j.addEventListener("close",B),()=>j.removeEventListener("close",B)},[n]),c.useEffect(()=>{const j=u.current;j&&(e?(d.current||b([Xn()]),d.current=!1,j.open||j.showModal()):(g.current.forEach(B=>clearTimeout(B)),g.current.clear(),j.open&&j.close()))},[e]),c.useEffect(()=>()=>{y.current.forEach(j=>clearInterval(j)),g.current.forEach(j=>clearTimeout(j))},[]);function Ne(j,B,A,D,F=null){if(y.current.has(B))return;const H=setInterval(async()=>{var ke,he,Re,ye;try{const Fe=await uf(D,B);if(Fe.status==="completed"){clearInterval(y.current.get(B)),y.current.delete(B),await Promise.resolve((ke=k.current)==null?void 0:ke.call(k)),(he=N.current)==null||he.call(N,j);try{const ce=Fe.notes_json?JSON.parse(Fe.notes_json):null;if(ce!=null&&ce.ublock_skipped||ce!=null&&ce.cookie_ext_skipped){const dt=ce.ublock_skipped&&ce.cookie_ext_skipped?"Captured without ad-blocking or cookie-consent extension. Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config.":ce.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.";E.current(dt,A,"warning"),pe(F,"warning",A)}else F||E.current(null,A,"success"),pe(F,"archived")}catch{F||E.current(null,A,"success"),pe(F,"archived")}}else if(Fe.status==="failed"){clearInterval(y.current.get(B)),y.current.delete(B),(Re=N.current)==null||Re.call(N,j);const ce=Fe.error_text||"Capture failed.";E.current(ce,A),pe(F,"failed",A)}}catch(Fe){clearInterval(y.current.get(B)),y.current.delete(B),(ye=N.current)==null||ye.call(N,j);const ce=Fe.message||"Network error";E.current(ce,A),pe(F,"failed",A)}},500);y.current.set(B,H)}function pe(j,B,A=null){if(!j)return;const D=m.current.get(j);if(!D||(B==="archived"||B==="warning"?(D.archived++,B==="warning"&&(D.warnings++,A&&D.warningLocators.push(A))):(D.failed++,A&&D.failedLocators.push(A)),D.archived+D.failed0?`${F} archived (${H} with warnings)`:`${F} archived`;ye=ke>0?`${dt}, ${ke} failed`:dt}const Fe=F===0?"error":ke>0||H>0?"warning":"success",ce=[];he.length>0&&ce.push(`Failed: -${he.map(dt=>` ${dt}`).join(` -`)}`),Re.length>0&&ce.push(`With warnings: -${Re.map(dt=>` ${dt}`).join(` -`)}`);const it=ce.length>0?ce.join(` -`):null;E.current(it,null,Fe,ye)}async function U(j,B){var Re,ye,Fe;const A=x.current,D=((Re=crypto.randomUUID)==null?void 0:Re.call(crypto))??`job-${Date.now()}-${Math.random()}`;if(j.type==="text"){try{const ce=await dm(A,{title:j.title,body:j.body,mime:j.mime}),it=`text:${j.title}`;(ye=P.current)==null||ye.call(P,{id:D,jobUid:ce.job_uid,locator:it,archiveId:A}),Ne(D,ce.job_uid,it,A,B)}catch(ce){const it=ce.message||"Submission failed.";E.current(it,`text:${j.title}`),pe(B,"failed",`text:${j.title}`)}return}const F=j.locator,H=j.quality,ke=j.extraExtensions||{},he={ublock_enabled:se,reader_mode:ie,cookie_ext_enabled:Le,modal_closer_enabled:I,via_freedium:K,...ke};try{const ce=await cm(A,F,H,he);(Fe=P.current)==null||Fe.call(P,{id:D,jobUid:ce.job_uid,locator:F,archiveId:A}),Ne(D,ce.job_uid,F,A,B)}catch(ce){const it=ce.message||"Submission failed.";E.current(it,F),pe(B,"failed",F),F.startsWith("file://")&&ce.status&&Ei(A,F).catch(()=>{})}}function te(){var D,F;if(v.some(H=>H.kind==="file"&&H.uploadStatus==="uploading"))return;const j=v.filter(H=>H.kind==="file"?H.uploadStatus==="done"&&H.uploadLocator:H.kind==="text"?H.title.trim()&&H.body.trim():H.locator.trim());if(j.length===0||j.some(H=>H.kind!=="file"&&H.kind!=="text"&&Au(H))||j.some(H=>H.kind!=="file"&&H.kind!=="text"&&(H.probeState==="probing"||Dn(H.locator)&&H.playlistProbeState!=="done"))||j.some(H=>H.kind!=="file"&&H.kind!=="text"&&Array.isArray(H.playlistItems)&&H.playlistItems.length===0))return;const B=j.length>1?((D=crypto.randomUUID)==null?void 0:D.call(crypto))??`batch-${Date.now()}`:null;B&&m.current.set(B,{total:j.length,archived:0,warnings:0,failed:0,failedLocators:[],warningLocators:[]});const A=j.map(H=>H.kind==="file"?{type:"file",locator:H.uploadLocator,quality:"best",extraExtensions:{}}:H.kind==="text"?{type:"text",title:H.title.trim(),body:H.body,mime:H.mime}:{type:"url",locator:H.locator.trim(),quality:H.playlistItems!==null?null:H.quality||"best",extraExtensions:H.playlistItems!==null?{per_item_quality:Object.fromEntries(H.playlistItems.map(ke=>[ke.id,ke.quality])),sync:H.syncEnabled}:{}});f.current=!0,b([Xn()]),(F=u.current)==null||F.close(),A.forEach(H=>U(H,B))}function re(){b(j=>[...j,Xn()])}function Ue(j){var A;clearTimeout(g.current.get(j)),g.current.delete(j);const B=p.current.find(D=>D.id===j);(B==null?void 0:B.kind)==="file"&&(B.uploadStatus==="uploading"?((A=h.current.get(j))==null||A(),h.current.delete(j)):B.uploadStatus==="done"&&B.uploadLocator&&Ei(x.current,B.uploadLocator).catch(()=>{})),b(D=>{const F=D.filter(H=>H.id!==j);return F.length===0?[Xn()]:F})}function Lt(j,B){if(clearTimeout(g.current.get(j)),b(A=>A.map(D=>D.id===j?{...D,locator:B,probeState:"idle",probeQualities:null,probeHasAudio:!1,quality:"best",playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1}:D)),ff(B)){const A=setTimeout(async()=>{g.current.delete(j),b(D=>D.map(F=>F.id===j?{...F,probeState:"probing"}:F));try{const D=await fm(x.current,B.trim());b(F=>F.map(H=>{if(H.id!==j||H.locator!==B)return H;const ke=D.qualities??[],he=D.has_audio??!1,Re=ke.length===0&&he?"audio":"best";return{...H,probeState:"done",probeQualities:ke,probeHasAudio:he,quality:Re}}))}catch{b(D=>D.map(F=>F.id===j?{...F,probeState:"idle",probeQualities:null}:F))}},600);g.current.set(j,A)}else if(Dn(B)){const A=setTimeout(async()=>{g.current.delete(j),b(D=>D.map(F=>F.id===j?{...F,playlistProbeState:"probing"}:F));try{const D=await pm(x.current,B.trim());b(F=>F.map(H=>H.id!==j||H.locator!==B?H:{...H,playlistProbeState:"done",playlistInfo:D,playlistItems:D.items.map(ke=>({...ke,quality:null})),playlistQuality:null}))}catch{b(D=>D.map(F=>F.id===j?{...F,playlistProbeState:"error"}:F))}},800);g.current.set(j,A)}}function yt(j,B){b(A=>A.map(D=>D.id===j?{...D,quality:B}:D))}function Ie(j,B){b(A=>A.map(D=>{if(D.id!==j)return D;const F=qm(B,D.playlistItems);return{...D,playlistQuality:B,playlistItems:F}}))}function st(j,B,A){b(D=>D.map(F=>F.id!==j?F:{...F,playlistItems:F.playlistItems.map(H=>H.id===B?{...H,quality:A}:H)}))}function Ze(j){b(B=>B.map(A=>A.id===j?{...A,playlistExpanded:!A.playlistExpanded}:A))}function $(j,B){b(A=>A.map(D=>D.id===j?{...D,syncEnabled:B}:D))}function Z(j,B){b(A=>A.map(D=>D.id!==j?D:{...D,playlistItems:D.playlistItems.filter(F=>F.id!==B)}))}function Ae(j){const B=Array.from(j);B.length!==0&&B.forEach(A=>{const D=Km(A.name);b(he=>he.length===1&&!he[0].kind&&!he[0].locator.trim()?[D]:[...he,D]);const F=x.current,{promise:H,abort:ke}=Bm(F,A,he=>{b(Re=>Re.map(ye=>ye.id===D.id?{...ye,uploadProgress:he}:ye))});h.current.set(D.id,ke),H.then(he=>{h.current.delete(D.id),b(Re=>Re.map(ye=>ye.id===D.id?{...ye,uploadStatus:"done",uploadLocator:he.locator,uploadProgress:100}:ye))}).catch(he=>{h.current.delete(D.id),he.message!=="Upload cancelled"&&b(Re=>Re.map(ye=>ye.id===D.id?{...ye,uploadStatus:"error",uploadError:he.message}:ye))})})}function Me(j){j.preventDefault(),j.stopPropagation(),j.dataTransfer.types.includes("Files")&&_(!0)}function Rt(j){j.currentTarget.contains(j.relatedTarget)||_(!1)}function zt(j){j.preventDefault(),j.stopPropagation(),_(!1),Ae(j.dataTransfer.files)}function It(j){Ae(j.target.files),j.target.value=""}const et=v.some(j=>j.kind==="file"&&j.uploadStatus==="uploading"),Xt=v.filter(j=>j.kind==="file"?j.uploadStatus==="done"&&j.uploadLocator:j.kind==="text"?j.title.trim()&&j.body.trim():j.locator.trim()).length,$t=v.some(j=>j.kind!=="file"&&j.kind!=="text"&&Au(j)),an=v.some(j=>j.kind!=="file"&&j.kind!=="text"&&Array.isArray(j.playlistItems)&&j.playlistItems.length===0),He=v.some(j=>j.kind!=="file"&&j.kind!=="text"&&(j.probeState==="probing"||Dn(j.locator)&&j.playlistProbeState!=="done"));return s.jsx("dialog",{ref:u,className:`capture-dialog${S?" capture-dialog--dragover":""}`,onDragOver:Me,onDragLeave:Rt,onDrop:zt,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:v.map((j,B)=>j.kind==="file"?s.jsx(Gm,{item:j,onRemove:()=>Ue(j.id)},j.id):j.kind==="text"?s.jsx(Ym,{item:j,autoFocus:B===v.length-1,onTitleChange:A=>b(D=>D.map(F=>F.id===j.id?{...F,title:A}:F)),onBodyChange:A=>b(D=>D.map(F=>F.id===j.id?{...F,body:A}:F)),onMimeChange:A=>b(D=>D.map(F=>F.id===j.id?{...F,mime:A}:F)),onRemove:()=>Ue(j.id),onSubmit:te},j.id):s.jsx(Jm,{item:j,autoFocus:B===v.length-1,onLocatorChange:A=>Lt(j.id,A),onQualityChange:A=>yt(j.id,A),onRemove:()=>Ue(j.id),onSubmit:te,onPlaylistQualityChange:A=>Ie(j.id,A),onPlaylistItemQualityChange:(A,D)=>st(j.id,A,D),onPlaylistToggle:()=>Ze(j.id),onSyncChange:A=>$(j.id,A),onPlaylistItemDelete:A=>Z(j.id,A)},j.id))}),s.jsx("input",{ref:w,type:"file",multiple:!0,hidden:!0,onChange:It,"aria-hidden":"true",tabIndex:-1}),s.jsxs("div",{className:"capture-add-row-group",children:[s.jsxs("button",{type:"button",className:"capture-add-row",onClick:re,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=w.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("button",{type:"button",className:"capture-add-row capture-add-text",onClick:()=>b(j=>[...j,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(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":se,className:`ext-toggle ext-toggle--sm${se?" ext-toggle--on":""}`,onClick:()=>ne(j=>j===null?!se:!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"}),!(q!=null&&q.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":Le,className:`ext-toggle ext-toggle--sm${Le?" ext-toggle--on":""}`,onClick:()=>ve(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":ie,className:`ext-toggle ext-toggle--sm${ie?" 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":I,className:`ext-toggle ext-toggle--sm${I?" ext-toggle--on":""}`,onClick:()=>R(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":K,className:`ext-toggle ext-toggle--sm${K?" ext-toggle--on":""}`,onClick:()=>ee(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:te,disabled:Xt===0||$t||He||an||et,children:Xt>1?`Archive ${Xt}`:"Archive"}),s.jsx("button",{type:"button",className:"capture-cancel",onClick:()=>{var j;return(j=u.current)==null?void 0:j.close()},children:"Cancel"})]})]})})}function Jm({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 w;t&&((w=g.current)==null||w.focus())},[t]);const m=(()=>{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 w=[...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),_=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"}),w.map(p=>s.jsxs("option",{value:`${p}p`,children:[p,"p"]},p)),S&&s.jsx("option",{value:"audio",children:"Audio only"})]}),_>0&&s.jsxs("span",{className:"capture-conflict-badge",children:[_," 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(!ff(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 w=e.probeQualities??[],S=e.probeHasAudio??!1;return w.length===0&&!S?s.jsx("span",{className:"capture-quality-hint",children:"No media detected"}):w.length===0&&S?s.jsx("select",{className:"capture-quality",value:"audio",onChange:_=>r(_.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:_=>r(_.target.value),"aria-label":"Video quality",children:[s.jsx("option",{value:"best",children:"Best quality"}),w.map(_=>s.jsx("option",{value:_,children:_},_)),S&&s.jsx("option",{value:"audio",children:"Audio only"})]})}return null})(),x=Dn(e.locator)&&e.playlistProbeState==="done"?s.jsxs("label",{className:"capture-sync-row",children:[s.jsx("input",{type:"checkbox",checked:e.syncEnabled,onChange:w=>d(w.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:w=>n(w.target.value),onKeyDown:w=>{w.key==="Enter"&&i()},autoComplete:"off",spellCheck:!1}),m,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(w=>s.jsxs("div",{className:`capture-playlist-item${w.quality===null?" capture-playlist-item--conflict":""}`,children:[s.jsx("span",{className:"capture-playlist-item-title",children:w.title||w.url}),s.jsxs("select",{className:"capture-item-quality",value:w.quality??"",onChange:S=>o(w.id,S.target.value),"aria-label":`Quality for ${w.title||w.url}`,children:[w.quality===null&&s.jsx("option",{value:"",disabled:!0,children:"Choose…"}),s.jsx("option",{value:"best",children:"Best quality"}),w.qualities.map(S=>s.jsx("option",{value:S,children:S},S)),w.has_audio&&s.jsx("option",{value:"audio",children:"Audio only"})]}),w.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 ${w.title||w.url}`,onClick:()=>y(w.id),children:"×"})]},w.id)),x]}):x]})}function Gm({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 Ym({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 Zm=["list=","/playlist/","/channel/","yt:playlist:","yt:channel:","ytm:playlist:","spotify:playlist:","spotify:album:"];function eg(e){const t=e.toLowerCase();return Zm.some(n=>t.includes(n))}function tg(e){return e.length>80?`${e.slice(0,79)}…`:e}function ng({locator:e=""}){const t=String(e),n=eg(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:tg(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 ml(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 xt(e){return rg(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 Mu={youtube:'',youtube_music:'',spotify:'',x:'',instagram:'',facebook:'',tiktok:'',reddit:'',snapchat:'',local:'',web:'',other:'?'};function Us(e){return Mu[e]??Mu.other}function pf(e){return e.split("/").map(t=>t?t.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"").join("/")}function lg({entry:e,index:t,onRowClick:n,selectedUids:r,isFirst:l,isLast:i,reorderDisabled:a,onMove:o,canReorder:u,isDragging:d,dropEdge:y,onHandleDragStart:g,onHandleDragEnd:m,onRowDragOver:x,onRowDrop:w}){const S=(r==null?void 0:r.size)===1&&r.has(e.entry_uid),_=(r==null?void 0:r.size)>=2&&r.has(e.entry_uid),p=xt(e.title)||xt(e.entry_uid),f=["child-entry-row",t%2===0?"child-entry-row--light":"child-entry-row--dark",S&&"is-selected",_&&"is-multi-selected",d&&"is-dragging",y==="before"&&"is-drop-before",y==="after"&&"is-drop-after"].filter(Boolean).join(" ");return s.jsxs("div",{className:f,tabIndex:0,"data-entry-uid":e.entry_uid,onMouseDown:h=>{h.shiftKey&&h.preventDefault()},onClick:h=>n(e,h),onDragOver:u?x:void 0,onDrop:u?w:void 0,"aria-keyshortcuts":u?"Alt+ArrowUp Alt+ArrowDown":void 0,onKeyDown:h=>{if(u&&h.altKey&&(h.key==="ArrowUp"||h.key==="ArrowDown")){h.preventDefault(),a||o(h.key==="ArrowUp"?-1:1);return}h.key==="Enter"&&n(e,h)},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:[u&&s.jsxs("span",{className:"child-reorder-controls",children:[s.jsx("span",{className:"child-drag-handle",draggable:!a,title:"Drag to reorder (or Alt+↑/↓)","aria-hidden":"true",onClick:h=>h.stopPropagation(),onDragStart:g,onDragEnd:m,children:"⋮⋮"}),s.jsx("button",{type:"button",className:"child-move-btn","aria-label":`Move ${p} up`,disabled:a||l,onClick:h=>{h.stopPropagation(),o(-1)},onKeyDown:h=>h.stopPropagation(),children:"↑"}),s.jsx("button",{type:"button",className:"child-move-btn","aria-label":`Move ${p} down`,disabled:a||i,onClick:h=>{h.stopPropagation(),o(1)},onKeyDown:h=>h.stopPropagation(),children:"↓"})]}),s.jsx("span",{className:"source-icon",children:s.jsx("span",{dangerouslySetInnerHTML:{__html:Us(e.source_kind)}})}),s.jsx("span",{className:"entry-title",children:p})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"type-pill",children:xt(e.entity_kind)})}),s.jsx("div",{className:"col-size",children:s.jsx("span",{className:"size-total",children:ml(e.total_artifact_bytes)})}),s.jsx("div",{className:"url-cell col-url",children:xt(e.original_url)})]})}function sg({entry:e,archiveId:t,rowIndex:n,isSelected:r,isMultiSelected:l,onRowClick:i,selectedUids:a,deletedUids:o,renamedTitles:u,isPublicSession:d,canReorder:y=!1,onReorderError:g}){const[m,x]=c.useState(!1),[w,S]=c.useState(!1),[_,p]=c.useState(null),[f,h]=c.useState(!1),[k,E]=c.useState(!1),[P,N]=c.useState(null),[v,b]=c.useState(null),L=c.useRef(null),X=c.useRef(null),ne=e.source_kind==="web"&&e.entity_kind==="page"&&e.has_favicon&&t&&!m?s.jsx("img",{src:`/api/archives/${t}/entries/${e.entry_uid}/favicon`,width:"16",height:"16",alt:"",onError:()=>x(!0),style:{objectFit:"contain"}}):s.jsx("span",{dangerouslySetInnerHTML:{__html:Us(e.source_kind)}}),q=r||l,fe=e.child_count>0&&!d;function Le(U){U.stopPropagation(),i(e,{ctrlKey:!0,metaKey:!1,shiftKey:!1,preventDefault(){}})}async function ve(U){if(U.stopPropagation(),w){S(!1);return}if(S(!0),_===null&&!f){h(!0);try{const te=await Iu(t,e.entry_uid);p(te)}catch{p([])}finally{h(!1)}}}const I=(_??[]).filter(U=>!(o!=null&&o.has(U.entry_uid))).map(U=>u!=null&&u.has(U.entry_uid)?{...U,title:u.get(U.entry_uid)}:U);async function R(U){const te=_;p(U),E(!0);try{await tm(t,e.entry_uid,U.map(re=>re.entry_uid))}catch(re){if(p(te),g==null||g(re.message),re.status===400)try{p(await Iu(t,e.entry_uid))}catch{}}finally{E(!1)}}function K(U,te){if(!y||k||U===te||te<0||te>=I.length)return;const re=I.slice(),[Ue]=re.splice(U,1);re.splice(te,0,Ue),R(re)}function ee(U,te){var re;X.current=((re=I[U])==null?void 0:re.entry_uid)??null,K(U,U+te)}c.useEffect(()=>{const U=X.current;if(!U||!L.current)return;X.current=null;const te=L.current.querySelector(`[data-entry-uid="${CSS.escape(U)}"]`);te&&!te.contains(document.activeElement)&&te.focus()},[_]);function se(U,te){te.stopPropagation(),te.dataTransfer.effectAllowed="move",te.dataTransfer.setData("text/plain",U);const re=te.currentTarget.closest(".child-entry-row");re&&te.dataTransfer.setDragImage(re,16,re.offsetHeight/2),N(U)}function ie(){N(null),b(null)}function Y(U,te){if(!P)return;te.preventDefault(),te.dataTransfer.dropEffect="move";const re=te.currentTarget.getBoundingClientRect(),Ue=te.clientY>re.top+re.height/2;((v==null?void 0:v.uid)!==U||(v==null?void 0:v.after)!==Ue)&&b({uid:U,after:Ue})}function Ne(U,te){if(!P)return;te.preventDefault();const re=I.findIndex(Ie=>Ie.entry_uid===P),Ue=I.findIndex(Ie=>Ie.entry_uid===U),Lt=(v==null?void 0:v.uid)===U?v.after:!1;if(ie(),re===-1||Ue===-1)return;let yt=Ue+(Lt?1:0);re{U.shiftKey&&U.preventDefault()},onClick:U=>i(e,U),onKeyDown:U=>{U.key==="Enter"&&i(e,U)},children:[s.jsx("div",{className:"col-check",children:s.jsx("button",{type:"button",className:`row-checkbox${q?" is-checked":""}`,"aria-pressed":q,"aria-label":q?"Deselect entry":"Select entry",onClick:Le,onKeyDown:U=>U.stopPropagation()})}),s.jsx("div",{className:"col-added",children:ko(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[fe&&s.jsx("button",{type:"button",className:`entry-expand-btn${w?" is-expanded":""}`,"aria-label":w?"Collapse children":`Expand ${e.child_count} items`,"aria-expanded":w,onClick:ve,onKeyDown:U=>U.stopPropagation()}),s.jsx("span",{className:"source-icon",children:ne}),s.jsx("span",{className:"entry-title",children:xt(e.title)||xt(e.entry_uid)}),fe&&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:xt(e.entity_kind)})}),s.jsxs("div",{className:"col-size",children:[s.jsx("span",{className:"size-total",children:ml(e.total_artifact_bytes)}),e.cached_bytes>0&&e.cacheable_bytes>0&&s.jsxs("span",{className:"size-cached-pct",title:`${ml(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:xt(e.original_url)})]}),w&&s.jsxs(s.Fragment,{children:[f&&s.jsx("div",{className:"child-entries-loading",children:"Loading…"}),s.jsx("div",{className:"child-entries",ref:L,"aria-busy":k,"aria-label":`${e.child_count} child entries`,children:I.map((U,te)=>s.jsx(lg,{entry:U,index:te,onRowClick:i,selectedUids:a,isFirst:te===0,isLast:te===I.length-1,reorderDisabled:k,canReorder:y,onMove:re=>ee(te,re),isDragging:P===U.entry_uid,dropEdge:(v==null?void 0:v.uid)===U.entry_uid&&P!==U.entry_uid?v.after?"after":"before":null,onHandleDragStart:re=>se(U.entry_uid,re),onHandleDragEnd:ie,onRowDragOver:re=>Y(U.entry_uid,re),onRowDrop:re=>Ne(U.entry_uid,re)},U.entry_uid))})]})]})}function ig({entries:e,selectedUids:t,onRowClick:n,archiveId:r,pendingCaptures:l=[],deletedUids:i,renamedTitles:a,isPublicSession:o,canReorder:u=!1,onChildReorderError:d}){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(y=>y.archiveId===r).reverse().map(y=>s.jsx(ng,{locator:y.locator},y.id)),e.map((y,g)=>s.jsx(sg,{entry:y,rowIndex:g,archiveId:r,isSelected:t.size===1&&t.has(y.entry_uid),isMultiSelected:t.size>=2&&t.has(y.entry_uid),onRowClick:n,selectedUids:t,deletedUids:i,renamedTitles:a,isPublicSession:o,canReorder:u,onReorderError:d},y.entry_uid))]})]})})}function ag(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 og({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 ug({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:ag(l.started_at)}),s.jsxs("td",{children:[s.jsx(og,{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 cg=4;function dg({archives:e}){const{currentUser:t}=c.useContext(Hs)??{},n=t&&(t.role_bits&cg)!==0,[r,l]=c.useState("users"),[i,a]=c.useState([]),[o,u]=c.useState([]),[d,y]=c.useState(!1),[g,m]=c.useState(null),[x,w]=c.useState(""),[S,_]=c.useState(""),[p,f]=c.useState(""),[h,k]=c.useState(null),[E,P]=c.useState(!1),[N,v]=c.useState(""),[b,L]=c.useState(""),[X,Q]=c.useState(null),[ne,q]=c.useState(!1),fe=c.useCallback(async()=>{if(n){y(!0),m(null);try{const[R,K]=await Promise.all([_m(),df()]);a(R),u(K)}catch(R){m(R.message)}finally{y(!1)}}},[n]);c.useEffect(()=>{fe()},[fe]);async function Le(R){const K=R.status==="active"?"disabled":"active";try{await Cm(R.user_uid,K),a(ee=>ee.map(se=>se.user_uid===R.user_uid?{...se,status:K}:se))}catch(ee){m(ee.message)}}async function ve(R){if(R.preventDefault(),!x.trim()||!S){k("Username and password required");return}P(!0),k(null);try{await Nm(x.trim(),S,p.trim()||void 0),w(""),_(""),f(""),await fe()}catch(K){k(K.message)}finally{P(!1)}}async function I(R){if(R.preventDefault(),!N.trim()||!b.trim()){Q("Slug and name required");return}q(!0),Q(null);try{await Em(N.trim(),b.trim()),v(""),L(""),await fe()}catch(K){Q(K.message)}finally{q(!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(R=>s.jsxs("tr",{className:R.status==="disabled"?"admin-row-disabled":"",children:[s.jsx("td",{children:R.username}),s.jsx("td",{className:"muted",children:R.email||"—"}),s.jsx("td",{children:R.role_slugs.join(", ")||"—"}),s.jsx("td",{children:s.jsx("span",{className:`status-badge status-${R.status}`,children:R.status})}),s.jsx("td",{children:s.jsx("button",{className:"admin-action-btn",onClick:()=>Le(R),children:R.status==="active"?"Ban":"Unban"})})]},R.user_uid))})]}),s.jsx("h3",{children:"Create User"}),s.jsxs("form",{className:"admin-form",onSubmit:ve,children:[s.jsx("input",{className:"admin-input",placeholder:"Username",value:x,onChange:R=>w(R.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"password",placeholder:"Password (min 8 chars)",value:S,onChange:R=>_(R.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"email",placeholder:"Email (optional)",value:p,onChange:R=>f(R.target.value)}),h&&s.jsx("div",{className:"form-msg form-msg--err",children:h}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:E,children:E?"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(R=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:R.slug})}),s.jsx("td",{children:R.name}),s.jsx("td",{children:R.level}),s.jsx("td",{children:R.bit_position}),s.jsx("td",{children:R.is_builtin?"✓":""})]},R.role_uid))})]}),s.jsx("h3",{children:"Create Custom Role"}),s.jsxs("form",{className:"admin-form",onSubmit:I,children:[s.jsx("input",{className:"admin-input",placeholder:"Slug (e.g. moderator)",value:N,onChange:R=>v(R.target.value),required:!0}),s.jsx("input",{className:"admin-input",placeholder:"Display Name (e.g. Moderator)",value:b,onChange:R=>L(R.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:ne,children:ne?"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(R=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:R.label}),s.jsx("div",{className:"muted",children:R.archive_path})]},R.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(R=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:R.label}),s.jsx("div",{className:"muted",children:R.archive_path})]},R.id))})]})}function hf({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(hf,{node:r,onPick:t},r.tag.tag_uid))})})]})}function Fu({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(hf,{node:o,onPick:r},o.tag.tag_uid))}):s.jsx("p",{className:"tag-picker-empty",children:"No other tags available."})]})]})})}function mf({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 om(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 gf({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:m,onCreateCancel:x}){var X;const w=n===e.tag.full_path,[S,_]=c.useState(!1),[p,f]=c.useState(""),h=c.useRef(!1);function k(){if(S)return;if(d){y(e);return}const Q=w?null:e.tag.full_path;r(Q),l("archive")}function E(Q){Q.stopPropagation(),!d&&(f(e.tag.slug),_(!0))}async function P(){const Q=p.trim();if(!Q||Q===e.tag.slug){_(!1);return}try{const ne=await im(t,e.tag.tag_uid,Q);i(e.tag.full_path,ne.full_path),o()}catch{}finally{_(!1)}}async function N(Q){var q;Q.stopPropagation();const ne=((q=e.children)==null?void 0:q.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(ne))try{await am(t,e.tag.tag_uid),a(e.tag.full_path),o()}catch{}}const v={archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:d,onMoveSourceSelect:y,pendingCreateParentUid:g,onCreateDone:m,onCreateCancel:x},b=g===e.tag.tag_uid,L=((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:Q=>f(Q.target.value),onKeyDown:Q=>{Q.key==="Enter"&&Q.currentTarget.blur(),Q.key==="Escape"&&(h.current=!0,Q.currentTarget.blur())},onBlur:()=>{h.current?(h.current=!1,_(!1)):P()}}):s.jsxs("button",{className:`tag-node-btn${w?" 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:E,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:Q=>{Q.stopPropagation(),E(Q)},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:N,"aria-label":`Delete "${e.tag.full_path}"`,children:"×"})]}),(L||b)&&s.jsx("div",{className:"tag-children",children:s.jsxs("ul",{className:"tag-tree-list",children:[e.children.map(Q=>s.jsx(gf,{node:Q,...v},Q.tag.tag_uid)),b&&s.jsx("li",{children:s.jsx(mf,{parentPath:e.tag.full_path,archiveId:t,onDone:m,onCancel:x})})]})})]})}function fg({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,m]=c.useState(null);function x(){y("select-source"),m(null)}function w(){y(null),m(null)}c.useEffect(()=>{if(d!=="select-source")return;function ne(q){q.key==="Escape"&&(q.preventDefault(),q.stopPropagation(),w())}return document.addEventListener("keydown",ne),()=>document.removeEventListener("keydown",ne)},[d]);function S(ne){m(ne),y("select-dest")}async function _(ne){const q=g.tag.full_path,fe=g.tag.tag_uid,Le=(ne==null?void 0:ne.tag_uid)??null;w();try{const ve=await um(e,fe,Le);i(q,ve.full_path),o()}catch(ve){alert(ve.message||"Move failed")}}const[p,f]=c.useState(null),[h,k]=c.useState(void 0);function E(){f("select-parent"),k(void 0)}function P(){f(null),k(void 0)}function N(ne){k(ne??null),f("input")}function v(){f(null),k(void 0),o()}const b=d==="select-source",L=p==="input"?h?h.tag_uid:"__root__":void 0,X={archiveId:e,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:b,onMoveSourceSelect:S,pendingCreateParentUid:L,onCreateDone:v,onCreateCancel:P},Q=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:b?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:w,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:E,title:"Create a new tag",disabled:!!p||!!d,children:"+ New"}),s.jsx("button",{className:"tag-tree-action-btn",onClick:x,title:"Move a tag to a different parent",disabled:!!p||!!d||t.length===0,children:"Move"})]})]})}),t.length===0&&!Q?s.jsx("p",{className:"muted",style:{padding:"8px 0"},children:"No tags yet."}):s.jsxs("ul",{className:"tag-tree-list",children:[t.map(ne=>s.jsx(gf,{node:ne,...X},ne.tag.tag_uid)),Q&&s.jsx("li",{children:s.jsx(mf,{parentPath:null,archiveId:e,onDone:v,onCancel:P})})]})]}),p==="select-parent"&&s.jsx(Fu,{title:"Create tag under…",tagNodes:t,excludeUid:null,onPick:N,onCancel:P}),d==="select-dest"&&g&&s.jsx(Fu,{title:`Move "${g.tag.slug}" under…`,tagNodes:t,excludeUid:g.tag.tag_uid,onPick:_,onCancel:w})]})}const Fr=[{value:0,label:"Private"},{value:2,label:"Users only"},{value:3,label:"Public"}],pg=e=>{var t;return((t=Fr.find(n=>n.value===e))==null?void 0:t.label)??String(e)};function hg({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,m]=c.useState(!1),[x,w]=c.useState(null),[S,_]=c.useState(""),[p,f]=c.useState(""),[h,k]=c.useState(2),[E,P]=c.useState(!1),[N,v]=c.useState(!0),[b,L]=c.useState(null),[X,Q]=c.useState(""),[ne,q]=c.useState(2),[fe,Le]=c.useState(!1),[ve,I]=c.useState(null),[R,K]=c.useState(!1),[ee,se]=c.useState(""),ie=c.useRef(null),Y=t.find($=>$.collection_uid===o)??null,Ne=(Y==null?void 0:Y.slug)==="_default_",pe=c.useCallback(async()=>{if(e){l(!0),a(null);try{const $=await wo(e);n($)}catch($){a($.message)}finally{l(!1)}}},[e]),U=c.useCallback(async $=>{if(!$){y(null);return}m(!0),w(null);try{const Z=await Tm(e,$);y(Z)}catch(Z){w(Z.message)}finally{m(!1)}},[e]);c.useEffect(()=>{pe()},[pe]),c.useEffect(()=>{U(o)},[o,U]),c.useEffect(()=>{R&&ie.current&&ie.current.focus()},[R]),c.useEffect(()=>{d!=null&&q(d.default_visibility_bits)},[d]);async function te($){$.preventDefault();const Z=S.trim(),Ae=p.trim();if(!(!Z||!Ae)){P(!0),L(null);try{const Me=await bm(e,Z,Ae,h,N);_(""),f(""),k(2),v(!0),await pe(),u(Me.collection_uid)}catch(Me){L(Me.message)}finally{P(!1)}}}async function re(){const $=ee.trim();if(!$||!Y){K(!1);return}try{await Ci(e,Y.collection_uid,{name:$}),await pe(),y(Z=>Z&&{...Z,name:$})}catch(Z){a(Z.message)}finally{K(!1)}}async function Ue($){if(Y)try{await Ci(e,Y.collection_uid,{default_visibility_bits:$}),await pe(),y(Z=>Z&&{...Z,default_visibility_bits:$})}catch(Z){a(Z.message)}}async function Lt($){if(Y)try{await Ci(e,Y.collection_uid,{requires_auth:$}),await pe(),y(Z=>Z&&{...Z,requires_auth:$})}catch(Z){a(Z.message)}}async function yt(){if(Y&&window.confirm(`Delete collection "${Y.name}"? Entries will not be deleted.`))try{await Rm(e,Y.collection_uid),u(null),y(null),await pe()}catch($){a($.message)}}async function Ie($){$.preventDefault();const Z=X.trim();if(!(!Z||!Y)){Le(!0),I(null);try{await Sa(e,Y.collection_uid,Z,ne),Q(""),await U(Y.collection_uid)}catch(Ae){I(Ae.message)}finally{Le(!1)}}}async function st($){if(Y)try{await Pm(e,Y.collection_uid,$),await U(Y.collection_uid)}catch(Z){w(Z.message)}}async function Ze($,Z){if(Y)try{await Lm(e,Y.collection_uid,$,Z),y(Ae=>Ae&&{...Ae,entries:Ae.entries.map(Me=>Me.entry_uid===$?{...Me,collection_visibility_bits:Z}:Me)})}catch(Ae){w(Ae.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($=>s.jsxs("button",{className:`coll-sidebar-row${o===$.collection_uid?" is-active":""}`,onClick:()=>u($.collection_uid),children:[s.jsx("span",{className:"coll-row-name",children:$.name}),s.jsx("span",{className:"coll-row-meta",children:pg($.default_visibility_bits)})]},$.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:[R?s.jsx("input",{ref:ie,className:"coll-rename-input",value:ee,onChange:$=>se($.target.value),onBlur:re,onKeyDown:$=>{$.key==="Enter"&&re(),$.key==="Escape"&&K(!1)}}):s.jsxs("h3",{className:`coll-detail-name${Ne?"":" coll-detail-name--editable"}`,title:Ne?void 0:"Click to rename",onClick:()=>{Ne||(se(Y.name),K(!0))},children:[(d==null?void 0:d.name)??Y.name,!Ne&&s.jsx("span",{className:"coll-edit-hint",children:" ✎"})]}),!Ne&&s.jsx("button",{className:"coll-delete-btn",onClick:yt,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)??Y.default_visibility_bits,onChange:$=>Ue(Number($.target.value)),children:Fr.map($=>s.jsx("option",{value:$.value,children:$.label},$.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)??Y.requires_auth),onChange:$=>Lt($.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…"}),x&&s.jsx("div",{className:"collections-error",children:x}),!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($=>s.jsxs("li",{className:"coll-entry-row",children:[s.jsxs("div",{className:"coll-entry-info",children:[s.jsx("span",{className:"coll-entry-title",children:$.title||$.entry_uid}),s.jsx("span",{className:"coll-entry-kind muted",children:$.source_kind})]}),s.jsxs("div",{className:"coll-entry-actions",children:[s.jsx("select",{className:"coll-entry-vis-select",value:$.collection_visibility_bits,onChange:Z=>Ze($.entry_uid,Number(Z.target.value)),children:Fr.map(Z=>s.jsx("option",{value:Z.value,children:Z.label},Z.value))}),!Ne&&s.jsx("button",{className:"coll-entry-remove",onClick:()=>st($.entry_uid),title:"Remove from collection",children:"×"})]})]},$.entry_uid))}))]}),!Ne&&s.jsxs("form",{className:"coll-add-entry-form",onSubmit:Ie,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:$=>Q($.target.value),placeholder:"entry_uid",required:!0}),s.jsx("select",{className:"coll-vis-select",value:ne,onChange:$=>q(Number($.target.value)),children:Fr.map($=>s.jsx("option",{value:$.value,children:$.label},$.value))}),s.jsx("button",{className:"coll-add-btn",type:"submit",disabled:fe,children:fe?"…":"Add"})]}),ve&&s.jsx("div",{className:"collections-error",style:{marginTop:4},children:ve})]})]}):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:te,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:$=>{_($.target.value),p||f($.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:$=>f($.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:h,onChange:$=>k(Number($.target.value)),children:Fr.map($=>s.jsx("option",{value:$.value,children:$.label},$.value))})]}),s.jsx("div",{className:"form-field",children:s.jsxs("label",{className:"form-label",children:[s.jsx("input",{type:"checkbox",checked:N,onChange:$=>v($.target.checked)})," Require authentication to view"]})}),b&&s.jsx("div",{className:"collections-error",children:b}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:E,children:E?"Creating…":"Create collection"})]})]})]}):s.jsx("div",{className:"view-placeholder",children:"Select an archive."})}const mg=4,gg=8;function yg({tab:e,onTabChange:t,archiveId:n}){const{currentUser:r,setCurrentUser:l}=c.useContext(Hs)??{},i=r&&(r.role_bits&mg)!==0,a=!!r&&(r.role_bits&gg)!==0,o=["profile","tokens",...i?["instance","cookies","extensions","storage"]:[]],u={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:o.map(d=>s.jsx("button",{className:`view-tab${e===d?" is-active":""}`,onClick:()=>t(d),children:u[d]},d))}),e==="profile"&&s.jsx(vg,{currentUser:r,setCurrentUser:l}),e==="tokens"&&s.jsx(xg,{}),e==="instance"&&i&&s.jsx(wg,{isOwner:a,setCurrentUser:l}),e==="cookies"&&i&&s.jsx(jg,{}),e==="extensions"&&i&&s.jsx(Sg,{}),e==="storage"&&i&&s.jsx(kg,{archiveId:n})]})}function vg({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(""),[m,x]=c.useState(""),[w,S]=c.useState(!1),[_,p]=c.useState(null);async function f(k){k.preventDefault(),i(!0),o(null);try{await vm(n),t(E=>({...E,display_name:n||null})),o({ok:!0,text:"Saved."})}catch(E){o({ok:!1,text:E.message})}finally{i(!1)}}async function h(k){if(k.preventDefault(),y!==m){p({ok:!1,text:"Passwords do not match."});return}S(!0),p(null);try{await wm(u,y),d(""),g(""),x(""),p({ok:!0,text:"Password changed."})}catch(E){p({ok:!1,text:E.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 E=k.target.checked;try{await xm({humanize_slugs:E}),t(P=>({...P,humanize_slugs:E}))}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:h,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:m,onChange:k=>x(k.target.value),required:!0})]}),_&&s.jsx("div",{className:`form-msg form-msg--${_.ok?"ok":"err"}`,children:_.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:w,children:w?"Changing…":"Change Password"})]})]})]})}function xg(){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),m=c.useCallback(async()=>{r(!0),i(null);try{t(await km())}catch(S){i(S.message)}finally{r(!1)}},[]);c.useEffect(()=>{m()},[m]);async function x(S){if(S.preventDefault(),!!a.trim()){d(!0);try{const _=await jm(a.trim());g(_),o(""),m()}catch(_){i(_.message)}finally{d(!1)}}}async function w(S){try{await Sm(S),t(_=>_.filter(p=>p.token_uid!==S))}catch(_){i(_.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:x,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:()=>w(S.token_uid),children:"Revoke"})]},S.token_uid))]})]})})}function wg({isOwner:e,setCurrentUser:t}){const[n,r]=c.useState(null),[l,i]=c.useState(!0),[a,o]=c.useState(null),[u,d]=c.useState(!1),[y,g]=c.useState(null),[m,x]=c.useState([]),[w,S]=c.useState(12),[_,p]=c.useState(!1),[f,h]=c.useState(null);c.useEffect(()=>{(async()=>{try{const[N,v]=await Promise.all([xo(),df()]);r(N),x(v.filter(b=>b.bit_position>0)),S(N.reorder_children_role_bits??12)}catch(N){o(N.message)}finally{i(!1)}})()},[]);function k(N,v){S(b=>v?(b|N)>>>0:(b&~N)>>>0)}async function E(N){N.preventDefault(),p(!0),h(null);try{await Jr({reorder_children_role_bits:w}),r(b=>({...b,reorder_children_role_bits:w}));const v=await cf();v&&(t==null||t(v)),h({ok:!0,text:"Saved."})}catch(v){h({ok:!1,text:v.message})}finally{p(!1)}}async function P(N){N.preventDefault(),d(!0),g(null);try{const{reorder_children_role_bits:v,...b}=n;await Jr(b),g({ok:!0,text:"Saved."})}catch(v){g({ok:!1,text:v.message})}finally{d(!1)}}return l?s.jsx("div",{className:"muted",children:"Loading…"}):a?s.jsx("div",{className:"form-msg form-msg--err",children:a}):n?s.jsxs("div",{style:{maxWidth:440},children:[s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Instance Settings"}),s.jsxs("form",{onSubmit:P,children:[[["public_index_enabled","Public index (unauthenticated browsing)"],["public_entry_content_enabled","Public entry content"],["open_registration_enabled","Open registration"]].map(([N,v])=>s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:!!n[N],onChange:b=>r(L=>({...L,[N]:b.target.checked}))}),v]},N)),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:n.default_entry_visibility,onChange:N=>r(v=>({...v,default_entry_visibility:Number(N.target.value)})),children:[s.jsx("option",{value:0,children:"Private"}),s.jsx("option",{value:2,children:"Unlisted"}),s.jsx("option",{value:3,children:"Public"})]})]}),y&&s.jsx("div",{className:`form-msg form-msg--${y.ok?"ok":"err"}`,children:y.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:u,children:u?"Saving…":"Save Settings"})]})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Permissions"}),s.jsxs("form",{onSubmit:E,children:[s.jsx("label",{className:"form-label",children:"Reorder child entries"}),m.map(N=>{const v=1<>>0;return s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",disabled:!e||_,checked:(w&v)!==0,onChange:b=>k(v,b.target.checked)}),N.name,!N.is_builtin&&s.jsx("span",{className:"muted",children:" (custom)"})]},N.role_uid)}),s.jsx("p",{className:"form-hint",children:"Roles are cumulative: every signed-in account also has User, and owners also have Admin. Checking User lets every signed-in account reorder."}),!e&&s.jsx("p",{className:"form-hint",children:"Only the owner can change this."}),f&&s.jsx("div",{className:`form-msg form-msg--${f.ok?"ok":"err"}`,children:f.text}),e&&s.jsx("button",{className:"btn-primary",type:"submit",disabled:_,children:_?"Saving…":"Save Permissions"})]})]})]}):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 kg({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 x=await zm(e);l(x),n("scanned")}catch(x){u(x.message),n("error")}}async function g(){n("deleting"),u(null);try{const x=await Im(e);a(x),n("done")}catch(x){u(x.message),n("error")}}const m=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&&m&&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&&!m&&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 jg(){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("{}"),[m,x]=c.useState(null),[w,S]=c.useState(!1),[_,p]=c.useState({});c.useEffect(()=>{f()},[]);async function f(){r(!0),i(null);try{t(await Om())}catch(v){i(v.message)}finally{r(!1)}}async function h(v){v.preventDefault();try{JSON.parse(y)}catch{x({ok:!1,text:'cookies must be valid JSON, e.g. {"session": "abc"}'});return}S(!0),x(null);try{await Am(a==="global"?null:u.trim(),a,y),d(""),g("{}"),o("global"),x({ok:!0,text:"Rule added."}),await f()}catch(b){x({ok:!1,text:b.message})}finally{S(!1)}}async function k(v){try{await Fm(v),await f()}catch(b){i(b.message)}}function E(v){p(b=>({...b,[v.rule_uid]:{cookiesInput:v.cookies_json,saving:!1,msg:null}}))}function P(v){p(b=>{const L={...b};return delete L[v],L})}async function N(v){const b=_[v.rule_uid];try{JSON.parse(b.cookiesInput)}catch{p(L=>({...L,[v.rule_uid]:{...L[v.rule_uid],msg:{ok:!1,text:"Invalid JSON"}}}));return}p(L=>({...L,[v.rule_uid]:{...L[v.rule_uid],saving:!0,msg:null}}));try{await Mm(v.rule_uid,{cookies_json:b.cookiesInput}),P(v.rule_uid),await f()}catch(L){p(X=>({...X,[v.rule_uid]:{...X[v.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(v=>{const b=_[v.rule_uid],L=v.url_pattern?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"muted",children:[v.pattern_kind,":"]})," ",s.jsx("code",{children:v.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:b?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:12,width:"100%",minHeight:60},value:b.cookiesInput,onChange:X=>p(Q=>({...Q,[v.rule_uid]:{...Q[v.rule_uid],cookiesInput:X.target.value}}))}),b.msg&&s.jsx("div",{className:`form-msg form-msg--${b.msg.ok?"ok":"err"}`,children:b.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:b.saving,onClick:()=>N(v),children:b.saving?"Saving…":"Save"}),s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>P(v.rule_uid),children:"Cancel"})]})]}):s.jsx("code",{style:{fontSize:12,wordBreak:"break-all"},children:v.cookies_json})}),s.jsx("td",{children:!b&&s.jsxs("div",{style:{display:"flex",gap:6},children:[s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>E(v),children:"Edit"}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"2px 8px"},onClick:()=>k(v.rule_uid),children:"Del"})]})})]},v.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:h,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:v=>o(v.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:v=>d(v.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:v=>g(v.target.value),placeholder:'{"SESSION": "abc123", "token": "xyz"}',required:!0})]}),m&&s.jsx("div",{className:`form-msg form-msg--${m.ok?"ok":"err"}`,children:m.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:w,children:w?"Adding…":"Add Rule"})]})]})})}function Sg(){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(_){o({ok:!1,text:_.message})}finally{r(!1)}})()},[]);async function u(_){i(!0),o(null);try{await Jr({ublock_enabled:_}),t(p=>({...p,ublock_enabled:_})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function d(_){i(!0),o(null);try{await Jr({cookie_ext_enabled:_}),t(p=>({...p,cookie_ext_enabled:_})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function y(_){i(!0),o(null);try{await Jr({modal_closer_enabled:_}),t(p=>({...p,modal_closer_enabled:_})),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,m=(e==null?void 0:e.ublock_enabled)??!0,x=(e==null?void 0:e.cookie_ext_available)??!1,w=(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":m,className:`ext-toggle${m?" ext-toggle--on":""}`,onClick:()=>u(!m),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."}),!x&&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":w,className:`ext-toggle${w?" ext-toggle--on":""}`,onClick:()=>d(!w),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 Bu={0:"Private",1:"Public",2:"Users only",3:"Public"},es=[{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"}],_g=Object.fromEntries(es.map(e=>[e.value,e.label])),Uu="archivr:summary:provider",Ng=1500,yf="This entry can’t be summarized yet.",vf="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.",Hu=`${yf} - -${vf}`;function Cg(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 Eg=()=>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 bg({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:m,onOpenPreview:x,onPlay:w,isPublicSession:S}){var Ee,We,je;const[_,p]=c.useState([]),[f,h]=c.useState(""),[k,E]=c.useState([]),[P,N]=c.useState(""),v=c.useRef(0),b=c.useRef(!1),[L,X]=c.useState(!1),[Q,ne]=c.useState(""),[q,fe]=c.useState("idle"),[Le,ve]=c.useState(""),I=c.useRef(null),[R,K]=c.useState(!1);c.useEffect(()=>{K(!1)},[(Ee=l==null?void 0:l.summary)==null?void 0:Ee.entry_uid]);const[ee,se]=c.useState(null),[ie,Y]=c.useState(null),[Ne,pe]=c.useState(""),[U,te]=c.useState(!1),[re,Ue]=c.useState(()=>{try{return sessionStorage.getItem(Uu)||es[0].value}catch{return es[0].value}}),[Lt,yt]=c.useState(!1),Ie=c.useRef(null),st=c.useRef(null),Ze=c.useRef(null),$=c.useRef(null),Z=e&&(t!=null&&t.entry_uid)?`${e}:${t.entry_uid}`:null;$.current=Z;const Ae=(n==null?void 0:n.size)>=2,[Me,Rt]=c.useState(""),[zt,It]=c.useState("idle"),[et,Xt]=c.useState(""),[$t,an]=c.useState([]),[He,j]=c.useState(""),[B,A]=c.useState("idle"),[D,F]=c.useState(""),[H,ke]=c.useState("idle"),[he,Re]=c.useState(""),[ye,Fe]=c.useState("idle"),[ce,it]=c.useState("");c.useEffect(()=>{const T=++v.current;if(I.current&&(clearInterval(I.current),I.current=null),fe("idle"),ve(""),!t||!e){p([]),E([]);return}if(S){p([]),E([]);return}X(!1),ne(""),b.current=!1,p([]),Promise.all([Fl(e,t.entry_uid),Ou(e,t.entry_uid)]).then(([J,ae])=>{T===v.current&&(p(J),E(ae))}).catch(()=>{})},[t,e,S]),c.useEffect(()=>()=>{clearInterval(I.current)},[]),c.useLayoutEffect(()=>{var J,ae,me;clearInterval(Ie.current),Ie.current=null,(J=st.current)==null||J.abort(),st.current=null,(ae=Ze.current)==null||ae.abort(),Ze.current=null;const T=(t==null?void 0:t.entry_uid)!=null&&((me=l==null?void 0:l.summary)==null?void 0:me.entry_uid)===(t==null?void 0:t.entry_uid);se(T?l.latest_summary??null:null),Y(T?l.summary_attempt??null:null),pe(""),te(!1),yt(!1)},[e,t==null?void 0:t.entry_uid,(We=l==null?void 0:l.summary)==null?void 0:We.entry_uid]);const dt=ie==null?void 0:ie.status;c.useEffect(()=>{var on;if(clearInterval(Ie.current),Ie.current=null,dt!=="pending"&&dt!=="running"||!e||!((on=l==null?void 0:l.summary)!=null&&on.entry_uid))return;const T=l.summary.entry_uid,J=`${e}:${T}`;if(Z!==J)return;const ae=new AbortController;st.current=ae;const $e=setInterval(async()=>{var xe;try{const un=await Yh(e,T,{signal:ae.signal});if(ae.signal.aborted||$.current!==J)return;se(un.summary??null),Y(un.attempt??null);const Ys=(xe=un.attempt)==null?void 0:xe.status;Ys!=="pending"&&Ys!=="running"&&(clearInterval($e),Ie.current===$e&&(Ie.current=null),te(!1),Ys==="completed"&&$.current===J&&(m==null||m()))}catch{if(ae.signal.aborted||$.current!==J)return}},Ng);return Ie.current=$e,()=>{clearInterval($e),Ie.current===$e&&(Ie.current=null),ae.abort(),st.current===ae&&(st.current=null)}},[dt,e,t==null?void 0:t.entry_uid,(je=l==null?void 0:l.summary)==null?void 0:je.entry_uid,Z]),c.useEffect(()=>()=>{var T,J;clearInterval(Ie.current),(T=st.current)==null||T.abort(),(J=Ze.current)==null||J.abort()},[]);async function Nr(T=!1){var $e,on;if(!e||!(($e=l==null?void 0:l.summary)!=null&&$e.entry_uid)||U)return;const J=l.summary.entry_uid,ae=`${e}:${J}`;if($.current!==ae)return;const me=new AbortController;(on=Ze.current)==null||on.abort(),Ze.current=me,te(!0),pe("");try{const xe=await Zh(e,J,{provider:re,force:T,includeImages:Lt,signal:me.signal});if(me.signal.aborted||$.current!==ae)return;xe.status==="completed"?(se(xe),Y(null),te(!1),$.current===ae&&(m==null||m())):Y({...xe??{},status:"pending"})}catch(xe){if(me.signal.aborted||$.current!==ae)return;pe(xe.message||"Summary request failed"),te(!1)}finally{Ze.current===me&&(Ze.current=null)}}function Ws(T){Ue(T),T==="claude_cli"&&yt(!1);try{sessionStorage.setItem(Uu,T)}catch{}}c.useEffect(()=>{if(!e){an([]);return}wo(e).then(an).catch(()=>an([]))},[e]),c.useEffect(()=>{Rt(""),It("idle"),Xt(""),j(""),A("idle"),F(""),ke("idle"),Re(""),Fe("idle"),it("")},[n]);async function Vs(){const T=n.size;if(!window.confirm(`Delete ${T} entr${T===1?"y":"ies"}? This cannot be undone.`))return;ke("running");const J=new Set;for(const ae of n)try{await Du(e,ae),J.add(ae)}catch{}ke("idle"),y==null||y(J)}async function kl(){const T=Me.trim();if(T){It("running"),Xt("");try{for(const J of n)await $u(e,J,T);Rt(""),It("done"),o==null||o(),setTimeout(()=>It("idle"),1800)}catch(J){Xt(J.message),It("error")}}}async function Ks(){if(!He)return;A("running"),F("");const T=[],J=$t.find(ae=>ae.collection_uid===He);for(const ae of n)try{await Sa(e,He,ae,(J==null?void 0:J.default_visibility_bits)??2)}catch{T.push(ae)}T.length>0?(F(`Failed for ${T.length} entr${T.length===1?"y":"ies"}.`),A("error")):(A("done"),setTimeout(()=>A("idle"),1800))}async function Qs(){if(!he||!t)return;Fe("running"),it("");const T=$t.find(J=>J.collection_uid===he);try{await Sa(e,he,t.entry_uid,(T==null?void 0:T.default_visibility_bits)??2),Fe("done"),Re("");const J=await Ou(e,t.entry_uid);E(J),setTimeout(()=>Fe("idle"),1800)}catch(J){it(J.message),Fe("error")}}async function Kn(){const T=Q.trim()||null;try{await lm(e,t.entry_uid,T),u==null||u(t.entry_uid,T)}catch{}finally{X(!1)}}async function Qn(){const T=f.trim();if(!(!T||!t))try{await $u(e,t.entry_uid,T),h(""),N("");const J=await Fl(e,t.entry_uid);p(J),o()}catch(J){N(J.message)}}async function Pn(T){try{await sm(e,t.entry_uid,T);const J=await Fl(e,t.entry_uid);p(J),o()}catch{}}async function jl(){if(!(!t||!e)&&window.confirm("Delete this entry? This cannot be undone."))try{await Du(e,t.entry_uid),d==null||d(t.entry_uid)}catch{}}async function qs(){if(!t||!e||q==="running")return;const T=v.current,J=t.entry_uid;fe("running"),ve("");try{const{job_uid:ae}=await $m(e,J);if(v.current!==T)return;I.current=setInterval(async()=>{try{const me=await uf(e,ae);if(me.status==="completed"){if(clearInterval(I.current),I.current=null,v.current!==T)return;fe("done");const $e=await Fl(e,J);if(v.current!==T)return;p($e),m==null||m()}else if(me.status==="failed"){if(clearInterval(I.current),I.current=null,v.current!==T)return;fe("error"),ve(me.error_text||"Re-archive failed.")}}catch{if(clearInterval(I.current),I.current=null,v.current!==T)return;fe("error"),ve("Network error while polling.")}},500)}catch(ae){if(v.current!==T)return;fe("error"),ve(ae.message||"Failed to start re-archive.")}}const Xs=l?[["Added",ko(l.summary.archived_at)],["Source",l.summary.source_kind],["Type",l.summary.entity_kind],["Visibility",Bu[l.summary.visibility]??l.summary.visibility],["Root",l.structured_root_relpath]]:[],Js=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),Gs=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv","pdf","html","htm","md","markdown","txt","jpg","jpeg","png","gif","webp","avif","svg","bmp"]),C=l?l.artifacts.findIndex(T=>T.artifact_role==="primary_media"):-1,z=C>=0?l.artifacts[C]:null,M=z?z.relpath.split(".").pop().toLowerCase():"",W=z&&Js.has(M),G=C>=0&&t?`/api/archives/${e}/entries/${t.entry_uid}/artifacts/${C}`:null,ue=l&&!W&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread"||z&&Gs.has(M));return s.jsxs("aside",{className:"context-rail",children:[s.jsx("div",{className:"rail-eyebrow",children:"Context"}),Ae?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"}),et&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:et}),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:Me,onChange:T=>Rt(T.target.value),onKeyDown:T=>{T.key==="Enter"&&kl()}}),s.jsx("button",{className:"tag-add-btn",onClick:kl,disabled:zt==="running"||!Me.trim(),children:zt==="running"?"…":zt==="done"?"✓":"Add"})]})]}),$t.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:He,onChange:T=>j(T.target.value),children:[s.jsx("option",{value:"",children:"Pick a collection…"}),$t.filter(T=>T.slug!=="_default_").map(T=>s.jsx("option",{value:T.collection_uid,children:T.name},T.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:Ks,disabled:!He||B==="running",children:B==="running"?"…":B==="done"?"✓":B==="error"?"!":"Add"})]}),D&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"6px 0 0"},children:D})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:Vs,disabled:H==="running",children:H==="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:xt(l.summary.title)||xt(l.summary.entry_uid)}):L?s.jsx("input",{className:"rail-title-input",autoFocus:!0,value:Q,onChange:T=>ne(T.target.value),onKeyDown:T=>{T.key==="Enter"&&T.currentTarget.blur(),T.key==="Escape"&&(b.current=!0,T.currentTarget.blur())},onBlur:()=>{b.current?X(!1):Kn(),b.current=!1}}):s.jsxs("h2",{className:"rail-title rail-title--editable",title:"Click to rename",onClick:()=>{ne(l.summary.title??""),X(!0)},children:[xt(l.summary.title)||xt(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:Us(l.summary.source_kind)}}),s.jsx("span",{className:"u-text",children:l.summary.original_url}),s.jsx("span",{className:"ext",children:s.jsx(Eg,{})})]}),W&&w&&s.jsx("button",{className:"rail-preview-btn",onClick:()=>w(G,t),children:"▶ Play"}),ue&&x&&s.jsx("button",{className:"rail-preview-btn",onClick:x,children:"Preview"}),(()=>{const T=(ee==null?void 0:ee.status)==="completed"?Cg(ee.summary_text):null,J=(ie==null?void 0:ie.status)==="pending"||(ie==null?void 0:ie.status)==="running",ae=(ie==null?void 0:ie.status)==="failed"&&ie.error_text===Hu||Ne===Hu;return S&&!T?null:s.jsxs("div",{className:"rail-section rail-summary",children:[s.jsx("div",{className:"rail-section-heading",children:"Summary"}),T&&s.jsxs("div",{className:"rail-summary-body",children:[T.tldr&&s.jsx("p",{className:"rail-summary-tldr",children:T.tldr}),T.summary&&s.jsx("p",{className:"rail-summary-text",children:T.summary}),T.tags.length>0&&s.jsx("div",{className:"rail-summary-tags",children:T.tags.map(me=>s.jsx("span",{className:"rail-summary-tag",children:me},me))}),s.jsxs("p",{className:"rail-summary-provider",children:[_g[ee.provider_kind]||ee.provider_kind,ee.resolved_model||ee.provider_model?` · ${ee.resolved_model||ee.provider_model}`:""]})]}),J&&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:yf}),s.jsx("p",{className:"rail-summary-info__detail",children:vf})]}),(ie==null?void 0:ie.status)==="failed"&&ie.error_text&&!ae&&!S&&s.jsx("p",{className:"form-msg form-msg--err rail-summary-error",children:ie.error_text}),Ne&&!ae&&s.jsx("p",{className:"form-msg form-msg--err rail-summary-error",children:Ne}),!S&&!J&&s.jsxs("div",{className:"rail-summary-controls",children:[s.jsx("select",{className:"rail-summary-select",value:re,onChange:me=>Ws(me.target.value),"aria-label":"Summary provider",children:es.map(me=>s.jsx("option",{value:me.value,children:me.label},me.value))}),s.jsxs("div",{className:`rail-summary-image-option${re==="claude_cli"?" rail-summary-image-option--disabled":""}`,children:[s.jsxs("label",{className:"rail-summary-image-option__label",children:[s.jsx("input",{type:"checkbox",checked:Lt,disabled:re==="claude_cli",onChange:me=>yt(me.target.checked)}),"Include attached images"]}),s.jsx("p",{className:"rail-summary-image-option__note",children:re==="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:()=>Nr(!!T),disabled:U,children:U?"…":T?"Regenerate":"Generate"})]})]})})(),s.jsx("div",{className:"meta-list",children:Xs.filter(([,T])=>T!=null&&T!=="").map(([T,J])=>s.jsxs("div",{className:"meta-item",children:[s.jsx("span",{className:"meta-k",children:T}),s.jsx("span",{className:`meta-v${T==="Root"?" mono":""}`,children:xt(J)})]},T))}),l.artifacts.length>0&&(()=>{const T=l.artifacts.map((xe,un)=>({...xe,_idx:un})),J=T.filter(xe=>xe.artifact_role==="font"),ae=T.filter(xe=>xe.artifact_role!=="font"),me=J.reduce((xe,un)=>xe+(un.byte_size||0),0),$e=l.summary.entry_uid,on=xe=>s.jsx("li",{children:s.jsxs("a",{href:`/api/archives/${e}/entries/${$e}/artifacts/${xe._idx}`,target:"_blank",rel:"noopener noreferrer",className:"artifact-link",children:[s.jsx("span",{className:"artifact-name",children:xe.artifact_role==="font"?xe.relpath.split("/").pop():xe.artifact_role.replace(/_/g," ")}),s.jsx("span",{className:"artifact-size",children:xe.byte_size!=null?ml(xe.byte_size):"—"})]})},xe._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(on),J.length>0&&s.jsxs("li",{className:"artifact-group",children:[s.jsxs("button",{type:"button",className:"artifact-group-header artifact-link","aria-expanded":R,onClick:()=>K(xe=>!xe),children:[s.jsxs("span",{className:"artifact-name",children:[s.jsx("span",{"aria-hidden":"true",className:`artifact-group-chevron${R?" open":""}`,children:"›"}),` fonts (${J.length})`]}),s.jsx("span",{className:"artifact-size",children:ml(me)})]}),R&&s.jsx("ul",{className:"artifact-list artifact-group-body",children:J.map(on)})]})]})]})})()]}):s.jsx("p",{className:"tags-empty",children:"Loading\\u2026"}):s.jsx("p",{className:"tags-empty",children:"Select an entry."}),t&&!Ae&&!S&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Tags"}),_.length===0?s.jsx("p",{className:"tags-empty",children:"No tags yet."}):s.jsx("div",{className:"tags-wrap",children:_.map(T=>s.jsxs("span",{className:"tag-pill",title:T.full_path,children:[g?pf(T.full_path):T.full_path,s.jsx("button",{className:"remove",title:`Remove tag ${T.full_path}`,onClick:()=>Pn(T.tag_uid),children:"×"})]},T.tag_uid))}),P&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:P}),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:T=>h(T.target.value),onKeyDown:T=>{T.key==="Enter"&&Qn()}}),s.jsx("button",{className:"tag-add-btn",onClick:Qn,children:"Add"})]})]}),(k.length>0||$t.filter(T=>T.slug!=="_default_").length>0)&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Collections"}),k.map(T=>s.jsxs("div",{className:"coll-row",children:[s.jsx("span",{className:"coll-name",children:T.name}),s.jsx("span",{className:"vis-badge",children:Bu[T.visibility_bits]??`bits:${T.visibility_bits}`})]},T.collection_uid)),$t.filter(T=>T.slug!=="_default_").length>0&&s.jsxs("div",{className:"bulk-coll-row",style:{marginTop:8},children:[s.jsxs("select",{className:"bulk-coll-select",value:he,onChange:T=>Re(T.target.value),children:[s.jsx("option",{value:"",children:"Add to collection…"}),$t.filter(T=>T.slug!=="_default_").map(T=>s.jsx("option",{value:T.collection_uid,children:T.name},T.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:Qs,disabled:!he||ye==="running",children:ye==="running"?"…":ye==="done"?"✓":ye==="error"?"!":"Add"})]}),ce&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"4px 0 0"},children:ce})]}),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:qs,disabled:q==="running",children:q==="running"?"Re-archiving…":"Re-archive"}),q==="done"&&s.jsx("p",{className:"form-msg form-msg--ok",style:{marginTop:"6px"},children:"Re-archived successfully."}),q==="error"&&s.jsx("p",{className:"form-msg form-msg--err",style:{marginTop:"6px"},children:Le})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:jl,children:"Delete entry"})})]})]})}const Tg=/\/api\/archives\/([^/]+)\/entries\/([^/]+)\/artifacts\/(\d+)/;function Pg(){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 Lg({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(Tg);if(!g){l(e);return}let m=!1;return l(null),Dm(g[1],g[2],parseInt(g[3],10)).then(({url:x})=>{m||l(x)}).catch(()=>{m||l(e)}),()=>{m=!0}},[e]),c.useEffect(()=>{n.current&&n.current.load()},[r]),c.useEffect(()=>{u(typeof HTMLVideoElement<"u"&&"webkitShowPlaybackTargetPicker"in HTMLVideoElement.prototype)},[]),c.useEffect(()=>{var m;const g=x=>{if(x)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((m=window.cast)!=null&&m.framework)g(!0);else if(window.__onGCastApiAvailable=g,!document.querySelector('script[src*="cast_sender"]')){const x=document.createElement("script");x.src="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1",document.head.appendChild(x)}},[]),c.useEffect(()=>{if(!i||!r)return;const g=cast.framework.CastContext.getInstance(),{CastContextEventType:m,SessionState:x}=cast.framework,w=_=>{if(!_)return;const p=new chrome.cast.media.MediaInfo(window.location.origin+r,t);_.loadMedia(new chrome.cast.media.LoadRequest(p)).catch(()=>{})};w(g.getCurrentSession());const S=_=>{(_.sessionState===x.SESSION_STARTED||_.sessionState===x.SESSION_RESUMED)&&w(g.getCurrentSession())};return g.addEventListener(m.SESSION_STATE_CHANGED,S),()=>g.removeEventListener(m.SESSION_STATE_CHANGED,S)},[i,r,t]);const d=()=>{var g,m;(m=(g=n.current)==null?void 0:g.webkitShowPlaybackTargetPicker)==null||m.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(Pg,{})}),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 Wu({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 Rg({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 xf(e){return e?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(new Date(e*1e3)):""}function Vu(e){return!e||!e.includes("&")?e:e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}const le={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"}},Ve={bg:"#000000",border:"#2f3336",text:"#e7e9ea",dim:"#71767b",accent:"#1d9bf0",codeBg:"#16181c"},Ti={article:{background:Ve.bg,color:Ve.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:Ve.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:Ve.border,flexShrink:0},aAuthorName:{fontSize:"15px",fontWeight:"700",color:Ve.text,lineHeight:"1.3"},aAuthorSub:{fontSize:"15px",color:Ve.dim,lineHeight:"1.3"},aDivider:{border:"none",borderTop:`1px solid ${Ve.border}`,margin:"0"},aBody:{padding:"4px 16px 0"},bH1:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:Ve.text,lineHeight:"36px",margin:"24px 0 10px"},bH2:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:Ve.text,lineHeight:"36px",margin:"24px 0 10px"},bP:{fontSize:"17px",color:Ve.text,lineHeight:"1.5",marginBottom:"16px",marginTop:"0"},bSpacer:{height:"6px",display:"block"},bQuote:{borderLeft:`3px solid ${Ve.border}`,padding:"2px 14px",margin:"14px 0",color:Ve.dim,fontSize:"17px",lineHeight:"1.5"},bHr:{border:"none",borderTop:`1px solid ${Ve.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:Ve.text,lineHeight:"1.5",marginBottom:"6px"},bTweet:{display:"flex",alignItems:"center",gap:"12px",border:`1px solid ${Ve.border}`,borderRadius:"12px",padding:"14px 16px",margin:"14px 0",color:Ve.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:Ve.text,background:"transparent"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:Ve.codeBg,padding:"2px 6px",borderRadius:"4px",color:"#e6edf3"},link:{color:Ve.accent,textDecoration:"none"}};function zg(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 wf(){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 kf(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 jf(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 Ku=/https?:\/\/[^\s<>"'\])]+/g,Ig=/[.,;:!?)()]+$/;function Ns(e,t){const n=[];let r=0,l;for(Ku.lastIndex=0;(l=Ku.exec(e))!==null;){l.index>r&&n.push(e.slice(r,l.index));let i=l[0].replace(Ig,"");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:(rkf(o,e)).filter(Boolean),...(t.user_mentions||[]).map(o=>jf(o,e)).filter(Boolean)];if(r.length===0&&n.length===0)return Ns(Vu(e),le.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(w=>w.s<=o&&w.e>=d),m=g.find(w=>w.kind==="url");if(m)return s.jsx("a",{href:m.href,target:"_blank",rel:"noopener noreferrer",style:le.link,children:m.display||y},u);const x=g.find(w=>w.kind==="mention");return x?s.jsx("a",{href:`https://x.com/${x.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:le.link,children:y},u):s.jsx("span",{children:Ns(Vu(y),le.link)},u)}).filter(o=>o!==null)}function Dg(e,t,n,r,l=le){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=kf(u,e);d&&i.push(d)}for(const u of r){const d=jf(u,e);d&&i.push(d)}if(i.length===0)return Ns(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(_=>_.s<=u&&_.e>=y),m=e.slice(u,y);let x;if(m.includes(` -`)){const _=m.split(` -`);x=_.flatMap((p,f)=>f<_.length-1?[p,s.jsx("br",{},f)]:[p])}else x=m;g.some(_=>_.kind==="style"&&_.style==="Code")&&(x=s.jsx("code",{style:l.iCode,children:x})),g.some(_=>_.kind==="style"&&_.style==="Bold")&&(x=s.jsx("strong",{children:x})),g.some(_=>_.kind==="style"&&_.style==="Italic")&&(x=s.jsx("em",{children:x})),g.some(_=>_.kind==="style"&&_.style==="Underline")&&(x=s.jsx("u",{children:x})),g.some(_=>_.kind==="style"&&_.style==="Strikethrough")&&(x=s.jsx("s",{children:x}));const w=g.find(_=>_.kind==="url");if(w){const _=/^https?:\/\/t\.co\//i.test(x);x=s.jsx("a",{href:w.href,target:"_blank",rel:"noopener noreferrer",style:l.link,children:_?w.display:x})}const S=g.find(_=>_.kind==="mention");return S&&(x=s.jsx("a",{href:`https://x.com/${S.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:l.link,children:x})),s.jsx("span",{children:typeof x=="string"?Ns(x,l.link):x},d)})}function Og(e,t,n){const r=(n==null?void 0:n.st)||le,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(wf,{}),"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)||le,i=e.type||"",a=e.text||"",o=e.inline_style_ranges||[],u=e.data||{},d=Dg(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(wf,{}),"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:Og(e,n,r)},t);default:return a?s.jsx("p",{style:l.bP,children:d},t):null}}function Ag(e,t,n){const r=(n==null?void 0:n.st)||le,l=[];let i=0;for(;i{r&&(l==null||l(!0))},[r,l]);const o=r?Ti:le,u=e.cover_media||{},d=e.author||t||{},y=e.first_published_at_secs?xf(e.first_published_at_secs):"",m=[d.screen_name?`@${d.screen_name}`:"",y].filter(Boolean).join(" · "),x=hr(u.local_path,u.url,n),w=hr(d.avatar_local_path,d.avatar_url,n),S=s.jsxs(s.Fragment,{children:[i&&s.jsx(Sf,{items:[{src:i,alt:""}],startIndex:0,onClose:()=>a(null)}),x&&s.jsx("a",{href:x,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:_=>{!_.metaKey&&!_.ctrlKey&&(_.preventDefault(),a(x))},children:s.jsx("img",{src:x,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:[w?s.jsx("img",{src:w,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"}),m&&s.jsx("div",{style:o.aAuthorSub,children:m})]})]})]}),s.jsx("hr",{style:o.aDivider}),s.jsx("div",{style:o.aBody,children:Ag(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:le.article,children:S})}function Fg({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:le.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]=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:le.lightboxBackdrop,onClick:n,children:s.jsxs("div",{style:le.lightboxContent,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{style:le.lightboxToolbar,children:[e.length>1&&s.jsxs("span",{style:le.lightboxCounter,children:[r+1," / ",e.length]}),s.jsx("a",{href:i.src,target:"_blank",rel:"noopener noreferrer",style:le.lightboxLink,title:"Open in new tab",children:"↗"}),s.jsx("button",{style:le.lightboxBtn,onClick:n,"aria-label":"Close",children:"×"})]}),s.jsx("img",{src:i.src,alt:i.alt||"",style:le.lightboxImg}),e.length>1&&s.jsxs("div",{style:le.lightboxNav,children:[s.jsx("button",{style:le.lightboxNavBtn,onClick:()=>l(a=>Math.max(a-1,0)),disabled:r===0,children:"‹"}),s.jsx("button",{style:le.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,h;const[l,i]=c.useState(null),a=e.author||{},o=e.created_at_secs?xf(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,m=t?le.tweetRowThread:le.tweetRow,x=e.full_text||"",w=((h=(f=e.extended_entities)==null?void 0:f.media)!=null&&h.length?e.extended_entities.media:u.media)||[],S=[],_=[];for(const k of w)if(k.type==="photo"){const E=hr(k.local_path,k.media_url_https,r);E&&S.push({kind:"photo",src:E,alt:k.alt_text||""})}else if(k.type==="video"||k.type==="animated_gif"){const E=k.local_path&&r[k.local_path]||(()=>{var N,v;return(v=(((N=k.video_info)==null?void 0:N.variants)||[]).filter(b=>b.content_type==="video/mp4").sort((b,L)=>(L.bitrate||0)-(b.bitrate||0))[0])==null?void 0:v.url})();E&&_.push({kind:k.type==="animated_gif"?"gif":"video",src:E})}const p=[];for(const k of w){if(!k.url||!(k.type==="photo"?S.some(N=>N.src===hr(k.local_path,k.media_url_https,r)):_.length>0))continue;const P=jo(k,x,k.url);P&&p.push([P.s,P.e])}return s.jsxs(s.Fragment,{children:[l!==null&&s.jsx(Sf,{items:S,startIndex:l,onClose:()=>i(null)}),s.jsxs("div",{style:m,children:[s.jsxs("div",{style:le.leftCol,children:[d?s.jsx("img",{src:d,style:le.avatar,alt:a.name||""}):s.jsx("div",{style:le.avatarPh}),y&&s.jsx("div",{style:le.threadLine})]}),s.jsxs("div",{style:le.rightCol,children:[s.jsxs("div",{style:le.authorRow,children:[s.jsx("span",{style:le.authorName,children:a.name||a.screen_name||"Unknown"}),a.screen_name&&s.jsxs("span",{style:le.authorHandle,children:["@",a.screen_name]}),o&&s.jsxs("span",{style:le.datePart,children:["· ",o]}),g&&s.jsx("span",{style:le.qtBadge,title:"Quote tweet",children:"↻ QT"})]}),s.jsx("div",{style:le.tweetText,children:$g(x,u,p)}),S.length>0&&s.jsx("div",{style:le.mediaGrid,children:s.jsx(Fg,{photos:S,onOpen:k=>i(k)})}),_.map((k,E)=>s.jsx("div",{style:le.mediaGrid,children:s.jsx("video",{src:k.src,style:le.mediaVideo,controls:!0,loop:k.kind==="gif",muted:k.kind==="gif",autoPlay:k.kind==="gif"})},E)),(e.retweet_count>0||e.favorite_count>0)&&s.jsxs("div",{style:le.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 Bg({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 w=n.map((_,p)=>({..._,index:p})).filter(_=>_.artifact_role==="raw_tweet_json");if(w.length===0){d("No tweet data found."),o(!1);return}let S=!1;return nm(e,t,w.map(_=>_.index)).then(async _=>{if(S)return;const p=/https?:\/\/t\.co\/[A-Za-z0-9]+/g,f=N=>{var b;const v=N.full_text||"";return(((b=N.entities)==null?void 0:b.urls)||[]).map(L=>{var X;if(L.fromIndex!=null&&L.toIndex!=null)return[L.fromIndex,L.toIndex];if(((X=L.indices)==null?void 0:X.length)===2)return[L.indices[0],L.indices[1]];if(L.url){const Q=v.indexOf(L.url);if(Q!==-1)return[Q,Q+L.url.length]}return null}).filter(Boolean)},h=(N,v,b)=>N.some(([L,X])=>L<=v&&X>=b),k=new Set;for(const N of _){const v=N.full_text||"",b=f(N);let L;for(p.lastIndex=0;(L=p.exec(v))!==null;)h(b,L.index,L.index+L[0].length)||k.add(L[0])}const E=k.size>0?await rm([...k]).catch(()=>({})):{},P=_.map(N=>{var Q;const v=N.full_text||"",b=f(N),L=[];let X;for(p.lastIndex=0;(X=p.exec(v))!==null;){const ne=X[0],q=E[ne];q&&q!==ne&&!h(b,X.index,X.index+ne.length)&&L.push({url:ne,expanded_url:q,display_url:(()=>{try{const fe=new URL(q);return fe.hostname+(fe.pathname.length>1?"/…":"")}catch{return q}})(),fromIndex:X.index,toIndex:X.index+ne.length})}return L.length===0?N:{...N,entities:{...N.entities||{},urls:[...((Q=N.entities)==null?void 0:Q.urls)||[],...L]}}});S||g(P)}).catch(_=>{S||d(_.message||"Failed to load tweet.")}).finally(()=>{S||o(!1)}),()=>{S=!0}},[e,t,n]),a)return s.jsx("div",{style:le.loading,children:"Loading…"});if(u)return s.jsxs("div",{style:le.error,children:["Error: ",u]});if(y.length===0)return null;const m=zg(e,t,n);if(r==="tweet_thread")return s.jsx("div",{style:le.threadOuter,children:y.map((w,S)=>s.jsx(Qu,{tweet:w,isInThread:!0,isLast:S===y.length-1,artifactMap:m},w.id||S))});const x=y[0];return x.is_article&&x.article?s.jsx(Mg,{article:x.article,tweetAuthor:x.author,artifactMap:m,fullPage:l,onXArticle:i}):s.jsx("div",{style:le.card,children:s.jsx(Qu,{tweet:x,isInThread:!1,isLast:!0,artifactMap:m})})}function Ug({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),em(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 Hg=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv"]),Wg=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),Vg=new Set(["jpg","jpeg","png","gif","webp","avif","svg","bmp"]),Kg=new Set(["md","markdown","txt"]),Qg={mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo",m4v:"video/mp4",ogv:"video/ogg"};function _f({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 x=s.jsx(Bg,{archiveId:e,entryUid:o,artifacts:a,entityKind:u,fullPage:r,onXArticle:l});return r?x:s.jsx("div",{className:"preview-tweet-wrap",children:x})}const d=a.findIndex(x=>x.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((x,w)=>s.jsxs("li",{children:[x.artifact_role,": ",x.relpath]},w))})]});const y=a[d],g=`/api/archives/${e}/entries/${o}/artifacts/${d}`,m=y.relpath.split(".").pop().toLowerCase();return Hg.has(m)?s.jsx("div",{className:"preview-panel",children:s.jsx(Lg,{src:g,contentType:Qg[m]||"video/mp4"})}):Wg.has(m)?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"}})]}):m==="pdf"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(Wu,{src:g,type:"pdf",title:i.title,originalUrl:i.original_url})}):m==="html"||m==="htm"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(Wu,{src:g,type:"page",title:i.title,originalUrl:i.original_url})}):Kg.has(m)?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0,overflow:"auto"},children:s.jsx(Ug,{src:g,mime:y.mime_type,title:i.title})}):Vg.has(m)?s.jsx("div",{className:"preview-panel",style:{height:"100%"},children:s.jsx(Rg,{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((x,w)=>s.jsxs("li",{children:[x.artifact_role,": ",x.relpath]},w))})]})}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(_f,{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 Xg({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,m]=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 x(){const f=l.current;f&&(i?f.pause():f.play().catch(()=>{}))}function w(f){const h=l.current;if(!h||!isFinite(d))return;const k=Number(f.target.value);h.currentTime=k,u(k)}function S(f){m(Number(f.target.value))}const _=(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:Us(p)}}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.85rem",color:"var(--ink)"},title:_,children:_})]}),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:x,"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:w,"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 Jg({archiveId:e,entryUid:t}){var m,x;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 w=document.documentElement,S=document.body,_=w.style.colorScheme,p=S.style.background;return w.style.colorScheme="dark",S.style.background="#000",()=>{w.style.colorScheme=_,S.style.background=p}},[u]),c.useEffect(()=>{d(!1),Mr(e,t).then(w=>{r(w),i(!1)}).catch(w=>{o((w==null?void 0:w.message)||"Failed to load entry"),i(!1)})},[e,t]);const y=((m=n==null?void 0:n.summary)==null?void 0:m.title)||t,g=(x=n==null?void 0:n.summary)==null?void 0:x.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(_f,{archiveId:e,entry:n.summary,detail:n,fullPage:!0,onXArticle:d})]})]})}const Gg=7e3;function Yg({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(ey,{toast:r,onDismiss:t,onIgnoreUblock:n},r.id))}):null}function Zg(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 ey({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),Gg);return()=>clearTimeout(u)},[r,e.id,t]);const o=Zg(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 Hs=c.createContext(null),ty=["archive","tags","collections","runs","admin","settings"],ny=["profile","tokens","instance","cookies","extensions","storage"],Ir=(()=>{const e=window.location.pathname.match(/^\/preview\/([^/]+)\/([^/]+)/);return e?{archiveId:e[1],entryUid:e[2]}:null})();function Wt(){const e=window.location.pathname.split("/").filter(Boolean),t=ty.includes(e[0])?e[0]:"archive",n=t==="settings"&&ny.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 ry(e,t){return e==="archive"?"/":e==="settings"?`/settings/${t}`:`/${e}`}function ly(){const[e,t]=c.useState("loading"),[n,r]=c.useState(null);c.useEffect(()=>{(async()=>{var M,W,G;if(await hm()){t("setup");return}const z=await cf();if(!z){const{collection:ue,archive:Ee}=Wt();try{const We=await Ru(),je=Ee?((M=We.find(T=>T.id===Ee))==null?void 0:M.id)??((W=We[0])==null?void 0:W.id):(G=We[0])==null?void 0:G.id;if(je){await zu(je,ue),i(We),o(je),d(ue),t("authenticated");return}}catch{}t("login");return}r(z),t("authenticated")})()},[]),c.useEffect(()=>{const C=()=>{n&&(r(null),t("login"))};return window.addEventListener("auth:expired",C),()=>window.removeEventListener("auth:expired",C)},[n]),c.useEffect(()=>{const C=()=>{const{view:z,settingsTab:M,q:W,tag:G,entry:ue,collection:Ee}=Wt();X(z),ne(M),fe(W),b(G),h(ue),E(null),N(ue?new Set([ue]):new Set),d(Ee)};return window.addEventListener("popstate",C),()=>window.removeEventListener("popstate",C)},[]);const[l,i]=c.useState([]),[a,o]=c.useState(null),[u,d]=c.useState(()=>Wt().collection),[y,g]=c.useState([]),[m,x]=c.useState([]),[w,S]=c.useState(()=>new Set),[_,p]=c.useState(()=>new Map),[f,h]=c.useState(()=>Wt().entry),[k,E]=c.useState(null),[P,N]=c.useState(()=>{const C=Wt().entry;return C?new Set([C]):new Set}),[v,b]=c.useState(()=>Wt().tag),[L,X]=c.useState(()=>Wt().view),[Q,ne]=c.useState(()=>Wt().settingsTab),[q,fe]=c.useState(()=>Wt().q),[Le,ve]=c.useState(""),[I,R]=c.useState(!1),[K,ee]=c.useState([]),[se,ie]=c.useState([]),[Y,Ne]=c.useState(()=>sessionStorage.getItem("captureDialogOpen")==="true"),[pe,U]=c.useState([]),te=c.useRef(0),[re,Ue]=c.useState(()=>{try{const C=JSON.parse(sessionStorage.getItem("pendingCaptures")||"[]");if(Array.isArray(C))return C}catch{}return[]});c.useEffect(()=>{sessionStorage.setItem("pendingCaptures",JSON.stringify(re))},[re]);const[Lt,yt]=c.useState(()=>sessionStorage.getItem("ublockWarningIgnored")==="true"),[Ie,st]=c.useState(null),Ze=c.useRef(0),$=c.useRef(null),Z=c.useRef(!1),Ae=c.useRef(!0),Me=c.useRef(null),Rt=c.useRef(0),zt=c.useRef(new Map),It=(n==null?void 0:n.humanize_slugs)??!1;c.useEffect(()=>{const C=++Ze.current;st(null),!(!k||!a)&&Mr(a,k.entry_uid).then(z=>{C===Ze.current&&st(z)}).catch(()=>{})},[k,a]),c.useEffect(()=>{sessionStorage.setItem("captureDialogOpen",Y)},[Y]);const et=c.useCallback(async(C,z,M,W)=>{if(C){R(!0);try{let G;z||M?G=await Gh(C,z,M,W):G=await zu(C,W),x(G),N(ue=>{if(ue.size<2)return ue;const Ee=new Set(G.map(je=>je.entry_uid)),We=new Set([...ue].filter(je=>Ee.has(je)));return We.size===ue.size?ue:We}),ve(G.length===0?"No results":`${G.length} result${G.length===1?"":"s"}`)}catch{x([]),ve("Search failed. Try again.")}finally{R(!1)}}},[]);c.useEffect(()=>{e==="authenticated"&&(a||Ru().then(C=>{if(i(C),C.length>0){const{archive:z}=Wt(),M=z?C.find(W=>W.id===z):null;o((M==null?void 0:M.id)??C[0].id)}}))},[e,a]),c.useEffect(()=>{if(!a)return;const C=!n;if(Ae.current){Ae.current=!1;const M=[];C||(M.push(Ni(a).then(ee)),M.push(Bl(a).then(ie))),M.length&&Promise.all(M);return}b(null),E(null),h(null),N(new Set),d(null);const z=[et(a,"",null,null)];C||(z.push(Ni(a).then(ee)),z.push(Bl(a).then(ie))),Promise.all(z)},[a,n]),c.useEffect(()=>{if(a===null)return;const C=setTimeout(()=>{et(a,q,v,u)},300);return()=>clearTimeout(C)},[q,a,u]),c.useEffect(()=>{a!==null&&(v!==null&&X("archive"),et(a,q,v,u))},[v,a,u]);const Xt=c.useCallback(C=>{o(C),d(null);const z=new URLSearchParams(window.location.search);z.set("archive",C),z.delete("collection");const M=z.toString();history.replaceState(null,"",window.location.pathname+(M?"?"+M:""))},[]);c.useEffect(()=>{if(!a){g([]);return}wo(a).then(g).catch(()=>g([]))},[a]);const $t=c.useCallback(C=>{if(!n){const W=C?y.find(G=>G.collection_uid===C):y.find(G=>G.slug==="_default_");if(W!=null&&W.requires_auth){t("login");return}}d(C),E(null),h(null),N(new Set),et(a,q,v,C);const z=new URLSearchParams(window.location.search);C?(z.set("collection",C),z.set("archive",a)):(z.delete("collection"),a&&z.set("archive",a));const M=z.toString();history.replaceState(null,"",window.location.pathname+(M?"?"+M:""))},[a,q,v,n,y,et]),an=c.useCallback(C=>{X(C),C==="tags"&&a&&Bl(a).then(ie)},[a]);c.useEffect(()=>{if(Ir)return;const C=ry(L,Q);window.location.pathname!==C&&history.pushState(null,"",C+window.location.search)},[L,Q]);const He=c.useCallback(C=>{h(C?C.entry_uid:null),E(C)},[]),j=c.useCallback((C,z)=>{if(zt.current.set(C.entry_uid,C),++Rt.current,z.shiftKey&&Me.current!==null){z.preventDefault();const M=[...document.querySelectorAll("#entries-body [data-entry-uid]")],W=M.findIndex(je=>je.dataset.entryUid===Me.current),G=M.findIndex(je=>je.dataset.entryUid===C.entry_uid);if(W===-1||G===-1){Me.current=C.entry_uid,N(new Set([C.entry_uid])),He(C);return}const ue=Math.min(W,G),Ee=Math.max(W,G),We=new Set(M.slice(ue,Ee+1).map(je=>je.dataset.entryUid));N(We),We.size===1&&He(C)}else if(z.ctrlKey||z.metaKey){Me.current=C.entry_uid;const M=new Set(P);if(M.has(C.entry_uid)?M.delete(C.entry_uid):M.add(C.entry_uid),N(M),M.size===0)He(null);else if(M.size===1){const[W]=M,G=zt.current.get(W)??m.find(ue=>ue.entry_uid===W)??null;if(G)He(G);else{const ue=++Rt.current;Mr(a,W).then(Ee=>{ue===Rt.current&&(Ee!=null&&Ee.summary)&&He(Ee.summary)}).catch(()=>{})}}else He(null)}else Me.current=C.entry_uid,N(new Set([C.entry_uid])),He(C)},[m,P,He,a]),B=c.useCallback(C=>{b(C)},[]),A=c.useCallback(()=>{b(null)},[]),D=c.useCallback(()=>{a&&Bl(a).then(ie)},[a]),F=c.useCallback((C,z)=>{v===C?b(z):v!=null&&v.startsWith(C+"/")&&b(z+v.slice(C.length))},[v]),H=c.useCallback(C=>{(v===C||v!=null&&v.startsWith(C+"/"))&&b(null)},[v]),ke=c.useCallback((C,z)=>{p(W=>new Map(W).set(C,z));const M=zt.current.get(C);M&&zt.current.set(C,{...M,title:z}),x(W=>W.map(G=>G.entry_uid===C?{...G,title:z}:G)),E(W=>W&&W.entry_uid===C?{...W,title:z}:W),st(W=>W&&W.summary.entry_uid===C?{...W,summary:{...W.summary,title:z}}:W)},[]),he=c.useCallback(()=>{if(!a||!k)return;const C=++Ze.current;Mr(a,k.entry_uid).then(z=>{C===Ze.current&&st(z)}).catch(()=>{})},[a,k]),Re=c.useCallback(C=>{const z=m.some(M=>M.entry_uid===C);S(M=>{const W=new Set(M);return W.add(C),W}),x(M=>M.filter(W=>W.entry_uid!==C)),E(M=>(M==null?void 0:M.entry_uid)===C?null:M),h(M=>M===C?null:M),N(M=>{const W=new Set(M);return W.delete(C),W}),z||et(a,q,v,u)},[m,a,q,v,u,et]),ye=c.useCallback(C=>{const z=new Set(m.map(W=>W.entry_uid)),M=[...C].some(W=>!z.has(W));S(W=>{const G=new Set(W);return C.forEach(ue=>G.add(ue)),G}),x(W=>W.filter(G=>!C.has(G.entry_uid))),N(new Set),E(null),h(null),M&&et(a,q,v,u)},[m,a,q,v,u,et]);c.useEffect(()=>{if(P.size>=2)h(null),E(null);else if(P.size===1){const[C]=P;h(C)}else h(null),E(null)},[P]);const Fe=c.useMemo(()=>m.filter(C=>P.has(C.entry_uid)),[m,P]);c.useEffect(()=>{if(!f||k)return;const C=m.find(z=>z.entry_uid===f);C&&E(C)},[m,f,k]),c.useEffect(()=>{if(Ir)return;const C=new URLSearchParams(window.location.search).get("archive"),z=new URLSearchParams;q&&z.set("q",q),L==="archive"&&v&&z.set("tag",v),L==="archive"&&f&&z.set("entry",f),L==="archive"&&u?(z.set("collection",u),a&&z.set("archive",a)):C&&a&&z.set("archive",a);const M=z.toString(),W=window.location.pathname+(M?"?"+M:"");window.location.pathname+window.location.search!==W&&history.replaceState(null,"",W)},[q,v,f,u,a,L]),c.useEffect(()=>{const C=z=>{var ue,Ee,We,je;const M=z.key==="/"&&!z.metaKey&&!z.ctrlKey&&!z.altKey,W=(z.metaKey||z.ctrlKey)&&z.key==="k";if(!M&&!W)return;const G=(ue=document.activeElement)==null?void 0:ue.tagName;M&&(G==="INPUT"||G==="TEXTAREA"||G==="SELECT")||M&&((Ee=document.activeElement)!=null&&Ee.isContentEditable)||(z.preventDefault(),L==="archive"?((We=$.current)==null||We.focus(),(je=$.current)==null||je.select()):(Z.current=!0,X("archive")))};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[L]),c.useEffect(()=>{const C=z=>{var ae,me;if(z.metaKey||z.ctrlKey||z.altKey||z.key!=="j"&&z.key!=="k")return;const M=(ae=document.activeElement)==null?void 0:ae.tagName;if(M==="INPUT"||M==="TEXTAREA"||M==="SELECT"||(me=document.activeElement)!=null&&me.isContentEditable)return;const W=[...document.querySelectorAll("#entries-body [data-entry-uid]")];if(W.length===0)return;const[G]=P.size===1?P:[null],ue=G?W.findIndex($e=>$e.dataset.entryUid===G):-1,Ee=z.key==="j"?Math.min(ue+1,W.length-1):Math.max(ue-1,0);if(Ee===ue&&ue!==-1)return;const We=W[Ee<0?0:Ee],je=We.dataset.entryUid;Me.current=je;const T=++Rt.current;N(new Set([je]));const J=zt.current.get(je)??m.find($e=>$e.entry_uid===je)??null;J?He(J):Mr(a,je).then($e=>{T===Rt.current&&($e!=null&&$e.summary)&&He($e.summary)}).catch(()=>{}),We.scrollIntoView({block:"nearest"}),z.preventDefault()};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[P,m,He,a]),c.useEffect(()=>{L==="archive"&&Z.current&&(Z.current=!1,requestAnimationFrame(()=>{var C,z;(C=$.current)==null||C.focus(),(z=$.current)==null||z.select()}))},[L]);const ce=c.useCallback(()=>{Ne(!0)},[]),it=c.useCallback(()=>{Ne(!1)},[]),dt=c.useCallback(()=>{if(a)return Promise.allSettled([et(a,q,v,u),Ni(a).then(ee)])},[a,q,v,u,et]),Nr=c.useCallback((C,z,M="error",W=null)=>{if(M==="warning"&&Lt&&z)return;const G=++te.current;U(ue=>[...ue,{id:G,text:C,locator:z,type:M,headline:W}])},[Lt]),Ws=c.useCallback(C=>{U(z=>z.filter(M=>M.id!==C))},[]),Vs=c.useCallback(C=>{Nr(C,null,"error","Reorder failed")},[Nr]),kl=c.useCallback(()=>{sessionStorage.setItem("ublockWarningIgnored","true"),yt(!0),U(C=>C.filter(z=>!(z.type==="warning"&&z.locator)))},[]),Ks=c.useCallback(C=>{Ue(z=>[...z,C])},[]),Qs=c.useCallback(C=>{Ue(z=>z.filter(M=>M.id!==C))},[]),[Kn,Qn]=c.useState(null),[Pn,jl]=c.useState(null),qs=c.useCallback(()=>{k&&Qn(k.entry_uid)},[k]),Xs=c.useCallback(()=>Qn(null),[]),Js=c.useCallback((C,z)=>{jl({src:C,entry:z})},[]),Gs=c.useCallback(()=>jl(null),[]);return c.useEffect(()=>{Qn(null)},[k]),c.useEffect(()=>{const C=z=>{var W,G,ue;if(z.key!=="Escape"||Y||Kn)return;const M=(W=document.activeElement)==null?void 0:W.tagName;M==="INPUT"||M==="TEXTAREA"||M==="SELECT"||P.size>0&&(z.preventDefault(),N(new Set),(ue=(G=document.activeElement)==null?void 0:G.blur)==null||ue.call(G))};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[Y,Kn,P]),c.useEffect(()=>(document.body.classList.toggle("has-audio-bar",!!Pn),()=>document.body.classList.remove("has-audio-bar")),[Pn]),Ir?s.jsx(Jg,{archiveId:Ir.archiveId,entryUid:Ir.entryUid}):e==="loading"?s.jsx("div",{className:"auth-loading",children:"Loading\\u2026"}):e==="setup"?s.jsx(Wm,{onComplete:()=>t("login")}):e==="login"?s.jsx(Hm,{onLogin:C=>{r(C),t("authenticated")}}):s.jsx(Hs.Provider,{value:{currentUser:n,setCurrentUser:r},children:s.jsxs(s.Fragment,{children:[s.jsx(Vm,{archives:l,archiveId:a,onArchiveChange:Xt,view:L,onViewChange:an,onCaptureClick:ce,collections:y,selectedCollectionUid:u,onCollectionChange:$t,isPublicSession:!n,onSignInClick:()=>t("login")}),s.jsxs("main",{className:"app-shell",children:[s.jsxs("div",{className:"workspace",children:[L==="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:$,className:"search-input",type:"search","aria-label":"Search archive","aria-busy":I,placeholder:"Search titles, URLs, types, tags…",value:q,onChange:C=>fe(C.target.value)}),s.jsx("span",{className:"kbd",children:"⌘K"})]}),s.jsxs("span",{className:"result-count",children:[Le&&s.jsxs(s.Fragment,{children:[s.jsx("b",{children:Le.split(" ")[0]})," ",Le.split(" ").slice(1).join(" ")]}),v&&s.jsxs("button",{className:"tag-filter-badge",onClick:A,children:["× ",It?pf(v):v]})]})]}),L==="archive"&&s.jsx(ig,{entries:m,selectedUids:P,onRowClick:j,archiveId:a,pendingCaptures:re,deletedUids:w,renamedTitles:_,isPublicSession:!n,canReorder:!!(n!=null&&n.can_reorder_children),onChildReorderError:Vs}),L==="runs"&&s.jsx(ug,{runs:K}),L==="admin"&&s.jsx(dg,{archives:l}),L==="tags"&&s.jsx(fg,{archiveId:a,tagNodes:se,tagFilter:v,onTagFilterSet:B,onViewChange:an,onTagRenamed:F,onTagDeleted:H,onTagsRefresh:D,humanizeTags:It}),L==="collections"&&s.jsx(hg,{archiveId:a}),L==="settings"&&s.jsx(yg,{tab:Q,onTabChange:ne,archiveId:a})]}),s.jsx(bg,{archiveId:a,selectedEntry:k,selectedUids:P,selectedEntries:Fe,detail:Ie,onTagFilterSet:B,tagNodes:se,onTagsRefresh:D,onEntryTitleChange:ke,onEntryDeleted:Re,onBulkDeleted:ye,humanizeTags:It,onDetailRefresh:he,onOpenPreview:qs,onPlay:Js,isPublicSession:!n})]}),Kn&&k&&k.entry_uid===Kn&&s.jsx(qg,{archiveId:a,entry:k,detail:Ie,onClose:Xs}),Pn&&s.jsx(Xg,{entry:Pn.entry,src:Pn.src,archiveId:a,onClose:Gs}),s.jsx(Xm,{open:Y,archiveId:a,onClose:it,onCaptured:dt,onToast:Nr,activeJobs:re,onJobStarted:Ks,onJobSettled:Qs}),s.jsx(Yg,{toasts:pe,onDismiss:Ws,onIgnoreUblock:kl})]})})}of(document.getElementById("root")).render(s.jsx(c.StrictMode,{children:s.jsx(ly,{})})); diff --git a/crates/archivr-server/static/assets/index-CQKWq7vB.css b/crates/archivr-server/static/assets/index-CQKWq7vB.css deleted file mode 100644 index 448f473..0000000 --- a/crates/archivr-server/static/assets/index-CQKWq7vB.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-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}.child-reorder-controls{display:inline-flex;align-items:center;gap:4px;flex-shrink:0;transition:opacity .15s}.child-drag-handle{display:none;cursor:grab;padding:0 3px;font-size:.8em;letter-spacing:-2px;-webkit-user-select:none;user-select:none;color:var(--muted)}.child-drag-handle:active{cursor:grabbing}.child-move-btn{width:28px;height:28px;padding:0;border:none;background:none;color:inherit;font-size:.9em;line-height:1;cursor:pointer}.child-move-btn:disabled{opacity:.3;cursor:default}.child-move-btn:focus{outline:none}.child-move-btn:focus-visible{outline:2px solid var(--accent);outline-offset:1px;border-radius:2px}@media (hover: hover) and (pointer: fine) and (min-width: 641px){.child-reorder-controls{gap:1px;opacity:.3}.child-entry-row:hover .child-reorder-controls,.child-entry-row:focus-within .child-reorder-controls{opacity:1}.child-drag-handle{display:inline}.child-move-btn{display:none}}.child-entry-row.is-dragging{opacity:.4}.child-entry-row.is-drop-before{box-shadow:inset 0 2px 0 var(--accent)}.child-entry-row.is-drop-after{box-shadow:inset 0 -2px 0 var(--accent)}.child-entries[aria-busy=true] .child-entry-row{cursor:progress}.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/index.html b/crates/archivr-server/static/index.html index a8b7f0e..8f14403 100644 --- a/crates/archivr-server/static/index.html +++ b/crates/archivr-server/static/index.html @@ -6,8 +6,8 @@ Archivr - - + +
diff --git a/frontend/src/components/ContextRail.jsx b/frontend/src/components/ContextRail.jsx index 3c2f685..9280fc3 100644 --- a/frontend/src/components/ContextRail.jsx +++ b/frontend/src/components/ContextRail.jsx @@ -697,15 +697,16 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se )}
-

Export

+
Actions
+
- )} {(() => { // Public sessions get read-only treatment: the completed text if the @@ -1047,43 +1043,52 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se
)} - {detail && (detail.summary.entity_kind === 'tweet' || detail.summary.entity_kind === 'tweet_thread') && ( -
-
Actions
- - {rearchiveState === 'done' && ( -

Re-archived successfully.

- )} - {rearchiveState === 'error' && ( -

{rearchiveError}

- )} - {detail.summary.entity_kind === 'tweet_thread' && ( - <> - - {titleGenState === 'done' && ( -

Title updated.

- )} - {titleGenState === 'error' && ( -

{titleGenError}

- )} - - )} -
- )} +
+
Actions
+ {detail && (detail.summary.entity_kind === 'tweet' || detail.summary.entity_kind === 'tweet_thread') && ( + <> + + {rearchiveState === 'done' && ( +

Re-archived successfully.

+ )} + {rearchiveState === 'error' && ( +

{rearchiveError}

+ )} + {detail.summary.entity_kind === 'tweet_thread' && ( + <> + + {titleGenState === 'done' && ( +

Title updated.

+ )} + {titleGenState === 'error' && ( +

{titleGenError}

+ )} + + )} + + )} + +
"); diff --git a/crates/archivr-core/src/export/mod.rs b/crates/archivr-core/src/export/mod.rs index 0687701..36687ff 100644 --- a/crates/archivr-core/src/export/mod.rs +++ b/crates/archivr-core/src/export/mod.rs @@ -1,4 +1,4 @@ -//! Entry export: HTML ZIP, PDF, Markdown ZIP. +//! Entry export: HTML ZIP and Markdown ZIP. //! //! The public entry point is [`export_entries`]. @@ -7,7 +7,6 @@ mod bundle; mod html; mod markdown; mod model; -mod pdf; use std::collections::HashMap; use std::fs; @@ -32,7 +31,6 @@ use crate::process; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ExportFormat { Html, - Pdf, Markdown, } @@ -40,7 +38,6 @@ impl ExportFormat { pub fn parse(s: &str) -> Option { match s.to_lowercase().as_str() { "html" => Some(Self::Html), - "pdf" => Some(Self::Pdf), "markdown" => Some(Self::Markdown), _ => None, } @@ -202,7 +199,7 @@ pub fn export_entries( // 7. Dispatch. let (out_path, filename, content_type) = - assemble(&entries, options, &wpath, &posters, &paths.store_path)?; + assemble(&entries, options, &wpath, &posters)?; Ok(ExportFile { path: out_path, @@ -374,7 +371,6 @@ fn assemble( options: &ExportOptions, work_dir: &Path, posters: &HashMap, - store_path: &Path, ) -> Result<(PathBuf, String, &'static str)> { let date = Utc::now().format("%Y-%m-%d").to_string(); let n = entries.len(); @@ -384,7 +380,6 @@ fn assemble( ExportFormat::Markdown => { assemble_markdown(entries, options, work_dir, posters, &date, n) } - ExportFormat::Pdf => assemble_pdf(entries, options, work_dir, posters, store_path, &date, n), } } @@ -503,74 +498,6 @@ fn assemble_markdown( } } -// --------------------------------------------------------------------------- -// PDF assembly -// --------------------------------------------------------------------------- - -fn assemble_pdf( - entries: &[model::ExportEntry], - options: &ExportOptions, - work_dir: &Path, - posters: &HashMap, - _store_path: &Path, - date: &str, - n: usize, -) -> Result<(PathBuf, String, &'static str)> { - if n == 1 { - let slug = entry_slug(entries[0].summary.title.as_deref().unwrap_or("")); - let filename = format!("{slug}.pdf"); - let pdf_path = work_dir.join(&filename); - let entry_path = - pdf::entry_pdf(&entries[0], 0, options.include_credit, work_dir, posters)?; - fs::rename(&entry_path, &pdf_path) - .or_else(|_| fs::copy(&entry_path, &pdf_path).map(|_| ()))?; - return Ok((pdf_path, filename, "application/pdf")); - } - - match options.layout { - ExportLayout::Together => { - let filename = format!("export-{n}-entries-{date}.pdf"); - let out = work_dir.join(&filename); - - // Cover page. - let cover_html = html::render_cover(entries, options.include_credit); - let cover_html_path = work_dir.join("cover.html"); - fs::write(&cover_html_path, &cover_html)?; - let cover_pdf_path = work_dir.join("cover.pdf"); - let profile_dir = work_dir.join("chrome-profile"); - fs::create_dir_all(&profile_dir)?; - pdf::print_pdf(&cover_html_path, &cover_pdf_path, &profile_dir)?; - - // Per-entry PDFs (no credit: it's on the cover). - let mut pdf_paths: Vec = vec![cover_pdf_path]; - for (i, entry) in entries.iter().enumerate() { - let p = pdf::entry_pdf(entry, i, false, work_dir, posters)?; - pdf_paths.push(p); - } - - pdf::merge_pdf_files(&pdf_paths, &out)?; - Ok((out, filename, "application/pdf")) - } - ExportLayout::Separate => { - // A ZIP of individual PDFs. - let outer = format!("export-{date}"); - let filename = format!("export-{n}-entries-{date}.zip"); - let zip_path = work_dir.join(&filename); - - let mut pdf_names: Vec<(String, PathBuf)> = Vec::new(); - for (i, entry) in entries.iter().enumerate() { - let nn = format!("{:02}", i + 1); - let slug = entry_slug(entry.summary.title.as_deref().unwrap_or("")); - let pdf_path = pdf::entry_pdf(entry, i, options.include_credit, work_dir, posters)?; - let name_in_zip = format!("{nn}-{slug}.pdf"); - pdf_names.push((name_in_zip, pdf_path)); - } - - bundle::write_pdf_zip(&zip_path, &outer, &pdf_names)?; - Ok((zip_path, filename, "application/zip")) - } - } -} // --------------------------------------------------------------------------- // Asset collection @@ -762,7 +689,6 @@ pub fn prune_stale_export_dirs(store_path: &Path, older_than: Duration) { #[cfg(test)] mod tests { use super::*; - use super::pdf::merge_documents; use crate::archive::initialize_archive; use crate::database; @@ -1031,45 +957,4 @@ mod tests { assert_eq!(entry_slug("my-entry"), "my-entry"); } - #[test] - fn test_merge_pdfs_page_count() { - use lopdf::{Dictionary, Document, Object, Stream}; - let make_doc = |content: &[u8]| -> Document { - let mut doc = Document::with_version("1.4"); - let stream_id = doc.add_object(Object::Stream(Stream::new(Dictionary::new(), content.to_vec()))); - let mut page_dict = Dictionary::new(); - page_dict.set("Type", Object::Name(b"Page".to_vec())); - page_dict.set("Contents", Object::Reference(stream_id)); - page_dict.set("MediaBox", Object::Array(vec![ - Object::Integer(0), Object::Integer(0), - Object::Integer(612), Object::Integer(792), - ])); - let page_id = doc.add_object(Object::Dictionary(page_dict)); - let mut pages_dict = Dictionary::new(); - pages_dict.set("Type", Object::Name(b"Pages".to_vec())); - pages_dict.set("Kids", Object::Array(vec![Object::Reference(page_id)])); - pages_dict.set("Count", Object::Integer(1)); - let pages_id = doc.add_object(Object::Dictionary(pages_dict)); - if let Some(Object::Dictionary(pd)) = doc.objects.get_mut(&page_id) { - pd.set("Parent", Object::Reference(pages_id)); - } - let mut catalog = Dictionary::new(); - catalog.set("Type", Object::Name(b"Catalog".to_vec())); - catalog.set("Pages", Object::Reference(pages_id)); - let catalog_id = doc.add_object(Object::Dictionary(catalog)); - doc.trailer.set("Root", Object::Reference(catalog_id)); - doc - }; - - let doc1 = make_doc(b"BT /F1 12 Tf 100 700 Td (Page one) Tj ET"); - let doc2_p1 = make_doc(b"BT /F1 12 Tf 100 700 Td (Page two) Tj ET"); - let doc2_p2 = make_doc(b"BT /F1 12 Tf 100 700 Td (Page three) Tj ET"); - - let doc2 = merge_documents(vec![doc2_p1, doc2_p2]).unwrap(); - let mut merged = merge_documents(vec![doc1, doc2]).unwrap(); - let mut bytes: Vec = Vec::new(); - merged.save_to(&mut bytes).unwrap(); - let reloaded = lopdf::Document::load_mem(&bytes).unwrap(); - assert_eq!(reloaded.get_pages().len(), 3, "merged PDF should have 3 pages"); - } } diff --git a/crates/archivr-core/src/export/pdf.rs b/crates/archivr-core/src/export/pdf.rs deleted file mode 100644 index 39364c7..0000000 --- a/crates/archivr-core/src/export/pdf.rs +++ /dev/null @@ -1,395 +0,0 @@ -//! PDF generation via headless Chrome and lopdf merging. - -use std::collections::HashMap; -use std::ffi::OsString; -use std::path::{Path, PathBuf}; -use std::time::Duration; - -use anyhow::{Context, Result, bail}; -use lopdf::{Dictionary, Document, Object, ObjectId, Stream}; - -use crate::env_config::{env_or, env_timeout}; -use crate::export::brand; -use crate::export::html::{AssetMode, entry_title, render_document, source_label}; -use crate::export::model::{Asset, ExportBody, ExportEntry}; -use crate::process; - -// --------------------------------------------------------------------------- -// Chrome PDF printing -// --------------------------------------------------------------------------- - -/// Print an HTML file to PDF using headless Chrome. -pub(crate) fn print_pdf(html_path: &Path, out: &Path, profile_dir: &Path) -> Result<()> { - let chrome = env_or("ARCHIVR_CHROME", "chromium"); - let chrome_path = PathBuf::from(&chrome); - - let timeout_secs = env_timeout("ARCHIVR_EXPORT_PDF_TIMEOUT", 120); - - let extra_args: Vec = std::env::var("ARCHIVR_CHROME_ARGS") - .unwrap_or_default() - .split_whitespace() - .filter(|s| !s.is_empty()) - .map(str::to_string) - .collect(); - - let html_url = percent_encode_path(html_path); - - let mut args: Vec = vec![ - "--headless=new".into(), - "--disable-gpu".into(), - "--no-first-run".into(), - "--no-default-browser-check".into(), - "--hide-scrollbars".into(), - format!("--user-data-dir={}", profile_dir.display()).into(), - "--no-pdf-header-footer".into(), - "--run-all-compositor-stages-before-draw".into(), - "--virtual-time-budget=15000".into(), - format!("--print-to-pdf={}", out.display()).into(), - ]; - for a in &extra_args { - args.push(a.into()); - } - args.push(html_url.into()); - - process::run_with_timeout(&chrome_path, &args, None, Duration::from_secs(timeout_secs)) - .with_context(|| "PDF export needs Chromium: set ARCHIVR_CHROME")?; - - if !out.exists() || out.metadata().map(|m| m.len()).unwrap_or(0) == 0 { - bail!( - "Chromium produced no PDF (set ARCHIVR_CHROME to a Chromium/Chrome binary); \ - tried: {chrome}" - ); - } - Ok(()) -} - -fn percent_encode_path(path: &Path) -> String { - let s = path.to_string_lossy(); - let mut out = String::with_capacity(s.len() + 7); - out.push_str("file://"); - for byte in s.as_bytes() { - match byte { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'/' | b'.' | b'_' | b'-' | b'~' => { - out.push(*byte as char) - } - b => out.push_str(&format!("%{b:02X}")), - } - } - out -} - -// --------------------------------------------------------------------------- -// lopdf merging -// --------------------------------------------------------------------------- - -/// Merge PDF files on disk into a single output PDF. -pub(crate) fn merge_pdf_files(inputs: &[PathBuf], output: &Path) -> Result<()> { - if inputs.is_empty() { - bail!("merge_pdf_files: no inputs"); - } - if inputs.len() == 1 { - std::fs::copy(&inputs[0], output) - .with_context(|| format!("failed to copy PDF to {}", output.display()))?; - return Ok(()); - } - - let docs: Vec = inputs - .iter() - .map(|p| Document::load(p).with_context(|| format!("failed to load PDF: {}", p.display()))) - .collect::>>()?; - - let mut merged = merge_documents(docs)?; - merged - .save(output) - .with_context(|| format!("failed to save merged PDF to {}", output.display()))?; - Ok(()) -} - -/// Merge multiple `Document` values into one, appending pages in order. -/// -/// Follows the lopdf `examples/merge.rs` pattern: each source document's -/// object IDs are shifted by an offset so they do not collide, then all -/// objects are copied into a fresh document with a new Pages tree and Catalog. -pub(crate) fn merge_documents(docs: Vec) -> Result { - if docs.is_empty() { - bail!("merge_documents: no documents provided"); - } - if docs.len() == 1 { - return Ok(docs.into_iter().next().unwrap()); - } - - let mut merged = Document::with_version("1.5"); - let mut all_page_ids: Vec = Vec::new(); - // next_id tracks the next free object number so we can assign the Pages - // and Catalog objects after all source objects have been copied in. - let mut next_id: u32 = 0; - - for doc in docs { - let offset = next_id; - - // Collect pages in page-number order before we consume the doc. - let pages = doc.get_pages(); // BTreeMap - for (_page_num, page_oid) in &pages { - all_page_ids.push((page_oid.0 + offset, page_oid.1)); - } - - let doc_max = doc.objects.keys().map(|(n, _)| *n).max().unwrap_or(0); - - for (oid, obj) in &doc.objects { - let new_oid: ObjectId = (oid.0 + offset, oid.1); - let remapped = remap_refs(obj, offset); - merged.objects.insert(new_oid, remapped); - } - - next_id += doc_max + 1; - } - - // Build the Pages dictionary. - let pages_oid: ObjectId = (next_id, 0); - next_id += 1; - - // Point every collected page at the new Pages parent. - for page_id in &all_page_ids { - if let Some(Object::Dictionary(dict)) = merged.objects.get_mut(page_id) { - dict.set("Parent", Object::Reference(pages_oid)); - } - } - - let mut pages_dict = Dictionary::new(); - pages_dict.set("Type", Object::Name(b"Pages".to_vec())); - pages_dict.set( - "Kids", - Object::Array(all_page_ids.iter().map(|id| Object::Reference(*id)).collect()), - ); - pages_dict.set("Count", Object::Integer(all_page_ids.len() as i64)); - merged.objects.insert(pages_oid, Object::Dictionary(pages_dict)); - - // Build the Catalog. - let catalog_oid: ObjectId = (next_id, 0); - let mut catalog = Dictionary::new(); - catalog.set("Type", Object::Name(b"Catalog".to_vec())); - catalog.set("Pages", Object::Reference(pages_oid)); - merged.objects.insert(catalog_oid, Object::Dictionary(catalog)); - - merged.trailer.set("Root", Object::Reference(catalog_oid)); - merged.trailer.set("Size", Object::Integer((next_id + 1) as i64)); - merged.max_id = next_id; - - Ok(merged) -} - -/// Recursively remap all `Reference` object IDs by adding `offset` to the -/// object number component. -fn remap_refs(obj: &Object, offset: u32) -> Object { - match obj { - Object::Reference(id) => Object::Reference((id.0 + offset, id.1)), - Object::Array(arr) => Object::Array(arr.iter().map(|o| remap_refs(o, offset)).collect()), - Object::Dictionary(dict) => { - let mut new_dict = Dictionary::new(); - for (k, v) in dict.iter() { - new_dict.set(k.clone(), remap_refs(v, offset)); - } - Object::Dictionary(new_dict) - } - Object::Stream(stream) => { - let mut new_dict = Dictionary::new(); - for (k, v) in stream.dict.iter() { - new_dict.set(k.clone(), remap_refs(v, offset)); - } - Object::Stream(Stream::new(new_dict, stream.content.clone())) - } - other => other.clone(), - } -} - -// --------------------------------------------------------------------------- -// Per-entry PDF generation -// --------------------------------------------------------------------------- - -/// Generate a PDF for a single entry. Returns the path inside `work_dir`. -pub(crate) fn entry_pdf( - entry: &ExportEntry, - index: usize, - with_credit: bool, - work_dir: &Path, - posters: &HashMap, -) -> Result { - let profile_dir = work_dir.join("chrome-profile"); - std::fs::create_dir_all(&profile_dir)?; - - match &entry.body { - ExportBody::Page(asset) => { - entry_pdf_from_page(entry, index, with_credit, work_dir, &profile_dir, asset) - } - ExportBody::Pdf(asset) => { - entry_pdf_from_existing_pdf(entry, index, with_credit, work_dir, &profile_dir, asset) - } - _ => entry_pdf_from_html(entry, index, with_credit, work_dir, &profile_dir, posters), - } -} - -fn entry_pdf_from_html( - entry: &ExportEntry, - index: usize, - with_credit: bool, - work_dir: &Path, - profile_dir: &Path, - posters: &HashMap, -) -> Result { - let html = render_document(std::slice::from_ref(entry), AssetMode::Print, posters, with_credit); - let html_path = work_dir.join(format!("print-{index}.html")); - std::fs::write(&html_path, &html) - .with_context(|| format!("failed to write print HTML: {}", html_path.display()))?; - let out = work_dir.join(format!("entry-{index}.pdf")); - print_pdf(&html_path, &out, profile_dir)?; - Ok(out) -} - -fn entry_pdf_from_page( - entry: &ExportEntry, - index: usize, - with_credit: bool, - work_dir: &Path, - profile_dir: &Path, - asset: &Asset, -) -> Result { - let snapshot_bytes = std::fs::read(&asset.source) - .with_context(|| format!("failed to read snapshot: {}", asset.source.display()))?; - let snapshot = String::from_utf8_lossy(&snapshot_bytes); - - let title = entry_title(entry); - let label = source_label(&entry.summary.source_kind, &entry.summary.entity_kind); - let masthead = build_masthead_div(&title, &label, &entry.summary.archived_at); - - let injected = inject_after_body_open(&snapshot, &masthead); - let injected = if with_credit { - inject_before_body_close(&injected, brand::CREDIT_INLINE_HTML) - } else { - injected - }; - - let html_path = work_dir.join(format!("print-page-{index}.html")); - std::fs::write(&html_path, injected.as_bytes()) - .with_context(|| format!("failed to write page HTML: {}", html_path.display()))?; - let out = work_dir.join(format!("entry-{index}.pdf")); - print_pdf(&html_path, &out, profile_dir)?; - Ok(out) -} - -fn entry_pdf_from_existing_pdf( - entry: &ExportEntry, - index: usize, - with_credit: bool, - work_dir: &Path, - profile_dir: &Path, - asset: &Asset, -) -> Result { - // Print the masthead as its own page. - let title = entry_title(entry); - let label = source_label(&entry.summary.source_kind, &entry.summary.entity_kind); - let mhtml = build_masthead_page(&title, &label, &entry.summary.archived_at, with_credit); - let mhtml_path = work_dir.join(format!("masthead-{index}.html")); - std::fs::write(&mhtml_path, mhtml.as_bytes()).context("failed to write masthead HTML")?; - let mast_pdf_path = work_dir.join(format!("masthead-{index}.pdf")); - print_pdf(&mhtml_path, &mast_pdf_path, profile_dir)?; - - let out = work_dir.join(format!("entry-{index}.pdf")); - - match Document::load(&asset.source) { - Ok(orig_doc) => { - let mast_doc = Document::load(&mast_pdf_path).context("failed to reload masthead PDF")?; - let mut merged = merge_documents(vec![mast_doc, orig_doc])?; - merged.save(&out).context("failed to save merged PDF")?; - Ok(out) - } - Err(e) => { - eprintln!("warn: export: failed to load PDF artifact: {e:#}"); - // Fallback: render a plain HTML page for this entry. - let html = render_document( - std::slice::from_ref(entry), - AssetMode::Print, - &HashMap::new(), - with_credit, - ); - let html_path = work_dir.join(format!("print-{index}.html")); - std::fs::write(&html_path, &html)?; - print_pdf(&html_path, &out, profile_dir)?; - Ok(out) - } - } -} - -// --------------------------------------------------------------------------- -// Masthead injection helpers -// --------------------------------------------------------------------------- - -fn build_masthead_div(title: &str, label: &str, archived_at: &str) -> String { - use chrono::DateTime; - let date = DateTime::parse_from_rfc3339(archived_at) - .map(|dt| dt.format("%-d %B %Y").to_string()) - .unwrap_or_else(|_| archived_at.to_string()); - - format!( - r#"
-

{label}

-

{title}

-

Archived {date}

-
"#, - label = html_esc(label), - title = html_esc(title), - date = html_esc(&date), - ) -} - -fn build_masthead_page(title: &str, label: &str, archived_at: &str, with_credit: bool) -> String { - let masthead = build_masthead_div(title, label, archived_at); - let credit = if with_credit { brand::CREDIT_HTML } else { "" }; - format!( - r#" -
{masthead}
{credit}"#, - ) -} - -fn inject_after_body_open(html: &str, to_inject: &str) -> String { - let lower = html.to_lowercase(); - if let Some(body_start) = lower.find("') { - let insert_at = body_start + rel_end + 1; - let mut out = String::with_capacity(html.len() + to_inject.len() + 1); - out.push_str(&html[..insert_at]); - out.push('\n'); - out.push_str(to_inject); - out.push_str(&html[insert_at..]); - return out; - } - } - let mut out = String::with_capacity(html.len() + to_inject.len() + 1); - out.push_str(to_inject); - out.push('\n'); - out.push_str(html); - out -} - -fn inject_before_body_close(html: &str, to_inject: &str) -> String { - let lower = html.to_lowercase(); - if let Some(close_pos) = lower.rfind("") { - let mut out = String::with_capacity(html.len() + to_inject.len() + 1); - out.push_str(&html[..close_pos]); - out.push('\n'); - out.push_str(to_inject); - out.push_str(&html[close_pos..]); - return out; - } - let mut out = html.to_string(); - out.push('\n'); - out.push_str(to_inject); - out -} - -fn html_esc(s: &str) -> String { - s.replace('&', "&") - .replace('<', "<") - .replace('>', ">") - .replace('"', """) - .replace('\'', "'") -} diff --git a/crates/archivr-server/src/effective_config.rs b/crates/archivr-server/src/effective_config.rs index 57f61f0..c9c5d32 100644 --- a/crates/archivr-server/src/effective_config.rs +++ b/crates/archivr-server/src/effective_config.rs @@ -69,9 +69,8 @@ pub(crate) static ENV_VARS: &[EnvSpec] = &[ spec("ARCHIVR_DENO", "tools", None, "Pinned Deno binary offered to the JS runtime resolver."), spec("ARCHIVR_JS_RUNTIME", "tools", None, "Forced JS runtime for yt-dlp as RUNTIME[:ABS_PATH] (deno, node, bun, quickjs)."), spec("ARCHIVR_SINGLE_FILE", "tools", Some("single-file"), "single-file-cli binary for web page archiving."), - spec("ARCHIVR_CHROME", "tools", Some("chromium"), "Chromium executable used by single-file and PDF export."), + spec("ARCHIVR_CHROME", "tools", Some("chromium"), "Chromium executable used by single-file captures."), spec("ARCHIVR_CHROME_ARGS", "tools", None, "Extra space-separated Chromium flags."), - spec("ARCHIVR_EXPORT_PDF_TIMEOUT", "tools", Some("120"), "Seconds allowed for each Chromium PDF render during entry export."), spec("ARCHIVR_UBLOCK", "tools", Some("true"), "Default for the uBlock extension toggle when no instance setting overrides it (false or 0 disables)."), spec("ARCHIVR_UBLOCK_EXT", "tools", None, "Directory of the unpacked uBlock extension."), spec("ARCHIVR_COOKIE_CONSENT", "tools", Some("true"), "Default for the cookie-consent extension toggle when no instance setting overrides it (false or 0 disables)."), diff --git a/crates/archivr-server/src/exports.rs b/crates/archivr-server/src/exports.rs index 07b5c1c..55ebbc6 100644 --- a/crates/archivr-server/src/exports.rs +++ b/crates/archivr-server/src/exports.rs @@ -42,7 +42,7 @@ async fn export_handler( // 2. Parse format, layout, and credit. let format = export::ExportFormat::parse(&q.format) - .ok_or_else(|| ApiError::bad_request("format must be html, pdf, or markdown"))?; + .ok_or_else(|| ApiError::bad_request("format must be html or markdown"))?; let layout = match q.layout.as_deref().unwrap_or("together") { "together" => export::ExportLayout::Together, diff --git a/frontend/src/components/ExportDialog.jsx b/frontend/src/components/ExportDialog.jsx index 236ab75..a212e04 100644 --- a/frontend/src/components/ExportDialog.jsx +++ b/frontend/src/components/ExportDialog.jsx @@ -101,7 +101,6 @@ export default function ExportDialog({ open, archiveId, entryUids, onClose }) { disabled={status === 'running'} > - From 78d003fb12c2b32a3b302db131b0d38c5b3c2b27 Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Tue, 13 Oct 2026 14:31:41 +0200 Subject: [PATCH 06/14] fix: keep generated static assets out of entry export PR --- .../static/assets/index-CKGxin5o.js | 49 +++++++++++++++++++ .../static/assets/index-CQKWq7vB.css | 1 + crates/archivr-server/static/index.html | 4 +- 3 files changed, 52 insertions(+), 2 deletions(-) create mode 100644 crates/archivr-server/static/assets/index-CKGxin5o.js create mode 100644 crates/archivr-server/static/assets/index-CQKWq7vB.css diff --git a/crates/archivr-server/static/assets/index-CKGxin5o.js b/crates/archivr-server/static/assets/index-CKGxin5o.js new file mode 100644 index 0000000..6b965c1 --- /dev/null +++ b/crates/archivr-server/static/assets/index-CKGxin5o.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 Xu={exports:{}},Cs={},Ju={exports:{}},oe={};/** + * @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 gl=Symbol.for("react.element"),Nf=Symbol.for("react.portal"),Cf=Symbol.for("react.fragment"),Ef=Symbol.for("react.strict_mode"),bf=Symbol.for("react.profiler"),Tf=Symbol.for("react.provider"),Pf=Symbol.for("react.context"),Lf=Symbol.for("react.forward_ref"),Rf=Symbol.for("react.suspense"),zf=Symbol.for("react.memo"),If=Symbol.for("react.lazy"),So=Symbol.iterator;function $f(e){return e===null||typeof e!="object"?null:(e=So&&e[So]||e["@@iterator"],typeof e=="function"?e:null)}var Gu={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Yu=Object.assign,Zu={};function jr(e,t,n){this.props=e,this.context=t,this.refs=Zu,this.updater=n||Gu}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 ec(){}ec.prototype=jr.prototype;function _a(e,t,n){this.props=e,this.context=t,this.refs=Zu,this.updater=n||Gu}var Na=_a.prototype=new ec;Na.constructor=_a;Yu(Na,jr.prototype);Na.isPureReactComponent=!0;var _o=Array.isArray,tc=Object.prototype.hasOwnProperty,Ca={current:null},nc={key:!0,ref:!0,__self:!0,__source:!0};function rc(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)tc.call(t,r)&&!nc.hasOwnProperty(r)&&(l[r]=t[r]);var o=arguments.length-2;if(o===1)l.children=n;else if(1>>1,se=I[ee];if(0>>1;eel(Ne,K))pel(U,Ne)?(I[ee]=U,I[pe]=K,ee=pe):(I[ee]=Ne,I[Y]=K,ee=Y);else if(pel(U,K))I[ee]=U,I[pe]=K,ee=pe;else break e}}return R}function l(I,R){var K=I.sortIndex-R.sortIndex;return K!==0?K:I.id-R.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,m=3,x=!1,w=!1,S=!1,_=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 h(I){for(var R=n(d);R!==null;){if(R.callback===null)r(d);else if(R.startTime<=I)r(d),R.sortIndex=R.expirationTime,t(u,R);else break;R=n(d)}}function k(I){if(S=!1,h(I),!w)if(n(u)!==null)w=!0,Le(E);else{var R=n(d);R!==null&&ve(k,R.startTime-I)}}function E(I,R){w=!1,S&&(S=!1,p(v),v=-1),x=!0;var K=m;try{for(h(R),g=n(u);g!==null&&(!(g.expirationTime>R)||I&&!X());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,m=g.priorityLevel;var se=ee(g.expirationTime<=R);R=e.unstable_now(),typeof se=="function"?g.callback=se:g===n(u)&&r(u),h(R)}else r(u);g=n(u)}if(g!==null)var ie=!0;else{var Y=n(d);Y!==null&&ve(k,Y.startTime-R),ie=!1}return ie}finally{g=null,m=K,x=!1}}var P=!1,N=null,v=-1,b=5,L=-1;function X(){return!(e.unstable_now()-LI||125ee?(I.sortIndex=K,t(d,I),n(u)===null&&I===n(d)&&(S?(p(v),v=-1):S=!0,ve(k,K-ee))):(I.sortIndex=se,t(u,I),w||x||(w=!0,Le(E))),I},e.unstable_shouldYield=X,e.unstable_wrapCallback=function(I){var R=m;return function(){var K=m;m=R;try{return I.apply(this,arguments)}finally{m=K}}}})(oc);ac.exports=oc;var Kf=ac.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 Qf=c,jt=Kf;function O(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,qf=/^[: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 Xf(e){return Li.call(Eo,e)?!0:Li.call(Co,e)?!1:qf.test(e)?Eo[e]=!0:(Co[e]=!0,!1)}function Jf(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 Gf(e,t,n,r){if(t===null||typeof t>"u"||Jf(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 ct(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 Ye={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Ye[e]=new ct(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Ye[t]=new ct(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Ye[e]=new ct(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Ye[e]=new ct(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){Ye[e]=new ct(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Ye[e]=new ct(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Ye[e]=new ct(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Ye[e]=new ct(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Ye[e]=new ct(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);Ye[t]=new ct(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);Ye[t]=new ct(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);Ye[t]=new ct(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Ye[e]=new ct(e,1,!1,e.toLowerCase(),null,!1,!1)});Ye.xlinkHref=new ct("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Ye[e]=new ct(e,1,!1,e.toLowerCase(),null,!0,!0)});function Pa(e,t,n,r){var l=Ye.hasOwnProperty(t)?Ye[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:"")?$r(e):""}function Yf(e){switch(e.tag){case 5:return $r(e.type);case 16:return $r("Lazy");case 13:return $r("Suspense");case 19:return $r("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 dc:return(e.displayName||"Context")+".Consumer";case cc: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 dn:t=e._payload,e=e._init;try{return $i(e(t))}catch{}}return null}function Zf(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 Nn(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function pc(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function ep(e){var t=pc(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 Nl(e){e._valueTracker||(e._valueTracker=ep(e))}function hc(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=pc(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function ts(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 Pe({},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=Nn(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 mc(e,t){t=t.checked,t!=null&&Pa(e,"checked",t,!1)}function Oi(e,t){mc(e,t);var n=Nn(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,Nn(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"||ts(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Dr=Array.isArray;function or(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=Cl.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Yr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Br={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},tp=["Webkit","ms","Moz","O"];Object.keys(Br).forEach(function(e){tp.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Br[t]=Br[e]})});function xc(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Br.hasOwnProperty(e)&&Br[e]?(""+t).trim():t+"px"}function wc(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=xc(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var np=Pe({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(np[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(O(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(O(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(O(61))}if(t.style!=null&&typeof t.style!="object")throw Error(O(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=xl(e)){if(typeof Wi!="function")throw Error(O(280));var t=e.stateNode;t&&(t=Ls(t),Wi(e.stateNode,e.type,t))}}function kc(e){ur?cr?cr.push(e):cr=[e]:ur=e}function jc(){if(ur){var e=ur,t=cr;if(cr=ur=null,zo(e),t)for(e=0;e>>=0,e===0?32:31-(pp(e)/hp|0)|0}var El=64,bl=4194304;function Or(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 ss(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=Or(o):(i&=a,i!==0&&(r=Or(i)))}else a=n&~l,a!==0?r=Or(a):i!==0&&(r=Or(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 yl(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ft(t),e[t]=n}function vp(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=Hr),Uo=" ",Ho=!1;function Uc(e,t){switch(e){case"keyup":return Kp.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Hc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Yn=!1;function qp(e,t){switch(e){case"compositionend":return Hc(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 Xp(e,t){if(Yn)return e==="compositionend"||!Ua&&Uc(e,t)?(e=Fc(),Vl=Ma=mn=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=ts();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=ts(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 lh(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=qo(n,i);var a=qo(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,Vr=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!==ts(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}),Vr&&ll(Vr,r)||(Vr=r,r=os(Ji,"onSelect"),0nr||(e.current=ra[nr],ra[nr]=null,nr--)}function we(e,t){nr++,ra[nr]=e.current,e.current=t}var Cn={},lt=bn(Cn),ht=bn(!1),Mn=Cn;function gr(e,t){var n=e.type.contextTypes;if(!n)return Cn;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 mt(e){return e=e.childContextTypes,e!=null}function cs(){_e(ht),_e(lt)}function nu(e,t,n){if(lt.current!==Cn)throw Error(O(168));we(lt,t),we(ht,n)}function rd(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(O(108,Zf(e)||"Unknown",l));return Pe({},n,r)}function ds(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Cn,Mn=lt.current,we(lt,e),we(ht,ht.current),!0}function ru(e,t,n){var r=e.stateNode;if(!r)throw Error(O(169));n?(e=rd(e,t,Mn),r.__reactInternalMemoizedMergedChildContext=e,_e(ht),_e(lt),we(lt,e)):_e(ht),we(ht,n)}var Gt=null,Rs=!1,gi=!1;function ld(e){Gt===null?Gt=[e]:Gt.push(e)}function gh(e){Rs=!0,ld(e)}function Tn(){if(!gi&&Gt!==null){gi=!0;var e=0,t=ge;try{var n=Gt;for(ge=1;e>=a,l-=a,Yt=1<<32-Ft(t)+l|n<v?(b=N,N=null):b=N.sibling;var L=m(p,N,h[v],k);if(L===null){N===null&&(N=b);break}e&&N&&L.alternate===null&&t(p,N),f=i(L,f,v),P===null?E=L:P.sibling=L,P=L,N=b}if(v===h.length)return n(p,N),Ce&&Ln(p,v),E;if(N===null){for(;vv?(b=N,N=null):b=N.sibling;var X=m(p,N,L.value,k);if(X===null){N===null&&(N=b);break}e&&N&&X.alternate===null&&t(p,N),f=i(X,f,v),P===null?E=X:P.sibling=X,P=X,N=b}if(L.done)return n(p,N),Ce&&Ln(p,v),E;if(N===null){for(;!L.done;v++,L=h.next())L=g(p,L.value,k),L!==null&&(f=i(L,f,v),P===null?E=L:P.sibling=L,P=L);return Ce&&Ln(p,v),E}for(N=r(p,N);!L.done;v++,L=h.next())L=x(N,p,v,L.value,k),L!==null&&(e&&L.alternate!==null&&N.delete(L.key===null?v:L.key),f=i(L,f,v),P===null?E=L:P.sibling=L,P=L);return e&&N.forEach(function(Q){return t(p,Q)}),Ce&&Ln(p,v),E}function _(p,f,h,k){if(typeof h=="object"&&h!==null&&h.type===Gn&&h.key===null&&(h=h.props.children),typeof h=="object"&&h!==null){switch(h.$$typeof){case _l:e:{for(var E=h.key,P=f;P!==null;){if(P.key===E){if(E=h.type,E===Gn){if(P.tag===7){n(p,P.sibling),f=l(P,h.props.children),f.return=p,p=f;break e}}else if(P.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===dn&&iu(E)===P.type){n(p,P.sibling),f=l(P,h.props),f.ref=Lr(p,P,h),f.return=p,p=f;break e}n(p,P);break}else t(p,P);P=P.sibling}h.type===Gn?(f=An(h.props.children,p.mode,k,h.key),f.return=p,p=f):(k=Zl(h.type,h.key,h.props,null,p.mode,k),k.ref=Lr(p,f,h),k.return=p,p=k)}return a(p);case Jn:e:{for(P=h.key;f!==null;){if(f.key===P)if(f.tag===4&&f.stateNode.containerInfo===h.containerInfo&&f.stateNode.implementation===h.implementation){n(p,f.sibling),f=l(f,h.children||[]),f.return=p,p=f;break e}else{n(p,f);break}else t(p,f);f=f.sibling}f=_i(h,p.mode,k),f.return=p,p=f}return a(p);case dn:return P=h._init,_(p,f,P(h._payload),k)}if(Dr(h))return w(p,f,h,k);if(Cr(h))return S(p,f,h,k);$l(p,h)}return typeof h=="string"&&h!==""||typeof h=="number"?(h=""+h,f!==null&&f.tag===6?(n(p,f.sibling),f=l(f,h),f.return=p,p=f):(n(p,f),f=Si(h,p.mode,k),f.return=p,p=f),a(p)):n(p,f)}return _}var vr=od(!0),ud=od(!1),hs=bn(null),ms=null,sr=null,Qa=null;function qa(){Qa=sr=ms=null}function Xa(e){var t=hs.current;_e(hs),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){ms=e,Qa=sr=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(pt=!0),e.firstContext=null)}function Tt(e){var t=e._currentValue;if(Qa!==e)if(e={context:e,memoizedValue:t,next:null},sr===null){if(ms===null)throw Error(O(308));sr=e,ms.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 cd(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,rn(e,r)}function rn(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 fn=!1;function Ga(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function dd(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 en(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function kn(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,de&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,rn(e,n)}return l=r.interleaved,l===null?(t.next=t,Ja(r)):(t.next=l.next,l.next=t),r.interleaved=t,rn(e,n)}function Ql(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 gs(e,t,n,r){var l=e.updateQueue;fn=!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 m=o.lane,x=o.eventTime;if((r&m)===m){y!==null&&(y=y.next={eventTime:x,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var w=e,S=o;switch(m=t,x=n,S.tag){case 1:if(w=S.payload,typeof w=="function"){g=w.call(x,g,m);break e}g=w;break e;case 3:w.flags=w.flags&-65537|128;case 0:if(w=S.payload,m=typeof w=="function"?w.call(x,g,m):w,m==null)break e;g=Pe({},g,m);break e;case 2:fn=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,m=l.effects,m===null?l.effects=[o]:m.push(o))}else x={eventTime:x,lane:m,tag:o.tag,payload:o.payload,callback:o.callback,next:null},y===null?(d=y=x,u=g):y=y.next=x,a|=m;if(o=o.next,o===null){if(o=l.shared.pending,o===null)break;m=o,o=m.next,m.next=null,l.lastBaseUpdate=m,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{ge=n,vi.transition=r}}function bd(){return Pt().memoizedState}function wh(e,t,n){var r=Sn(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Td(e))Pd(t,n);else if(n=cd(e,t,n,r),n!==null){var l=ot();Bt(n,e,r,l),Ld(n,t,r)}}function kh(e,t,n){var r=Sn(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Td(e))Pd(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,Ut(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=cd(e,t,l,r),n!==null&&(l=ot(),Bt(n,e,r,l),Ld(n,t,r))}}function Td(e){var t=e.alternate;return e===Te||t!==null&&t===Te}function Pd(e,t){Kr=vs=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Ld(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Da(e,n)}}var xs={readContext:Tt,useCallback:tt,useContext:tt,useEffect:tt,useImperativeHandle:tt,useInsertionEffect:tt,useLayoutEffect:tt,useMemo:tt,useReducer:tt,useRef:tt,useState:tt,useDebugValue:tt,useDeferredValue:tt,useTransition:tt,useMutableSource:tt,useSyncExternalStore:tt,useId:tt,unstable_isNewReconciler:!1},jh={readContext:Tt,useCallback:function(e,t){return Vt().memoizedState=[e,t===void 0?null:t],e},useContext:Tt,useEffect:cu,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Xl(4194308,4,Sd.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Xl(4194308,4,e,t)},useInsertionEffect:function(e,t){return Xl(4,2,e,t)},useMemo:function(e,t){var n=Vt();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Vt();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=wh.bind(null,Te,e),[r.memoizedState,e]},useRef:function(e){var t=Vt();return e={current:e},t.memoizedState=e},useState:uu,useDebugValue:so,useDeferredValue:function(e){return Vt().memoizedState=e},useTransition:function(){var e=uu(!1),t=e[0];return e=xh.bind(null,e[1]),Vt().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Te,l=Vt();if(Ce){if(n===void 0)throw Error(O(407));n=n()}else{if(n=t(),Xe===null)throw Error(O(349));Bn&30||md(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,cu(yd.bind(null,r,i,e),[e]),r.flags|=2048,fl(9,gd.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Vt(),t=Xe.identifierPrefix;if(Ce){var n=Zt,r=Yt;n=(r&~(1<<32-Ft(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=cl++,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[Kt]=t,e[al]=r,Bd(e,t,!1,!1),t.stateNode=e;e:{switch(a=Ui(n,r),n){case"dialog":Se("cancel",e),Se("close",e),l=r;break;case"iframe":case"object":case"embed":Se("load",e),l=r;break;case"video":case"audio":for(l=0;lkr&&(t.flags|=128,r=!0,Rr(i,!1),t.lanes=4194304)}else{if(!r)if(e=ys(a),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Rr(i,!0),i.tail===null&&i.tailMode==="hidden"&&!a.alternate&&!Ce)return nt(t),null}else 2*De()-i.renderingStartTime>kr&&n!==1073741824&&(t.flags|=128,r=!0,Rr(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=De(),t.sibling=null,n=be.current,we(be,r?n&1|2:n&1),t):(nt(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?vt&1073741824&&(nt(t),t.subtreeFlags&6&&(t.flags|=8192)):nt(t),null;case 24:return null;case 25:return null}throw Error(O(156,t.tag))}function Ph(e,t){switch(Va(t),t.tag){case 1:return mt(t.type)&&cs(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return xr(),_e(ht),_e(lt),eo(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Za(t),null;case 13:if(_e(be),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(O(340));yr()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return _e(be),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 Ol=!1,rt=!1,Lh=typeof WeakSet=="function"?WeakSet:Set,V=null;function ir(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){ze(e,t,r)}else n.current=null}function ma(e,t,n){try{n()}catch(r){ze(e,t,r)}}var ku=!1;function Rh(e,t){if(Yi=is,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,m=null;t:for(;;){for(var x;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),(x=g.firstChild)!==null;)m=g,g=x;for(;;){if(g===e)break t;if(m===n&&++d===l&&(o=a),m===i&&++y===r&&(u=a),(x=g.nextSibling)!==null)break;g=m,m=g.parentNode}g=x}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},is=!1,V=t;V!==null;)if(t=V,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,V=e;else for(;V!==null;){t=V;try{var w=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(w!==null){var S=w.memoizedProps,_=w.memoizedState,p=t.stateNode,f=p.getSnapshotBeforeUpdate(t.elementType===t.type?S:Ot(t.type,S),_);p.__reactInternalSnapshotBeforeUpdate=f}break;case 3:var h=t.stateNode.containerInfo;h.nodeType===1?h.textContent="":h.nodeType===9&&h.documentElement&&h.removeChild(h.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(O(163))}}catch(k){ze(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,V=e;break}V=t.return}return w=ku,ku=!1,w}function Qr(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 $s(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 Wd(e){var t=e.alternate;t!==null&&(e.alternate=null,Wd(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Kt],delete t[al],delete t[na],delete t[hh],delete t[mh])),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 Vd(e){return e.tag===5||e.tag===3||e.tag===4}function ju(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Vd(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=us));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 Je=null,At=!1;function cn(e,t,n){for(n=n.child;n!==null;)Kd(e,t,n),n=n.sibling}function Kd(e,t,n){if(Qt&&typeof Qt.onCommitFiberUnmount=="function")try{Qt.onCommitFiberUnmount(Es,n)}catch{}switch(n.tag){case 5:rt||ir(n,t);case 6:var r=Je,l=At;Je=null,cn(e,t,n),Je=r,At=l,Je!==null&&(At?(e=Je,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Je.removeChild(n.stateNode));break;case 18:Je!==null&&(At?(e=Je,n=n.stateNode,e.nodeType===8?mi(e.parentNode,n):e.nodeType===1&&mi(e,n),nl(e)):mi(Je,n.stateNode));break;case 4:r=Je,l=At,Je=n.stateNode.containerInfo,At=!0,cn(e,t,n),Je=r,At=l;break;case 0:case 11:case 14:case 15:if(!rt&&(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)}cn(e,t,n);break;case 1:if(!rt&&(ir(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){ze(n,t,o)}cn(e,t,n);break;case 21:cn(e,t,n);break;case 22:n.mode&1?(rt=(r=rt)||n.memoizedState!==null,cn(e,t,n),rt=r):cn(e,t,n);break;default:cn(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 Lh),t.forEach(function(r){var l=Bh.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function Dt(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=a),r&=~i}if(r=l,r=De()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Ih(r/1960))-r,10e?16:e,gn===null)var r=!1;else{if(e=gn,gn=null,js=0,de&6)throw Error(O(331));var l=de;for(de|=4,V=e.current;V!==null;){var i=V,a=i.child;if(V.flags&16){var o=i.deletions;if(o!==null){for(var u=0;uDe()-uo?On(e,0):oo|=n),gt(e,t)}function ef(e,t){t===0&&(e.mode&1?(t=bl,bl<<=1,!(bl&130023424)&&(bl=4194304)):t=1);var n=ot();e=rn(e,t),e!==null&&(yl(e,t,n),gt(e,n))}function Fh(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),ef(e,n)}function Bh(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(O(314))}r!==null&&r.delete(t),ef(e,n)}var tf;tf=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||ht.current)pt=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return pt=!1,bh(e,t,n);pt=!!(e.flags&131072)}else pt=!1,Ce&&t.flags&1048576&&sd(t,ps,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Jl(e,t),e=t.pendingProps;var l=gr(t,lt.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,mt(r)?(i=!0,ds(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,Ga(t),l.updater=Is,t.stateNode=l,l._reactInternals=t,oa(t,r,e,n),t=da(null,t,r,!0,i,n)):(t.tag=0,Ce&&i&&Wa(t),at(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Jl(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=Hh(r),e=Ot(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,Ot(r.type,e),n);break e}throw Error(O(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ot(r,l),ca(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ot(r,l),vu(e,t,r,l,n);case 3:e:{if(Ad(t),e===null)throw Error(O(387));r=t.pendingProps,i=t.memoizedState,l=i.element,dd(e,t),gs(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(O(423)),t),t=xu(e,t,r,n,l);break e}else if(r!==l){l=wr(Error(O(424)),t),t=xu(e,t,r,n,l);break e}else for(wt=wn(t.stateNode.containerInfo.firstChild),kt=t,Ce=!0,Mt=null,n=ud(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(yr(),r===l){t=ln(e,t,n);break e}at(e,t,r,n)}t=t.child}return t;case 5:return fd(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),Od(e,t),at(e,t,a,n),t.child;case 6:return e===null&&sa(t),null;case 13:return Md(e,t,n);case 4:return Ya(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=vr(t,null,r,n):at(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ot(r,l),gu(e,t,r,l,n);case 7:return at(e,t,t.pendingProps,n),t.child;case 8:return at(e,t,t.pendingProps.children,n),t.child;case 12:return at(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,we(hs,r._currentValue),r._currentValue=a,i!==null)if(Ut(i.value,a)){if(i.children===l.children&&!ht.current){t=ln(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=en(-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(O(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}at(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,fr(t,n),l=Tt(l),r=r(l),t.flags|=1,at(e,t,r,n),t.child;case 14:return r=t.type,l=Ot(r,t.pendingProps),l=Ot(r.type,l),yu(e,t,r,l,n);case 15:return $d(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ot(r,l),Jl(e,t),t.tag=1,mt(r)?(e=!0,ds(t)):e=!1,fr(t,n),Rd(t,r,l),oa(t,r,l,n),da(null,t,r,!0,e,n);case 19:return Fd(e,t,n);case 22:return Dd(e,t,n)}throw Error(O(156,t.tag))};function nf(e,t){return Tc(e,t)}function Uh(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 Et(e,t,n,r){return new Uh(e,t,n,r)}function ho(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Hh(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 _n(e,t){var n=e.alternate;return n===null?(n=Et(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 Zl(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=Et(12,n,t,l|2),e.elementType=Ri,e.lanes=i,e;case zi:return e=Et(13,n,t,l),e.elementType=zi,e.lanes=i,e;case Ii:return e=Et(19,n,t,l),e.elementType=Ii,e.lanes=i,e;case fc:return Os(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case cc:a=10;break e;case dc:a=9;break e;case Ra:a=11;break e;case za:a=14;break e;case dn:a=16,r=null;break e}throw Error(O(130,e==null?e:typeof e,""))}return t=Et(a,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function An(e,t,n,r){return e=Et(7,e,r,t),e.lanes=n,e}function Os(e,t,n,r){return e=Et(22,e,r,t),e.elementType=fc,e.lanes=n,e.stateNode={isHidden:!1},e}function Si(e,t,n){return e=Et(6,e,null,t),e.lanes=n,e}function _i(e,t,n){return t=Et(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Wh(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 Wh(e,t,n,o,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Et(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 Vh(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(af)}catch(e){console.error(e)}}af(),ic.exports=St;var Jh=ic.exports,of,Lu=Jh;of=Lu.createRoot,Lu.hydrateRoot;async function Oe(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 Oe("/api/archives")}async function zu(e,t=null){const n=t?`/api/archives/${e}/entries?collection=${encodeURIComponent(t)}`:`/api/archives/${e}/entries`;return Oe(n)}async function Gh(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),Oe(`/api/archives/${e}/entries/search?${l}`)}async function Mr(e,t){return Oe(`/api/archives/${e}/entries/${t}`)}async function Yh(e,t,{signal:n}={}){return Oe(`/api/archives/${e}/entries/${t}/summary`,{signal:n})}async function Zh(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 em(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 Iu(e,t){return Oe(`/api/archives/${e}/entries/${t}/children`)}async function tm(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/children/order`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({child_uids:n})});if(!r.ok){const l=await r.json().catch(()=>({})),i=new Error(l.error||`HTTP ${r.status}`);throw i.status=r.status,i}}function nm(e,t,n){return Promise.all(n.map(r=>Oe(`/api/archives/${e}/entries/${t}/artifacts/${r}`)))}async function rm(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 lm(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 Fl(e,t){return Oe(`/api/archives/${e}/entries/${t}/tags`)}async function $u(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 sm(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 Du(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 im(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 am(e,t){const n=await fetch(`/api/archives/${e}/tags/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(await n.text())}async function om(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 um(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 Ni(e){return Oe(`/api/archives/${e}/runs`)}async function Bl(e){return Oe(`/api/archives/${e}/tags`)}async function cm(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 dm(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 fm(e,t){return Oe(`/api/archives/${e}/captures/probe?locator=${encodeURIComponent(t)}`)}async function pm(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 uf(e,t){return Oe(`/api/archives/${e}/capture_jobs/${t}`)}async function hm(){return(await(await fetch("/api/auth/setup")).json()).setup_required===!0}async function mm(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 gm(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 ym(){await fetch("/api/auth/logout",{method:"POST"})}async function cf(){const e=await fetch("/api/auth/me");return e.status===401?null:e.json()}async function vm(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 xm(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 wm(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 km(){return Oe("/api/auth/tokens")}async function jm(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 xo(){return Oe("/api/admin/instance-settings")}async function Jr(e){const t=await fetch("/api/admin/instance-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error||`HTTP ${t.status}`)}}async function _m(){return Oe("/api/admin/users")}async function Nm(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 Cm(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 df(){return Oe("/api/admin/roles")}async function Em(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 Oe(`/api/archives/${e}/collections`)}async function bm(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 Tm(e,t){return Oe(`/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 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 Lm(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 Ou(e,t){return Oe(`/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 Rm(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 zm(e){return Oe(`/api/archives/${e}/blob-cleanup`)}async function Im(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 $m(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 Dm(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 Om(){return Oe("/api/admin/cookie-rules")}async function Am(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 Mm(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 Fm(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 Bm(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 Um=window.fetch;window.fetch=async(...e)=>{var n;const t=await Um(...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 Hm({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 gm(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 Wm({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(m){if(m.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 mm(t,r),e()}catch(x){u(x.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:m=>n(m.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:m=>l(m.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:m=>a(m.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 Vm({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:m}=c.useContext(Hs)??{},[x,w]=c.useState(!1);async function S(){w(!0),await ym(),m(null),window.location.reload()}const _=a.find(h=>h.slug==="_default_"),p=!d||!!_&&!_.requires_auth,f=a.filter(h=>h.slug!=="_default_").filter(h=>!d||!h.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:h=>n(h.target.value),children:e.map(h=>s.jsx("option",{value:h.id,children:h.label},h.id))})}),f.length>0&&s.jsx("div",{className:"switcher",children:s.jsxs("select",{"aria-label":"Select collection",value:o??"",onChange:h=>u(h.target.value||null),children:[p&&s.jsx("option",{value:"",children:"All entries"}),f.map(h=>s.jsx("option",{value:h.collection_uid,children:h.name},h.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(h=>s.jsx("button",{className:`nav-link${r===h?" is-active":""}`,onClick:()=>l(h),children:h.charAt(0).toUpperCase()+h.slice(1)},h))}),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:x,children:x?"Logging out…":"Log out"})]})]})]})}let hl=1;function ff(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:hl++,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 Km(e){return{id:hl++,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:hl++,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 Au(e){return Array.isArray(e.playlistItems)&&e.playlistItems.some(t=>t.quality===null)}function Xm({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),m=c.useRef(new Map),x=c.useRef(t);c.useEffect(()=>{x.current=t},[t]);const w=c.useRef(null),[S,_]=c.useState(!1),p=c.useRef([]),f=c.useRef(!1),h=c.useRef(new Map),k=c.useRef(r),E=c.useRef(l);c.useEffect(()=>{k.current=r},[r]),c.useEffect(()=>{E.current=l},[l]);const P=c.useRef(i),N=c.useRef(a);c.useEffect(()=>{P.current=i},[i]),c.useEffect(()=>{N.current=a},[a]);const[v,b]=c.useState(()=>{try{const j=JSON.parse(sessionStorage.getItem("captureItems")||"null");if(Array.isArray(j)&&j.length>0){const B=j.filter(A=>!A.status||A.status==="idle");if(B.length>0)return B.forEach(A=>{A.id>=hl&&(hl=A.id+1)}),B.map(A=>({...Xn(A.locator),...A}))}}catch{}return[Xn()]});c.useEffect(()=>{sessionStorage.setItem("captureItems",JSON.stringify(v.filter(j=>j.kind!=="file")))},[v]),c.useEffect(()=>{p.current=v},[v]);const[L,X]=c.useState(!1),[Q,ne]=c.useState(null),[q,fe]=c.useState(null),[Le,ve]=c.useState(!0),[I,R]=c.useState(!0),[K,ee]=c.useState(!0);c.useEffect(()=>{xo().then(j=>{fe(j),ve(j.cookie_ext_enabled??!0),R(j.modal_closer_enabled??!0)}).catch(()=>fe({}))},[]);const se=Q!==null?Q:(q==null?void 0:q.ublock_enabled)??!0,[ie,Y]=c.useState(!1);c.useEffect(()=>{["captureDialogLocator","captureDialogError","captureDialogBusy","captureDialogJobStatus","captureDialogJobUid"].forEach(j=>sessionStorage.removeItem(j)),o.forEach(j=>{j.jobUid&&!y.current.has(j.jobUid)&&Ne(j.id,j.jobUid,j.locator,j.archiveId,null)})},[]),c.useEffect(()=>{const j=u.current;if(!j)return;const B=()=>{if(g.current.forEach(A=>clearTimeout(A)),g.current.clear(),!f.current){const A=x.current;p.current.forEach(D=>{var F;D.kind==="file"&&(D.uploadStatus==="uploading"?((F=h.current.get(D.id))==null||F(),h.current.delete(D.id)):D.uploadStatus==="done"&&D.uploadLocator&&Ei(A,D.uploadLocator).catch(()=>{}))})}f.current=!1,n()};return j.addEventListener("close",B),()=>j.removeEventListener("close",B)},[n]),c.useEffect(()=>{const j=u.current;j&&(e?(d.current||b([Xn()]),d.current=!1,j.open||j.showModal()):(g.current.forEach(B=>clearTimeout(B)),g.current.clear(),j.open&&j.close()))},[e]),c.useEffect(()=>()=>{y.current.forEach(j=>clearInterval(j)),g.current.forEach(j=>clearTimeout(j))},[]);function Ne(j,B,A,D,F=null){if(y.current.has(B))return;const H=setInterval(async()=>{var ke,he,Re,ye;try{const Fe=await uf(D,B);if(Fe.status==="completed"){clearInterval(y.current.get(B)),y.current.delete(B),await Promise.resolve((ke=k.current)==null?void 0:ke.call(k)),(he=N.current)==null||he.call(N,j);try{const ce=Fe.notes_json?JSON.parse(Fe.notes_json):null;if(ce!=null&&ce.ublock_skipped||ce!=null&&ce.cookie_ext_skipped){const dt=ce.ublock_skipped&&ce.cookie_ext_skipped?"Captured without ad-blocking or cookie-consent extension. Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config.":ce.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.";E.current(dt,A,"warning"),pe(F,"warning",A)}else F||E.current(null,A,"success"),pe(F,"archived")}catch{F||E.current(null,A,"success"),pe(F,"archived")}}else if(Fe.status==="failed"){clearInterval(y.current.get(B)),y.current.delete(B),(Re=N.current)==null||Re.call(N,j);const ce=Fe.error_text||"Capture failed.";E.current(ce,A),pe(F,"failed",A)}}catch(Fe){clearInterval(y.current.get(B)),y.current.delete(B),(ye=N.current)==null||ye.call(N,j);const ce=Fe.message||"Network error";E.current(ce,A),pe(F,"failed",A)}},500);y.current.set(B,H)}function pe(j,B,A=null){if(!j)return;const D=m.current.get(j);if(!D||(B==="archived"||B==="warning"?(D.archived++,B==="warning"&&(D.warnings++,A&&D.warningLocators.push(A))):(D.failed++,A&&D.failedLocators.push(A)),D.archived+D.failed0?`${F} archived (${H} with warnings)`:`${F} archived`;ye=ke>0?`${dt}, ${ke} failed`:dt}const Fe=F===0?"error":ke>0||H>0?"warning":"success",ce=[];he.length>0&&ce.push(`Failed: +${he.map(dt=>` ${dt}`).join(` +`)}`),Re.length>0&&ce.push(`With warnings: +${Re.map(dt=>` ${dt}`).join(` +`)}`);const it=ce.length>0?ce.join(` +`):null;E.current(it,null,Fe,ye)}async function U(j,B){var Re,ye,Fe;const A=x.current,D=((Re=crypto.randomUUID)==null?void 0:Re.call(crypto))??`job-${Date.now()}-${Math.random()}`;if(j.type==="text"){try{const ce=await dm(A,{title:j.title,body:j.body,mime:j.mime}),it=`text:${j.title}`;(ye=P.current)==null||ye.call(P,{id:D,jobUid:ce.job_uid,locator:it,archiveId:A}),Ne(D,ce.job_uid,it,A,B)}catch(ce){const it=ce.message||"Submission failed.";E.current(it,`text:${j.title}`),pe(B,"failed",`text:${j.title}`)}return}const F=j.locator,H=j.quality,ke=j.extraExtensions||{},he={ublock_enabled:se,reader_mode:ie,cookie_ext_enabled:Le,modal_closer_enabled:I,via_freedium:K,...ke};try{const ce=await cm(A,F,H,he);(Fe=P.current)==null||Fe.call(P,{id:D,jobUid:ce.job_uid,locator:F,archiveId:A}),Ne(D,ce.job_uid,F,A,B)}catch(ce){const it=ce.message||"Submission failed.";E.current(it,F),pe(B,"failed",F),F.startsWith("file://")&&ce.status&&Ei(A,F).catch(()=>{})}}function te(){var D,F;if(v.some(H=>H.kind==="file"&&H.uploadStatus==="uploading"))return;const j=v.filter(H=>H.kind==="file"?H.uploadStatus==="done"&&H.uploadLocator:H.kind==="text"?H.title.trim()&&H.body.trim():H.locator.trim());if(j.length===0||j.some(H=>H.kind!=="file"&&H.kind!=="text"&&Au(H))||j.some(H=>H.kind!=="file"&&H.kind!=="text"&&(H.probeState==="probing"||Dn(H.locator)&&H.playlistProbeState!=="done"))||j.some(H=>H.kind!=="file"&&H.kind!=="text"&&Array.isArray(H.playlistItems)&&H.playlistItems.length===0))return;const B=j.length>1?((D=crypto.randomUUID)==null?void 0:D.call(crypto))??`batch-${Date.now()}`:null;B&&m.current.set(B,{total:j.length,archived:0,warnings:0,failed:0,failedLocators:[],warningLocators:[]});const A=j.map(H=>H.kind==="file"?{type:"file",locator:H.uploadLocator,quality:"best",extraExtensions:{}}:H.kind==="text"?{type:"text",title:H.title.trim(),body:H.body,mime:H.mime}:{type:"url",locator:H.locator.trim(),quality:H.playlistItems!==null?null:H.quality||"best",extraExtensions:H.playlistItems!==null?{per_item_quality:Object.fromEntries(H.playlistItems.map(ke=>[ke.id,ke.quality])),sync:H.syncEnabled}:{}});f.current=!0,b([Xn()]),(F=u.current)==null||F.close(),A.forEach(H=>U(H,B))}function re(){b(j=>[...j,Xn()])}function Ue(j){var A;clearTimeout(g.current.get(j)),g.current.delete(j);const B=p.current.find(D=>D.id===j);(B==null?void 0:B.kind)==="file"&&(B.uploadStatus==="uploading"?((A=h.current.get(j))==null||A(),h.current.delete(j)):B.uploadStatus==="done"&&B.uploadLocator&&Ei(x.current,B.uploadLocator).catch(()=>{})),b(D=>{const F=D.filter(H=>H.id!==j);return F.length===0?[Xn()]:F})}function Lt(j,B){if(clearTimeout(g.current.get(j)),b(A=>A.map(D=>D.id===j?{...D,locator:B,probeState:"idle",probeQualities:null,probeHasAudio:!1,quality:"best",playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1}:D)),ff(B)){const A=setTimeout(async()=>{g.current.delete(j),b(D=>D.map(F=>F.id===j?{...F,probeState:"probing"}:F));try{const D=await fm(x.current,B.trim());b(F=>F.map(H=>{if(H.id!==j||H.locator!==B)return H;const ke=D.qualities??[],he=D.has_audio??!1,Re=ke.length===0&&he?"audio":"best";return{...H,probeState:"done",probeQualities:ke,probeHasAudio:he,quality:Re}}))}catch{b(D=>D.map(F=>F.id===j?{...F,probeState:"idle",probeQualities:null}:F))}},600);g.current.set(j,A)}else if(Dn(B)){const A=setTimeout(async()=>{g.current.delete(j),b(D=>D.map(F=>F.id===j?{...F,playlistProbeState:"probing"}:F));try{const D=await pm(x.current,B.trim());b(F=>F.map(H=>H.id!==j||H.locator!==B?H:{...H,playlistProbeState:"done",playlistInfo:D,playlistItems:D.items.map(ke=>({...ke,quality:null})),playlistQuality:null}))}catch{b(D=>D.map(F=>F.id===j?{...F,playlistProbeState:"error"}:F))}},800);g.current.set(j,A)}}function yt(j,B){b(A=>A.map(D=>D.id===j?{...D,quality:B}:D))}function Ie(j,B){b(A=>A.map(D=>{if(D.id!==j)return D;const F=qm(B,D.playlistItems);return{...D,playlistQuality:B,playlistItems:F}}))}function st(j,B,A){b(D=>D.map(F=>F.id!==j?F:{...F,playlistItems:F.playlistItems.map(H=>H.id===B?{...H,quality:A}:H)}))}function Ze(j){b(B=>B.map(A=>A.id===j?{...A,playlistExpanded:!A.playlistExpanded}:A))}function $(j,B){b(A=>A.map(D=>D.id===j?{...D,syncEnabled:B}:D))}function Z(j,B){b(A=>A.map(D=>D.id!==j?D:{...D,playlistItems:D.playlistItems.filter(F=>F.id!==B)}))}function Ae(j){const B=Array.from(j);B.length!==0&&B.forEach(A=>{const D=Km(A.name);b(he=>he.length===1&&!he[0].kind&&!he[0].locator.trim()?[D]:[...he,D]);const F=x.current,{promise:H,abort:ke}=Bm(F,A,he=>{b(Re=>Re.map(ye=>ye.id===D.id?{...ye,uploadProgress:he}:ye))});h.current.set(D.id,ke),H.then(he=>{h.current.delete(D.id),b(Re=>Re.map(ye=>ye.id===D.id?{...ye,uploadStatus:"done",uploadLocator:he.locator,uploadProgress:100}:ye))}).catch(he=>{h.current.delete(D.id),he.message!=="Upload cancelled"&&b(Re=>Re.map(ye=>ye.id===D.id?{...ye,uploadStatus:"error",uploadError:he.message}:ye))})})}function Me(j){j.preventDefault(),j.stopPropagation(),j.dataTransfer.types.includes("Files")&&_(!0)}function Rt(j){j.currentTarget.contains(j.relatedTarget)||_(!1)}function zt(j){j.preventDefault(),j.stopPropagation(),_(!1),Ae(j.dataTransfer.files)}function It(j){Ae(j.target.files),j.target.value=""}const et=v.some(j=>j.kind==="file"&&j.uploadStatus==="uploading"),Xt=v.filter(j=>j.kind==="file"?j.uploadStatus==="done"&&j.uploadLocator:j.kind==="text"?j.title.trim()&&j.body.trim():j.locator.trim()).length,$t=v.some(j=>j.kind!=="file"&&j.kind!=="text"&&Au(j)),an=v.some(j=>j.kind!=="file"&&j.kind!=="text"&&Array.isArray(j.playlistItems)&&j.playlistItems.length===0),He=v.some(j=>j.kind!=="file"&&j.kind!=="text"&&(j.probeState==="probing"||Dn(j.locator)&&j.playlistProbeState!=="done"));return s.jsx("dialog",{ref:u,className:`capture-dialog${S?" capture-dialog--dragover":""}`,onDragOver:Me,onDragLeave:Rt,onDrop:zt,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:v.map((j,B)=>j.kind==="file"?s.jsx(Gm,{item:j,onRemove:()=>Ue(j.id)},j.id):j.kind==="text"?s.jsx(Ym,{item:j,autoFocus:B===v.length-1,onTitleChange:A=>b(D=>D.map(F=>F.id===j.id?{...F,title:A}:F)),onBodyChange:A=>b(D=>D.map(F=>F.id===j.id?{...F,body:A}:F)),onMimeChange:A=>b(D=>D.map(F=>F.id===j.id?{...F,mime:A}:F)),onRemove:()=>Ue(j.id),onSubmit:te},j.id):s.jsx(Jm,{item:j,autoFocus:B===v.length-1,onLocatorChange:A=>Lt(j.id,A),onQualityChange:A=>yt(j.id,A),onRemove:()=>Ue(j.id),onSubmit:te,onPlaylistQualityChange:A=>Ie(j.id,A),onPlaylistItemQualityChange:(A,D)=>st(j.id,A,D),onPlaylistToggle:()=>Ze(j.id),onSyncChange:A=>$(j.id,A),onPlaylistItemDelete:A=>Z(j.id,A)},j.id))}),s.jsx("input",{ref:w,type:"file",multiple:!0,hidden:!0,onChange:It,"aria-hidden":"true",tabIndex:-1}),s.jsxs("div",{className:"capture-add-row-group",children:[s.jsxs("button",{type:"button",className:"capture-add-row",onClick:re,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=w.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("button",{type:"button",className:"capture-add-row capture-add-text",onClick:()=>b(j=>[...j,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(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":se,className:`ext-toggle ext-toggle--sm${se?" ext-toggle--on":""}`,onClick:()=>ne(j=>j===null?!se:!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"}),!(q!=null&&q.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":Le,className:`ext-toggle ext-toggle--sm${Le?" ext-toggle--on":""}`,onClick:()=>ve(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":ie,className:`ext-toggle ext-toggle--sm${ie?" 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":I,className:`ext-toggle ext-toggle--sm${I?" ext-toggle--on":""}`,onClick:()=>R(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":K,className:`ext-toggle ext-toggle--sm${K?" ext-toggle--on":""}`,onClick:()=>ee(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:te,disabled:Xt===0||$t||He||an||et,children:Xt>1?`Archive ${Xt}`:"Archive"}),s.jsx("button",{type:"button",className:"capture-cancel",onClick:()=>{var j;return(j=u.current)==null?void 0:j.close()},children:"Cancel"})]})]})})}function Jm({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 w;t&&((w=g.current)==null||w.focus())},[t]);const m=(()=>{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 w=[...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),_=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"}),w.map(p=>s.jsxs("option",{value:`${p}p`,children:[p,"p"]},p)),S&&s.jsx("option",{value:"audio",children:"Audio only"})]}),_>0&&s.jsxs("span",{className:"capture-conflict-badge",children:[_," 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(!ff(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 w=e.probeQualities??[],S=e.probeHasAudio??!1;return w.length===0&&!S?s.jsx("span",{className:"capture-quality-hint",children:"No media detected"}):w.length===0&&S?s.jsx("select",{className:"capture-quality",value:"audio",onChange:_=>r(_.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:_=>r(_.target.value),"aria-label":"Video quality",children:[s.jsx("option",{value:"best",children:"Best quality"}),w.map(_=>s.jsx("option",{value:_,children:_},_)),S&&s.jsx("option",{value:"audio",children:"Audio only"})]})}return null})(),x=Dn(e.locator)&&e.playlistProbeState==="done"?s.jsxs("label",{className:"capture-sync-row",children:[s.jsx("input",{type:"checkbox",checked:e.syncEnabled,onChange:w=>d(w.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:w=>n(w.target.value),onKeyDown:w=>{w.key==="Enter"&&i()},autoComplete:"off",spellCheck:!1}),m,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(w=>s.jsxs("div",{className:`capture-playlist-item${w.quality===null?" capture-playlist-item--conflict":""}`,children:[s.jsx("span",{className:"capture-playlist-item-title",children:w.title||w.url}),s.jsxs("select",{className:"capture-item-quality",value:w.quality??"",onChange:S=>o(w.id,S.target.value),"aria-label":`Quality for ${w.title||w.url}`,children:[w.quality===null&&s.jsx("option",{value:"",disabled:!0,children:"Choose…"}),s.jsx("option",{value:"best",children:"Best quality"}),w.qualities.map(S=>s.jsx("option",{value:S,children:S},S)),w.has_audio&&s.jsx("option",{value:"audio",children:"Audio only"})]}),w.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 ${w.title||w.url}`,onClick:()=>y(w.id),children:"×"})]},w.id)),x]}):x]})}function Gm({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 Ym({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 Zm=["list=","/playlist/","/channel/","yt:playlist:","yt:channel:","ytm:playlist:","spotify:playlist:","spotify:album:"];function eg(e){const t=e.toLowerCase();return Zm.some(n=>t.includes(n))}function tg(e){return e.length>80?`${e.slice(0,79)}…`:e}function ng({locator:e=""}){const t=String(e),n=eg(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:tg(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 ml(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 xt(e){return rg(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 Mu={youtube:'',youtube_music:'',spotify:'',x:'',instagram:'',facebook:'',tiktok:'',reddit:'',snapchat:'',local:'',web:'',other:'?'};function Us(e){return Mu[e]??Mu.other}function pf(e){return e.split("/").map(t=>t?t.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"").join("/")}function lg({entry:e,index:t,onRowClick:n,selectedUids:r,isFirst:l,isLast:i,reorderDisabled:a,onMove:o,canReorder:u,isDragging:d,dropEdge:y,onHandleDragStart:g,onHandleDragEnd:m,onRowDragOver:x,onRowDrop:w}){const S=(r==null?void 0:r.size)===1&&r.has(e.entry_uid),_=(r==null?void 0:r.size)>=2&&r.has(e.entry_uid),p=xt(e.title)||xt(e.entry_uid),f=["child-entry-row",t%2===0?"child-entry-row--light":"child-entry-row--dark",S&&"is-selected",_&&"is-multi-selected",d&&"is-dragging",y==="before"&&"is-drop-before",y==="after"&&"is-drop-after"].filter(Boolean).join(" ");return s.jsxs("div",{className:f,tabIndex:0,"data-entry-uid":e.entry_uid,onMouseDown:h=>{h.shiftKey&&h.preventDefault()},onClick:h=>n(e,h),onDragOver:u?x:void 0,onDrop:u?w:void 0,"aria-keyshortcuts":u?"Alt+ArrowUp Alt+ArrowDown":void 0,onKeyDown:h=>{if(u&&h.altKey&&(h.key==="ArrowUp"||h.key==="ArrowDown")){h.preventDefault(),a||o(h.key==="ArrowUp"?-1:1);return}h.key==="Enter"&&n(e,h)},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:[u&&s.jsxs("span",{className:"child-reorder-controls",children:[s.jsx("span",{className:"child-drag-handle",draggable:!a,title:"Drag to reorder (or Alt+↑/↓)","aria-hidden":"true",onClick:h=>h.stopPropagation(),onDragStart:g,onDragEnd:m,children:"⋮⋮"}),s.jsx("button",{type:"button",className:"child-move-btn","aria-label":`Move ${p} up`,disabled:a||l,onClick:h=>{h.stopPropagation(),o(-1)},onKeyDown:h=>h.stopPropagation(),children:"↑"}),s.jsx("button",{type:"button",className:"child-move-btn","aria-label":`Move ${p} down`,disabled:a||i,onClick:h=>{h.stopPropagation(),o(1)},onKeyDown:h=>h.stopPropagation(),children:"↓"})]}),s.jsx("span",{className:"source-icon",children:s.jsx("span",{dangerouslySetInnerHTML:{__html:Us(e.source_kind)}})}),s.jsx("span",{className:"entry-title",children:p})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"type-pill",children:xt(e.entity_kind)})}),s.jsx("div",{className:"col-size",children:s.jsx("span",{className:"size-total",children:ml(e.total_artifact_bytes)})}),s.jsx("div",{className:"url-cell col-url",children:xt(e.original_url)})]})}function sg({entry:e,archiveId:t,rowIndex:n,isSelected:r,isMultiSelected:l,onRowClick:i,selectedUids:a,deletedUids:o,renamedTitles:u,isPublicSession:d,canReorder:y=!1,onReorderError:g}){const[m,x]=c.useState(!1),[w,S]=c.useState(!1),[_,p]=c.useState(null),[f,h]=c.useState(!1),[k,E]=c.useState(!1),[P,N]=c.useState(null),[v,b]=c.useState(null),L=c.useRef(null),X=c.useRef(null),ne=e.source_kind==="web"&&e.entity_kind==="page"&&e.has_favicon&&t&&!m?s.jsx("img",{src:`/api/archives/${t}/entries/${e.entry_uid}/favicon`,width:"16",height:"16",alt:"",onError:()=>x(!0),style:{objectFit:"contain"}}):s.jsx("span",{dangerouslySetInnerHTML:{__html:Us(e.source_kind)}}),q=r||l,fe=e.child_count>0&&!d;function Le(U){U.stopPropagation(),i(e,{ctrlKey:!0,metaKey:!1,shiftKey:!1,preventDefault(){}})}async function ve(U){if(U.stopPropagation(),w){S(!1);return}if(S(!0),_===null&&!f){h(!0);try{const te=await Iu(t,e.entry_uid);p(te)}catch{p([])}finally{h(!1)}}}const I=(_??[]).filter(U=>!(o!=null&&o.has(U.entry_uid))).map(U=>u!=null&&u.has(U.entry_uid)?{...U,title:u.get(U.entry_uid)}:U);async function R(U){const te=_;p(U),E(!0);try{await tm(t,e.entry_uid,U.map(re=>re.entry_uid))}catch(re){if(p(te),g==null||g(re.message),re.status===400)try{p(await Iu(t,e.entry_uid))}catch{}}finally{E(!1)}}function K(U,te){if(!y||k||U===te||te<0||te>=I.length)return;const re=I.slice(),[Ue]=re.splice(U,1);re.splice(te,0,Ue),R(re)}function ee(U,te){var re;X.current=((re=I[U])==null?void 0:re.entry_uid)??null,K(U,U+te)}c.useEffect(()=>{const U=X.current;if(!U||!L.current)return;X.current=null;const te=L.current.querySelector(`[data-entry-uid="${CSS.escape(U)}"]`);te&&!te.contains(document.activeElement)&&te.focus()},[_]);function se(U,te){te.stopPropagation(),te.dataTransfer.effectAllowed="move",te.dataTransfer.setData("text/plain",U);const re=te.currentTarget.closest(".child-entry-row");re&&te.dataTransfer.setDragImage(re,16,re.offsetHeight/2),N(U)}function ie(){N(null),b(null)}function Y(U,te){if(!P)return;te.preventDefault(),te.dataTransfer.dropEffect="move";const re=te.currentTarget.getBoundingClientRect(),Ue=te.clientY>re.top+re.height/2;((v==null?void 0:v.uid)!==U||(v==null?void 0:v.after)!==Ue)&&b({uid:U,after:Ue})}function Ne(U,te){if(!P)return;te.preventDefault();const re=I.findIndex(Ie=>Ie.entry_uid===P),Ue=I.findIndex(Ie=>Ie.entry_uid===U),Lt=(v==null?void 0:v.uid)===U?v.after:!1;if(ie(),re===-1||Ue===-1)return;let yt=Ue+(Lt?1:0);re{U.shiftKey&&U.preventDefault()},onClick:U=>i(e,U),onKeyDown:U=>{U.key==="Enter"&&i(e,U)},children:[s.jsx("div",{className:"col-check",children:s.jsx("button",{type:"button",className:`row-checkbox${q?" is-checked":""}`,"aria-pressed":q,"aria-label":q?"Deselect entry":"Select entry",onClick:Le,onKeyDown:U=>U.stopPropagation()})}),s.jsx("div",{className:"col-added",children:ko(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[fe&&s.jsx("button",{type:"button",className:`entry-expand-btn${w?" is-expanded":""}`,"aria-label":w?"Collapse children":`Expand ${e.child_count} items`,"aria-expanded":w,onClick:ve,onKeyDown:U=>U.stopPropagation()}),s.jsx("span",{className:"source-icon",children:ne}),s.jsx("span",{className:"entry-title",children:xt(e.title)||xt(e.entry_uid)}),fe&&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:xt(e.entity_kind)})}),s.jsxs("div",{className:"col-size",children:[s.jsx("span",{className:"size-total",children:ml(e.total_artifact_bytes)}),e.cached_bytes>0&&e.cacheable_bytes>0&&s.jsxs("span",{className:"size-cached-pct",title:`${ml(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:xt(e.original_url)})]}),w&&s.jsxs(s.Fragment,{children:[f&&s.jsx("div",{className:"child-entries-loading",children:"Loading…"}),s.jsx("div",{className:"child-entries",ref:L,"aria-busy":k,"aria-label":`${e.child_count} child entries`,children:I.map((U,te)=>s.jsx(lg,{entry:U,index:te,onRowClick:i,selectedUids:a,isFirst:te===0,isLast:te===I.length-1,reorderDisabled:k,canReorder:y,onMove:re=>ee(te,re),isDragging:P===U.entry_uid,dropEdge:(v==null?void 0:v.uid)===U.entry_uid&&P!==U.entry_uid?v.after?"after":"before":null,onHandleDragStart:re=>se(U.entry_uid,re),onHandleDragEnd:ie,onRowDragOver:re=>Y(U.entry_uid,re),onRowDrop:re=>Ne(U.entry_uid,re)},U.entry_uid))})]})]})}function ig({entries:e,selectedUids:t,onRowClick:n,archiveId:r,pendingCaptures:l=[],deletedUids:i,renamedTitles:a,isPublicSession:o,canReorder:u=!1,onChildReorderError:d}){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(y=>y.archiveId===r).reverse().map(y=>s.jsx(ng,{locator:y.locator},y.id)),e.map((y,g)=>s.jsx(sg,{entry:y,rowIndex:g,archiveId:r,isSelected:t.size===1&&t.has(y.entry_uid),isMultiSelected:t.size>=2&&t.has(y.entry_uid),onRowClick:n,selectedUids:t,deletedUids:i,renamedTitles:a,isPublicSession:o,canReorder:u,onReorderError:d},y.entry_uid))]})]})})}function ag(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 og({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 ug({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:ag(l.started_at)}),s.jsxs("td",{children:[s.jsx(og,{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 cg=4;function dg({archives:e}){const{currentUser:t}=c.useContext(Hs)??{},n=t&&(t.role_bits&cg)!==0,[r,l]=c.useState("users"),[i,a]=c.useState([]),[o,u]=c.useState([]),[d,y]=c.useState(!1),[g,m]=c.useState(null),[x,w]=c.useState(""),[S,_]=c.useState(""),[p,f]=c.useState(""),[h,k]=c.useState(null),[E,P]=c.useState(!1),[N,v]=c.useState(""),[b,L]=c.useState(""),[X,Q]=c.useState(null),[ne,q]=c.useState(!1),fe=c.useCallback(async()=>{if(n){y(!0),m(null);try{const[R,K]=await Promise.all([_m(),df()]);a(R),u(K)}catch(R){m(R.message)}finally{y(!1)}}},[n]);c.useEffect(()=>{fe()},[fe]);async function Le(R){const K=R.status==="active"?"disabled":"active";try{await Cm(R.user_uid,K),a(ee=>ee.map(se=>se.user_uid===R.user_uid?{...se,status:K}:se))}catch(ee){m(ee.message)}}async function ve(R){if(R.preventDefault(),!x.trim()||!S){k("Username and password required");return}P(!0),k(null);try{await Nm(x.trim(),S,p.trim()||void 0),w(""),_(""),f(""),await fe()}catch(K){k(K.message)}finally{P(!1)}}async function I(R){if(R.preventDefault(),!N.trim()||!b.trim()){Q("Slug and name required");return}q(!0),Q(null);try{await Em(N.trim(),b.trim()),v(""),L(""),await fe()}catch(K){Q(K.message)}finally{q(!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(R=>s.jsxs("tr",{className:R.status==="disabled"?"admin-row-disabled":"",children:[s.jsx("td",{children:R.username}),s.jsx("td",{className:"muted",children:R.email||"—"}),s.jsx("td",{children:R.role_slugs.join(", ")||"—"}),s.jsx("td",{children:s.jsx("span",{className:`status-badge status-${R.status}`,children:R.status})}),s.jsx("td",{children:s.jsx("button",{className:"admin-action-btn",onClick:()=>Le(R),children:R.status==="active"?"Ban":"Unban"})})]},R.user_uid))})]}),s.jsx("h3",{children:"Create User"}),s.jsxs("form",{className:"admin-form",onSubmit:ve,children:[s.jsx("input",{className:"admin-input",placeholder:"Username",value:x,onChange:R=>w(R.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"password",placeholder:"Password (min 8 chars)",value:S,onChange:R=>_(R.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"email",placeholder:"Email (optional)",value:p,onChange:R=>f(R.target.value)}),h&&s.jsx("div",{className:"form-msg form-msg--err",children:h}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:E,children:E?"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(R=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:R.slug})}),s.jsx("td",{children:R.name}),s.jsx("td",{children:R.level}),s.jsx("td",{children:R.bit_position}),s.jsx("td",{children:R.is_builtin?"✓":""})]},R.role_uid))})]}),s.jsx("h3",{children:"Create Custom Role"}),s.jsxs("form",{className:"admin-form",onSubmit:I,children:[s.jsx("input",{className:"admin-input",placeholder:"Slug (e.g. moderator)",value:N,onChange:R=>v(R.target.value),required:!0}),s.jsx("input",{className:"admin-input",placeholder:"Display Name (e.g. Moderator)",value:b,onChange:R=>L(R.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:ne,children:ne?"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(R=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:R.label}),s.jsx("div",{className:"muted",children:R.archive_path})]},R.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(R=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:R.label}),s.jsx("div",{className:"muted",children:R.archive_path})]},R.id))})]})}function hf({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(hf,{node:r,onPick:t},r.tag.tag_uid))})})]})}function Fu({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(hf,{node:o,onPick:r},o.tag.tag_uid))}):s.jsx("p",{className:"tag-picker-empty",children:"No other tags available."})]})]})})}function mf({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 om(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 gf({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:m,onCreateCancel:x}){var X;const w=n===e.tag.full_path,[S,_]=c.useState(!1),[p,f]=c.useState(""),h=c.useRef(!1);function k(){if(S)return;if(d){y(e);return}const Q=w?null:e.tag.full_path;r(Q),l("archive")}function E(Q){Q.stopPropagation(),!d&&(f(e.tag.slug),_(!0))}async function P(){const Q=p.trim();if(!Q||Q===e.tag.slug){_(!1);return}try{const ne=await im(t,e.tag.tag_uid,Q);i(e.tag.full_path,ne.full_path),o()}catch{}finally{_(!1)}}async function N(Q){var q;Q.stopPropagation();const ne=((q=e.children)==null?void 0:q.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(ne))try{await am(t,e.tag.tag_uid),a(e.tag.full_path),o()}catch{}}const v={archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:d,onMoveSourceSelect:y,pendingCreateParentUid:g,onCreateDone:m,onCreateCancel:x},b=g===e.tag.tag_uid,L=((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:Q=>f(Q.target.value),onKeyDown:Q=>{Q.key==="Enter"&&Q.currentTarget.blur(),Q.key==="Escape"&&(h.current=!0,Q.currentTarget.blur())},onBlur:()=>{h.current?(h.current=!1,_(!1)):P()}}):s.jsxs("button",{className:`tag-node-btn${w?" 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:E,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:Q=>{Q.stopPropagation(),E(Q)},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:N,"aria-label":`Delete "${e.tag.full_path}"`,children:"×"})]}),(L||b)&&s.jsx("div",{className:"tag-children",children:s.jsxs("ul",{className:"tag-tree-list",children:[e.children.map(Q=>s.jsx(gf,{node:Q,...v},Q.tag.tag_uid)),b&&s.jsx("li",{children:s.jsx(mf,{parentPath:e.tag.full_path,archiveId:t,onDone:m,onCancel:x})})]})})]})}function fg({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,m]=c.useState(null);function x(){y("select-source"),m(null)}function w(){y(null),m(null)}c.useEffect(()=>{if(d!=="select-source")return;function ne(q){q.key==="Escape"&&(q.preventDefault(),q.stopPropagation(),w())}return document.addEventListener("keydown",ne),()=>document.removeEventListener("keydown",ne)},[d]);function S(ne){m(ne),y("select-dest")}async function _(ne){const q=g.tag.full_path,fe=g.tag.tag_uid,Le=(ne==null?void 0:ne.tag_uid)??null;w();try{const ve=await um(e,fe,Le);i(q,ve.full_path),o()}catch(ve){alert(ve.message||"Move failed")}}const[p,f]=c.useState(null),[h,k]=c.useState(void 0);function E(){f("select-parent"),k(void 0)}function P(){f(null),k(void 0)}function N(ne){k(ne??null),f("input")}function v(){f(null),k(void 0),o()}const b=d==="select-source",L=p==="input"?h?h.tag_uid:"__root__":void 0,X={archiveId:e,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:b,onMoveSourceSelect:S,pendingCreateParentUid:L,onCreateDone:v,onCreateCancel:P},Q=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:b?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:w,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:E,title:"Create a new tag",disabled:!!p||!!d,children:"+ New"}),s.jsx("button",{className:"tag-tree-action-btn",onClick:x,title:"Move a tag to a different parent",disabled:!!p||!!d||t.length===0,children:"Move"})]})]})}),t.length===0&&!Q?s.jsx("p",{className:"muted",style:{padding:"8px 0"},children:"No tags yet."}):s.jsxs("ul",{className:"tag-tree-list",children:[t.map(ne=>s.jsx(gf,{node:ne,...X},ne.tag.tag_uid)),Q&&s.jsx("li",{children:s.jsx(mf,{parentPath:null,archiveId:e,onDone:v,onCancel:P})})]})]}),p==="select-parent"&&s.jsx(Fu,{title:"Create tag under…",tagNodes:t,excludeUid:null,onPick:N,onCancel:P}),d==="select-dest"&&g&&s.jsx(Fu,{title:`Move "${g.tag.slug}" under…`,tagNodes:t,excludeUid:g.tag.tag_uid,onPick:_,onCancel:w})]})}const Fr=[{value:0,label:"Private"},{value:2,label:"Users only"},{value:3,label:"Public"}],pg=e=>{var t;return((t=Fr.find(n=>n.value===e))==null?void 0:t.label)??String(e)};function hg({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,m]=c.useState(!1),[x,w]=c.useState(null),[S,_]=c.useState(""),[p,f]=c.useState(""),[h,k]=c.useState(2),[E,P]=c.useState(!1),[N,v]=c.useState(!0),[b,L]=c.useState(null),[X,Q]=c.useState(""),[ne,q]=c.useState(2),[fe,Le]=c.useState(!1),[ve,I]=c.useState(null),[R,K]=c.useState(!1),[ee,se]=c.useState(""),ie=c.useRef(null),Y=t.find($=>$.collection_uid===o)??null,Ne=(Y==null?void 0:Y.slug)==="_default_",pe=c.useCallback(async()=>{if(e){l(!0),a(null);try{const $=await wo(e);n($)}catch($){a($.message)}finally{l(!1)}}},[e]),U=c.useCallback(async $=>{if(!$){y(null);return}m(!0),w(null);try{const Z=await Tm(e,$);y(Z)}catch(Z){w(Z.message)}finally{m(!1)}},[e]);c.useEffect(()=>{pe()},[pe]),c.useEffect(()=>{U(o)},[o,U]),c.useEffect(()=>{R&&ie.current&&ie.current.focus()},[R]),c.useEffect(()=>{d!=null&&q(d.default_visibility_bits)},[d]);async function te($){$.preventDefault();const Z=S.trim(),Ae=p.trim();if(!(!Z||!Ae)){P(!0),L(null);try{const Me=await bm(e,Z,Ae,h,N);_(""),f(""),k(2),v(!0),await pe(),u(Me.collection_uid)}catch(Me){L(Me.message)}finally{P(!1)}}}async function re(){const $=ee.trim();if(!$||!Y){K(!1);return}try{await Ci(e,Y.collection_uid,{name:$}),await pe(),y(Z=>Z&&{...Z,name:$})}catch(Z){a(Z.message)}finally{K(!1)}}async function Ue($){if(Y)try{await Ci(e,Y.collection_uid,{default_visibility_bits:$}),await pe(),y(Z=>Z&&{...Z,default_visibility_bits:$})}catch(Z){a(Z.message)}}async function Lt($){if(Y)try{await Ci(e,Y.collection_uid,{requires_auth:$}),await pe(),y(Z=>Z&&{...Z,requires_auth:$})}catch(Z){a(Z.message)}}async function yt(){if(Y&&window.confirm(`Delete collection "${Y.name}"? Entries will not be deleted.`))try{await Rm(e,Y.collection_uid),u(null),y(null),await pe()}catch($){a($.message)}}async function Ie($){$.preventDefault();const Z=X.trim();if(!(!Z||!Y)){Le(!0),I(null);try{await Sa(e,Y.collection_uid,Z,ne),Q(""),await U(Y.collection_uid)}catch(Ae){I(Ae.message)}finally{Le(!1)}}}async function st($){if(Y)try{await Pm(e,Y.collection_uid,$),await U(Y.collection_uid)}catch(Z){w(Z.message)}}async function Ze($,Z){if(Y)try{await Lm(e,Y.collection_uid,$,Z),y(Ae=>Ae&&{...Ae,entries:Ae.entries.map(Me=>Me.entry_uid===$?{...Me,collection_visibility_bits:Z}:Me)})}catch(Ae){w(Ae.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($=>s.jsxs("button",{className:`coll-sidebar-row${o===$.collection_uid?" is-active":""}`,onClick:()=>u($.collection_uid),children:[s.jsx("span",{className:"coll-row-name",children:$.name}),s.jsx("span",{className:"coll-row-meta",children:pg($.default_visibility_bits)})]},$.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:[R?s.jsx("input",{ref:ie,className:"coll-rename-input",value:ee,onChange:$=>se($.target.value),onBlur:re,onKeyDown:$=>{$.key==="Enter"&&re(),$.key==="Escape"&&K(!1)}}):s.jsxs("h3",{className:`coll-detail-name${Ne?"":" coll-detail-name--editable"}`,title:Ne?void 0:"Click to rename",onClick:()=>{Ne||(se(Y.name),K(!0))},children:[(d==null?void 0:d.name)??Y.name,!Ne&&s.jsx("span",{className:"coll-edit-hint",children:" ✎"})]}),!Ne&&s.jsx("button",{className:"coll-delete-btn",onClick:yt,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)??Y.default_visibility_bits,onChange:$=>Ue(Number($.target.value)),children:Fr.map($=>s.jsx("option",{value:$.value,children:$.label},$.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)??Y.requires_auth),onChange:$=>Lt($.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…"}),x&&s.jsx("div",{className:"collections-error",children:x}),!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($=>s.jsxs("li",{className:"coll-entry-row",children:[s.jsxs("div",{className:"coll-entry-info",children:[s.jsx("span",{className:"coll-entry-title",children:$.title||$.entry_uid}),s.jsx("span",{className:"coll-entry-kind muted",children:$.source_kind})]}),s.jsxs("div",{className:"coll-entry-actions",children:[s.jsx("select",{className:"coll-entry-vis-select",value:$.collection_visibility_bits,onChange:Z=>Ze($.entry_uid,Number(Z.target.value)),children:Fr.map(Z=>s.jsx("option",{value:Z.value,children:Z.label},Z.value))}),!Ne&&s.jsx("button",{className:"coll-entry-remove",onClick:()=>st($.entry_uid),title:"Remove from collection",children:"×"})]})]},$.entry_uid))}))]}),!Ne&&s.jsxs("form",{className:"coll-add-entry-form",onSubmit:Ie,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:$=>Q($.target.value),placeholder:"entry_uid",required:!0}),s.jsx("select",{className:"coll-vis-select",value:ne,onChange:$=>q(Number($.target.value)),children:Fr.map($=>s.jsx("option",{value:$.value,children:$.label},$.value))}),s.jsx("button",{className:"coll-add-btn",type:"submit",disabled:fe,children:fe?"…":"Add"})]}),ve&&s.jsx("div",{className:"collections-error",style:{marginTop:4},children:ve})]})]}):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:te,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:$=>{_($.target.value),p||f($.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:$=>f($.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:h,onChange:$=>k(Number($.target.value)),children:Fr.map($=>s.jsx("option",{value:$.value,children:$.label},$.value))})]}),s.jsx("div",{className:"form-field",children:s.jsxs("label",{className:"form-label",children:[s.jsx("input",{type:"checkbox",checked:N,onChange:$=>v($.target.checked)})," Require authentication to view"]})}),b&&s.jsx("div",{className:"collections-error",children:b}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:E,children:E?"Creating…":"Create collection"})]})]})]}):s.jsx("div",{className:"view-placeholder",children:"Select an archive."})}const mg=4,gg=8;function yg({tab:e,onTabChange:t,archiveId:n}){const{currentUser:r,setCurrentUser:l}=c.useContext(Hs)??{},i=r&&(r.role_bits&mg)!==0,a=!!r&&(r.role_bits&gg)!==0,o=["profile","tokens",...i?["instance","cookies","extensions","storage"]:[]],u={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:o.map(d=>s.jsx("button",{className:`view-tab${e===d?" is-active":""}`,onClick:()=>t(d),children:u[d]},d))}),e==="profile"&&s.jsx(vg,{currentUser:r,setCurrentUser:l}),e==="tokens"&&s.jsx(xg,{}),e==="instance"&&i&&s.jsx(wg,{isOwner:a,setCurrentUser:l}),e==="cookies"&&i&&s.jsx(jg,{}),e==="extensions"&&i&&s.jsx(Sg,{}),e==="storage"&&i&&s.jsx(kg,{archiveId:n})]})}function vg({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(""),[m,x]=c.useState(""),[w,S]=c.useState(!1),[_,p]=c.useState(null);async function f(k){k.preventDefault(),i(!0),o(null);try{await vm(n),t(E=>({...E,display_name:n||null})),o({ok:!0,text:"Saved."})}catch(E){o({ok:!1,text:E.message})}finally{i(!1)}}async function h(k){if(k.preventDefault(),y!==m){p({ok:!1,text:"Passwords do not match."});return}S(!0),p(null);try{await wm(u,y),d(""),g(""),x(""),p({ok:!0,text:"Password changed."})}catch(E){p({ok:!1,text:E.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 E=k.target.checked;try{await xm({humanize_slugs:E}),t(P=>({...P,humanize_slugs:E}))}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:h,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:m,onChange:k=>x(k.target.value),required:!0})]}),_&&s.jsx("div",{className:`form-msg form-msg--${_.ok?"ok":"err"}`,children:_.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:w,children:w?"Changing…":"Change Password"})]})]})]})}function xg(){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),m=c.useCallback(async()=>{r(!0),i(null);try{t(await km())}catch(S){i(S.message)}finally{r(!1)}},[]);c.useEffect(()=>{m()},[m]);async function x(S){if(S.preventDefault(),!!a.trim()){d(!0);try{const _=await jm(a.trim());g(_),o(""),m()}catch(_){i(_.message)}finally{d(!1)}}}async function w(S){try{await Sm(S),t(_=>_.filter(p=>p.token_uid!==S))}catch(_){i(_.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:x,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:()=>w(S.token_uid),children:"Revoke"})]},S.token_uid))]})]})})}function wg({isOwner:e,setCurrentUser:t}){const[n,r]=c.useState(null),[l,i]=c.useState(!0),[a,o]=c.useState(null),[u,d]=c.useState(!1),[y,g]=c.useState(null),[m,x]=c.useState([]),[w,S]=c.useState(12),[_,p]=c.useState(!1),[f,h]=c.useState(null);c.useEffect(()=>{(async()=>{try{const[N,v]=await Promise.all([xo(),df()]);r(N),x(v.filter(b=>b.bit_position>0)),S(N.reorder_children_role_bits??12)}catch(N){o(N.message)}finally{i(!1)}})()},[]);function k(N,v){S(b=>v?(b|N)>>>0:(b&~N)>>>0)}async function E(N){N.preventDefault(),p(!0),h(null);try{await Jr({reorder_children_role_bits:w}),r(b=>({...b,reorder_children_role_bits:w}));const v=await cf();v&&(t==null||t(v)),h({ok:!0,text:"Saved."})}catch(v){h({ok:!1,text:v.message})}finally{p(!1)}}async function P(N){N.preventDefault(),d(!0),g(null);try{const{reorder_children_role_bits:v,...b}=n;await Jr(b),g({ok:!0,text:"Saved."})}catch(v){g({ok:!1,text:v.message})}finally{d(!1)}}return l?s.jsx("div",{className:"muted",children:"Loading…"}):a?s.jsx("div",{className:"form-msg form-msg--err",children:a}):n?s.jsxs("div",{style:{maxWidth:440},children:[s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Instance Settings"}),s.jsxs("form",{onSubmit:P,children:[[["public_index_enabled","Public index (unauthenticated browsing)"],["public_entry_content_enabled","Public entry content"],["open_registration_enabled","Open registration"]].map(([N,v])=>s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:!!n[N],onChange:b=>r(L=>({...L,[N]:b.target.checked}))}),v]},N)),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:n.default_entry_visibility,onChange:N=>r(v=>({...v,default_entry_visibility:Number(N.target.value)})),children:[s.jsx("option",{value:0,children:"Private"}),s.jsx("option",{value:2,children:"Unlisted"}),s.jsx("option",{value:3,children:"Public"})]})]}),y&&s.jsx("div",{className:`form-msg form-msg--${y.ok?"ok":"err"}`,children:y.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:u,children:u?"Saving…":"Save Settings"})]})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Permissions"}),s.jsxs("form",{onSubmit:E,children:[s.jsx("label",{className:"form-label",children:"Reorder child entries"}),m.map(N=>{const v=1<>>0;return s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",disabled:!e||_,checked:(w&v)!==0,onChange:b=>k(v,b.target.checked)}),N.name,!N.is_builtin&&s.jsx("span",{className:"muted",children:" (custom)"})]},N.role_uid)}),s.jsx("p",{className:"form-hint",children:"Roles are cumulative: every signed-in account also has User, and owners also have Admin. Checking User lets every signed-in account reorder."}),!e&&s.jsx("p",{className:"form-hint",children:"Only the owner can change this."}),f&&s.jsx("div",{className:`form-msg form-msg--${f.ok?"ok":"err"}`,children:f.text}),e&&s.jsx("button",{className:"btn-primary",type:"submit",disabled:_,children:_?"Saving…":"Save Permissions"})]})]})]}):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 kg({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 x=await zm(e);l(x),n("scanned")}catch(x){u(x.message),n("error")}}async function g(){n("deleting"),u(null);try{const x=await Im(e);a(x),n("done")}catch(x){u(x.message),n("error")}}const m=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&&m&&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&&!m&&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 jg(){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("{}"),[m,x]=c.useState(null),[w,S]=c.useState(!1),[_,p]=c.useState({});c.useEffect(()=>{f()},[]);async function f(){r(!0),i(null);try{t(await Om())}catch(v){i(v.message)}finally{r(!1)}}async function h(v){v.preventDefault();try{JSON.parse(y)}catch{x({ok:!1,text:'cookies must be valid JSON, e.g. {"session": "abc"}'});return}S(!0),x(null);try{await Am(a==="global"?null:u.trim(),a,y),d(""),g("{}"),o("global"),x({ok:!0,text:"Rule added."}),await f()}catch(b){x({ok:!1,text:b.message})}finally{S(!1)}}async function k(v){try{await Fm(v),await f()}catch(b){i(b.message)}}function E(v){p(b=>({...b,[v.rule_uid]:{cookiesInput:v.cookies_json,saving:!1,msg:null}}))}function P(v){p(b=>{const L={...b};return delete L[v],L})}async function N(v){const b=_[v.rule_uid];try{JSON.parse(b.cookiesInput)}catch{p(L=>({...L,[v.rule_uid]:{...L[v.rule_uid],msg:{ok:!1,text:"Invalid JSON"}}}));return}p(L=>({...L,[v.rule_uid]:{...L[v.rule_uid],saving:!0,msg:null}}));try{await Mm(v.rule_uid,{cookies_json:b.cookiesInput}),P(v.rule_uid),await f()}catch(L){p(X=>({...X,[v.rule_uid]:{...X[v.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(v=>{const b=_[v.rule_uid],L=v.url_pattern?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"muted",children:[v.pattern_kind,":"]})," ",s.jsx("code",{children:v.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:b?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:12,width:"100%",minHeight:60},value:b.cookiesInput,onChange:X=>p(Q=>({...Q,[v.rule_uid]:{...Q[v.rule_uid],cookiesInput:X.target.value}}))}),b.msg&&s.jsx("div",{className:`form-msg form-msg--${b.msg.ok?"ok":"err"}`,children:b.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:b.saving,onClick:()=>N(v),children:b.saving?"Saving…":"Save"}),s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>P(v.rule_uid),children:"Cancel"})]})]}):s.jsx("code",{style:{fontSize:12,wordBreak:"break-all"},children:v.cookies_json})}),s.jsx("td",{children:!b&&s.jsxs("div",{style:{display:"flex",gap:6},children:[s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>E(v),children:"Edit"}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"2px 8px"},onClick:()=>k(v.rule_uid),children:"Del"})]})})]},v.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:h,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:v=>o(v.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:v=>d(v.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:v=>g(v.target.value),placeholder:'{"SESSION": "abc123", "token": "xyz"}',required:!0})]}),m&&s.jsx("div",{className:`form-msg form-msg--${m.ok?"ok":"err"}`,children:m.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:w,children:w?"Adding…":"Add Rule"})]})]})})}function Sg(){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(_){o({ok:!1,text:_.message})}finally{r(!1)}})()},[]);async function u(_){i(!0),o(null);try{await Jr({ublock_enabled:_}),t(p=>({...p,ublock_enabled:_})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function d(_){i(!0),o(null);try{await Jr({cookie_ext_enabled:_}),t(p=>({...p,cookie_ext_enabled:_})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function y(_){i(!0),o(null);try{await Jr({modal_closer_enabled:_}),t(p=>({...p,modal_closer_enabled:_})),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,m=(e==null?void 0:e.ublock_enabled)??!0,x=(e==null?void 0:e.cookie_ext_available)??!1,w=(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":m,className:`ext-toggle${m?" ext-toggle--on":""}`,onClick:()=>u(!m),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."}),!x&&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":w,className:`ext-toggle${w?" ext-toggle--on":""}`,onClick:()=>d(!w),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 Bu={0:"Private",1:"Public",2:"Users only",3:"Public"},es=[{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"}],_g=Object.fromEntries(es.map(e=>[e.value,e.label])),Uu="archivr:summary:provider",Ng=1500,yf="This entry can’t be summarized yet.",vf="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.",Hu=`${yf} + +${vf}`;function Cg(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 Eg=()=>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 bg({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:m,onOpenPreview:x,onPlay:w,isPublicSession:S}){var Ee,We,je;const[_,p]=c.useState([]),[f,h]=c.useState(""),[k,E]=c.useState([]),[P,N]=c.useState(""),v=c.useRef(0),b=c.useRef(!1),[L,X]=c.useState(!1),[Q,ne]=c.useState(""),[q,fe]=c.useState("idle"),[Le,ve]=c.useState(""),I=c.useRef(null),[R,K]=c.useState(!1);c.useEffect(()=>{K(!1)},[(Ee=l==null?void 0:l.summary)==null?void 0:Ee.entry_uid]);const[ee,se]=c.useState(null),[ie,Y]=c.useState(null),[Ne,pe]=c.useState(""),[U,te]=c.useState(!1),[re,Ue]=c.useState(()=>{try{return sessionStorage.getItem(Uu)||es[0].value}catch{return es[0].value}}),[Lt,yt]=c.useState(!1),Ie=c.useRef(null),st=c.useRef(null),Ze=c.useRef(null),$=c.useRef(null),Z=e&&(t!=null&&t.entry_uid)?`${e}:${t.entry_uid}`:null;$.current=Z;const Ae=(n==null?void 0:n.size)>=2,[Me,Rt]=c.useState(""),[zt,It]=c.useState("idle"),[et,Xt]=c.useState(""),[$t,an]=c.useState([]),[He,j]=c.useState(""),[B,A]=c.useState("idle"),[D,F]=c.useState(""),[H,ke]=c.useState("idle"),[he,Re]=c.useState(""),[ye,Fe]=c.useState("idle"),[ce,it]=c.useState("");c.useEffect(()=>{const T=++v.current;if(I.current&&(clearInterval(I.current),I.current=null),fe("idle"),ve(""),!t||!e){p([]),E([]);return}if(S){p([]),E([]);return}X(!1),ne(""),b.current=!1,p([]),Promise.all([Fl(e,t.entry_uid),Ou(e,t.entry_uid)]).then(([J,ae])=>{T===v.current&&(p(J),E(ae))}).catch(()=>{})},[t,e,S]),c.useEffect(()=>()=>{clearInterval(I.current)},[]),c.useLayoutEffect(()=>{var J,ae,me;clearInterval(Ie.current),Ie.current=null,(J=st.current)==null||J.abort(),st.current=null,(ae=Ze.current)==null||ae.abort(),Ze.current=null;const T=(t==null?void 0:t.entry_uid)!=null&&((me=l==null?void 0:l.summary)==null?void 0:me.entry_uid)===(t==null?void 0:t.entry_uid);se(T?l.latest_summary??null:null),Y(T?l.summary_attempt??null:null),pe(""),te(!1),yt(!1)},[e,t==null?void 0:t.entry_uid,(We=l==null?void 0:l.summary)==null?void 0:We.entry_uid]);const dt=ie==null?void 0:ie.status;c.useEffect(()=>{var on;if(clearInterval(Ie.current),Ie.current=null,dt!=="pending"&&dt!=="running"||!e||!((on=l==null?void 0:l.summary)!=null&&on.entry_uid))return;const T=l.summary.entry_uid,J=`${e}:${T}`;if(Z!==J)return;const ae=new AbortController;st.current=ae;const $e=setInterval(async()=>{var xe;try{const un=await Yh(e,T,{signal:ae.signal});if(ae.signal.aborted||$.current!==J)return;se(un.summary??null),Y(un.attempt??null);const Ys=(xe=un.attempt)==null?void 0:xe.status;Ys!=="pending"&&Ys!=="running"&&(clearInterval($e),Ie.current===$e&&(Ie.current=null),te(!1),Ys==="completed"&&$.current===J&&(m==null||m()))}catch{if(ae.signal.aborted||$.current!==J)return}},Ng);return Ie.current=$e,()=>{clearInterval($e),Ie.current===$e&&(Ie.current=null),ae.abort(),st.current===ae&&(st.current=null)}},[dt,e,t==null?void 0:t.entry_uid,(je=l==null?void 0:l.summary)==null?void 0:je.entry_uid,Z]),c.useEffect(()=>()=>{var T,J;clearInterval(Ie.current),(T=st.current)==null||T.abort(),(J=Ze.current)==null||J.abort()},[]);async function Nr(T=!1){var $e,on;if(!e||!(($e=l==null?void 0:l.summary)!=null&&$e.entry_uid)||U)return;const J=l.summary.entry_uid,ae=`${e}:${J}`;if($.current!==ae)return;const me=new AbortController;(on=Ze.current)==null||on.abort(),Ze.current=me,te(!0),pe("");try{const xe=await Zh(e,J,{provider:re,force:T,includeImages:Lt,signal:me.signal});if(me.signal.aborted||$.current!==ae)return;xe.status==="completed"?(se(xe),Y(null),te(!1),$.current===ae&&(m==null||m())):Y({...xe??{},status:"pending"})}catch(xe){if(me.signal.aborted||$.current!==ae)return;pe(xe.message||"Summary request failed"),te(!1)}finally{Ze.current===me&&(Ze.current=null)}}function Ws(T){Ue(T),T==="claude_cli"&&yt(!1);try{sessionStorage.setItem(Uu,T)}catch{}}c.useEffect(()=>{if(!e){an([]);return}wo(e).then(an).catch(()=>an([]))},[e]),c.useEffect(()=>{Rt(""),It("idle"),Xt(""),j(""),A("idle"),F(""),ke("idle"),Re(""),Fe("idle"),it("")},[n]);async function Vs(){const T=n.size;if(!window.confirm(`Delete ${T} entr${T===1?"y":"ies"}? This cannot be undone.`))return;ke("running");const J=new Set;for(const ae of n)try{await Du(e,ae),J.add(ae)}catch{}ke("idle"),y==null||y(J)}async function kl(){const T=Me.trim();if(T){It("running"),Xt("");try{for(const J of n)await $u(e,J,T);Rt(""),It("done"),o==null||o(),setTimeout(()=>It("idle"),1800)}catch(J){Xt(J.message),It("error")}}}async function Ks(){if(!He)return;A("running"),F("");const T=[],J=$t.find(ae=>ae.collection_uid===He);for(const ae of n)try{await Sa(e,He,ae,(J==null?void 0:J.default_visibility_bits)??2)}catch{T.push(ae)}T.length>0?(F(`Failed for ${T.length} entr${T.length===1?"y":"ies"}.`),A("error")):(A("done"),setTimeout(()=>A("idle"),1800))}async function Qs(){if(!he||!t)return;Fe("running"),it("");const T=$t.find(J=>J.collection_uid===he);try{await Sa(e,he,t.entry_uid,(T==null?void 0:T.default_visibility_bits)??2),Fe("done"),Re("");const J=await Ou(e,t.entry_uid);E(J),setTimeout(()=>Fe("idle"),1800)}catch(J){it(J.message),Fe("error")}}async function Kn(){const T=Q.trim()||null;try{await lm(e,t.entry_uid,T),u==null||u(t.entry_uid,T)}catch{}finally{X(!1)}}async function Qn(){const T=f.trim();if(!(!T||!t))try{await $u(e,t.entry_uid,T),h(""),N("");const J=await Fl(e,t.entry_uid);p(J),o()}catch(J){N(J.message)}}async function Pn(T){try{await sm(e,t.entry_uid,T);const J=await Fl(e,t.entry_uid);p(J),o()}catch{}}async function jl(){if(!(!t||!e)&&window.confirm("Delete this entry? This cannot be undone."))try{await Du(e,t.entry_uid),d==null||d(t.entry_uid)}catch{}}async function qs(){if(!t||!e||q==="running")return;const T=v.current,J=t.entry_uid;fe("running"),ve("");try{const{job_uid:ae}=await $m(e,J);if(v.current!==T)return;I.current=setInterval(async()=>{try{const me=await uf(e,ae);if(me.status==="completed"){if(clearInterval(I.current),I.current=null,v.current!==T)return;fe("done");const $e=await Fl(e,J);if(v.current!==T)return;p($e),m==null||m()}else if(me.status==="failed"){if(clearInterval(I.current),I.current=null,v.current!==T)return;fe("error"),ve(me.error_text||"Re-archive failed.")}}catch{if(clearInterval(I.current),I.current=null,v.current!==T)return;fe("error"),ve("Network error while polling.")}},500)}catch(ae){if(v.current!==T)return;fe("error"),ve(ae.message||"Failed to start re-archive.")}}const Xs=l?[["Added",ko(l.summary.archived_at)],["Source",l.summary.source_kind],["Type",l.summary.entity_kind],["Visibility",Bu[l.summary.visibility]??l.summary.visibility],["Root",l.structured_root_relpath]]:[],Js=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),Gs=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv","pdf","html","htm","md","markdown","txt","jpg","jpeg","png","gif","webp","avif","svg","bmp"]),C=l?l.artifacts.findIndex(T=>T.artifact_role==="primary_media"):-1,z=C>=0?l.artifacts[C]:null,M=z?z.relpath.split(".").pop().toLowerCase():"",W=z&&Js.has(M),G=C>=0&&t?`/api/archives/${e}/entries/${t.entry_uid}/artifacts/${C}`:null,ue=l&&!W&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread"||z&&Gs.has(M));return s.jsxs("aside",{className:"context-rail",children:[s.jsx("div",{className:"rail-eyebrow",children:"Context"}),Ae?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"}),et&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:et}),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:Me,onChange:T=>Rt(T.target.value),onKeyDown:T=>{T.key==="Enter"&&kl()}}),s.jsx("button",{className:"tag-add-btn",onClick:kl,disabled:zt==="running"||!Me.trim(),children:zt==="running"?"…":zt==="done"?"✓":"Add"})]})]}),$t.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:He,onChange:T=>j(T.target.value),children:[s.jsx("option",{value:"",children:"Pick a collection…"}),$t.filter(T=>T.slug!=="_default_").map(T=>s.jsx("option",{value:T.collection_uid,children:T.name},T.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:Ks,disabled:!He||B==="running",children:B==="running"?"…":B==="done"?"✓":B==="error"?"!":"Add"})]}),D&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"6px 0 0"},children:D})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:Vs,disabled:H==="running",children:H==="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:xt(l.summary.title)||xt(l.summary.entry_uid)}):L?s.jsx("input",{className:"rail-title-input",autoFocus:!0,value:Q,onChange:T=>ne(T.target.value),onKeyDown:T=>{T.key==="Enter"&&T.currentTarget.blur(),T.key==="Escape"&&(b.current=!0,T.currentTarget.blur())},onBlur:()=>{b.current?X(!1):Kn(),b.current=!1}}):s.jsxs("h2",{className:"rail-title rail-title--editable",title:"Click to rename",onClick:()=>{ne(l.summary.title??""),X(!0)},children:[xt(l.summary.title)||xt(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:Us(l.summary.source_kind)}}),s.jsx("span",{className:"u-text",children:l.summary.original_url}),s.jsx("span",{className:"ext",children:s.jsx(Eg,{})})]}),W&&w&&s.jsx("button",{className:"rail-preview-btn",onClick:()=>w(G,t),children:"▶ Play"}),ue&&x&&s.jsx("button",{className:"rail-preview-btn",onClick:x,children:"Preview"}),(()=>{const T=(ee==null?void 0:ee.status)==="completed"?Cg(ee.summary_text):null,J=(ie==null?void 0:ie.status)==="pending"||(ie==null?void 0:ie.status)==="running",ae=(ie==null?void 0:ie.status)==="failed"&&ie.error_text===Hu||Ne===Hu;return S&&!T?null:s.jsxs("div",{className:"rail-section rail-summary",children:[s.jsx("div",{className:"rail-section-heading",children:"Summary"}),T&&s.jsxs("div",{className:"rail-summary-body",children:[T.tldr&&s.jsx("p",{className:"rail-summary-tldr",children:T.tldr}),T.summary&&s.jsx("p",{className:"rail-summary-text",children:T.summary}),T.tags.length>0&&s.jsx("div",{className:"rail-summary-tags",children:T.tags.map(me=>s.jsx("span",{className:"rail-summary-tag",children:me},me))}),s.jsxs("p",{className:"rail-summary-provider",children:[_g[ee.provider_kind]||ee.provider_kind,ee.resolved_model||ee.provider_model?` · ${ee.resolved_model||ee.provider_model}`:""]})]}),J&&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:yf}),s.jsx("p",{className:"rail-summary-info__detail",children:vf})]}),(ie==null?void 0:ie.status)==="failed"&&ie.error_text&&!ae&&!S&&s.jsx("p",{className:"form-msg form-msg--err rail-summary-error",children:ie.error_text}),Ne&&!ae&&s.jsx("p",{className:"form-msg form-msg--err rail-summary-error",children:Ne}),!S&&!J&&s.jsxs("div",{className:"rail-summary-controls",children:[s.jsx("select",{className:"rail-summary-select",value:re,onChange:me=>Ws(me.target.value),"aria-label":"Summary provider",children:es.map(me=>s.jsx("option",{value:me.value,children:me.label},me.value))}),s.jsxs("div",{className:`rail-summary-image-option${re==="claude_cli"?" rail-summary-image-option--disabled":""}`,children:[s.jsxs("label",{className:"rail-summary-image-option__label",children:[s.jsx("input",{type:"checkbox",checked:Lt,disabled:re==="claude_cli",onChange:me=>yt(me.target.checked)}),"Include attached images"]}),s.jsx("p",{className:"rail-summary-image-option__note",children:re==="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:()=>Nr(!!T),disabled:U,children:U?"…":T?"Regenerate":"Generate"})]})]})})(),s.jsx("div",{className:"meta-list",children:Xs.filter(([,T])=>T!=null&&T!=="").map(([T,J])=>s.jsxs("div",{className:"meta-item",children:[s.jsx("span",{className:"meta-k",children:T}),s.jsx("span",{className:`meta-v${T==="Root"?" mono":""}`,children:xt(J)})]},T))}),l.artifacts.length>0&&(()=>{const T=l.artifacts.map((xe,un)=>({...xe,_idx:un})),J=T.filter(xe=>xe.artifact_role==="font"),ae=T.filter(xe=>xe.artifact_role!=="font"),me=J.reduce((xe,un)=>xe+(un.byte_size||0),0),$e=l.summary.entry_uid,on=xe=>s.jsx("li",{children:s.jsxs("a",{href:`/api/archives/${e}/entries/${$e}/artifacts/${xe._idx}`,target:"_blank",rel:"noopener noreferrer",className:"artifact-link",children:[s.jsx("span",{className:"artifact-name",children:xe.artifact_role==="font"?xe.relpath.split("/").pop():xe.artifact_role.replace(/_/g," ")}),s.jsx("span",{className:"artifact-size",children:xe.byte_size!=null?ml(xe.byte_size):"—"})]})},xe._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(on),J.length>0&&s.jsxs("li",{className:"artifact-group",children:[s.jsxs("button",{type:"button",className:"artifact-group-header artifact-link","aria-expanded":R,onClick:()=>K(xe=>!xe),children:[s.jsxs("span",{className:"artifact-name",children:[s.jsx("span",{"aria-hidden":"true",className:`artifact-group-chevron${R?" open":""}`,children:"›"}),` fonts (${J.length})`]}),s.jsx("span",{className:"artifact-size",children:ml(me)})]}),R&&s.jsx("ul",{className:"artifact-list artifact-group-body",children:J.map(on)})]})]})]})})()]}):s.jsx("p",{className:"tags-empty",children:"Loading\\u2026"}):s.jsx("p",{className:"tags-empty",children:"Select an entry."}),t&&!Ae&&!S&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Tags"}),_.length===0?s.jsx("p",{className:"tags-empty",children:"No tags yet."}):s.jsx("div",{className:"tags-wrap",children:_.map(T=>s.jsxs("span",{className:"tag-pill",title:T.full_path,children:[g?pf(T.full_path):T.full_path,s.jsx("button",{className:"remove",title:`Remove tag ${T.full_path}`,onClick:()=>Pn(T.tag_uid),children:"×"})]},T.tag_uid))}),P&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:P}),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:T=>h(T.target.value),onKeyDown:T=>{T.key==="Enter"&&Qn()}}),s.jsx("button",{className:"tag-add-btn",onClick:Qn,children:"Add"})]})]}),(k.length>0||$t.filter(T=>T.slug!=="_default_").length>0)&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Collections"}),k.map(T=>s.jsxs("div",{className:"coll-row",children:[s.jsx("span",{className:"coll-name",children:T.name}),s.jsx("span",{className:"vis-badge",children:Bu[T.visibility_bits]??`bits:${T.visibility_bits}`})]},T.collection_uid)),$t.filter(T=>T.slug!=="_default_").length>0&&s.jsxs("div",{className:"bulk-coll-row",style:{marginTop:8},children:[s.jsxs("select",{className:"bulk-coll-select",value:he,onChange:T=>Re(T.target.value),children:[s.jsx("option",{value:"",children:"Add to collection…"}),$t.filter(T=>T.slug!=="_default_").map(T=>s.jsx("option",{value:T.collection_uid,children:T.name},T.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:Qs,disabled:!he||ye==="running",children:ye==="running"?"…":ye==="done"?"✓":ye==="error"?"!":"Add"})]}),ce&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"4px 0 0"},children:ce})]}),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:qs,disabled:q==="running",children:q==="running"?"Re-archiving…":"Re-archive"}),q==="done"&&s.jsx("p",{className:"form-msg form-msg--ok",style:{marginTop:"6px"},children:"Re-archived successfully."}),q==="error"&&s.jsx("p",{className:"form-msg form-msg--err",style:{marginTop:"6px"},children:Le})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:jl,children:"Delete entry"})})]})]})}const Tg=/\/api\/archives\/([^/]+)\/entries\/([^/]+)\/artifacts\/(\d+)/;function Pg(){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 Lg({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(Tg);if(!g){l(e);return}let m=!1;return l(null),Dm(g[1],g[2],parseInt(g[3],10)).then(({url:x})=>{m||l(x)}).catch(()=>{m||l(e)}),()=>{m=!0}},[e]),c.useEffect(()=>{n.current&&n.current.load()},[r]),c.useEffect(()=>{u(typeof HTMLVideoElement<"u"&&"webkitShowPlaybackTargetPicker"in HTMLVideoElement.prototype)},[]),c.useEffect(()=>{var m;const g=x=>{if(x)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((m=window.cast)!=null&&m.framework)g(!0);else if(window.__onGCastApiAvailable=g,!document.querySelector('script[src*="cast_sender"]')){const x=document.createElement("script");x.src="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1",document.head.appendChild(x)}},[]),c.useEffect(()=>{if(!i||!r)return;const g=cast.framework.CastContext.getInstance(),{CastContextEventType:m,SessionState:x}=cast.framework,w=_=>{if(!_)return;const p=new chrome.cast.media.MediaInfo(window.location.origin+r,t);_.loadMedia(new chrome.cast.media.LoadRequest(p)).catch(()=>{})};w(g.getCurrentSession());const S=_=>{(_.sessionState===x.SESSION_STARTED||_.sessionState===x.SESSION_RESUMED)&&w(g.getCurrentSession())};return g.addEventListener(m.SESSION_STATE_CHANGED,S),()=>g.removeEventListener(m.SESSION_STATE_CHANGED,S)},[i,r,t]);const d=()=>{var g,m;(m=(g=n.current)==null?void 0:g.webkitShowPlaybackTargetPicker)==null||m.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(Pg,{})}),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 Wu({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 Rg({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 xf(e){return e?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(new Date(e*1e3)):""}function Vu(e){return!e||!e.includes("&")?e:e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}const le={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"}},Ve={bg:"#000000",border:"#2f3336",text:"#e7e9ea",dim:"#71767b",accent:"#1d9bf0",codeBg:"#16181c"},Ti={article:{background:Ve.bg,color:Ve.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:Ve.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:Ve.border,flexShrink:0},aAuthorName:{fontSize:"15px",fontWeight:"700",color:Ve.text,lineHeight:"1.3"},aAuthorSub:{fontSize:"15px",color:Ve.dim,lineHeight:"1.3"},aDivider:{border:"none",borderTop:`1px solid ${Ve.border}`,margin:"0"},aBody:{padding:"4px 16px 0"},bH1:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:Ve.text,lineHeight:"36px",margin:"24px 0 10px"},bH2:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:Ve.text,lineHeight:"36px",margin:"24px 0 10px"},bP:{fontSize:"17px",color:Ve.text,lineHeight:"1.5",marginBottom:"16px",marginTop:"0"},bSpacer:{height:"6px",display:"block"},bQuote:{borderLeft:`3px solid ${Ve.border}`,padding:"2px 14px",margin:"14px 0",color:Ve.dim,fontSize:"17px",lineHeight:"1.5"},bHr:{border:"none",borderTop:`1px solid ${Ve.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:Ve.text,lineHeight:"1.5",marginBottom:"6px"},bTweet:{display:"flex",alignItems:"center",gap:"12px",border:`1px solid ${Ve.border}`,borderRadius:"12px",padding:"14px 16px",margin:"14px 0",color:Ve.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:Ve.text,background:"transparent"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:Ve.codeBg,padding:"2px 6px",borderRadius:"4px",color:"#e6edf3"},link:{color:Ve.accent,textDecoration:"none"}};function zg(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 wf(){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 kf(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 jf(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 Ku=/https?:\/\/[^\s<>"'\])]+/g,Ig=/[.,;:!?)()]+$/;function Ns(e,t){const n=[];let r=0,l;for(Ku.lastIndex=0;(l=Ku.exec(e))!==null;){l.index>r&&n.push(e.slice(r,l.index));let i=l[0].replace(Ig,"");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:(rkf(o,e)).filter(Boolean),...(t.user_mentions||[]).map(o=>jf(o,e)).filter(Boolean)];if(r.length===0&&n.length===0)return Ns(Vu(e),le.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(w=>w.s<=o&&w.e>=d),m=g.find(w=>w.kind==="url");if(m)return s.jsx("a",{href:m.href,target:"_blank",rel:"noopener noreferrer",style:le.link,children:m.display||y},u);const x=g.find(w=>w.kind==="mention");return x?s.jsx("a",{href:`https://x.com/${x.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:le.link,children:y},u):s.jsx("span",{children:Ns(Vu(y),le.link)},u)}).filter(o=>o!==null)}function Dg(e,t,n,r,l=le){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=kf(u,e);d&&i.push(d)}for(const u of r){const d=jf(u,e);d&&i.push(d)}if(i.length===0)return Ns(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(_=>_.s<=u&&_.e>=y),m=e.slice(u,y);let x;if(m.includes(` +`)){const _=m.split(` +`);x=_.flatMap((p,f)=>f<_.length-1?[p,s.jsx("br",{},f)]:[p])}else x=m;g.some(_=>_.kind==="style"&&_.style==="Code")&&(x=s.jsx("code",{style:l.iCode,children:x})),g.some(_=>_.kind==="style"&&_.style==="Bold")&&(x=s.jsx("strong",{children:x})),g.some(_=>_.kind==="style"&&_.style==="Italic")&&(x=s.jsx("em",{children:x})),g.some(_=>_.kind==="style"&&_.style==="Underline")&&(x=s.jsx("u",{children:x})),g.some(_=>_.kind==="style"&&_.style==="Strikethrough")&&(x=s.jsx("s",{children:x}));const w=g.find(_=>_.kind==="url");if(w){const _=/^https?:\/\/t\.co\//i.test(x);x=s.jsx("a",{href:w.href,target:"_blank",rel:"noopener noreferrer",style:l.link,children:_?w.display:x})}const S=g.find(_=>_.kind==="mention");return S&&(x=s.jsx("a",{href:`https://x.com/${S.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:l.link,children:x})),s.jsx("span",{children:typeof x=="string"?Ns(x,l.link):x},d)})}function Og(e,t,n){const r=(n==null?void 0:n.st)||le,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(wf,{}),"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)||le,i=e.type||"",a=e.text||"",o=e.inline_style_ranges||[],u=e.data||{},d=Dg(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(wf,{}),"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:Og(e,n,r)},t);default:return a?s.jsx("p",{style:l.bP,children:d},t):null}}function Ag(e,t,n){const r=(n==null?void 0:n.st)||le,l=[];let i=0;for(;i{r&&(l==null||l(!0))},[r,l]);const o=r?Ti:le,u=e.cover_media||{},d=e.author||t||{},y=e.first_published_at_secs?xf(e.first_published_at_secs):"",m=[d.screen_name?`@${d.screen_name}`:"",y].filter(Boolean).join(" · "),x=hr(u.local_path,u.url,n),w=hr(d.avatar_local_path,d.avatar_url,n),S=s.jsxs(s.Fragment,{children:[i&&s.jsx(Sf,{items:[{src:i,alt:""}],startIndex:0,onClose:()=>a(null)}),x&&s.jsx("a",{href:x,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:_=>{!_.metaKey&&!_.ctrlKey&&(_.preventDefault(),a(x))},children:s.jsx("img",{src:x,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:[w?s.jsx("img",{src:w,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"}),m&&s.jsx("div",{style:o.aAuthorSub,children:m})]})]})]}),s.jsx("hr",{style:o.aDivider}),s.jsx("div",{style:o.aBody,children:Ag(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:le.article,children:S})}function Fg({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:le.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]=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:le.lightboxBackdrop,onClick:n,children:s.jsxs("div",{style:le.lightboxContent,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{style:le.lightboxToolbar,children:[e.length>1&&s.jsxs("span",{style:le.lightboxCounter,children:[r+1," / ",e.length]}),s.jsx("a",{href:i.src,target:"_blank",rel:"noopener noreferrer",style:le.lightboxLink,title:"Open in new tab",children:"↗"}),s.jsx("button",{style:le.lightboxBtn,onClick:n,"aria-label":"Close",children:"×"})]}),s.jsx("img",{src:i.src,alt:i.alt||"",style:le.lightboxImg}),e.length>1&&s.jsxs("div",{style:le.lightboxNav,children:[s.jsx("button",{style:le.lightboxNavBtn,onClick:()=>l(a=>Math.max(a-1,0)),disabled:r===0,children:"‹"}),s.jsx("button",{style:le.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,h;const[l,i]=c.useState(null),a=e.author||{},o=e.created_at_secs?xf(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,m=t?le.tweetRowThread:le.tweetRow,x=e.full_text||"",w=((h=(f=e.extended_entities)==null?void 0:f.media)!=null&&h.length?e.extended_entities.media:u.media)||[],S=[],_=[];for(const k of w)if(k.type==="photo"){const E=hr(k.local_path,k.media_url_https,r);E&&S.push({kind:"photo",src:E,alt:k.alt_text||""})}else if(k.type==="video"||k.type==="animated_gif"){const E=k.local_path&&r[k.local_path]||(()=>{var N,v;return(v=(((N=k.video_info)==null?void 0:N.variants)||[]).filter(b=>b.content_type==="video/mp4").sort((b,L)=>(L.bitrate||0)-(b.bitrate||0))[0])==null?void 0:v.url})();E&&_.push({kind:k.type==="animated_gif"?"gif":"video",src:E})}const p=[];for(const k of w){if(!k.url||!(k.type==="photo"?S.some(N=>N.src===hr(k.local_path,k.media_url_https,r)):_.length>0))continue;const P=jo(k,x,k.url);P&&p.push([P.s,P.e])}return s.jsxs(s.Fragment,{children:[l!==null&&s.jsx(Sf,{items:S,startIndex:l,onClose:()=>i(null)}),s.jsxs("div",{style:m,children:[s.jsxs("div",{style:le.leftCol,children:[d?s.jsx("img",{src:d,style:le.avatar,alt:a.name||""}):s.jsx("div",{style:le.avatarPh}),y&&s.jsx("div",{style:le.threadLine})]}),s.jsxs("div",{style:le.rightCol,children:[s.jsxs("div",{style:le.authorRow,children:[s.jsx("span",{style:le.authorName,children:a.name||a.screen_name||"Unknown"}),a.screen_name&&s.jsxs("span",{style:le.authorHandle,children:["@",a.screen_name]}),o&&s.jsxs("span",{style:le.datePart,children:["· ",o]}),g&&s.jsx("span",{style:le.qtBadge,title:"Quote tweet",children:"↻ QT"})]}),s.jsx("div",{style:le.tweetText,children:$g(x,u,p)}),S.length>0&&s.jsx("div",{style:le.mediaGrid,children:s.jsx(Fg,{photos:S,onOpen:k=>i(k)})}),_.map((k,E)=>s.jsx("div",{style:le.mediaGrid,children:s.jsx("video",{src:k.src,style:le.mediaVideo,controls:!0,loop:k.kind==="gif",muted:k.kind==="gif",autoPlay:k.kind==="gif"})},E)),(e.retweet_count>0||e.favorite_count>0)&&s.jsxs("div",{style:le.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 Bg({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 w=n.map((_,p)=>({..._,index:p})).filter(_=>_.artifact_role==="raw_tweet_json");if(w.length===0){d("No tweet data found."),o(!1);return}let S=!1;return nm(e,t,w.map(_=>_.index)).then(async _=>{if(S)return;const p=/https?:\/\/t\.co\/[A-Za-z0-9]+/g,f=N=>{var b;const v=N.full_text||"";return(((b=N.entities)==null?void 0:b.urls)||[]).map(L=>{var X;if(L.fromIndex!=null&&L.toIndex!=null)return[L.fromIndex,L.toIndex];if(((X=L.indices)==null?void 0:X.length)===2)return[L.indices[0],L.indices[1]];if(L.url){const Q=v.indexOf(L.url);if(Q!==-1)return[Q,Q+L.url.length]}return null}).filter(Boolean)},h=(N,v,b)=>N.some(([L,X])=>L<=v&&X>=b),k=new Set;for(const N of _){const v=N.full_text||"",b=f(N);let L;for(p.lastIndex=0;(L=p.exec(v))!==null;)h(b,L.index,L.index+L[0].length)||k.add(L[0])}const E=k.size>0?await rm([...k]).catch(()=>({})):{},P=_.map(N=>{var Q;const v=N.full_text||"",b=f(N),L=[];let X;for(p.lastIndex=0;(X=p.exec(v))!==null;){const ne=X[0],q=E[ne];q&&q!==ne&&!h(b,X.index,X.index+ne.length)&&L.push({url:ne,expanded_url:q,display_url:(()=>{try{const fe=new URL(q);return fe.hostname+(fe.pathname.length>1?"/…":"")}catch{return q}})(),fromIndex:X.index,toIndex:X.index+ne.length})}return L.length===0?N:{...N,entities:{...N.entities||{},urls:[...((Q=N.entities)==null?void 0:Q.urls)||[],...L]}}});S||g(P)}).catch(_=>{S||d(_.message||"Failed to load tweet.")}).finally(()=>{S||o(!1)}),()=>{S=!0}},[e,t,n]),a)return s.jsx("div",{style:le.loading,children:"Loading…"});if(u)return s.jsxs("div",{style:le.error,children:["Error: ",u]});if(y.length===0)return null;const m=zg(e,t,n);if(r==="tweet_thread")return s.jsx("div",{style:le.threadOuter,children:y.map((w,S)=>s.jsx(Qu,{tweet:w,isInThread:!0,isLast:S===y.length-1,artifactMap:m},w.id||S))});const x=y[0];return x.is_article&&x.article?s.jsx(Mg,{article:x.article,tweetAuthor:x.author,artifactMap:m,fullPage:l,onXArticle:i}):s.jsx("div",{style:le.card,children:s.jsx(Qu,{tweet:x,isInThread:!1,isLast:!0,artifactMap:m})})}function Ug({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),em(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 Hg=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv"]),Wg=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),Vg=new Set(["jpg","jpeg","png","gif","webp","avif","svg","bmp"]),Kg=new Set(["md","markdown","txt"]),Qg={mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo",m4v:"video/mp4",ogv:"video/ogg"};function _f({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 x=s.jsx(Bg,{archiveId:e,entryUid:o,artifacts:a,entityKind:u,fullPage:r,onXArticle:l});return r?x:s.jsx("div",{className:"preview-tweet-wrap",children:x})}const d=a.findIndex(x=>x.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((x,w)=>s.jsxs("li",{children:[x.artifact_role,": ",x.relpath]},w))})]});const y=a[d],g=`/api/archives/${e}/entries/${o}/artifacts/${d}`,m=y.relpath.split(".").pop().toLowerCase();return Hg.has(m)?s.jsx("div",{className:"preview-panel",children:s.jsx(Lg,{src:g,contentType:Qg[m]||"video/mp4"})}):Wg.has(m)?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"}})]}):m==="pdf"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(Wu,{src:g,type:"pdf",title:i.title,originalUrl:i.original_url})}):m==="html"||m==="htm"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(Wu,{src:g,type:"page",title:i.title,originalUrl:i.original_url})}):Kg.has(m)?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0,overflow:"auto"},children:s.jsx(Ug,{src:g,mime:y.mime_type,title:i.title})}):Vg.has(m)?s.jsx("div",{className:"preview-panel",style:{height:"100%"},children:s.jsx(Rg,{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((x,w)=>s.jsxs("li",{children:[x.artifact_role,": ",x.relpath]},w))})]})}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(_f,{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 Xg({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,m]=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 x(){const f=l.current;f&&(i?f.pause():f.play().catch(()=>{}))}function w(f){const h=l.current;if(!h||!isFinite(d))return;const k=Number(f.target.value);h.currentTime=k,u(k)}function S(f){m(Number(f.target.value))}const _=(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:Us(p)}}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.85rem",color:"var(--ink)"},title:_,children:_})]}),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:x,"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:w,"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 Jg({archiveId:e,entryUid:t}){var m,x;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 w=document.documentElement,S=document.body,_=w.style.colorScheme,p=S.style.background;return w.style.colorScheme="dark",S.style.background="#000",()=>{w.style.colorScheme=_,S.style.background=p}},[u]),c.useEffect(()=>{d(!1),Mr(e,t).then(w=>{r(w),i(!1)}).catch(w=>{o((w==null?void 0:w.message)||"Failed to load entry"),i(!1)})},[e,t]);const y=((m=n==null?void 0:n.summary)==null?void 0:m.title)||t,g=(x=n==null?void 0:n.summary)==null?void 0:x.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(_f,{archiveId:e,entry:n.summary,detail:n,fullPage:!0,onXArticle:d})]})]})}const Gg=7e3;function Yg({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(ey,{toast:r,onDismiss:t,onIgnoreUblock:n},r.id))}):null}function Zg(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 ey({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),Gg);return()=>clearTimeout(u)},[r,e.id,t]);const o=Zg(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 Hs=c.createContext(null),ty=["archive","tags","collections","runs","admin","settings"],ny=["profile","tokens","instance","cookies","extensions","storage"],Ir=(()=>{const e=window.location.pathname.match(/^\/preview\/([^/]+)\/([^/]+)/);return e?{archiveId:e[1],entryUid:e[2]}:null})();function Wt(){const e=window.location.pathname.split("/").filter(Boolean),t=ty.includes(e[0])?e[0]:"archive",n=t==="settings"&&ny.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 ry(e,t){return e==="archive"?"/":e==="settings"?`/settings/${t}`:`/${e}`}function ly(){const[e,t]=c.useState("loading"),[n,r]=c.useState(null);c.useEffect(()=>{(async()=>{var M,W,G;if(await hm()){t("setup");return}const z=await cf();if(!z){const{collection:ue,archive:Ee}=Wt();try{const We=await Ru(),je=Ee?((M=We.find(T=>T.id===Ee))==null?void 0:M.id)??((W=We[0])==null?void 0:W.id):(G=We[0])==null?void 0:G.id;if(je){await zu(je,ue),i(We),o(je),d(ue),t("authenticated");return}}catch{}t("login");return}r(z),t("authenticated")})()},[]),c.useEffect(()=>{const C=()=>{n&&(r(null),t("login"))};return window.addEventListener("auth:expired",C),()=>window.removeEventListener("auth:expired",C)},[n]),c.useEffect(()=>{const C=()=>{const{view:z,settingsTab:M,q:W,tag:G,entry:ue,collection:Ee}=Wt();X(z),ne(M),fe(W),b(G),h(ue),E(null),N(ue?new Set([ue]):new Set),d(Ee)};return window.addEventListener("popstate",C),()=>window.removeEventListener("popstate",C)},[]);const[l,i]=c.useState([]),[a,o]=c.useState(null),[u,d]=c.useState(()=>Wt().collection),[y,g]=c.useState([]),[m,x]=c.useState([]),[w,S]=c.useState(()=>new Set),[_,p]=c.useState(()=>new Map),[f,h]=c.useState(()=>Wt().entry),[k,E]=c.useState(null),[P,N]=c.useState(()=>{const C=Wt().entry;return C?new Set([C]):new Set}),[v,b]=c.useState(()=>Wt().tag),[L,X]=c.useState(()=>Wt().view),[Q,ne]=c.useState(()=>Wt().settingsTab),[q,fe]=c.useState(()=>Wt().q),[Le,ve]=c.useState(""),[I,R]=c.useState(!1),[K,ee]=c.useState([]),[se,ie]=c.useState([]),[Y,Ne]=c.useState(()=>sessionStorage.getItem("captureDialogOpen")==="true"),[pe,U]=c.useState([]),te=c.useRef(0),[re,Ue]=c.useState(()=>{try{const C=JSON.parse(sessionStorage.getItem("pendingCaptures")||"[]");if(Array.isArray(C))return C}catch{}return[]});c.useEffect(()=>{sessionStorage.setItem("pendingCaptures",JSON.stringify(re))},[re]);const[Lt,yt]=c.useState(()=>sessionStorage.getItem("ublockWarningIgnored")==="true"),[Ie,st]=c.useState(null),Ze=c.useRef(0),$=c.useRef(null),Z=c.useRef(!1),Ae=c.useRef(!0),Me=c.useRef(null),Rt=c.useRef(0),zt=c.useRef(new Map),It=(n==null?void 0:n.humanize_slugs)??!1;c.useEffect(()=>{const C=++Ze.current;st(null),!(!k||!a)&&Mr(a,k.entry_uid).then(z=>{C===Ze.current&&st(z)}).catch(()=>{})},[k,a]),c.useEffect(()=>{sessionStorage.setItem("captureDialogOpen",Y)},[Y]);const et=c.useCallback(async(C,z,M,W)=>{if(C){R(!0);try{let G;z||M?G=await Gh(C,z,M,W):G=await zu(C,W),x(G),N(ue=>{if(ue.size<2)return ue;const Ee=new Set(G.map(je=>je.entry_uid)),We=new Set([...ue].filter(je=>Ee.has(je)));return We.size===ue.size?ue:We}),ve(G.length===0?"No results":`${G.length} result${G.length===1?"":"s"}`)}catch{x([]),ve("Search failed. Try again.")}finally{R(!1)}}},[]);c.useEffect(()=>{e==="authenticated"&&(a||Ru().then(C=>{if(i(C),C.length>0){const{archive:z}=Wt(),M=z?C.find(W=>W.id===z):null;o((M==null?void 0:M.id)??C[0].id)}}))},[e,a]),c.useEffect(()=>{if(!a)return;const C=!n;if(Ae.current){Ae.current=!1;const M=[];C||(M.push(Ni(a).then(ee)),M.push(Bl(a).then(ie))),M.length&&Promise.all(M);return}b(null),E(null),h(null),N(new Set),d(null);const z=[et(a,"",null,null)];C||(z.push(Ni(a).then(ee)),z.push(Bl(a).then(ie))),Promise.all(z)},[a,n]),c.useEffect(()=>{if(a===null)return;const C=setTimeout(()=>{et(a,q,v,u)},300);return()=>clearTimeout(C)},[q,a,u]),c.useEffect(()=>{a!==null&&(v!==null&&X("archive"),et(a,q,v,u))},[v,a,u]);const Xt=c.useCallback(C=>{o(C),d(null);const z=new URLSearchParams(window.location.search);z.set("archive",C),z.delete("collection");const M=z.toString();history.replaceState(null,"",window.location.pathname+(M?"?"+M:""))},[]);c.useEffect(()=>{if(!a){g([]);return}wo(a).then(g).catch(()=>g([]))},[a]);const $t=c.useCallback(C=>{if(!n){const W=C?y.find(G=>G.collection_uid===C):y.find(G=>G.slug==="_default_");if(W!=null&&W.requires_auth){t("login");return}}d(C),E(null),h(null),N(new Set),et(a,q,v,C);const z=new URLSearchParams(window.location.search);C?(z.set("collection",C),z.set("archive",a)):(z.delete("collection"),a&&z.set("archive",a));const M=z.toString();history.replaceState(null,"",window.location.pathname+(M?"?"+M:""))},[a,q,v,n,y,et]),an=c.useCallback(C=>{X(C),C==="tags"&&a&&Bl(a).then(ie)},[a]);c.useEffect(()=>{if(Ir)return;const C=ry(L,Q);window.location.pathname!==C&&history.pushState(null,"",C+window.location.search)},[L,Q]);const He=c.useCallback(C=>{h(C?C.entry_uid:null),E(C)},[]),j=c.useCallback((C,z)=>{if(zt.current.set(C.entry_uid,C),++Rt.current,z.shiftKey&&Me.current!==null){z.preventDefault();const M=[...document.querySelectorAll("#entries-body [data-entry-uid]")],W=M.findIndex(je=>je.dataset.entryUid===Me.current),G=M.findIndex(je=>je.dataset.entryUid===C.entry_uid);if(W===-1||G===-1){Me.current=C.entry_uid,N(new Set([C.entry_uid])),He(C);return}const ue=Math.min(W,G),Ee=Math.max(W,G),We=new Set(M.slice(ue,Ee+1).map(je=>je.dataset.entryUid));N(We),We.size===1&&He(C)}else if(z.ctrlKey||z.metaKey){Me.current=C.entry_uid;const M=new Set(P);if(M.has(C.entry_uid)?M.delete(C.entry_uid):M.add(C.entry_uid),N(M),M.size===0)He(null);else if(M.size===1){const[W]=M,G=zt.current.get(W)??m.find(ue=>ue.entry_uid===W)??null;if(G)He(G);else{const ue=++Rt.current;Mr(a,W).then(Ee=>{ue===Rt.current&&(Ee!=null&&Ee.summary)&&He(Ee.summary)}).catch(()=>{})}}else He(null)}else Me.current=C.entry_uid,N(new Set([C.entry_uid])),He(C)},[m,P,He,a]),B=c.useCallback(C=>{b(C)},[]),A=c.useCallback(()=>{b(null)},[]),D=c.useCallback(()=>{a&&Bl(a).then(ie)},[a]),F=c.useCallback((C,z)=>{v===C?b(z):v!=null&&v.startsWith(C+"/")&&b(z+v.slice(C.length))},[v]),H=c.useCallback(C=>{(v===C||v!=null&&v.startsWith(C+"/"))&&b(null)},[v]),ke=c.useCallback((C,z)=>{p(W=>new Map(W).set(C,z));const M=zt.current.get(C);M&&zt.current.set(C,{...M,title:z}),x(W=>W.map(G=>G.entry_uid===C?{...G,title:z}:G)),E(W=>W&&W.entry_uid===C?{...W,title:z}:W),st(W=>W&&W.summary.entry_uid===C?{...W,summary:{...W.summary,title:z}}:W)},[]),he=c.useCallback(()=>{if(!a||!k)return;const C=++Ze.current;Mr(a,k.entry_uid).then(z=>{C===Ze.current&&st(z)}).catch(()=>{})},[a,k]),Re=c.useCallback(C=>{const z=m.some(M=>M.entry_uid===C);S(M=>{const W=new Set(M);return W.add(C),W}),x(M=>M.filter(W=>W.entry_uid!==C)),E(M=>(M==null?void 0:M.entry_uid)===C?null:M),h(M=>M===C?null:M),N(M=>{const W=new Set(M);return W.delete(C),W}),z||et(a,q,v,u)},[m,a,q,v,u,et]),ye=c.useCallback(C=>{const z=new Set(m.map(W=>W.entry_uid)),M=[...C].some(W=>!z.has(W));S(W=>{const G=new Set(W);return C.forEach(ue=>G.add(ue)),G}),x(W=>W.filter(G=>!C.has(G.entry_uid))),N(new Set),E(null),h(null),M&&et(a,q,v,u)},[m,a,q,v,u,et]);c.useEffect(()=>{if(P.size>=2)h(null),E(null);else if(P.size===1){const[C]=P;h(C)}else h(null),E(null)},[P]);const Fe=c.useMemo(()=>m.filter(C=>P.has(C.entry_uid)),[m,P]);c.useEffect(()=>{if(!f||k)return;const C=m.find(z=>z.entry_uid===f);C&&E(C)},[m,f,k]),c.useEffect(()=>{if(Ir)return;const C=new URLSearchParams(window.location.search).get("archive"),z=new URLSearchParams;q&&z.set("q",q),L==="archive"&&v&&z.set("tag",v),L==="archive"&&f&&z.set("entry",f),L==="archive"&&u?(z.set("collection",u),a&&z.set("archive",a)):C&&a&&z.set("archive",a);const M=z.toString(),W=window.location.pathname+(M?"?"+M:"");window.location.pathname+window.location.search!==W&&history.replaceState(null,"",W)},[q,v,f,u,a,L]),c.useEffect(()=>{const C=z=>{var ue,Ee,We,je;const M=z.key==="/"&&!z.metaKey&&!z.ctrlKey&&!z.altKey,W=(z.metaKey||z.ctrlKey)&&z.key==="k";if(!M&&!W)return;const G=(ue=document.activeElement)==null?void 0:ue.tagName;M&&(G==="INPUT"||G==="TEXTAREA"||G==="SELECT")||M&&((Ee=document.activeElement)!=null&&Ee.isContentEditable)||(z.preventDefault(),L==="archive"?((We=$.current)==null||We.focus(),(je=$.current)==null||je.select()):(Z.current=!0,X("archive")))};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[L]),c.useEffect(()=>{const C=z=>{var ae,me;if(z.metaKey||z.ctrlKey||z.altKey||z.key!=="j"&&z.key!=="k")return;const M=(ae=document.activeElement)==null?void 0:ae.tagName;if(M==="INPUT"||M==="TEXTAREA"||M==="SELECT"||(me=document.activeElement)!=null&&me.isContentEditable)return;const W=[...document.querySelectorAll("#entries-body [data-entry-uid]")];if(W.length===0)return;const[G]=P.size===1?P:[null],ue=G?W.findIndex($e=>$e.dataset.entryUid===G):-1,Ee=z.key==="j"?Math.min(ue+1,W.length-1):Math.max(ue-1,0);if(Ee===ue&&ue!==-1)return;const We=W[Ee<0?0:Ee],je=We.dataset.entryUid;Me.current=je;const T=++Rt.current;N(new Set([je]));const J=zt.current.get(je)??m.find($e=>$e.entry_uid===je)??null;J?He(J):Mr(a,je).then($e=>{T===Rt.current&&($e!=null&&$e.summary)&&He($e.summary)}).catch(()=>{}),We.scrollIntoView({block:"nearest"}),z.preventDefault()};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[P,m,He,a]),c.useEffect(()=>{L==="archive"&&Z.current&&(Z.current=!1,requestAnimationFrame(()=>{var C,z;(C=$.current)==null||C.focus(),(z=$.current)==null||z.select()}))},[L]);const ce=c.useCallback(()=>{Ne(!0)},[]),it=c.useCallback(()=>{Ne(!1)},[]),dt=c.useCallback(()=>{if(a)return Promise.allSettled([et(a,q,v,u),Ni(a).then(ee)])},[a,q,v,u,et]),Nr=c.useCallback((C,z,M="error",W=null)=>{if(M==="warning"&&Lt&&z)return;const G=++te.current;U(ue=>[...ue,{id:G,text:C,locator:z,type:M,headline:W}])},[Lt]),Ws=c.useCallback(C=>{U(z=>z.filter(M=>M.id!==C))},[]),Vs=c.useCallback(C=>{Nr(C,null,"error","Reorder failed")},[Nr]),kl=c.useCallback(()=>{sessionStorage.setItem("ublockWarningIgnored","true"),yt(!0),U(C=>C.filter(z=>!(z.type==="warning"&&z.locator)))},[]),Ks=c.useCallback(C=>{Ue(z=>[...z,C])},[]),Qs=c.useCallback(C=>{Ue(z=>z.filter(M=>M.id!==C))},[]),[Kn,Qn]=c.useState(null),[Pn,jl]=c.useState(null),qs=c.useCallback(()=>{k&&Qn(k.entry_uid)},[k]),Xs=c.useCallback(()=>Qn(null),[]),Js=c.useCallback((C,z)=>{jl({src:C,entry:z})},[]),Gs=c.useCallback(()=>jl(null),[]);return c.useEffect(()=>{Qn(null)},[k]),c.useEffect(()=>{const C=z=>{var W,G,ue;if(z.key!=="Escape"||Y||Kn)return;const M=(W=document.activeElement)==null?void 0:W.tagName;M==="INPUT"||M==="TEXTAREA"||M==="SELECT"||P.size>0&&(z.preventDefault(),N(new Set),(ue=(G=document.activeElement)==null?void 0:G.blur)==null||ue.call(G))};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[Y,Kn,P]),c.useEffect(()=>(document.body.classList.toggle("has-audio-bar",!!Pn),()=>document.body.classList.remove("has-audio-bar")),[Pn]),Ir?s.jsx(Jg,{archiveId:Ir.archiveId,entryUid:Ir.entryUid}):e==="loading"?s.jsx("div",{className:"auth-loading",children:"Loading\\u2026"}):e==="setup"?s.jsx(Wm,{onComplete:()=>t("login")}):e==="login"?s.jsx(Hm,{onLogin:C=>{r(C),t("authenticated")}}):s.jsx(Hs.Provider,{value:{currentUser:n,setCurrentUser:r},children:s.jsxs(s.Fragment,{children:[s.jsx(Vm,{archives:l,archiveId:a,onArchiveChange:Xt,view:L,onViewChange:an,onCaptureClick:ce,collections:y,selectedCollectionUid:u,onCollectionChange:$t,isPublicSession:!n,onSignInClick:()=>t("login")}),s.jsxs("main",{className:"app-shell",children:[s.jsxs("div",{className:"workspace",children:[L==="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:$,className:"search-input",type:"search","aria-label":"Search archive","aria-busy":I,placeholder:"Search titles, URLs, types, tags…",value:q,onChange:C=>fe(C.target.value)}),s.jsx("span",{className:"kbd",children:"⌘K"})]}),s.jsxs("span",{className:"result-count",children:[Le&&s.jsxs(s.Fragment,{children:[s.jsx("b",{children:Le.split(" ")[0]})," ",Le.split(" ").slice(1).join(" ")]}),v&&s.jsxs("button",{className:"tag-filter-badge",onClick:A,children:["× ",It?pf(v):v]})]})]}),L==="archive"&&s.jsx(ig,{entries:m,selectedUids:P,onRowClick:j,archiveId:a,pendingCaptures:re,deletedUids:w,renamedTitles:_,isPublicSession:!n,canReorder:!!(n!=null&&n.can_reorder_children),onChildReorderError:Vs}),L==="runs"&&s.jsx(ug,{runs:K}),L==="admin"&&s.jsx(dg,{archives:l}),L==="tags"&&s.jsx(fg,{archiveId:a,tagNodes:se,tagFilter:v,onTagFilterSet:B,onViewChange:an,onTagRenamed:F,onTagDeleted:H,onTagsRefresh:D,humanizeTags:It}),L==="collections"&&s.jsx(hg,{archiveId:a}),L==="settings"&&s.jsx(yg,{tab:Q,onTabChange:ne,archiveId:a})]}),s.jsx(bg,{archiveId:a,selectedEntry:k,selectedUids:P,selectedEntries:Fe,detail:Ie,onTagFilterSet:B,tagNodes:se,onTagsRefresh:D,onEntryTitleChange:ke,onEntryDeleted:Re,onBulkDeleted:ye,humanizeTags:It,onDetailRefresh:he,onOpenPreview:qs,onPlay:Js,isPublicSession:!n})]}),Kn&&k&&k.entry_uid===Kn&&s.jsx(qg,{archiveId:a,entry:k,detail:Ie,onClose:Xs}),Pn&&s.jsx(Xg,{entry:Pn.entry,src:Pn.src,archiveId:a,onClose:Gs}),s.jsx(Xm,{open:Y,archiveId:a,onClose:it,onCaptured:dt,onToast:Nr,activeJobs:re,onJobStarted:Ks,onJobSettled:Qs}),s.jsx(Yg,{toasts:pe,onDismiss:Ws,onIgnoreUblock:kl})]})})}of(document.getElementById("root")).render(s.jsx(c.StrictMode,{children:s.jsx(ly,{})})); diff --git a/crates/archivr-server/static/assets/index-CQKWq7vB.css b/crates/archivr-server/static/assets/index-CQKWq7vB.css new file mode 100644 index 0000000..448f473 --- /dev/null +++ b/crates/archivr-server/static/assets/index-CQKWq7vB.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}.child-reorder-controls{display:inline-flex;align-items:center;gap:4px;flex-shrink:0;transition:opacity .15s}.child-drag-handle{display:none;cursor:grab;padding:0 3px;font-size:.8em;letter-spacing:-2px;-webkit-user-select:none;user-select:none;color:var(--muted)}.child-drag-handle:active{cursor:grabbing}.child-move-btn{width:28px;height:28px;padding:0;border:none;background:none;color:inherit;font-size:.9em;line-height:1;cursor:pointer}.child-move-btn:disabled{opacity:.3;cursor:default}.child-move-btn:focus{outline:none}.child-move-btn:focus-visible{outline:2px solid var(--accent);outline-offset:1px;border-radius:2px}@media (hover: hover) and (pointer: fine) and (min-width: 641px){.child-reorder-controls{gap:1px;opacity:.3}.child-entry-row:hover .child-reorder-controls,.child-entry-row:focus-within .child-reorder-controls{opacity:1}.child-drag-handle{display:inline}.child-move-btn{display:none}}.child-entry-row.is-dragging{opacity:.4}.child-entry-row.is-drop-before{box-shadow:inset 0 2px 0 var(--accent)}.child-entry-row.is-drop-after{box-shadow:inset 0 -2px 0 var(--accent)}.child-entries[aria-busy=true] .child-entry-row{cursor:progress}.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/index.html b/crates/archivr-server/static/index.html index 8f14403..a8b7f0e 100644 --- a/crates/archivr-server/static/index.html +++ b/crates/archivr-server/static/index.html @@ -6,8 +6,8 @@ Archivr - - + +
From bf8ef34a7ab0a81a17458b5cf751b67ba9e6b3e1 Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Tue, 13 Oct 2026 14:35:19 +0200 Subject: [PATCH 07/14] Revert "fix: keep generated static assets out of entry export PR" This reverts commit 78d003fb12c2b32a3b302db131b0d38c5b3c2b27. --- .../static/assets/index-CKGxin5o.js | 49 ------------------- .../static/assets/index-CQKWq7vB.css | 1 - crates/archivr-server/static/index.html | 4 +- 3 files changed, 2 insertions(+), 52 deletions(-) delete mode 100644 crates/archivr-server/static/assets/index-CKGxin5o.js delete mode 100644 crates/archivr-server/static/assets/index-CQKWq7vB.css diff --git a/crates/archivr-server/static/assets/index-CKGxin5o.js b/crates/archivr-server/static/assets/index-CKGxin5o.js deleted file mode 100644 index 6b965c1..0000000 --- a/crates/archivr-server/static/assets/index-CKGxin5o.js +++ /dev/null @@ -1,49 +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 Xu={exports:{}},Cs={},Ju={exports:{}},oe={};/** - * @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 gl=Symbol.for("react.element"),Nf=Symbol.for("react.portal"),Cf=Symbol.for("react.fragment"),Ef=Symbol.for("react.strict_mode"),bf=Symbol.for("react.profiler"),Tf=Symbol.for("react.provider"),Pf=Symbol.for("react.context"),Lf=Symbol.for("react.forward_ref"),Rf=Symbol.for("react.suspense"),zf=Symbol.for("react.memo"),If=Symbol.for("react.lazy"),So=Symbol.iterator;function $f(e){return e===null||typeof e!="object"?null:(e=So&&e[So]||e["@@iterator"],typeof e=="function"?e:null)}var Gu={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Yu=Object.assign,Zu={};function jr(e,t,n){this.props=e,this.context=t,this.refs=Zu,this.updater=n||Gu}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 ec(){}ec.prototype=jr.prototype;function _a(e,t,n){this.props=e,this.context=t,this.refs=Zu,this.updater=n||Gu}var Na=_a.prototype=new ec;Na.constructor=_a;Yu(Na,jr.prototype);Na.isPureReactComponent=!0;var _o=Array.isArray,tc=Object.prototype.hasOwnProperty,Ca={current:null},nc={key:!0,ref:!0,__self:!0,__source:!0};function rc(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)tc.call(t,r)&&!nc.hasOwnProperty(r)&&(l[r]=t[r]);var o=arguments.length-2;if(o===1)l.children=n;else if(1>>1,se=I[ee];if(0>>1;eel(Ne,K))pel(U,Ne)?(I[ee]=U,I[pe]=K,ee=pe):(I[ee]=Ne,I[Y]=K,ee=Y);else if(pel(U,K))I[ee]=U,I[pe]=K,ee=pe;else break e}}return R}function l(I,R){var K=I.sortIndex-R.sortIndex;return K!==0?K:I.id-R.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,m=3,x=!1,w=!1,S=!1,_=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 h(I){for(var R=n(d);R!==null;){if(R.callback===null)r(d);else if(R.startTime<=I)r(d),R.sortIndex=R.expirationTime,t(u,R);else break;R=n(d)}}function k(I){if(S=!1,h(I),!w)if(n(u)!==null)w=!0,Le(E);else{var R=n(d);R!==null&&ve(k,R.startTime-I)}}function E(I,R){w=!1,S&&(S=!1,p(v),v=-1),x=!0;var K=m;try{for(h(R),g=n(u);g!==null&&(!(g.expirationTime>R)||I&&!X());){var ee=g.callback;if(typeof ee=="function"){g.callback=null,m=g.priorityLevel;var se=ee(g.expirationTime<=R);R=e.unstable_now(),typeof se=="function"?g.callback=se:g===n(u)&&r(u),h(R)}else r(u);g=n(u)}if(g!==null)var ie=!0;else{var Y=n(d);Y!==null&&ve(k,Y.startTime-R),ie=!1}return ie}finally{g=null,m=K,x=!1}}var P=!1,N=null,v=-1,b=5,L=-1;function X(){return!(e.unstable_now()-LI||125ee?(I.sortIndex=K,t(d,I),n(u)===null&&I===n(d)&&(S?(p(v),v=-1):S=!0,ve(k,K-ee))):(I.sortIndex=se,t(u,I),w||x||(w=!0,Le(E))),I},e.unstable_shouldYield=X,e.unstable_wrapCallback=function(I){var R=m;return function(){var K=m;m=R;try{return I.apply(this,arguments)}finally{m=K}}}})(oc);ac.exports=oc;var Kf=ac.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 Qf=c,jt=Kf;function O(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,qf=/^[: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 Xf(e){return Li.call(Eo,e)?!0:Li.call(Co,e)?!1:qf.test(e)?Eo[e]=!0:(Co[e]=!0,!1)}function Jf(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 Gf(e,t,n,r){if(t===null||typeof t>"u"||Jf(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 ct(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 Ye={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Ye[e]=new ct(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Ye[t]=new ct(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Ye[e]=new ct(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Ye[e]=new ct(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){Ye[e]=new ct(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Ye[e]=new ct(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Ye[e]=new ct(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Ye[e]=new ct(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Ye[e]=new ct(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);Ye[t]=new ct(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);Ye[t]=new ct(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);Ye[t]=new ct(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Ye[e]=new ct(e,1,!1,e.toLowerCase(),null,!1,!1)});Ye.xlinkHref=new ct("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Ye[e]=new ct(e,1,!1,e.toLowerCase(),null,!0,!0)});function Pa(e,t,n,r){var l=Ye.hasOwnProperty(t)?Ye[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:"")?$r(e):""}function Yf(e){switch(e.tag){case 5:return $r(e.type);case 16:return $r("Lazy");case 13:return $r("Suspense");case 19:return $r("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 dc:return(e.displayName||"Context")+".Consumer";case cc: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 dn:t=e._payload,e=e._init;try{return $i(e(t))}catch{}}return null}function Zf(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 Nn(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function pc(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function ep(e){var t=pc(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 Nl(e){e._valueTracker||(e._valueTracker=ep(e))}function hc(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=pc(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function ts(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 Pe({},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=Nn(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 mc(e,t){t=t.checked,t!=null&&Pa(e,"checked",t,!1)}function Oi(e,t){mc(e,t);var n=Nn(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,Nn(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"||ts(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Dr=Array.isArray;function or(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=Cl.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Yr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Br={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},tp=["Webkit","ms","Moz","O"];Object.keys(Br).forEach(function(e){tp.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Br[t]=Br[e]})});function xc(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Br.hasOwnProperty(e)&&Br[e]?(""+t).trim():t+"px"}function wc(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=xc(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var np=Pe({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(np[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(O(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(O(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(O(61))}if(t.style!=null&&typeof t.style!="object")throw Error(O(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=xl(e)){if(typeof Wi!="function")throw Error(O(280));var t=e.stateNode;t&&(t=Ls(t),Wi(e.stateNode,e.type,t))}}function kc(e){ur?cr?cr.push(e):cr=[e]:ur=e}function jc(){if(ur){var e=ur,t=cr;if(cr=ur=null,zo(e),t)for(e=0;e>>=0,e===0?32:31-(pp(e)/hp|0)|0}var El=64,bl=4194304;function Or(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 ss(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=Or(o):(i&=a,i!==0&&(r=Or(i)))}else a=n&~l,a!==0?r=Or(a):i!==0&&(r=Or(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 yl(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ft(t),e[t]=n}function vp(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=Hr),Uo=" ",Ho=!1;function Uc(e,t){switch(e){case"keyup":return Kp.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Hc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Yn=!1;function qp(e,t){switch(e){case"compositionend":return Hc(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 Xp(e,t){if(Yn)return e==="compositionend"||!Ua&&Uc(e,t)?(e=Fc(),Vl=Ma=mn=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=ts();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=ts(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 lh(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=qo(n,i);var a=qo(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,Vr=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!==ts(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}),Vr&&ll(Vr,r)||(Vr=r,r=os(Ji,"onSelect"),0nr||(e.current=ra[nr],ra[nr]=null,nr--)}function we(e,t){nr++,ra[nr]=e.current,e.current=t}var Cn={},lt=bn(Cn),ht=bn(!1),Mn=Cn;function gr(e,t){var n=e.type.contextTypes;if(!n)return Cn;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 mt(e){return e=e.childContextTypes,e!=null}function cs(){_e(ht),_e(lt)}function nu(e,t,n){if(lt.current!==Cn)throw Error(O(168));we(lt,t),we(ht,n)}function rd(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(O(108,Zf(e)||"Unknown",l));return Pe({},n,r)}function ds(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Cn,Mn=lt.current,we(lt,e),we(ht,ht.current),!0}function ru(e,t,n){var r=e.stateNode;if(!r)throw Error(O(169));n?(e=rd(e,t,Mn),r.__reactInternalMemoizedMergedChildContext=e,_e(ht),_e(lt),we(lt,e)):_e(ht),we(ht,n)}var Gt=null,Rs=!1,gi=!1;function ld(e){Gt===null?Gt=[e]:Gt.push(e)}function gh(e){Rs=!0,ld(e)}function Tn(){if(!gi&&Gt!==null){gi=!0;var e=0,t=ge;try{var n=Gt;for(ge=1;e>=a,l-=a,Yt=1<<32-Ft(t)+l|n<v?(b=N,N=null):b=N.sibling;var L=m(p,N,h[v],k);if(L===null){N===null&&(N=b);break}e&&N&&L.alternate===null&&t(p,N),f=i(L,f,v),P===null?E=L:P.sibling=L,P=L,N=b}if(v===h.length)return n(p,N),Ce&&Ln(p,v),E;if(N===null){for(;vv?(b=N,N=null):b=N.sibling;var X=m(p,N,L.value,k);if(X===null){N===null&&(N=b);break}e&&N&&X.alternate===null&&t(p,N),f=i(X,f,v),P===null?E=X:P.sibling=X,P=X,N=b}if(L.done)return n(p,N),Ce&&Ln(p,v),E;if(N===null){for(;!L.done;v++,L=h.next())L=g(p,L.value,k),L!==null&&(f=i(L,f,v),P===null?E=L:P.sibling=L,P=L);return Ce&&Ln(p,v),E}for(N=r(p,N);!L.done;v++,L=h.next())L=x(N,p,v,L.value,k),L!==null&&(e&&L.alternate!==null&&N.delete(L.key===null?v:L.key),f=i(L,f,v),P===null?E=L:P.sibling=L,P=L);return e&&N.forEach(function(Q){return t(p,Q)}),Ce&&Ln(p,v),E}function _(p,f,h,k){if(typeof h=="object"&&h!==null&&h.type===Gn&&h.key===null&&(h=h.props.children),typeof h=="object"&&h!==null){switch(h.$$typeof){case _l:e:{for(var E=h.key,P=f;P!==null;){if(P.key===E){if(E=h.type,E===Gn){if(P.tag===7){n(p,P.sibling),f=l(P,h.props.children),f.return=p,p=f;break e}}else if(P.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===dn&&iu(E)===P.type){n(p,P.sibling),f=l(P,h.props),f.ref=Lr(p,P,h),f.return=p,p=f;break e}n(p,P);break}else t(p,P);P=P.sibling}h.type===Gn?(f=An(h.props.children,p.mode,k,h.key),f.return=p,p=f):(k=Zl(h.type,h.key,h.props,null,p.mode,k),k.ref=Lr(p,f,h),k.return=p,p=k)}return a(p);case Jn:e:{for(P=h.key;f!==null;){if(f.key===P)if(f.tag===4&&f.stateNode.containerInfo===h.containerInfo&&f.stateNode.implementation===h.implementation){n(p,f.sibling),f=l(f,h.children||[]),f.return=p,p=f;break e}else{n(p,f);break}else t(p,f);f=f.sibling}f=_i(h,p.mode,k),f.return=p,p=f}return a(p);case dn:return P=h._init,_(p,f,P(h._payload),k)}if(Dr(h))return w(p,f,h,k);if(Cr(h))return S(p,f,h,k);$l(p,h)}return typeof h=="string"&&h!==""||typeof h=="number"?(h=""+h,f!==null&&f.tag===6?(n(p,f.sibling),f=l(f,h),f.return=p,p=f):(n(p,f),f=Si(h,p.mode,k),f.return=p,p=f),a(p)):n(p,f)}return _}var vr=od(!0),ud=od(!1),hs=bn(null),ms=null,sr=null,Qa=null;function qa(){Qa=sr=ms=null}function Xa(e){var t=hs.current;_e(hs),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){ms=e,Qa=sr=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(pt=!0),e.firstContext=null)}function Tt(e){var t=e._currentValue;if(Qa!==e)if(e={context:e,memoizedValue:t,next:null},sr===null){if(ms===null)throw Error(O(308));sr=e,ms.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 cd(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,rn(e,r)}function rn(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 fn=!1;function Ga(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function dd(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 en(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function kn(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,de&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,rn(e,n)}return l=r.interleaved,l===null?(t.next=t,Ja(r)):(t.next=l.next,l.next=t),r.interleaved=t,rn(e,n)}function Ql(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 gs(e,t,n,r){var l=e.updateQueue;fn=!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 m=o.lane,x=o.eventTime;if((r&m)===m){y!==null&&(y=y.next={eventTime:x,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var w=e,S=o;switch(m=t,x=n,S.tag){case 1:if(w=S.payload,typeof w=="function"){g=w.call(x,g,m);break e}g=w;break e;case 3:w.flags=w.flags&-65537|128;case 0:if(w=S.payload,m=typeof w=="function"?w.call(x,g,m):w,m==null)break e;g=Pe({},g,m);break e;case 2:fn=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,m=l.effects,m===null?l.effects=[o]:m.push(o))}else x={eventTime:x,lane:m,tag:o.tag,payload:o.payload,callback:o.callback,next:null},y===null?(d=y=x,u=g):y=y.next=x,a|=m;if(o=o.next,o===null){if(o=l.shared.pending,o===null)break;m=o,o=m.next,m.next=null,l.lastBaseUpdate=m,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{ge=n,vi.transition=r}}function bd(){return Pt().memoizedState}function wh(e,t,n){var r=Sn(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Td(e))Pd(t,n);else if(n=cd(e,t,n,r),n!==null){var l=ot();Bt(n,e,r,l),Ld(n,t,r)}}function kh(e,t,n){var r=Sn(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Td(e))Pd(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,Ut(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=cd(e,t,l,r),n!==null&&(l=ot(),Bt(n,e,r,l),Ld(n,t,r))}}function Td(e){var t=e.alternate;return e===Te||t!==null&&t===Te}function Pd(e,t){Kr=vs=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Ld(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Da(e,n)}}var xs={readContext:Tt,useCallback:tt,useContext:tt,useEffect:tt,useImperativeHandle:tt,useInsertionEffect:tt,useLayoutEffect:tt,useMemo:tt,useReducer:tt,useRef:tt,useState:tt,useDebugValue:tt,useDeferredValue:tt,useTransition:tt,useMutableSource:tt,useSyncExternalStore:tt,useId:tt,unstable_isNewReconciler:!1},jh={readContext:Tt,useCallback:function(e,t){return Vt().memoizedState=[e,t===void 0?null:t],e},useContext:Tt,useEffect:cu,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Xl(4194308,4,Sd.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Xl(4194308,4,e,t)},useInsertionEffect:function(e,t){return Xl(4,2,e,t)},useMemo:function(e,t){var n=Vt();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Vt();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=wh.bind(null,Te,e),[r.memoizedState,e]},useRef:function(e){var t=Vt();return e={current:e},t.memoizedState=e},useState:uu,useDebugValue:so,useDeferredValue:function(e){return Vt().memoizedState=e},useTransition:function(){var e=uu(!1),t=e[0];return e=xh.bind(null,e[1]),Vt().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Te,l=Vt();if(Ce){if(n===void 0)throw Error(O(407));n=n()}else{if(n=t(),Xe===null)throw Error(O(349));Bn&30||md(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,cu(yd.bind(null,r,i,e),[e]),r.flags|=2048,fl(9,gd.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Vt(),t=Xe.identifierPrefix;if(Ce){var n=Zt,r=Yt;n=(r&~(1<<32-Ft(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=cl++,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[Kt]=t,e[al]=r,Bd(e,t,!1,!1),t.stateNode=e;e:{switch(a=Ui(n,r),n){case"dialog":Se("cancel",e),Se("close",e),l=r;break;case"iframe":case"object":case"embed":Se("load",e),l=r;break;case"video":case"audio":for(l=0;lkr&&(t.flags|=128,r=!0,Rr(i,!1),t.lanes=4194304)}else{if(!r)if(e=ys(a),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Rr(i,!0),i.tail===null&&i.tailMode==="hidden"&&!a.alternate&&!Ce)return nt(t),null}else 2*De()-i.renderingStartTime>kr&&n!==1073741824&&(t.flags|=128,r=!0,Rr(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=De(),t.sibling=null,n=be.current,we(be,r?n&1|2:n&1),t):(nt(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?vt&1073741824&&(nt(t),t.subtreeFlags&6&&(t.flags|=8192)):nt(t),null;case 24:return null;case 25:return null}throw Error(O(156,t.tag))}function Ph(e,t){switch(Va(t),t.tag){case 1:return mt(t.type)&&cs(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return xr(),_e(ht),_e(lt),eo(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Za(t),null;case 13:if(_e(be),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(O(340));yr()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return _e(be),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 Ol=!1,rt=!1,Lh=typeof WeakSet=="function"?WeakSet:Set,V=null;function ir(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){ze(e,t,r)}else n.current=null}function ma(e,t,n){try{n()}catch(r){ze(e,t,r)}}var ku=!1;function Rh(e,t){if(Yi=is,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,m=null;t:for(;;){for(var x;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),(x=g.firstChild)!==null;)m=g,g=x;for(;;){if(g===e)break t;if(m===n&&++d===l&&(o=a),m===i&&++y===r&&(u=a),(x=g.nextSibling)!==null)break;g=m,m=g.parentNode}g=x}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},is=!1,V=t;V!==null;)if(t=V,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,V=e;else for(;V!==null;){t=V;try{var w=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(w!==null){var S=w.memoizedProps,_=w.memoizedState,p=t.stateNode,f=p.getSnapshotBeforeUpdate(t.elementType===t.type?S:Ot(t.type,S),_);p.__reactInternalSnapshotBeforeUpdate=f}break;case 3:var h=t.stateNode.containerInfo;h.nodeType===1?h.textContent="":h.nodeType===9&&h.documentElement&&h.removeChild(h.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(O(163))}}catch(k){ze(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,V=e;break}V=t.return}return w=ku,ku=!1,w}function Qr(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 $s(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 Wd(e){var t=e.alternate;t!==null&&(e.alternate=null,Wd(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Kt],delete t[al],delete t[na],delete t[hh],delete t[mh])),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 Vd(e){return e.tag===5||e.tag===3||e.tag===4}function ju(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Vd(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=us));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 Je=null,At=!1;function cn(e,t,n){for(n=n.child;n!==null;)Kd(e,t,n),n=n.sibling}function Kd(e,t,n){if(Qt&&typeof Qt.onCommitFiberUnmount=="function")try{Qt.onCommitFiberUnmount(Es,n)}catch{}switch(n.tag){case 5:rt||ir(n,t);case 6:var r=Je,l=At;Je=null,cn(e,t,n),Je=r,At=l,Je!==null&&(At?(e=Je,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Je.removeChild(n.stateNode));break;case 18:Je!==null&&(At?(e=Je,n=n.stateNode,e.nodeType===8?mi(e.parentNode,n):e.nodeType===1&&mi(e,n),nl(e)):mi(Je,n.stateNode));break;case 4:r=Je,l=At,Je=n.stateNode.containerInfo,At=!0,cn(e,t,n),Je=r,At=l;break;case 0:case 11:case 14:case 15:if(!rt&&(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)}cn(e,t,n);break;case 1:if(!rt&&(ir(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){ze(n,t,o)}cn(e,t,n);break;case 21:cn(e,t,n);break;case 22:n.mode&1?(rt=(r=rt)||n.memoizedState!==null,cn(e,t,n),rt=r):cn(e,t,n);break;default:cn(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 Lh),t.forEach(function(r){var l=Bh.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function Dt(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=a),r&=~i}if(r=l,r=De()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Ih(r/1960))-r,10e?16:e,gn===null)var r=!1;else{if(e=gn,gn=null,js=0,de&6)throw Error(O(331));var l=de;for(de|=4,V=e.current;V!==null;){var i=V,a=i.child;if(V.flags&16){var o=i.deletions;if(o!==null){for(var u=0;uDe()-uo?On(e,0):oo|=n),gt(e,t)}function ef(e,t){t===0&&(e.mode&1?(t=bl,bl<<=1,!(bl&130023424)&&(bl=4194304)):t=1);var n=ot();e=rn(e,t),e!==null&&(yl(e,t,n),gt(e,n))}function Fh(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),ef(e,n)}function Bh(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(O(314))}r!==null&&r.delete(t),ef(e,n)}var tf;tf=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||ht.current)pt=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return pt=!1,bh(e,t,n);pt=!!(e.flags&131072)}else pt=!1,Ce&&t.flags&1048576&&sd(t,ps,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Jl(e,t),e=t.pendingProps;var l=gr(t,lt.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,mt(r)?(i=!0,ds(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,Ga(t),l.updater=Is,t.stateNode=l,l._reactInternals=t,oa(t,r,e,n),t=da(null,t,r,!0,i,n)):(t.tag=0,Ce&&i&&Wa(t),at(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Jl(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=Hh(r),e=Ot(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,Ot(r.type,e),n);break e}throw Error(O(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ot(r,l),ca(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ot(r,l),vu(e,t,r,l,n);case 3:e:{if(Ad(t),e===null)throw Error(O(387));r=t.pendingProps,i=t.memoizedState,l=i.element,dd(e,t),gs(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(O(423)),t),t=xu(e,t,r,n,l);break e}else if(r!==l){l=wr(Error(O(424)),t),t=xu(e,t,r,n,l);break e}else for(wt=wn(t.stateNode.containerInfo.firstChild),kt=t,Ce=!0,Mt=null,n=ud(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(yr(),r===l){t=ln(e,t,n);break e}at(e,t,r,n)}t=t.child}return t;case 5:return fd(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),Od(e,t),at(e,t,a,n),t.child;case 6:return e===null&&sa(t),null;case 13:return Md(e,t,n);case 4:return Ya(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=vr(t,null,r,n):at(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ot(r,l),gu(e,t,r,l,n);case 7:return at(e,t,t.pendingProps,n),t.child;case 8:return at(e,t,t.pendingProps.children,n),t.child;case 12:return at(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,we(hs,r._currentValue),r._currentValue=a,i!==null)if(Ut(i.value,a)){if(i.children===l.children&&!ht.current){t=ln(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=en(-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(O(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}at(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,fr(t,n),l=Tt(l),r=r(l),t.flags|=1,at(e,t,r,n),t.child;case 14:return r=t.type,l=Ot(r,t.pendingProps),l=Ot(r.type,l),yu(e,t,r,l,n);case 15:return $d(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ot(r,l),Jl(e,t),t.tag=1,mt(r)?(e=!0,ds(t)):e=!1,fr(t,n),Rd(t,r,l),oa(t,r,l,n),da(null,t,r,!0,e,n);case 19:return Fd(e,t,n);case 22:return Dd(e,t,n)}throw Error(O(156,t.tag))};function nf(e,t){return Tc(e,t)}function Uh(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 Et(e,t,n,r){return new Uh(e,t,n,r)}function ho(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Hh(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 _n(e,t){var n=e.alternate;return n===null?(n=Et(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 Zl(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=Et(12,n,t,l|2),e.elementType=Ri,e.lanes=i,e;case zi:return e=Et(13,n,t,l),e.elementType=zi,e.lanes=i,e;case Ii:return e=Et(19,n,t,l),e.elementType=Ii,e.lanes=i,e;case fc:return Os(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case cc:a=10;break e;case dc:a=9;break e;case Ra:a=11;break e;case za:a=14;break e;case dn:a=16,r=null;break e}throw Error(O(130,e==null?e:typeof e,""))}return t=Et(a,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function An(e,t,n,r){return e=Et(7,e,r,t),e.lanes=n,e}function Os(e,t,n,r){return e=Et(22,e,r,t),e.elementType=fc,e.lanes=n,e.stateNode={isHidden:!1},e}function Si(e,t,n){return e=Et(6,e,null,t),e.lanes=n,e}function _i(e,t,n){return t=Et(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Wh(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 Wh(e,t,n,o,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Et(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 Vh(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(af)}catch(e){console.error(e)}}af(),ic.exports=St;var Jh=ic.exports,of,Lu=Jh;of=Lu.createRoot,Lu.hydrateRoot;async function Oe(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 Oe("/api/archives")}async function zu(e,t=null){const n=t?`/api/archives/${e}/entries?collection=${encodeURIComponent(t)}`:`/api/archives/${e}/entries`;return Oe(n)}async function Gh(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),Oe(`/api/archives/${e}/entries/search?${l}`)}async function Mr(e,t){return Oe(`/api/archives/${e}/entries/${t}`)}async function Yh(e,t,{signal:n}={}){return Oe(`/api/archives/${e}/entries/${t}/summary`,{signal:n})}async function Zh(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 em(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 Iu(e,t){return Oe(`/api/archives/${e}/entries/${t}/children`)}async function tm(e,t,n){const r=await fetch(`/api/archives/${e}/entries/${t}/children/order`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({child_uids:n})});if(!r.ok){const l=await r.json().catch(()=>({})),i=new Error(l.error||`HTTP ${r.status}`);throw i.status=r.status,i}}function nm(e,t,n){return Promise.all(n.map(r=>Oe(`/api/archives/${e}/entries/${t}/artifacts/${r}`)))}async function rm(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 lm(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 Fl(e,t){return Oe(`/api/archives/${e}/entries/${t}/tags`)}async function $u(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 sm(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 Du(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 im(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 am(e,t){const n=await fetch(`/api/archives/${e}/tags/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(await n.text())}async function om(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 um(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 Ni(e){return Oe(`/api/archives/${e}/runs`)}async function Bl(e){return Oe(`/api/archives/${e}/tags`)}async function cm(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 dm(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 fm(e,t){return Oe(`/api/archives/${e}/captures/probe?locator=${encodeURIComponent(t)}`)}async function pm(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 uf(e,t){return Oe(`/api/archives/${e}/capture_jobs/${t}`)}async function hm(){return(await(await fetch("/api/auth/setup")).json()).setup_required===!0}async function mm(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 gm(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 ym(){await fetch("/api/auth/logout",{method:"POST"})}async function cf(){const e=await fetch("/api/auth/me");return e.status===401?null:e.json()}async function vm(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 xm(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 wm(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 km(){return Oe("/api/auth/tokens")}async function jm(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 xo(){return Oe("/api/admin/instance-settings")}async function Jr(e){const t=await fetch("/api/admin/instance-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error||`HTTP ${t.status}`)}}async function _m(){return Oe("/api/admin/users")}async function Nm(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 Cm(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 df(){return Oe("/api/admin/roles")}async function Em(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 Oe(`/api/archives/${e}/collections`)}async function bm(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 Tm(e,t){return Oe(`/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 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 Lm(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 Ou(e,t){return Oe(`/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 Rm(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 zm(e){return Oe(`/api/archives/${e}/blob-cleanup`)}async function Im(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 $m(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 Dm(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 Om(){return Oe("/api/admin/cookie-rules")}async function Am(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 Mm(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 Fm(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 Bm(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 Um=window.fetch;window.fetch=async(...e)=>{var n;const t=await Um(...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 Hm({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 gm(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 Wm({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(m){if(m.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 mm(t,r),e()}catch(x){u(x.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:m=>n(m.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:m=>l(m.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:m=>a(m.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 Vm({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:m}=c.useContext(Hs)??{},[x,w]=c.useState(!1);async function S(){w(!0),await ym(),m(null),window.location.reload()}const _=a.find(h=>h.slug==="_default_"),p=!d||!!_&&!_.requires_auth,f=a.filter(h=>h.slug!=="_default_").filter(h=>!d||!h.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:h=>n(h.target.value),children:e.map(h=>s.jsx("option",{value:h.id,children:h.label},h.id))})}),f.length>0&&s.jsx("div",{className:"switcher",children:s.jsxs("select",{"aria-label":"Select collection",value:o??"",onChange:h=>u(h.target.value||null),children:[p&&s.jsx("option",{value:"",children:"All entries"}),f.map(h=>s.jsx("option",{value:h.collection_uid,children:h.name},h.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(h=>s.jsx("button",{className:`nav-link${r===h?" is-active":""}`,onClick:()=>l(h),children:h.charAt(0).toUpperCase()+h.slice(1)},h))}),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:x,children:x?"Logging out…":"Log out"})]})]})]})}let hl=1;function ff(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:hl++,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 Km(e){return{id:hl++,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:hl++,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 Au(e){return Array.isArray(e.playlistItems)&&e.playlistItems.some(t=>t.quality===null)}function Xm({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),m=c.useRef(new Map),x=c.useRef(t);c.useEffect(()=>{x.current=t},[t]);const w=c.useRef(null),[S,_]=c.useState(!1),p=c.useRef([]),f=c.useRef(!1),h=c.useRef(new Map),k=c.useRef(r),E=c.useRef(l);c.useEffect(()=>{k.current=r},[r]),c.useEffect(()=>{E.current=l},[l]);const P=c.useRef(i),N=c.useRef(a);c.useEffect(()=>{P.current=i},[i]),c.useEffect(()=>{N.current=a},[a]);const[v,b]=c.useState(()=>{try{const j=JSON.parse(sessionStorage.getItem("captureItems")||"null");if(Array.isArray(j)&&j.length>0){const B=j.filter(A=>!A.status||A.status==="idle");if(B.length>0)return B.forEach(A=>{A.id>=hl&&(hl=A.id+1)}),B.map(A=>({...Xn(A.locator),...A}))}}catch{}return[Xn()]});c.useEffect(()=>{sessionStorage.setItem("captureItems",JSON.stringify(v.filter(j=>j.kind!=="file")))},[v]),c.useEffect(()=>{p.current=v},[v]);const[L,X]=c.useState(!1),[Q,ne]=c.useState(null),[q,fe]=c.useState(null),[Le,ve]=c.useState(!0),[I,R]=c.useState(!0),[K,ee]=c.useState(!0);c.useEffect(()=>{xo().then(j=>{fe(j),ve(j.cookie_ext_enabled??!0),R(j.modal_closer_enabled??!0)}).catch(()=>fe({}))},[]);const se=Q!==null?Q:(q==null?void 0:q.ublock_enabled)??!0,[ie,Y]=c.useState(!1);c.useEffect(()=>{["captureDialogLocator","captureDialogError","captureDialogBusy","captureDialogJobStatus","captureDialogJobUid"].forEach(j=>sessionStorage.removeItem(j)),o.forEach(j=>{j.jobUid&&!y.current.has(j.jobUid)&&Ne(j.id,j.jobUid,j.locator,j.archiveId,null)})},[]),c.useEffect(()=>{const j=u.current;if(!j)return;const B=()=>{if(g.current.forEach(A=>clearTimeout(A)),g.current.clear(),!f.current){const A=x.current;p.current.forEach(D=>{var F;D.kind==="file"&&(D.uploadStatus==="uploading"?((F=h.current.get(D.id))==null||F(),h.current.delete(D.id)):D.uploadStatus==="done"&&D.uploadLocator&&Ei(A,D.uploadLocator).catch(()=>{}))})}f.current=!1,n()};return j.addEventListener("close",B),()=>j.removeEventListener("close",B)},[n]),c.useEffect(()=>{const j=u.current;j&&(e?(d.current||b([Xn()]),d.current=!1,j.open||j.showModal()):(g.current.forEach(B=>clearTimeout(B)),g.current.clear(),j.open&&j.close()))},[e]),c.useEffect(()=>()=>{y.current.forEach(j=>clearInterval(j)),g.current.forEach(j=>clearTimeout(j))},[]);function Ne(j,B,A,D,F=null){if(y.current.has(B))return;const H=setInterval(async()=>{var ke,he,Re,ye;try{const Fe=await uf(D,B);if(Fe.status==="completed"){clearInterval(y.current.get(B)),y.current.delete(B),await Promise.resolve((ke=k.current)==null?void 0:ke.call(k)),(he=N.current)==null||he.call(N,j);try{const ce=Fe.notes_json?JSON.parse(Fe.notes_json):null;if(ce!=null&&ce.ublock_skipped||ce!=null&&ce.cookie_ext_skipped){const dt=ce.ublock_skipped&&ce.cookie_ext_skipped?"Captured without ad-blocking or cookie-consent extension. Check ARCHIVR_UBLOCK_EXT and ARCHIVR_COOKIE_EXT in your server config.":ce.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.";E.current(dt,A,"warning"),pe(F,"warning",A)}else F||E.current(null,A,"success"),pe(F,"archived")}catch{F||E.current(null,A,"success"),pe(F,"archived")}}else if(Fe.status==="failed"){clearInterval(y.current.get(B)),y.current.delete(B),(Re=N.current)==null||Re.call(N,j);const ce=Fe.error_text||"Capture failed.";E.current(ce,A),pe(F,"failed",A)}}catch(Fe){clearInterval(y.current.get(B)),y.current.delete(B),(ye=N.current)==null||ye.call(N,j);const ce=Fe.message||"Network error";E.current(ce,A),pe(F,"failed",A)}},500);y.current.set(B,H)}function pe(j,B,A=null){if(!j)return;const D=m.current.get(j);if(!D||(B==="archived"||B==="warning"?(D.archived++,B==="warning"&&(D.warnings++,A&&D.warningLocators.push(A))):(D.failed++,A&&D.failedLocators.push(A)),D.archived+D.failed0?`${F} archived (${H} with warnings)`:`${F} archived`;ye=ke>0?`${dt}, ${ke} failed`:dt}const Fe=F===0?"error":ke>0||H>0?"warning":"success",ce=[];he.length>0&&ce.push(`Failed: -${he.map(dt=>` ${dt}`).join(` -`)}`),Re.length>0&&ce.push(`With warnings: -${Re.map(dt=>` ${dt}`).join(` -`)}`);const it=ce.length>0?ce.join(` -`):null;E.current(it,null,Fe,ye)}async function U(j,B){var Re,ye,Fe;const A=x.current,D=((Re=crypto.randomUUID)==null?void 0:Re.call(crypto))??`job-${Date.now()}-${Math.random()}`;if(j.type==="text"){try{const ce=await dm(A,{title:j.title,body:j.body,mime:j.mime}),it=`text:${j.title}`;(ye=P.current)==null||ye.call(P,{id:D,jobUid:ce.job_uid,locator:it,archiveId:A}),Ne(D,ce.job_uid,it,A,B)}catch(ce){const it=ce.message||"Submission failed.";E.current(it,`text:${j.title}`),pe(B,"failed",`text:${j.title}`)}return}const F=j.locator,H=j.quality,ke=j.extraExtensions||{},he={ublock_enabled:se,reader_mode:ie,cookie_ext_enabled:Le,modal_closer_enabled:I,via_freedium:K,...ke};try{const ce=await cm(A,F,H,he);(Fe=P.current)==null||Fe.call(P,{id:D,jobUid:ce.job_uid,locator:F,archiveId:A}),Ne(D,ce.job_uid,F,A,B)}catch(ce){const it=ce.message||"Submission failed.";E.current(it,F),pe(B,"failed",F),F.startsWith("file://")&&ce.status&&Ei(A,F).catch(()=>{})}}function te(){var D,F;if(v.some(H=>H.kind==="file"&&H.uploadStatus==="uploading"))return;const j=v.filter(H=>H.kind==="file"?H.uploadStatus==="done"&&H.uploadLocator:H.kind==="text"?H.title.trim()&&H.body.trim():H.locator.trim());if(j.length===0||j.some(H=>H.kind!=="file"&&H.kind!=="text"&&Au(H))||j.some(H=>H.kind!=="file"&&H.kind!=="text"&&(H.probeState==="probing"||Dn(H.locator)&&H.playlistProbeState!=="done"))||j.some(H=>H.kind!=="file"&&H.kind!=="text"&&Array.isArray(H.playlistItems)&&H.playlistItems.length===0))return;const B=j.length>1?((D=crypto.randomUUID)==null?void 0:D.call(crypto))??`batch-${Date.now()}`:null;B&&m.current.set(B,{total:j.length,archived:0,warnings:0,failed:0,failedLocators:[],warningLocators:[]});const A=j.map(H=>H.kind==="file"?{type:"file",locator:H.uploadLocator,quality:"best",extraExtensions:{}}:H.kind==="text"?{type:"text",title:H.title.trim(),body:H.body,mime:H.mime}:{type:"url",locator:H.locator.trim(),quality:H.playlistItems!==null?null:H.quality||"best",extraExtensions:H.playlistItems!==null?{per_item_quality:Object.fromEntries(H.playlistItems.map(ke=>[ke.id,ke.quality])),sync:H.syncEnabled}:{}});f.current=!0,b([Xn()]),(F=u.current)==null||F.close(),A.forEach(H=>U(H,B))}function re(){b(j=>[...j,Xn()])}function Ue(j){var A;clearTimeout(g.current.get(j)),g.current.delete(j);const B=p.current.find(D=>D.id===j);(B==null?void 0:B.kind)==="file"&&(B.uploadStatus==="uploading"?((A=h.current.get(j))==null||A(),h.current.delete(j)):B.uploadStatus==="done"&&B.uploadLocator&&Ei(x.current,B.uploadLocator).catch(()=>{})),b(D=>{const F=D.filter(H=>H.id!==j);return F.length===0?[Xn()]:F})}function Lt(j,B){if(clearTimeout(g.current.get(j)),b(A=>A.map(D=>D.id===j?{...D,locator:B,probeState:"idle",probeQualities:null,probeHasAudio:!1,quality:"best",playlistProbeState:"idle",playlistInfo:null,playlistItems:null,playlistQuality:null,playlistExpanded:!1}:D)),ff(B)){const A=setTimeout(async()=>{g.current.delete(j),b(D=>D.map(F=>F.id===j?{...F,probeState:"probing"}:F));try{const D=await fm(x.current,B.trim());b(F=>F.map(H=>{if(H.id!==j||H.locator!==B)return H;const ke=D.qualities??[],he=D.has_audio??!1,Re=ke.length===0&&he?"audio":"best";return{...H,probeState:"done",probeQualities:ke,probeHasAudio:he,quality:Re}}))}catch{b(D=>D.map(F=>F.id===j?{...F,probeState:"idle",probeQualities:null}:F))}},600);g.current.set(j,A)}else if(Dn(B)){const A=setTimeout(async()=>{g.current.delete(j),b(D=>D.map(F=>F.id===j?{...F,playlistProbeState:"probing"}:F));try{const D=await pm(x.current,B.trim());b(F=>F.map(H=>H.id!==j||H.locator!==B?H:{...H,playlistProbeState:"done",playlistInfo:D,playlistItems:D.items.map(ke=>({...ke,quality:null})),playlistQuality:null}))}catch{b(D=>D.map(F=>F.id===j?{...F,playlistProbeState:"error"}:F))}},800);g.current.set(j,A)}}function yt(j,B){b(A=>A.map(D=>D.id===j?{...D,quality:B}:D))}function Ie(j,B){b(A=>A.map(D=>{if(D.id!==j)return D;const F=qm(B,D.playlistItems);return{...D,playlistQuality:B,playlistItems:F}}))}function st(j,B,A){b(D=>D.map(F=>F.id!==j?F:{...F,playlistItems:F.playlistItems.map(H=>H.id===B?{...H,quality:A}:H)}))}function Ze(j){b(B=>B.map(A=>A.id===j?{...A,playlistExpanded:!A.playlistExpanded}:A))}function $(j,B){b(A=>A.map(D=>D.id===j?{...D,syncEnabled:B}:D))}function Z(j,B){b(A=>A.map(D=>D.id!==j?D:{...D,playlistItems:D.playlistItems.filter(F=>F.id!==B)}))}function Ae(j){const B=Array.from(j);B.length!==0&&B.forEach(A=>{const D=Km(A.name);b(he=>he.length===1&&!he[0].kind&&!he[0].locator.trim()?[D]:[...he,D]);const F=x.current,{promise:H,abort:ke}=Bm(F,A,he=>{b(Re=>Re.map(ye=>ye.id===D.id?{...ye,uploadProgress:he}:ye))});h.current.set(D.id,ke),H.then(he=>{h.current.delete(D.id),b(Re=>Re.map(ye=>ye.id===D.id?{...ye,uploadStatus:"done",uploadLocator:he.locator,uploadProgress:100}:ye))}).catch(he=>{h.current.delete(D.id),he.message!=="Upload cancelled"&&b(Re=>Re.map(ye=>ye.id===D.id?{...ye,uploadStatus:"error",uploadError:he.message}:ye))})})}function Me(j){j.preventDefault(),j.stopPropagation(),j.dataTransfer.types.includes("Files")&&_(!0)}function Rt(j){j.currentTarget.contains(j.relatedTarget)||_(!1)}function zt(j){j.preventDefault(),j.stopPropagation(),_(!1),Ae(j.dataTransfer.files)}function It(j){Ae(j.target.files),j.target.value=""}const et=v.some(j=>j.kind==="file"&&j.uploadStatus==="uploading"),Xt=v.filter(j=>j.kind==="file"?j.uploadStatus==="done"&&j.uploadLocator:j.kind==="text"?j.title.trim()&&j.body.trim():j.locator.trim()).length,$t=v.some(j=>j.kind!=="file"&&j.kind!=="text"&&Au(j)),an=v.some(j=>j.kind!=="file"&&j.kind!=="text"&&Array.isArray(j.playlistItems)&&j.playlistItems.length===0),He=v.some(j=>j.kind!=="file"&&j.kind!=="text"&&(j.probeState==="probing"||Dn(j.locator)&&j.playlistProbeState!=="done"));return s.jsx("dialog",{ref:u,className:`capture-dialog${S?" capture-dialog--dragover":""}`,onDragOver:Me,onDragLeave:Rt,onDrop:zt,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:v.map((j,B)=>j.kind==="file"?s.jsx(Gm,{item:j,onRemove:()=>Ue(j.id)},j.id):j.kind==="text"?s.jsx(Ym,{item:j,autoFocus:B===v.length-1,onTitleChange:A=>b(D=>D.map(F=>F.id===j.id?{...F,title:A}:F)),onBodyChange:A=>b(D=>D.map(F=>F.id===j.id?{...F,body:A}:F)),onMimeChange:A=>b(D=>D.map(F=>F.id===j.id?{...F,mime:A}:F)),onRemove:()=>Ue(j.id),onSubmit:te},j.id):s.jsx(Jm,{item:j,autoFocus:B===v.length-1,onLocatorChange:A=>Lt(j.id,A),onQualityChange:A=>yt(j.id,A),onRemove:()=>Ue(j.id),onSubmit:te,onPlaylistQualityChange:A=>Ie(j.id,A),onPlaylistItemQualityChange:(A,D)=>st(j.id,A,D),onPlaylistToggle:()=>Ze(j.id),onSyncChange:A=>$(j.id,A),onPlaylistItemDelete:A=>Z(j.id,A)},j.id))}),s.jsx("input",{ref:w,type:"file",multiple:!0,hidden:!0,onChange:It,"aria-hidden":"true",tabIndex:-1}),s.jsxs("div",{className:"capture-add-row-group",children:[s.jsxs("button",{type:"button",className:"capture-add-row",onClick:re,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=w.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("button",{type:"button",className:"capture-add-row capture-add-text",onClick:()=>b(j=>[...j,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(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":se,className:`ext-toggle ext-toggle--sm${se?" ext-toggle--on":""}`,onClick:()=>ne(j=>j===null?!se:!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"}),!(q!=null&&q.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":Le,className:`ext-toggle ext-toggle--sm${Le?" ext-toggle--on":""}`,onClick:()=>ve(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":ie,className:`ext-toggle ext-toggle--sm${ie?" 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":I,className:`ext-toggle ext-toggle--sm${I?" ext-toggle--on":""}`,onClick:()=>R(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":K,className:`ext-toggle ext-toggle--sm${K?" ext-toggle--on":""}`,onClick:()=>ee(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:te,disabled:Xt===0||$t||He||an||et,children:Xt>1?`Archive ${Xt}`:"Archive"}),s.jsx("button",{type:"button",className:"capture-cancel",onClick:()=>{var j;return(j=u.current)==null?void 0:j.close()},children:"Cancel"})]})]})})}function Jm({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 w;t&&((w=g.current)==null||w.focus())},[t]);const m=(()=>{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 w=[...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),_=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"}),w.map(p=>s.jsxs("option",{value:`${p}p`,children:[p,"p"]},p)),S&&s.jsx("option",{value:"audio",children:"Audio only"})]}),_>0&&s.jsxs("span",{className:"capture-conflict-badge",children:[_," 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(!ff(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 w=e.probeQualities??[],S=e.probeHasAudio??!1;return w.length===0&&!S?s.jsx("span",{className:"capture-quality-hint",children:"No media detected"}):w.length===0&&S?s.jsx("select",{className:"capture-quality",value:"audio",onChange:_=>r(_.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:_=>r(_.target.value),"aria-label":"Video quality",children:[s.jsx("option",{value:"best",children:"Best quality"}),w.map(_=>s.jsx("option",{value:_,children:_},_)),S&&s.jsx("option",{value:"audio",children:"Audio only"})]})}return null})(),x=Dn(e.locator)&&e.playlistProbeState==="done"?s.jsxs("label",{className:"capture-sync-row",children:[s.jsx("input",{type:"checkbox",checked:e.syncEnabled,onChange:w=>d(w.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:w=>n(w.target.value),onKeyDown:w=>{w.key==="Enter"&&i()},autoComplete:"off",spellCheck:!1}),m,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(w=>s.jsxs("div",{className:`capture-playlist-item${w.quality===null?" capture-playlist-item--conflict":""}`,children:[s.jsx("span",{className:"capture-playlist-item-title",children:w.title||w.url}),s.jsxs("select",{className:"capture-item-quality",value:w.quality??"",onChange:S=>o(w.id,S.target.value),"aria-label":`Quality for ${w.title||w.url}`,children:[w.quality===null&&s.jsx("option",{value:"",disabled:!0,children:"Choose…"}),s.jsx("option",{value:"best",children:"Best quality"}),w.qualities.map(S=>s.jsx("option",{value:S,children:S},S)),w.has_audio&&s.jsx("option",{value:"audio",children:"Audio only"})]}),w.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 ${w.title||w.url}`,onClick:()=>y(w.id),children:"×"})]},w.id)),x]}):x]})}function Gm({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 Ym({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 Zm=["list=","/playlist/","/channel/","yt:playlist:","yt:channel:","ytm:playlist:","spotify:playlist:","spotify:album:"];function eg(e){const t=e.toLowerCase();return Zm.some(n=>t.includes(n))}function tg(e){return e.length>80?`${e.slice(0,79)}…`:e}function ng({locator:e=""}){const t=String(e),n=eg(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:tg(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 ml(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 xt(e){return rg(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 Mu={youtube:'',youtube_music:'',spotify:'',x:'',instagram:'',facebook:'',tiktok:'',reddit:'',snapchat:'',local:'',web:'',other:'?'};function Us(e){return Mu[e]??Mu.other}function pf(e){return e.split("/").map(t=>t?t.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"").join("/")}function lg({entry:e,index:t,onRowClick:n,selectedUids:r,isFirst:l,isLast:i,reorderDisabled:a,onMove:o,canReorder:u,isDragging:d,dropEdge:y,onHandleDragStart:g,onHandleDragEnd:m,onRowDragOver:x,onRowDrop:w}){const S=(r==null?void 0:r.size)===1&&r.has(e.entry_uid),_=(r==null?void 0:r.size)>=2&&r.has(e.entry_uid),p=xt(e.title)||xt(e.entry_uid),f=["child-entry-row",t%2===0?"child-entry-row--light":"child-entry-row--dark",S&&"is-selected",_&&"is-multi-selected",d&&"is-dragging",y==="before"&&"is-drop-before",y==="after"&&"is-drop-after"].filter(Boolean).join(" ");return s.jsxs("div",{className:f,tabIndex:0,"data-entry-uid":e.entry_uid,onMouseDown:h=>{h.shiftKey&&h.preventDefault()},onClick:h=>n(e,h),onDragOver:u?x:void 0,onDrop:u?w:void 0,"aria-keyshortcuts":u?"Alt+ArrowUp Alt+ArrowDown":void 0,onKeyDown:h=>{if(u&&h.altKey&&(h.key==="ArrowUp"||h.key==="ArrowDown")){h.preventDefault(),a||o(h.key==="ArrowUp"?-1:1);return}h.key==="Enter"&&n(e,h)},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:[u&&s.jsxs("span",{className:"child-reorder-controls",children:[s.jsx("span",{className:"child-drag-handle",draggable:!a,title:"Drag to reorder (or Alt+↑/↓)","aria-hidden":"true",onClick:h=>h.stopPropagation(),onDragStart:g,onDragEnd:m,children:"⋮⋮"}),s.jsx("button",{type:"button",className:"child-move-btn","aria-label":`Move ${p} up`,disabled:a||l,onClick:h=>{h.stopPropagation(),o(-1)},onKeyDown:h=>h.stopPropagation(),children:"↑"}),s.jsx("button",{type:"button",className:"child-move-btn","aria-label":`Move ${p} down`,disabled:a||i,onClick:h=>{h.stopPropagation(),o(1)},onKeyDown:h=>h.stopPropagation(),children:"↓"})]}),s.jsx("span",{className:"source-icon",children:s.jsx("span",{dangerouslySetInnerHTML:{__html:Us(e.source_kind)}})}),s.jsx("span",{className:"entry-title",children:p})]}),s.jsx("div",{className:"col-type",children:s.jsx("span",{className:"type-pill",children:xt(e.entity_kind)})}),s.jsx("div",{className:"col-size",children:s.jsx("span",{className:"size-total",children:ml(e.total_artifact_bytes)})}),s.jsx("div",{className:"url-cell col-url",children:xt(e.original_url)})]})}function sg({entry:e,archiveId:t,rowIndex:n,isSelected:r,isMultiSelected:l,onRowClick:i,selectedUids:a,deletedUids:o,renamedTitles:u,isPublicSession:d,canReorder:y=!1,onReorderError:g}){const[m,x]=c.useState(!1),[w,S]=c.useState(!1),[_,p]=c.useState(null),[f,h]=c.useState(!1),[k,E]=c.useState(!1),[P,N]=c.useState(null),[v,b]=c.useState(null),L=c.useRef(null),X=c.useRef(null),ne=e.source_kind==="web"&&e.entity_kind==="page"&&e.has_favicon&&t&&!m?s.jsx("img",{src:`/api/archives/${t}/entries/${e.entry_uid}/favicon`,width:"16",height:"16",alt:"",onError:()=>x(!0),style:{objectFit:"contain"}}):s.jsx("span",{dangerouslySetInnerHTML:{__html:Us(e.source_kind)}}),q=r||l,fe=e.child_count>0&&!d;function Le(U){U.stopPropagation(),i(e,{ctrlKey:!0,metaKey:!1,shiftKey:!1,preventDefault(){}})}async function ve(U){if(U.stopPropagation(),w){S(!1);return}if(S(!0),_===null&&!f){h(!0);try{const te=await Iu(t,e.entry_uid);p(te)}catch{p([])}finally{h(!1)}}}const I=(_??[]).filter(U=>!(o!=null&&o.has(U.entry_uid))).map(U=>u!=null&&u.has(U.entry_uid)?{...U,title:u.get(U.entry_uid)}:U);async function R(U){const te=_;p(U),E(!0);try{await tm(t,e.entry_uid,U.map(re=>re.entry_uid))}catch(re){if(p(te),g==null||g(re.message),re.status===400)try{p(await Iu(t,e.entry_uid))}catch{}}finally{E(!1)}}function K(U,te){if(!y||k||U===te||te<0||te>=I.length)return;const re=I.slice(),[Ue]=re.splice(U,1);re.splice(te,0,Ue),R(re)}function ee(U,te){var re;X.current=((re=I[U])==null?void 0:re.entry_uid)??null,K(U,U+te)}c.useEffect(()=>{const U=X.current;if(!U||!L.current)return;X.current=null;const te=L.current.querySelector(`[data-entry-uid="${CSS.escape(U)}"]`);te&&!te.contains(document.activeElement)&&te.focus()},[_]);function se(U,te){te.stopPropagation(),te.dataTransfer.effectAllowed="move",te.dataTransfer.setData("text/plain",U);const re=te.currentTarget.closest(".child-entry-row");re&&te.dataTransfer.setDragImage(re,16,re.offsetHeight/2),N(U)}function ie(){N(null),b(null)}function Y(U,te){if(!P)return;te.preventDefault(),te.dataTransfer.dropEffect="move";const re=te.currentTarget.getBoundingClientRect(),Ue=te.clientY>re.top+re.height/2;((v==null?void 0:v.uid)!==U||(v==null?void 0:v.after)!==Ue)&&b({uid:U,after:Ue})}function Ne(U,te){if(!P)return;te.preventDefault();const re=I.findIndex(Ie=>Ie.entry_uid===P),Ue=I.findIndex(Ie=>Ie.entry_uid===U),Lt=(v==null?void 0:v.uid)===U?v.after:!1;if(ie(),re===-1||Ue===-1)return;let yt=Ue+(Lt?1:0);re{U.shiftKey&&U.preventDefault()},onClick:U=>i(e,U),onKeyDown:U=>{U.key==="Enter"&&i(e,U)},children:[s.jsx("div",{className:"col-check",children:s.jsx("button",{type:"button",className:`row-checkbox${q?" is-checked":""}`,"aria-pressed":q,"aria-label":q?"Deselect entry":"Select entry",onClick:Le,onKeyDown:U=>U.stopPropagation()})}),s.jsx("div",{className:"col-added",children:ko(e.archived_at)}),s.jsxs("div",{className:"col-title",children:[fe&&s.jsx("button",{type:"button",className:`entry-expand-btn${w?" is-expanded":""}`,"aria-label":w?"Collapse children":`Expand ${e.child_count} items`,"aria-expanded":w,onClick:ve,onKeyDown:U=>U.stopPropagation()}),s.jsx("span",{className:"source-icon",children:ne}),s.jsx("span",{className:"entry-title",children:xt(e.title)||xt(e.entry_uid)}),fe&&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:xt(e.entity_kind)})}),s.jsxs("div",{className:"col-size",children:[s.jsx("span",{className:"size-total",children:ml(e.total_artifact_bytes)}),e.cached_bytes>0&&e.cacheable_bytes>0&&s.jsxs("span",{className:"size-cached-pct",title:`${ml(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:xt(e.original_url)})]}),w&&s.jsxs(s.Fragment,{children:[f&&s.jsx("div",{className:"child-entries-loading",children:"Loading…"}),s.jsx("div",{className:"child-entries",ref:L,"aria-busy":k,"aria-label":`${e.child_count} child entries`,children:I.map((U,te)=>s.jsx(lg,{entry:U,index:te,onRowClick:i,selectedUids:a,isFirst:te===0,isLast:te===I.length-1,reorderDisabled:k,canReorder:y,onMove:re=>ee(te,re),isDragging:P===U.entry_uid,dropEdge:(v==null?void 0:v.uid)===U.entry_uid&&P!==U.entry_uid?v.after?"after":"before":null,onHandleDragStart:re=>se(U.entry_uid,re),onHandleDragEnd:ie,onRowDragOver:re=>Y(U.entry_uid,re),onRowDrop:re=>Ne(U.entry_uid,re)},U.entry_uid))})]})]})}function ig({entries:e,selectedUids:t,onRowClick:n,archiveId:r,pendingCaptures:l=[],deletedUids:i,renamedTitles:a,isPublicSession:o,canReorder:u=!1,onChildReorderError:d}){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(y=>y.archiveId===r).reverse().map(y=>s.jsx(ng,{locator:y.locator},y.id)),e.map((y,g)=>s.jsx(sg,{entry:y,rowIndex:g,archiveId:r,isSelected:t.size===1&&t.has(y.entry_uid),isMultiSelected:t.size>=2&&t.has(y.entry_uid),onRowClick:n,selectedUids:t,deletedUids:i,renamedTitles:a,isPublicSession:o,canReorder:u,onReorderError:d},y.entry_uid))]})]})})}function ag(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 og({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 ug({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:ag(l.started_at)}),s.jsxs("td",{children:[s.jsx(og,{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 cg=4;function dg({archives:e}){const{currentUser:t}=c.useContext(Hs)??{},n=t&&(t.role_bits&cg)!==0,[r,l]=c.useState("users"),[i,a]=c.useState([]),[o,u]=c.useState([]),[d,y]=c.useState(!1),[g,m]=c.useState(null),[x,w]=c.useState(""),[S,_]=c.useState(""),[p,f]=c.useState(""),[h,k]=c.useState(null),[E,P]=c.useState(!1),[N,v]=c.useState(""),[b,L]=c.useState(""),[X,Q]=c.useState(null),[ne,q]=c.useState(!1),fe=c.useCallback(async()=>{if(n){y(!0),m(null);try{const[R,K]=await Promise.all([_m(),df()]);a(R),u(K)}catch(R){m(R.message)}finally{y(!1)}}},[n]);c.useEffect(()=>{fe()},[fe]);async function Le(R){const K=R.status==="active"?"disabled":"active";try{await Cm(R.user_uid,K),a(ee=>ee.map(se=>se.user_uid===R.user_uid?{...se,status:K}:se))}catch(ee){m(ee.message)}}async function ve(R){if(R.preventDefault(),!x.trim()||!S){k("Username and password required");return}P(!0),k(null);try{await Nm(x.trim(),S,p.trim()||void 0),w(""),_(""),f(""),await fe()}catch(K){k(K.message)}finally{P(!1)}}async function I(R){if(R.preventDefault(),!N.trim()||!b.trim()){Q("Slug and name required");return}q(!0),Q(null);try{await Em(N.trim(),b.trim()),v(""),L(""),await fe()}catch(K){Q(K.message)}finally{q(!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(R=>s.jsxs("tr",{className:R.status==="disabled"?"admin-row-disabled":"",children:[s.jsx("td",{children:R.username}),s.jsx("td",{className:"muted",children:R.email||"—"}),s.jsx("td",{children:R.role_slugs.join(", ")||"—"}),s.jsx("td",{children:s.jsx("span",{className:`status-badge status-${R.status}`,children:R.status})}),s.jsx("td",{children:s.jsx("button",{className:"admin-action-btn",onClick:()=>Le(R),children:R.status==="active"?"Ban":"Unban"})})]},R.user_uid))})]}),s.jsx("h3",{children:"Create User"}),s.jsxs("form",{className:"admin-form",onSubmit:ve,children:[s.jsx("input",{className:"admin-input",placeholder:"Username",value:x,onChange:R=>w(R.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"password",placeholder:"Password (min 8 chars)",value:S,onChange:R=>_(R.target.value),required:!0}),s.jsx("input",{className:"admin-input",type:"email",placeholder:"Email (optional)",value:p,onChange:R=>f(R.target.value)}),h&&s.jsx("div",{className:"form-msg form-msg--err",children:h}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:E,children:E?"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(R=>s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("code",{children:R.slug})}),s.jsx("td",{children:R.name}),s.jsx("td",{children:R.level}),s.jsx("td",{children:R.bit_position}),s.jsx("td",{children:R.is_builtin?"✓":""})]},R.role_uid))})]}),s.jsx("h3",{children:"Create Custom Role"}),s.jsxs("form",{className:"admin-form",onSubmit:I,children:[s.jsx("input",{className:"admin-input",placeholder:"Slug (e.g. moderator)",value:N,onChange:R=>v(R.target.value),required:!0}),s.jsx("input",{className:"admin-input",placeholder:"Display Name (e.g. Moderator)",value:b,onChange:R=>L(R.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:ne,children:ne?"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(R=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:R.label}),s.jsx("div",{className:"muted",children:R.archive_path})]},R.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(R=>s.jsxs("div",{className:"admin-archive",children:[s.jsx("strong",{children:R.label}),s.jsx("div",{className:"muted",children:R.archive_path})]},R.id))})]})}function hf({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(hf,{node:r,onPick:t},r.tag.tag_uid))})})]})}function Fu({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(hf,{node:o,onPick:r},o.tag.tag_uid))}):s.jsx("p",{className:"tag-picker-empty",children:"No other tags available."})]})]})})}function mf({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 om(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 gf({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:m,onCreateCancel:x}){var X;const w=n===e.tag.full_path,[S,_]=c.useState(!1),[p,f]=c.useState(""),h=c.useRef(!1);function k(){if(S)return;if(d){y(e);return}const Q=w?null:e.tag.full_path;r(Q),l("archive")}function E(Q){Q.stopPropagation(),!d&&(f(e.tag.slug),_(!0))}async function P(){const Q=p.trim();if(!Q||Q===e.tag.slug){_(!1);return}try{const ne=await im(t,e.tag.tag_uid,Q);i(e.tag.full_path,ne.full_path),o()}catch{}finally{_(!1)}}async function N(Q){var q;Q.stopPropagation();const ne=((q=e.children)==null?void 0:q.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(ne))try{await am(t,e.tag.tag_uid),a(e.tag.full_path),o()}catch{}}const v={archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:d,onMoveSourceSelect:y,pendingCreateParentUid:g,onCreateDone:m,onCreateCancel:x},b=g===e.tag.tag_uid,L=((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:Q=>f(Q.target.value),onKeyDown:Q=>{Q.key==="Enter"&&Q.currentTarget.blur(),Q.key==="Escape"&&(h.current=!0,Q.currentTarget.blur())},onBlur:()=>{h.current?(h.current=!1,_(!1)):P()}}):s.jsxs("button",{className:`tag-node-btn${w?" 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:E,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:Q=>{Q.stopPropagation(),E(Q)},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:N,"aria-label":`Delete "${e.tag.full_path}"`,children:"×"})]}),(L||b)&&s.jsx("div",{className:"tag-children",children:s.jsxs("ul",{className:"tag-tree-list",children:[e.children.map(Q=>s.jsx(gf,{node:Q,...v},Q.tag.tag_uid)),b&&s.jsx("li",{children:s.jsx(mf,{parentPath:e.tag.full_path,archiveId:t,onDone:m,onCancel:x})})]})})]})}function fg({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,m]=c.useState(null);function x(){y("select-source"),m(null)}function w(){y(null),m(null)}c.useEffect(()=>{if(d!=="select-source")return;function ne(q){q.key==="Escape"&&(q.preventDefault(),q.stopPropagation(),w())}return document.addEventListener("keydown",ne),()=>document.removeEventListener("keydown",ne)},[d]);function S(ne){m(ne),y("select-dest")}async function _(ne){const q=g.tag.full_path,fe=g.tag.tag_uid,Le=(ne==null?void 0:ne.tag_uid)??null;w();try{const ve=await um(e,fe,Le);i(q,ve.full_path),o()}catch(ve){alert(ve.message||"Move failed")}}const[p,f]=c.useState(null),[h,k]=c.useState(void 0);function E(){f("select-parent"),k(void 0)}function P(){f(null),k(void 0)}function N(ne){k(ne??null),f("input")}function v(){f(null),k(void 0),o()}const b=d==="select-source",L=p==="input"?h?h.tag_uid:"__root__":void 0,X={archiveId:e,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:i,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u,moveSelectMode:b,onMoveSourceSelect:S,pendingCreateParentUid:L,onCreateDone:v,onCreateCancel:P},Q=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:b?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:w,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:E,title:"Create a new tag",disabled:!!p||!!d,children:"+ New"}),s.jsx("button",{className:"tag-tree-action-btn",onClick:x,title:"Move a tag to a different parent",disabled:!!p||!!d||t.length===0,children:"Move"})]})]})}),t.length===0&&!Q?s.jsx("p",{className:"muted",style:{padding:"8px 0"},children:"No tags yet."}):s.jsxs("ul",{className:"tag-tree-list",children:[t.map(ne=>s.jsx(gf,{node:ne,...X},ne.tag.tag_uid)),Q&&s.jsx("li",{children:s.jsx(mf,{parentPath:null,archiveId:e,onDone:v,onCancel:P})})]})]}),p==="select-parent"&&s.jsx(Fu,{title:"Create tag under…",tagNodes:t,excludeUid:null,onPick:N,onCancel:P}),d==="select-dest"&&g&&s.jsx(Fu,{title:`Move "${g.tag.slug}" under…`,tagNodes:t,excludeUid:g.tag.tag_uid,onPick:_,onCancel:w})]})}const Fr=[{value:0,label:"Private"},{value:2,label:"Users only"},{value:3,label:"Public"}],pg=e=>{var t;return((t=Fr.find(n=>n.value===e))==null?void 0:t.label)??String(e)};function hg({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,m]=c.useState(!1),[x,w]=c.useState(null),[S,_]=c.useState(""),[p,f]=c.useState(""),[h,k]=c.useState(2),[E,P]=c.useState(!1),[N,v]=c.useState(!0),[b,L]=c.useState(null),[X,Q]=c.useState(""),[ne,q]=c.useState(2),[fe,Le]=c.useState(!1),[ve,I]=c.useState(null),[R,K]=c.useState(!1),[ee,se]=c.useState(""),ie=c.useRef(null),Y=t.find($=>$.collection_uid===o)??null,Ne=(Y==null?void 0:Y.slug)==="_default_",pe=c.useCallback(async()=>{if(e){l(!0),a(null);try{const $=await wo(e);n($)}catch($){a($.message)}finally{l(!1)}}},[e]),U=c.useCallback(async $=>{if(!$){y(null);return}m(!0),w(null);try{const Z=await Tm(e,$);y(Z)}catch(Z){w(Z.message)}finally{m(!1)}},[e]);c.useEffect(()=>{pe()},[pe]),c.useEffect(()=>{U(o)},[o,U]),c.useEffect(()=>{R&&ie.current&&ie.current.focus()},[R]),c.useEffect(()=>{d!=null&&q(d.default_visibility_bits)},[d]);async function te($){$.preventDefault();const Z=S.trim(),Ae=p.trim();if(!(!Z||!Ae)){P(!0),L(null);try{const Me=await bm(e,Z,Ae,h,N);_(""),f(""),k(2),v(!0),await pe(),u(Me.collection_uid)}catch(Me){L(Me.message)}finally{P(!1)}}}async function re(){const $=ee.trim();if(!$||!Y){K(!1);return}try{await Ci(e,Y.collection_uid,{name:$}),await pe(),y(Z=>Z&&{...Z,name:$})}catch(Z){a(Z.message)}finally{K(!1)}}async function Ue($){if(Y)try{await Ci(e,Y.collection_uid,{default_visibility_bits:$}),await pe(),y(Z=>Z&&{...Z,default_visibility_bits:$})}catch(Z){a(Z.message)}}async function Lt($){if(Y)try{await Ci(e,Y.collection_uid,{requires_auth:$}),await pe(),y(Z=>Z&&{...Z,requires_auth:$})}catch(Z){a(Z.message)}}async function yt(){if(Y&&window.confirm(`Delete collection "${Y.name}"? Entries will not be deleted.`))try{await Rm(e,Y.collection_uid),u(null),y(null),await pe()}catch($){a($.message)}}async function Ie($){$.preventDefault();const Z=X.trim();if(!(!Z||!Y)){Le(!0),I(null);try{await Sa(e,Y.collection_uid,Z,ne),Q(""),await U(Y.collection_uid)}catch(Ae){I(Ae.message)}finally{Le(!1)}}}async function st($){if(Y)try{await Pm(e,Y.collection_uid,$),await U(Y.collection_uid)}catch(Z){w(Z.message)}}async function Ze($,Z){if(Y)try{await Lm(e,Y.collection_uid,$,Z),y(Ae=>Ae&&{...Ae,entries:Ae.entries.map(Me=>Me.entry_uid===$?{...Me,collection_visibility_bits:Z}:Me)})}catch(Ae){w(Ae.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($=>s.jsxs("button",{className:`coll-sidebar-row${o===$.collection_uid?" is-active":""}`,onClick:()=>u($.collection_uid),children:[s.jsx("span",{className:"coll-row-name",children:$.name}),s.jsx("span",{className:"coll-row-meta",children:pg($.default_visibility_bits)})]},$.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:[R?s.jsx("input",{ref:ie,className:"coll-rename-input",value:ee,onChange:$=>se($.target.value),onBlur:re,onKeyDown:$=>{$.key==="Enter"&&re(),$.key==="Escape"&&K(!1)}}):s.jsxs("h3",{className:`coll-detail-name${Ne?"":" coll-detail-name--editable"}`,title:Ne?void 0:"Click to rename",onClick:()=>{Ne||(se(Y.name),K(!0))},children:[(d==null?void 0:d.name)??Y.name,!Ne&&s.jsx("span",{className:"coll-edit-hint",children:" ✎"})]}),!Ne&&s.jsx("button",{className:"coll-delete-btn",onClick:yt,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)??Y.default_visibility_bits,onChange:$=>Ue(Number($.target.value)),children:Fr.map($=>s.jsx("option",{value:$.value,children:$.label},$.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)??Y.requires_auth),onChange:$=>Lt($.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…"}),x&&s.jsx("div",{className:"collections-error",children:x}),!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($=>s.jsxs("li",{className:"coll-entry-row",children:[s.jsxs("div",{className:"coll-entry-info",children:[s.jsx("span",{className:"coll-entry-title",children:$.title||$.entry_uid}),s.jsx("span",{className:"coll-entry-kind muted",children:$.source_kind})]}),s.jsxs("div",{className:"coll-entry-actions",children:[s.jsx("select",{className:"coll-entry-vis-select",value:$.collection_visibility_bits,onChange:Z=>Ze($.entry_uid,Number(Z.target.value)),children:Fr.map(Z=>s.jsx("option",{value:Z.value,children:Z.label},Z.value))}),!Ne&&s.jsx("button",{className:"coll-entry-remove",onClick:()=>st($.entry_uid),title:"Remove from collection",children:"×"})]})]},$.entry_uid))}))]}),!Ne&&s.jsxs("form",{className:"coll-add-entry-form",onSubmit:Ie,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:$=>Q($.target.value),placeholder:"entry_uid",required:!0}),s.jsx("select",{className:"coll-vis-select",value:ne,onChange:$=>q(Number($.target.value)),children:Fr.map($=>s.jsx("option",{value:$.value,children:$.label},$.value))}),s.jsx("button",{className:"coll-add-btn",type:"submit",disabled:fe,children:fe?"…":"Add"})]}),ve&&s.jsx("div",{className:"collections-error",style:{marginTop:4},children:ve})]})]}):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:te,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:$=>{_($.target.value),p||f($.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:$=>f($.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:h,onChange:$=>k(Number($.target.value)),children:Fr.map($=>s.jsx("option",{value:$.value,children:$.label},$.value))})]}),s.jsx("div",{className:"form-field",children:s.jsxs("label",{className:"form-label",children:[s.jsx("input",{type:"checkbox",checked:N,onChange:$=>v($.target.checked)})," Require authentication to view"]})}),b&&s.jsx("div",{className:"collections-error",children:b}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:E,children:E?"Creating…":"Create collection"})]})]})]}):s.jsx("div",{className:"view-placeholder",children:"Select an archive."})}const mg=4,gg=8;function yg({tab:e,onTabChange:t,archiveId:n}){const{currentUser:r,setCurrentUser:l}=c.useContext(Hs)??{},i=r&&(r.role_bits&mg)!==0,a=!!r&&(r.role_bits&gg)!==0,o=["profile","tokens",...i?["instance","cookies","extensions","storage"]:[]],u={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:o.map(d=>s.jsx("button",{className:`view-tab${e===d?" is-active":""}`,onClick:()=>t(d),children:u[d]},d))}),e==="profile"&&s.jsx(vg,{currentUser:r,setCurrentUser:l}),e==="tokens"&&s.jsx(xg,{}),e==="instance"&&i&&s.jsx(wg,{isOwner:a,setCurrentUser:l}),e==="cookies"&&i&&s.jsx(jg,{}),e==="extensions"&&i&&s.jsx(Sg,{}),e==="storage"&&i&&s.jsx(kg,{archiveId:n})]})}function vg({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(""),[m,x]=c.useState(""),[w,S]=c.useState(!1),[_,p]=c.useState(null);async function f(k){k.preventDefault(),i(!0),o(null);try{await vm(n),t(E=>({...E,display_name:n||null})),o({ok:!0,text:"Saved."})}catch(E){o({ok:!1,text:E.message})}finally{i(!1)}}async function h(k){if(k.preventDefault(),y!==m){p({ok:!1,text:"Passwords do not match."});return}S(!0),p(null);try{await wm(u,y),d(""),g(""),x(""),p({ok:!0,text:"Password changed."})}catch(E){p({ok:!1,text:E.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 E=k.target.checked;try{await xm({humanize_slugs:E}),t(P=>({...P,humanize_slugs:E}))}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:h,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:m,onChange:k=>x(k.target.value),required:!0})]}),_&&s.jsx("div",{className:`form-msg form-msg--${_.ok?"ok":"err"}`,children:_.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:w,children:w?"Changing…":"Change Password"})]})]})]})}function xg(){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),m=c.useCallback(async()=>{r(!0),i(null);try{t(await km())}catch(S){i(S.message)}finally{r(!1)}},[]);c.useEffect(()=>{m()},[m]);async function x(S){if(S.preventDefault(),!!a.trim()){d(!0);try{const _=await jm(a.trim());g(_),o(""),m()}catch(_){i(_.message)}finally{d(!1)}}}async function w(S){try{await Sm(S),t(_=>_.filter(p=>p.token_uid!==S))}catch(_){i(_.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:x,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:()=>w(S.token_uid),children:"Revoke"})]},S.token_uid))]})]})})}function wg({isOwner:e,setCurrentUser:t}){const[n,r]=c.useState(null),[l,i]=c.useState(!0),[a,o]=c.useState(null),[u,d]=c.useState(!1),[y,g]=c.useState(null),[m,x]=c.useState([]),[w,S]=c.useState(12),[_,p]=c.useState(!1),[f,h]=c.useState(null);c.useEffect(()=>{(async()=>{try{const[N,v]=await Promise.all([xo(),df()]);r(N),x(v.filter(b=>b.bit_position>0)),S(N.reorder_children_role_bits??12)}catch(N){o(N.message)}finally{i(!1)}})()},[]);function k(N,v){S(b=>v?(b|N)>>>0:(b&~N)>>>0)}async function E(N){N.preventDefault(),p(!0),h(null);try{await Jr({reorder_children_role_bits:w}),r(b=>({...b,reorder_children_role_bits:w}));const v=await cf();v&&(t==null||t(v)),h({ok:!0,text:"Saved."})}catch(v){h({ok:!1,text:v.message})}finally{p(!1)}}async function P(N){N.preventDefault(),d(!0),g(null);try{const{reorder_children_role_bits:v,...b}=n;await Jr(b),g({ok:!0,text:"Saved."})}catch(v){g({ok:!1,text:v.message})}finally{d(!1)}}return l?s.jsx("div",{className:"muted",children:"Loading…"}):a?s.jsx("div",{className:"form-msg form-msg--err",children:a}):n?s.jsxs("div",{style:{maxWidth:440},children:[s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Instance Settings"}),s.jsxs("form",{onSubmit:P,children:[[["public_index_enabled","Public index (unauthenticated browsing)"],["public_entry_content_enabled","Public entry content"],["open_registration_enabled","Open registration"]].map(([N,v])=>s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",checked:!!n[N],onChange:b=>r(L=>({...L,[N]:b.target.checked}))}),v]},N)),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:n.default_entry_visibility,onChange:N=>r(v=>({...v,default_entry_visibility:Number(N.target.value)})),children:[s.jsx("option",{value:0,children:"Private"}),s.jsx("option",{value:2,children:"Unlisted"}),s.jsx("option",{value:3,children:"Public"})]})]}),y&&s.jsx("div",{className:`form-msg form-msg--${y.ok?"ok":"err"}`,children:y.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:u,children:u?"Saving…":"Save Settings"})]})]}),s.jsxs("div",{className:"form-section",children:[s.jsx("h2",{children:"Permissions"}),s.jsxs("form",{onSubmit:E,children:[s.jsx("label",{className:"form-label",children:"Reorder child entries"}),m.map(N=>{const v=1<>>0;return s.jsxs("label",{className:"checkbox-row",children:[s.jsx("input",{type:"checkbox",disabled:!e||_,checked:(w&v)!==0,onChange:b=>k(v,b.target.checked)}),N.name,!N.is_builtin&&s.jsx("span",{className:"muted",children:" (custom)"})]},N.role_uid)}),s.jsx("p",{className:"form-hint",children:"Roles are cumulative: every signed-in account also has User, and owners also have Admin. Checking User lets every signed-in account reorder."}),!e&&s.jsx("p",{className:"form-hint",children:"Only the owner can change this."}),f&&s.jsx("div",{className:`form-msg form-msg--${f.ok?"ok":"err"}`,children:f.text}),e&&s.jsx("button",{className:"btn-primary",type:"submit",disabled:_,children:_?"Saving…":"Save Permissions"})]})]})]}):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 kg({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 x=await zm(e);l(x),n("scanned")}catch(x){u(x.message),n("error")}}async function g(){n("deleting"),u(null);try{const x=await Im(e);a(x),n("done")}catch(x){u(x.message),n("error")}}const m=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&&m&&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&&!m&&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 jg(){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("{}"),[m,x]=c.useState(null),[w,S]=c.useState(!1),[_,p]=c.useState({});c.useEffect(()=>{f()},[]);async function f(){r(!0),i(null);try{t(await Om())}catch(v){i(v.message)}finally{r(!1)}}async function h(v){v.preventDefault();try{JSON.parse(y)}catch{x({ok:!1,text:'cookies must be valid JSON, e.g. {"session": "abc"}'});return}S(!0),x(null);try{await Am(a==="global"?null:u.trim(),a,y),d(""),g("{}"),o("global"),x({ok:!0,text:"Rule added."}),await f()}catch(b){x({ok:!1,text:b.message})}finally{S(!1)}}async function k(v){try{await Fm(v),await f()}catch(b){i(b.message)}}function E(v){p(b=>({...b,[v.rule_uid]:{cookiesInput:v.cookies_json,saving:!1,msg:null}}))}function P(v){p(b=>{const L={...b};return delete L[v],L})}async function N(v){const b=_[v.rule_uid];try{JSON.parse(b.cookiesInput)}catch{p(L=>({...L,[v.rule_uid]:{...L[v.rule_uid],msg:{ok:!1,text:"Invalid JSON"}}}));return}p(L=>({...L,[v.rule_uid]:{...L[v.rule_uid],saving:!0,msg:null}}));try{await Mm(v.rule_uid,{cookies_json:b.cookiesInput}),P(v.rule_uid),await f()}catch(L){p(X=>({...X,[v.rule_uid]:{...X[v.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(v=>{const b=_[v.rule_uid],L=v.url_pattern?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"muted",children:[v.pattern_kind,":"]})," ",s.jsx("code",{children:v.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:b?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:12,width:"100%",minHeight:60},value:b.cookiesInput,onChange:X=>p(Q=>({...Q,[v.rule_uid]:{...Q[v.rule_uid],cookiesInput:X.target.value}}))}),b.msg&&s.jsx("div",{className:`form-msg form-msg--${b.msg.ok?"ok":"err"}`,children:b.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:b.saving,onClick:()=>N(v),children:b.saving?"Saving…":"Save"}),s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>P(v.rule_uid),children:"Cancel"})]})]}):s.jsx("code",{style:{fontSize:12,wordBreak:"break-all"},children:v.cookies_json})}),s.jsx("td",{children:!b&&s.jsxs("div",{style:{display:"flex",gap:6},children:[s.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>E(v),children:"Edit"}),s.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"2px 8px"},onClick:()=>k(v.rule_uid),children:"Del"})]})})]},v.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:h,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:v=>o(v.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:v=>d(v.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:v=>g(v.target.value),placeholder:'{"SESSION": "abc123", "token": "xyz"}',required:!0})]}),m&&s.jsx("div",{className:`form-msg form-msg--${m.ok?"ok":"err"}`,children:m.text}),s.jsx("button",{className:"btn-primary",type:"submit",disabled:w,children:w?"Adding…":"Add Rule"})]})]})})}function Sg(){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(_){o({ok:!1,text:_.message})}finally{r(!1)}})()},[]);async function u(_){i(!0),o(null);try{await Jr({ublock_enabled:_}),t(p=>({...p,ublock_enabled:_})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function d(_){i(!0),o(null);try{await Jr({cookie_ext_enabled:_}),t(p=>({...p,cookie_ext_enabled:_})),o({ok:!0,text:"Saved."})}catch(p){o({ok:!1,text:p.message})}finally{i(!1)}}async function y(_){i(!0),o(null);try{await Jr({modal_closer_enabled:_}),t(p=>({...p,modal_closer_enabled:_})),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,m=(e==null?void 0:e.ublock_enabled)??!0,x=(e==null?void 0:e.cookie_ext_available)??!1,w=(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":m,className:`ext-toggle${m?" ext-toggle--on":""}`,onClick:()=>u(!m),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."}),!x&&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":w,className:`ext-toggle${w?" ext-toggle--on":""}`,onClick:()=>d(!w),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 Bu={0:"Private",1:"Public",2:"Users only",3:"Public"},es=[{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"}],_g=Object.fromEntries(es.map(e=>[e.value,e.label])),Uu="archivr:summary:provider",Ng=1500,yf="This entry can’t be summarized yet.",vf="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.",Hu=`${yf} - -${vf}`;function Cg(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 Eg=()=>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 bg({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:m,onOpenPreview:x,onPlay:w,isPublicSession:S}){var Ee,We,je;const[_,p]=c.useState([]),[f,h]=c.useState(""),[k,E]=c.useState([]),[P,N]=c.useState(""),v=c.useRef(0),b=c.useRef(!1),[L,X]=c.useState(!1),[Q,ne]=c.useState(""),[q,fe]=c.useState("idle"),[Le,ve]=c.useState(""),I=c.useRef(null),[R,K]=c.useState(!1);c.useEffect(()=>{K(!1)},[(Ee=l==null?void 0:l.summary)==null?void 0:Ee.entry_uid]);const[ee,se]=c.useState(null),[ie,Y]=c.useState(null),[Ne,pe]=c.useState(""),[U,te]=c.useState(!1),[re,Ue]=c.useState(()=>{try{return sessionStorage.getItem(Uu)||es[0].value}catch{return es[0].value}}),[Lt,yt]=c.useState(!1),Ie=c.useRef(null),st=c.useRef(null),Ze=c.useRef(null),$=c.useRef(null),Z=e&&(t!=null&&t.entry_uid)?`${e}:${t.entry_uid}`:null;$.current=Z;const Ae=(n==null?void 0:n.size)>=2,[Me,Rt]=c.useState(""),[zt,It]=c.useState("idle"),[et,Xt]=c.useState(""),[$t,an]=c.useState([]),[He,j]=c.useState(""),[B,A]=c.useState("idle"),[D,F]=c.useState(""),[H,ke]=c.useState("idle"),[he,Re]=c.useState(""),[ye,Fe]=c.useState("idle"),[ce,it]=c.useState("");c.useEffect(()=>{const T=++v.current;if(I.current&&(clearInterval(I.current),I.current=null),fe("idle"),ve(""),!t||!e){p([]),E([]);return}if(S){p([]),E([]);return}X(!1),ne(""),b.current=!1,p([]),Promise.all([Fl(e,t.entry_uid),Ou(e,t.entry_uid)]).then(([J,ae])=>{T===v.current&&(p(J),E(ae))}).catch(()=>{})},[t,e,S]),c.useEffect(()=>()=>{clearInterval(I.current)},[]),c.useLayoutEffect(()=>{var J,ae,me;clearInterval(Ie.current),Ie.current=null,(J=st.current)==null||J.abort(),st.current=null,(ae=Ze.current)==null||ae.abort(),Ze.current=null;const T=(t==null?void 0:t.entry_uid)!=null&&((me=l==null?void 0:l.summary)==null?void 0:me.entry_uid)===(t==null?void 0:t.entry_uid);se(T?l.latest_summary??null:null),Y(T?l.summary_attempt??null:null),pe(""),te(!1),yt(!1)},[e,t==null?void 0:t.entry_uid,(We=l==null?void 0:l.summary)==null?void 0:We.entry_uid]);const dt=ie==null?void 0:ie.status;c.useEffect(()=>{var on;if(clearInterval(Ie.current),Ie.current=null,dt!=="pending"&&dt!=="running"||!e||!((on=l==null?void 0:l.summary)!=null&&on.entry_uid))return;const T=l.summary.entry_uid,J=`${e}:${T}`;if(Z!==J)return;const ae=new AbortController;st.current=ae;const $e=setInterval(async()=>{var xe;try{const un=await Yh(e,T,{signal:ae.signal});if(ae.signal.aborted||$.current!==J)return;se(un.summary??null),Y(un.attempt??null);const Ys=(xe=un.attempt)==null?void 0:xe.status;Ys!=="pending"&&Ys!=="running"&&(clearInterval($e),Ie.current===$e&&(Ie.current=null),te(!1),Ys==="completed"&&$.current===J&&(m==null||m()))}catch{if(ae.signal.aborted||$.current!==J)return}},Ng);return Ie.current=$e,()=>{clearInterval($e),Ie.current===$e&&(Ie.current=null),ae.abort(),st.current===ae&&(st.current=null)}},[dt,e,t==null?void 0:t.entry_uid,(je=l==null?void 0:l.summary)==null?void 0:je.entry_uid,Z]),c.useEffect(()=>()=>{var T,J;clearInterval(Ie.current),(T=st.current)==null||T.abort(),(J=Ze.current)==null||J.abort()},[]);async function Nr(T=!1){var $e,on;if(!e||!(($e=l==null?void 0:l.summary)!=null&&$e.entry_uid)||U)return;const J=l.summary.entry_uid,ae=`${e}:${J}`;if($.current!==ae)return;const me=new AbortController;(on=Ze.current)==null||on.abort(),Ze.current=me,te(!0),pe("");try{const xe=await Zh(e,J,{provider:re,force:T,includeImages:Lt,signal:me.signal});if(me.signal.aborted||$.current!==ae)return;xe.status==="completed"?(se(xe),Y(null),te(!1),$.current===ae&&(m==null||m())):Y({...xe??{},status:"pending"})}catch(xe){if(me.signal.aborted||$.current!==ae)return;pe(xe.message||"Summary request failed"),te(!1)}finally{Ze.current===me&&(Ze.current=null)}}function Ws(T){Ue(T),T==="claude_cli"&&yt(!1);try{sessionStorage.setItem(Uu,T)}catch{}}c.useEffect(()=>{if(!e){an([]);return}wo(e).then(an).catch(()=>an([]))},[e]),c.useEffect(()=>{Rt(""),It("idle"),Xt(""),j(""),A("idle"),F(""),ke("idle"),Re(""),Fe("idle"),it("")},[n]);async function Vs(){const T=n.size;if(!window.confirm(`Delete ${T} entr${T===1?"y":"ies"}? This cannot be undone.`))return;ke("running");const J=new Set;for(const ae of n)try{await Du(e,ae),J.add(ae)}catch{}ke("idle"),y==null||y(J)}async function kl(){const T=Me.trim();if(T){It("running"),Xt("");try{for(const J of n)await $u(e,J,T);Rt(""),It("done"),o==null||o(),setTimeout(()=>It("idle"),1800)}catch(J){Xt(J.message),It("error")}}}async function Ks(){if(!He)return;A("running"),F("");const T=[],J=$t.find(ae=>ae.collection_uid===He);for(const ae of n)try{await Sa(e,He,ae,(J==null?void 0:J.default_visibility_bits)??2)}catch{T.push(ae)}T.length>0?(F(`Failed for ${T.length} entr${T.length===1?"y":"ies"}.`),A("error")):(A("done"),setTimeout(()=>A("idle"),1800))}async function Qs(){if(!he||!t)return;Fe("running"),it("");const T=$t.find(J=>J.collection_uid===he);try{await Sa(e,he,t.entry_uid,(T==null?void 0:T.default_visibility_bits)??2),Fe("done"),Re("");const J=await Ou(e,t.entry_uid);E(J),setTimeout(()=>Fe("idle"),1800)}catch(J){it(J.message),Fe("error")}}async function Kn(){const T=Q.trim()||null;try{await lm(e,t.entry_uid,T),u==null||u(t.entry_uid,T)}catch{}finally{X(!1)}}async function Qn(){const T=f.trim();if(!(!T||!t))try{await $u(e,t.entry_uid,T),h(""),N("");const J=await Fl(e,t.entry_uid);p(J),o()}catch(J){N(J.message)}}async function Pn(T){try{await sm(e,t.entry_uid,T);const J=await Fl(e,t.entry_uid);p(J),o()}catch{}}async function jl(){if(!(!t||!e)&&window.confirm("Delete this entry? This cannot be undone."))try{await Du(e,t.entry_uid),d==null||d(t.entry_uid)}catch{}}async function qs(){if(!t||!e||q==="running")return;const T=v.current,J=t.entry_uid;fe("running"),ve("");try{const{job_uid:ae}=await $m(e,J);if(v.current!==T)return;I.current=setInterval(async()=>{try{const me=await uf(e,ae);if(me.status==="completed"){if(clearInterval(I.current),I.current=null,v.current!==T)return;fe("done");const $e=await Fl(e,J);if(v.current!==T)return;p($e),m==null||m()}else if(me.status==="failed"){if(clearInterval(I.current),I.current=null,v.current!==T)return;fe("error"),ve(me.error_text||"Re-archive failed.")}}catch{if(clearInterval(I.current),I.current=null,v.current!==T)return;fe("error"),ve("Network error while polling.")}},500)}catch(ae){if(v.current!==T)return;fe("error"),ve(ae.message||"Failed to start re-archive.")}}const Xs=l?[["Added",ko(l.summary.archived_at)],["Source",l.summary.source_kind],["Type",l.summary.entity_kind],["Visibility",Bu[l.summary.visibility]??l.summary.visibility],["Root",l.structured_root_relpath]]:[],Js=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),Gs=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv","pdf","html","htm","md","markdown","txt","jpg","jpeg","png","gif","webp","avif","svg","bmp"]),C=l?l.artifacts.findIndex(T=>T.artifact_role==="primary_media"):-1,z=C>=0?l.artifacts[C]:null,M=z?z.relpath.split(".").pop().toLowerCase():"",W=z&&Js.has(M),G=C>=0&&t?`/api/archives/${e}/entries/${t.entry_uid}/artifacts/${C}`:null,ue=l&&!W&&(l.summary.entity_kind==="tweet"||l.summary.entity_kind==="tweet_thread"||z&&Gs.has(M));return s.jsxs("aside",{className:"context-rail",children:[s.jsx("div",{className:"rail-eyebrow",children:"Context"}),Ae?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"}),et&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:et}),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:Me,onChange:T=>Rt(T.target.value),onKeyDown:T=>{T.key==="Enter"&&kl()}}),s.jsx("button",{className:"tag-add-btn",onClick:kl,disabled:zt==="running"||!Me.trim(),children:zt==="running"?"…":zt==="done"?"✓":"Add"})]})]}),$t.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:He,onChange:T=>j(T.target.value),children:[s.jsx("option",{value:"",children:"Pick a collection…"}),$t.filter(T=>T.slug!=="_default_").map(T=>s.jsx("option",{value:T.collection_uid,children:T.name},T.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:Ks,disabled:!He||B==="running",children:B==="running"?"…":B==="done"?"✓":B==="error"?"!":"Add"})]}),D&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"6px 0 0"},children:D})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:Vs,disabled:H==="running",children:H==="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:xt(l.summary.title)||xt(l.summary.entry_uid)}):L?s.jsx("input",{className:"rail-title-input",autoFocus:!0,value:Q,onChange:T=>ne(T.target.value),onKeyDown:T=>{T.key==="Enter"&&T.currentTarget.blur(),T.key==="Escape"&&(b.current=!0,T.currentTarget.blur())},onBlur:()=>{b.current?X(!1):Kn(),b.current=!1}}):s.jsxs("h2",{className:"rail-title rail-title--editable",title:"Click to rename",onClick:()=>{ne(l.summary.title??""),X(!0)},children:[xt(l.summary.title)||xt(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:Us(l.summary.source_kind)}}),s.jsx("span",{className:"u-text",children:l.summary.original_url}),s.jsx("span",{className:"ext",children:s.jsx(Eg,{})})]}),W&&w&&s.jsx("button",{className:"rail-preview-btn",onClick:()=>w(G,t),children:"▶ Play"}),ue&&x&&s.jsx("button",{className:"rail-preview-btn",onClick:x,children:"Preview"}),(()=>{const T=(ee==null?void 0:ee.status)==="completed"?Cg(ee.summary_text):null,J=(ie==null?void 0:ie.status)==="pending"||(ie==null?void 0:ie.status)==="running",ae=(ie==null?void 0:ie.status)==="failed"&&ie.error_text===Hu||Ne===Hu;return S&&!T?null:s.jsxs("div",{className:"rail-section rail-summary",children:[s.jsx("div",{className:"rail-section-heading",children:"Summary"}),T&&s.jsxs("div",{className:"rail-summary-body",children:[T.tldr&&s.jsx("p",{className:"rail-summary-tldr",children:T.tldr}),T.summary&&s.jsx("p",{className:"rail-summary-text",children:T.summary}),T.tags.length>0&&s.jsx("div",{className:"rail-summary-tags",children:T.tags.map(me=>s.jsx("span",{className:"rail-summary-tag",children:me},me))}),s.jsxs("p",{className:"rail-summary-provider",children:[_g[ee.provider_kind]||ee.provider_kind,ee.resolved_model||ee.provider_model?` · ${ee.resolved_model||ee.provider_model}`:""]})]}),J&&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:yf}),s.jsx("p",{className:"rail-summary-info__detail",children:vf})]}),(ie==null?void 0:ie.status)==="failed"&&ie.error_text&&!ae&&!S&&s.jsx("p",{className:"form-msg form-msg--err rail-summary-error",children:ie.error_text}),Ne&&!ae&&s.jsx("p",{className:"form-msg form-msg--err rail-summary-error",children:Ne}),!S&&!J&&s.jsxs("div",{className:"rail-summary-controls",children:[s.jsx("select",{className:"rail-summary-select",value:re,onChange:me=>Ws(me.target.value),"aria-label":"Summary provider",children:es.map(me=>s.jsx("option",{value:me.value,children:me.label},me.value))}),s.jsxs("div",{className:`rail-summary-image-option${re==="claude_cli"?" rail-summary-image-option--disabled":""}`,children:[s.jsxs("label",{className:"rail-summary-image-option__label",children:[s.jsx("input",{type:"checkbox",checked:Lt,disabled:re==="claude_cli",onChange:me=>yt(me.target.checked)}),"Include attached images"]}),s.jsx("p",{className:"rail-summary-image-option__note",children:re==="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:()=>Nr(!!T),disabled:U,children:U?"…":T?"Regenerate":"Generate"})]})]})})(),s.jsx("div",{className:"meta-list",children:Xs.filter(([,T])=>T!=null&&T!=="").map(([T,J])=>s.jsxs("div",{className:"meta-item",children:[s.jsx("span",{className:"meta-k",children:T}),s.jsx("span",{className:`meta-v${T==="Root"?" mono":""}`,children:xt(J)})]},T))}),l.artifacts.length>0&&(()=>{const T=l.artifacts.map((xe,un)=>({...xe,_idx:un})),J=T.filter(xe=>xe.artifact_role==="font"),ae=T.filter(xe=>xe.artifact_role!=="font"),me=J.reduce((xe,un)=>xe+(un.byte_size||0),0),$e=l.summary.entry_uid,on=xe=>s.jsx("li",{children:s.jsxs("a",{href:`/api/archives/${e}/entries/${$e}/artifacts/${xe._idx}`,target:"_blank",rel:"noopener noreferrer",className:"artifact-link",children:[s.jsx("span",{className:"artifact-name",children:xe.artifact_role==="font"?xe.relpath.split("/").pop():xe.artifact_role.replace(/_/g," ")}),s.jsx("span",{className:"artifact-size",children:xe.byte_size!=null?ml(xe.byte_size):"—"})]})},xe._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(on),J.length>0&&s.jsxs("li",{className:"artifact-group",children:[s.jsxs("button",{type:"button",className:"artifact-group-header artifact-link","aria-expanded":R,onClick:()=>K(xe=>!xe),children:[s.jsxs("span",{className:"artifact-name",children:[s.jsx("span",{"aria-hidden":"true",className:`artifact-group-chevron${R?" open":""}`,children:"›"}),` fonts (${J.length})`]}),s.jsx("span",{className:"artifact-size",children:ml(me)})]}),R&&s.jsx("ul",{className:"artifact-list artifact-group-body",children:J.map(on)})]})]})]})})()]}):s.jsx("p",{className:"tags-empty",children:"Loading\\u2026"}):s.jsx("p",{className:"tags-empty",children:"Select an entry."}),t&&!Ae&&!S&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Tags"}),_.length===0?s.jsx("p",{className:"tags-empty",children:"No tags yet."}):s.jsx("div",{className:"tags-wrap",children:_.map(T=>s.jsxs("span",{className:"tag-pill",title:T.full_path,children:[g?pf(T.full_path):T.full_path,s.jsx("button",{className:"remove",title:`Remove tag ${T.full_path}`,onClick:()=>Pn(T.tag_uid),children:"×"})]},T.tag_uid))}),P&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:P}),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:T=>h(T.target.value),onKeyDown:T=>{T.key==="Enter"&&Qn()}}),s.jsx("button",{className:"tag-add-btn",onClick:Qn,children:"Add"})]})]}),(k.length>0||$t.filter(T=>T.slug!=="_default_").length>0)&&s.jsxs("div",{className:"rail-section",children:[s.jsx("div",{className:"rail-section-heading",children:"Collections"}),k.map(T=>s.jsxs("div",{className:"coll-row",children:[s.jsx("span",{className:"coll-name",children:T.name}),s.jsx("span",{className:"vis-badge",children:Bu[T.visibility_bits]??`bits:${T.visibility_bits}`})]},T.collection_uid)),$t.filter(T=>T.slug!=="_default_").length>0&&s.jsxs("div",{className:"bulk-coll-row",style:{marginTop:8},children:[s.jsxs("select",{className:"bulk-coll-select",value:he,onChange:T=>Re(T.target.value),children:[s.jsx("option",{value:"",children:"Add to collection…"}),$t.filter(T=>T.slug!=="_default_").map(T=>s.jsx("option",{value:T.collection_uid,children:T.name},T.collection_uid))]}),s.jsx("button",{className:"tag-add-btn",onClick:Qs,disabled:!he||ye==="running",children:ye==="running"?"…":ye==="done"?"✓":ye==="error"?"!":"Add"})]}),ce&&s.jsx("p",{className:"form-msg form-msg--err",style:{margin:"4px 0 0"},children:ce})]}),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:qs,disabled:q==="running",children:q==="running"?"Re-archiving…":"Re-archive"}),q==="done"&&s.jsx("p",{className:"form-msg form-msg--ok",style:{marginTop:"6px"},children:"Re-archived successfully."}),q==="error"&&s.jsx("p",{className:"form-msg form-msg--err",style:{marginTop:"6px"},children:Le})]}),s.jsx("div",{className:"rail-delete-zone",children:s.jsx("button",{className:"rail-delete-btn",onClick:jl,children:"Delete entry"})})]})]})}const Tg=/\/api\/archives\/([^/]+)\/entries\/([^/]+)\/artifacts\/(\d+)/;function Pg(){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 Lg({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(Tg);if(!g){l(e);return}let m=!1;return l(null),Dm(g[1],g[2],parseInt(g[3],10)).then(({url:x})=>{m||l(x)}).catch(()=>{m||l(e)}),()=>{m=!0}},[e]),c.useEffect(()=>{n.current&&n.current.load()},[r]),c.useEffect(()=>{u(typeof HTMLVideoElement<"u"&&"webkitShowPlaybackTargetPicker"in HTMLVideoElement.prototype)},[]),c.useEffect(()=>{var m;const g=x=>{if(x)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((m=window.cast)!=null&&m.framework)g(!0);else if(window.__onGCastApiAvailable=g,!document.querySelector('script[src*="cast_sender"]')){const x=document.createElement("script");x.src="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1",document.head.appendChild(x)}},[]),c.useEffect(()=>{if(!i||!r)return;const g=cast.framework.CastContext.getInstance(),{CastContextEventType:m,SessionState:x}=cast.framework,w=_=>{if(!_)return;const p=new chrome.cast.media.MediaInfo(window.location.origin+r,t);_.loadMedia(new chrome.cast.media.LoadRequest(p)).catch(()=>{})};w(g.getCurrentSession());const S=_=>{(_.sessionState===x.SESSION_STARTED||_.sessionState===x.SESSION_RESUMED)&&w(g.getCurrentSession())};return g.addEventListener(m.SESSION_STATE_CHANGED,S),()=>g.removeEventListener(m.SESSION_STATE_CHANGED,S)},[i,r,t]);const d=()=>{var g,m;(m=(g=n.current)==null?void 0:g.webkitShowPlaybackTargetPicker)==null||m.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(Pg,{})}),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 Wu({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 Rg({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 xf(e){return e?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(new Date(e*1e3)):""}function Vu(e){return!e||!e.includes("&")?e:e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'")}const le={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"}},Ve={bg:"#000000",border:"#2f3336",text:"#e7e9ea",dim:"#71767b",accent:"#1d9bf0",codeBg:"#16181c"},Ti={article:{background:Ve.bg,color:Ve.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:Ve.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:Ve.border,flexShrink:0},aAuthorName:{fontSize:"15px",fontWeight:"700",color:Ve.text,lineHeight:"1.3"},aAuthorSub:{fontSize:"15px",color:Ve.dim,lineHeight:"1.3"},aDivider:{border:"none",borderTop:`1px solid ${Ve.border}`,margin:"0"},aBody:{padding:"4px 16px 0"},bH1:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:Ve.text,lineHeight:"36px",margin:"24px 0 10px"},bH2:{fontSize:"26px",fontWeight:"800",letterSpacing:"-0.4px",color:Ve.text,lineHeight:"36px",margin:"24px 0 10px"},bP:{fontSize:"17px",color:Ve.text,lineHeight:"1.5",marginBottom:"16px",marginTop:"0"},bSpacer:{height:"6px",display:"block"},bQuote:{borderLeft:`3px solid ${Ve.border}`,padding:"2px 14px",margin:"14px 0",color:Ve.dim,fontSize:"17px",lineHeight:"1.5"},bHr:{border:"none",borderTop:`1px solid ${Ve.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:Ve.text,lineHeight:"1.5",marginBottom:"6px"},bTweet:{display:"flex",alignItems:"center",gap:"12px",border:`1px solid ${Ve.border}`,borderRadius:"12px",padding:"14px 16px",margin:"14px 0",color:Ve.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:Ve.text,background:"transparent"},iCode:{fontFamily:"ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace",fontSize:"0.875em",background:Ve.codeBg,padding:"2px 6px",borderRadius:"4px",color:"#e6edf3"},link:{color:Ve.accent,textDecoration:"none"}};function zg(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 wf(){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 kf(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 jf(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 Ku=/https?:\/\/[^\s<>"'\])]+/g,Ig=/[.,;:!?)()]+$/;function Ns(e,t){const n=[];let r=0,l;for(Ku.lastIndex=0;(l=Ku.exec(e))!==null;){l.index>r&&n.push(e.slice(r,l.index));let i=l[0].replace(Ig,"");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:(rkf(o,e)).filter(Boolean),...(t.user_mentions||[]).map(o=>jf(o,e)).filter(Boolean)];if(r.length===0&&n.length===0)return Ns(Vu(e),le.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(w=>w.s<=o&&w.e>=d),m=g.find(w=>w.kind==="url");if(m)return s.jsx("a",{href:m.href,target:"_blank",rel:"noopener noreferrer",style:le.link,children:m.display||y},u);const x=g.find(w=>w.kind==="mention");return x?s.jsx("a",{href:`https://x.com/${x.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:le.link,children:y},u):s.jsx("span",{children:Ns(Vu(y),le.link)},u)}).filter(o=>o!==null)}function Dg(e,t,n,r,l=le){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=kf(u,e);d&&i.push(d)}for(const u of r){const d=jf(u,e);d&&i.push(d)}if(i.length===0)return Ns(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(_=>_.s<=u&&_.e>=y),m=e.slice(u,y);let x;if(m.includes(` -`)){const _=m.split(` -`);x=_.flatMap((p,f)=>f<_.length-1?[p,s.jsx("br",{},f)]:[p])}else x=m;g.some(_=>_.kind==="style"&&_.style==="Code")&&(x=s.jsx("code",{style:l.iCode,children:x})),g.some(_=>_.kind==="style"&&_.style==="Bold")&&(x=s.jsx("strong",{children:x})),g.some(_=>_.kind==="style"&&_.style==="Italic")&&(x=s.jsx("em",{children:x})),g.some(_=>_.kind==="style"&&_.style==="Underline")&&(x=s.jsx("u",{children:x})),g.some(_=>_.kind==="style"&&_.style==="Strikethrough")&&(x=s.jsx("s",{children:x}));const w=g.find(_=>_.kind==="url");if(w){const _=/^https?:\/\/t\.co\//i.test(x);x=s.jsx("a",{href:w.href,target:"_blank",rel:"noopener noreferrer",style:l.link,children:_?w.display:x})}const S=g.find(_=>_.kind==="mention");return S&&(x=s.jsx("a",{href:`https://x.com/${S.screen_name}`,target:"_blank",rel:"noopener noreferrer",style:l.link,children:x})),s.jsx("span",{children:typeof x=="string"?Ns(x,l.link):x},d)})}function Og(e,t,n){const r=(n==null?void 0:n.st)||le,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(wf,{}),"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)||le,i=e.type||"",a=e.text||"",o=e.inline_style_ranges||[],u=e.data||{},d=Dg(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(wf,{}),"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:Og(e,n,r)},t);default:return a?s.jsx("p",{style:l.bP,children:d},t):null}}function Ag(e,t,n){const r=(n==null?void 0:n.st)||le,l=[];let i=0;for(;i{r&&(l==null||l(!0))},[r,l]);const o=r?Ti:le,u=e.cover_media||{},d=e.author||t||{},y=e.first_published_at_secs?xf(e.first_published_at_secs):"",m=[d.screen_name?`@${d.screen_name}`:"",y].filter(Boolean).join(" · "),x=hr(u.local_path,u.url,n),w=hr(d.avatar_local_path,d.avatar_url,n),S=s.jsxs(s.Fragment,{children:[i&&s.jsx(Sf,{items:[{src:i,alt:""}],startIndex:0,onClose:()=>a(null)}),x&&s.jsx("a",{href:x,target:"_blank",rel:"noopener noreferrer",style:{display:"block",cursor:"zoom-in"},onClick:_=>{!_.metaKey&&!_.ctrlKey&&(_.preventDefault(),a(x))},children:s.jsx("img",{src:x,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:[w?s.jsx("img",{src:w,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"}),m&&s.jsx("div",{style:o.aAuthorSub,children:m})]})]})]}),s.jsx("hr",{style:o.aDivider}),s.jsx("div",{style:o.aBody,children:Ag(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:le.article,children:S})}function Fg({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:le.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]=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:le.lightboxBackdrop,onClick:n,children:s.jsxs("div",{style:le.lightboxContent,onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{style:le.lightboxToolbar,children:[e.length>1&&s.jsxs("span",{style:le.lightboxCounter,children:[r+1," / ",e.length]}),s.jsx("a",{href:i.src,target:"_blank",rel:"noopener noreferrer",style:le.lightboxLink,title:"Open in new tab",children:"↗"}),s.jsx("button",{style:le.lightboxBtn,onClick:n,"aria-label":"Close",children:"×"})]}),s.jsx("img",{src:i.src,alt:i.alt||"",style:le.lightboxImg}),e.length>1&&s.jsxs("div",{style:le.lightboxNav,children:[s.jsx("button",{style:le.lightboxNavBtn,onClick:()=>l(a=>Math.max(a-1,0)),disabled:r===0,children:"‹"}),s.jsx("button",{style:le.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,h;const[l,i]=c.useState(null),a=e.author||{},o=e.created_at_secs?xf(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,m=t?le.tweetRowThread:le.tweetRow,x=e.full_text||"",w=((h=(f=e.extended_entities)==null?void 0:f.media)!=null&&h.length?e.extended_entities.media:u.media)||[],S=[],_=[];for(const k of w)if(k.type==="photo"){const E=hr(k.local_path,k.media_url_https,r);E&&S.push({kind:"photo",src:E,alt:k.alt_text||""})}else if(k.type==="video"||k.type==="animated_gif"){const E=k.local_path&&r[k.local_path]||(()=>{var N,v;return(v=(((N=k.video_info)==null?void 0:N.variants)||[]).filter(b=>b.content_type==="video/mp4").sort((b,L)=>(L.bitrate||0)-(b.bitrate||0))[0])==null?void 0:v.url})();E&&_.push({kind:k.type==="animated_gif"?"gif":"video",src:E})}const p=[];for(const k of w){if(!k.url||!(k.type==="photo"?S.some(N=>N.src===hr(k.local_path,k.media_url_https,r)):_.length>0))continue;const P=jo(k,x,k.url);P&&p.push([P.s,P.e])}return s.jsxs(s.Fragment,{children:[l!==null&&s.jsx(Sf,{items:S,startIndex:l,onClose:()=>i(null)}),s.jsxs("div",{style:m,children:[s.jsxs("div",{style:le.leftCol,children:[d?s.jsx("img",{src:d,style:le.avatar,alt:a.name||""}):s.jsx("div",{style:le.avatarPh}),y&&s.jsx("div",{style:le.threadLine})]}),s.jsxs("div",{style:le.rightCol,children:[s.jsxs("div",{style:le.authorRow,children:[s.jsx("span",{style:le.authorName,children:a.name||a.screen_name||"Unknown"}),a.screen_name&&s.jsxs("span",{style:le.authorHandle,children:["@",a.screen_name]}),o&&s.jsxs("span",{style:le.datePart,children:["· ",o]}),g&&s.jsx("span",{style:le.qtBadge,title:"Quote tweet",children:"↻ QT"})]}),s.jsx("div",{style:le.tweetText,children:$g(x,u,p)}),S.length>0&&s.jsx("div",{style:le.mediaGrid,children:s.jsx(Fg,{photos:S,onOpen:k=>i(k)})}),_.map((k,E)=>s.jsx("div",{style:le.mediaGrid,children:s.jsx("video",{src:k.src,style:le.mediaVideo,controls:!0,loop:k.kind==="gif",muted:k.kind==="gif",autoPlay:k.kind==="gif"})},E)),(e.retweet_count>0||e.favorite_count>0)&&s.jsxs("div",{style:le.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 Bg({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 w=n.map((_,p)=>({..._,index:p})).filter(_=>_.artifact_role==="raw_tweet_json");if(w.length===0){d("No tweet data found."),o(!1);return}let S=!1;return nm(e,t,w.map(_=>_.index)).then(async _=>{if(S)return;const p=/https?:\/\/t\.co\/[A-Za-z0-9]+/g,f=N=>{var b;const v=N.full_text||"";return(((b=N.entities)==null?void 0:b.urls)||[]).map(L=>{var X;if(L.fromIndex!=null&&L.toIndex!=null)return[L.fromIndex,L.toIndex];if(((X=L.indices)==null?void 0:X.length)===2)return[L.indices[0],L.indices[1]];if(L.url){const Q=v.indexOf(L.url);if(Q!==-1)return[Q,Q+L.url.length]}return null}).filter(Boolean)},h=(N,v,b)=>N.some(([L,X])=>L<=v&&X>=b),k=new Set;for(const N of _){const v=N.full_text||"",b=f(N);let L;for(p.lastIndex=0;(L=p.exec(v))!==null;)h(b,L.index,L.index+L[0].length)||k.add(L[0])}const E=k.size>0?await rm([...k]).catch(()=>({})):{},P=_.map(N=>{var Q;const v=N.full_text||"",b=f(N),L=[];let X;for(p.lastIndex=0;(X=p.exec(v))!==null;){const ne=X[0],q=E[ne];q&&q!==ne&&!h(b,X.index,X.index+ne.length)&&L.push({url:ne,expanded_url:q,display_url:(()=>{try{const fe=new URL(q);return fe.hostname+(fe.pathname.length>1?"/…":"")}catch{return q}})(),fromIndex:X.index,toIndex:X.index+ne.length})}return L.length===0?N:{...N,entities:{...N.entities||{},urls:[...((Q=N.entities)==null?void 0:Q.urls)||[],...L]}}});S||g(P)}).catch(_=>{S||d(_.message||"Failed to load tweet.")}).finally(()=>{S||o(!1)}),()=>{S=!0}},[e,t,n]),a)return s.jsx("div",{style:le.loading,children:"Loading…"});if(u)return s.jsxs("div",{style:le.error,children:["Error: ",u]});if(y.length===0)return null;const m=zg(e,t,n);if(r==="tweet_thread")return s.jsx("div",{style:le.threadOuter,children:y.map((w,S)=>s.jsx(Qu,{tweet:w,isInThread:!0,isLast:S===y.length-1,artifactMap:m},w.id||S))});const x=y[0];return x.is_article&&x.article?s.jsx(Mg,{article:x.article,tweetAuthor:x.author,artifactMap:m,fullPage:l,onXArticle:i}):s.jsx("div",{style:le.card,children:s.jsx(Qu,{tweet:x,isInThread:!1,isLast:!0,artifactMap:m})})}function Ug({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),em(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 Hg=new Set(["mp4","webm","mov","mkv","avi","m4v","ogv"]),Wg=new Set(["mp3","ogg","m4a","opus","wav","flac","aac"]),Vg=new Set(["jpg","jpeg","png","gif","webp","avif","svg","bmp"]),Kg=new Set(["md","markdown","txt"]),Qg={mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo",m4v:"video/mp4",ogv:"video/ogg"};function _f({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 x=s.jsx(Bg,{archiveId:e,entryUid:o,artifacts:a,entityKind:u,fullPage:r,onXArticle:l});return r?x:s.jsx("div",{className:"preview-tweet-wrap",children:x})}const d=a.findIndex(x=>x.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((x,w)=>s.jsxs("li",{children:[x.artifact_role,": ",x.relpath]},w))})]});const y=a[d],g=`/api/archives/${e}/entries/${o}/artifacts/${d}`,m=y.relpath.split(".").pop().toLowerCase();return Hg.has(m)?s.jsx("div",{className:"preview-panel",children:s.jsx(Lg,{src:g,contentType:Qg[m]||"video/mp4"})}):Wg.has(m)?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"}})]}):m==="pdf"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(Wu,{src:g,type:"pdf",title:i.title,originalUrl:i.original_url})}):m==="html"||m==="htm"?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0},children:s.jsx(Wu,{src:g,type:"page",title:i.title,originalUrl:i.original_url})}):Kg.has(m)?s.jsx("div",{className:"preview-panel",style:{flex:1,minHeight:0,overflow:"auto"},children:s.jsx(Ug,{src:g,mime:y.mime_type,title:i.title})}):Vg.has(m)?s.jsx("div",{className:"preview-panel",style:{height:"100%"},children:s.jsx(Rg,{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((x,w)=>s.jsxs("li",{children:[x.artifact_role,": ",x.relpath]},w))})]})}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(_f,{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 Xg({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,m]=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 x(){const f=l.current;f&&(i?f.pause():f.play().catch(()=>{}))}function w(f){const h=l.current;if(!h||!isFinite(d))return;const k=Number(f.target.value);h.currentTime=k,u(k)}function S(f){m(Number(f.target.value))}const _=(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:Us(p)}}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"0.85rem",color:"var(--ink)"},title:_,children:_})]}),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:x,"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:w,"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 Jg({archiveId:e,entryUid:t}){var m,x;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 w=document.documentElement,S=document.body,_=w.style.colorScheme,p=S.style.background;return w.style.colorScheme="dark",S.style.background="#000",()=>{w.style.colorScheme=_,S.style.background=p}},[u]),c.useEffect(()=>{d(!1),Mr(e,t).then(w=>{r(w),i(!1)}).catch(w=>{o((w==null?void 0:w.message)||"Failed to load entry"),i(!1)})},[e,t]);const y=((m=n==null?void 0:n.summary)==null?void 0:m.title)||t,g=(x=n==null?void 0:n.summary)==null?void 0:x.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(_f,{archiveId:e,entry:n.summary,detail:n,fullPage:!0,onXArticle:d})]})]})}const Gg=7e3;function Yg({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(ey,{toast:r,onDismiss:t,onIgnoreUblock:n},r.id))}):null}function Zg(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 ey({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),Gg);return()=>clearTimeout(u)},[r,e.id,t]);const o=Zg(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 Hs=c.createContext(null),ty=["archive","tags","collections","runs","admin","settings"],ny=["profile","tokens","instance","cookies","extensions","storage"],Ir=(()=>{const e=window.location.pathname.match(/^\/preview\/([^/]+)\/([^/]+)/);return e?{archiveId:e[1],entryUid:e[2]}:null})();function Wt(){const e=window.location.pathname.split("/").filter(Boolean),t=ty.includes(e[0])?e[0]:"archive",n=t==="settings"&&ny.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 ry(e,t){return e==="archive"?"/":e==="settings"?`/settings/${t}`:`/${e}`}function ly(){const[e,t]=c.useState("loading"),[n,r]=c.useState(null);c.useEffect(()=>{(async()=>{var M,W,G;if(await hm()){t("setup");return}const z=await cf();if(!z){const{collection:ue,archive:Ee}=Wt();try{const We=await Ru(),je=Ee?((M=We.find(T=>T.id===Ee))==null?void 0:M.id)??((W=We[0])==null?void 0:W.id):(G=We[0])==null?void 0:G.id;if(je){await zu(je,ue),i(We),o(je),d(ue),t("authenticated");return}}catch{}t("login");return}r(z),t("authenticated")})()},[]),c.useEffect(()=>{const C=()=>{n&&(r(null),t("login"))};return window.addEventListener("auth:expired",C),()=>window.removeEventListener("auth:expired",C)},[n]),c.useEffect(()=>{const C=()=>{const{view:z,settingsTab:M,q:W,tag:G,entry:ue,collection:Ee}=Wt();X(z),ne(M),fe(W),b(G),h(ue),E(null),N(ue?new Set([ue]):new Set),d(Ee)};return window.addEventListener("popstate",C),()=>window.removeEventListener("popstate",C)},[]);const[l,i]=c.useState([]),[a,o]=c.useState(null),[u,d]=c.useState(()=>Wt().collection),[y,g]=c.useState([]),[m,x]=c.useState([]),[w,S]=c.useState(()=>new Set),[_,p]=c.useState(()=>new Map),[f,h]=c.useState(()=>Wt().entry),[k,E]=c.useState(null),[P,N]=c.useState(()=>{const C=Wt().entry;return C?new Set([C]):new Set}),[v,b]=c.useState(()=>Wt().tag),[L,X]=c.useState(()=>Wt().view),[Q,ne]=c.useState(()=>Wt().settingsTab),[q,fe]=c.useState(()=>Wt().q),[Le,ve]=c.useState(""),[I,R]=c.useState(!1),[K,ee]=c.useState([]),[se,ie]=c.useState([]),[Y,Ne]=c.useState(()=>sessionStorage.getItem("captureDialogOpen")==="true"),[pe,U]=c.useState([]),te=c.useRef(0),[re,Ue]=c.useState(()=>{try{const C=JSON.parse(sessionStorage.getItem("pendingCaptures")||"[]");if(Array.isArray(C))return C}catch{}return[]});c.useEffect(()=>{sessionStorage.setItem("pendingCaptures",JSON.stringify(re))},[re]);const[Lt,yt]=c.useState(()=>sessionStorage.getItem("ublockWarningIgnored")==="true"),[Ie,st]=c.useState(null),Ze=c.useRef(0),$=c.useRef(null),Z=c.useRef(!1),Ae=c.useRef(!0),Me=c.useRef(null),Rt=c.useRef(0),zt=c.useRef(new Map),It=(n==null?void 0:n.humanize_slugs)??!1;c.useEffect(()=>{const C=++Ze.current;st(null),!(!k||!a)&&Mr(a,k.entry_uid).then(z=>{C===Ze.current&&st(z)}).catch(()=>{})},[k,a]),c.useEffect(()=>{sessionStorage.setItem("captureDialogOpen",Y)},[Y]);const et=c.useCallback(async(C,z,M,W)=>{if(C){R(!0);try{let G;z||M?G=await Gh(C,z,M,W):G=await zu(C,W),x(G),N(ue=>{if(ue.size<2)return ue;const Ee=new Set(G.map(je=>je.entry_uid)),We=new Set([...ue].filter(je=>Ee.has(je)));return We.size===ue.size?ue:We}),ve(G.length===0?"No results":`${G.length} result${G.length===1?"":"s"}`)}catch{x([]),ve("Search failed. Try again.")}finally{R(!1)}}},[]);c.useEffect(()=>{e==="authenticated"&&(a||Ru().then(C=>{if(i(C),C.length>0){const{archive:z}=Wt(),M=z?C.find(W=>W.id===z):null;o((M==null?void 0:M.id)??C[0].id)}}))},[e,a]),c.useEffect(()=>{if(!a)return;const C=!n;if(Ae.current){Ae.current=!1;const M=[];C||(M.push(Ni(a).then(ee)),M.push(Bl(a).then(ie))),M.length&&Promise.all(M);return}b(null),E(null),h(null),N(new Set),d(null);const z=[et(a,"",null,null)];C||(z.push(Ni(a).then(ee)),z.push(Bl(a).then(ie))),Promise.all(z)},[a,n]),c.useEffect(()=>{if(a===null)return;const C=setTimeout(()=>{et(a,q,v,u)},300);return()=>clearTimeout(C)},[q,a,u]),c.useEffect(()=>{a!==null&&(v!==null&&X("archive"),et(a,q,v,u))},[v,a,u]);const Xt=c.useCallback(C=>{o(C),d(null);const z=new URLSearchParams(window.location.search);z.set("archive",C),z.delete("collection");const M=z.toString();history.replaceState(null,"",window.location.pathname+(M?"?"+M:""))},[]);c.useEffect(()=>{if(!a){g([]);return}wo(a).then(g).catch(()=>g([]))},[a]);const $t=c.useCallback(C=>{if(!n){const W=C?y.find(G=>G.collection_uid===C):y.find(G=>G.slug==="_default_");if(W!=null&&W.requires_auth){t("login");return}}d(C),E(null),h(null),N(new Set),et(a,q,v,C);const z=new URLSearchParams(window.location.search);C?(z.set("collection",C),z.set("archive",a)):(z.delete("collection"),a&&z.set("archive",a));const M=z.toString();history.replaceState(null,"",window.location.pathname+(M?"?"+M:""))},[a,q,v,n,y,et]),an=c.useCallback(C=>{X(C),C==="tags"&&a&&Bl(a).then(ie)},[a]);c.useEffect(()=>{if(Ir)return;const C=ry(L,Q);window.location.pathname!==C&&history.pushState(null,"",C+window.location.search)},[L,Q]);const He=c.useCallback(C=>{h(C?C.entry_uid:null),E(C)},[]),j=c.useCallback((C,z)=>{if(zt.current.set(C.entry_uid,C),++Rt.current,z.shiftKey&&Me.current!==null){z.preventDefault();const M=[...document.querySelectorAll("#entries-body [data-entry-uid]")],W=M.findIndex(je=>je.dataset.entryUid===Me.current),G=M.findIndex(je=>je.dataset.entryUid===C.entry_uid);if(W===-1||G===-1){Me.current=C.entry_uid,N(new Set([C.entry_uid])),He(C);return}const ue=Math.min(W,G),Ee=Math.max(W,G),We=new Set(M.slice(ue,Ee+1).map(je=>je.dataset.entryUid));N(We),We.size===1&&He(C)}else if(z.ctrlKey||z.metaKey){Me.current=C.entry_uid;const M=new Set(P);if(M.has(C.entry_uid)?M.delete(C.entry_uid):M.add(C.entry_uid),N(M),M.size===0)He(null);else if(M.size===1){const[W]=M,G=zt.current.get(W)??m.find(ue=>ue.entry_uid===W)??null;if(G)He(G);else{const ue=++Rt.current;Mr(a,W).then(Ee=>{ue===Rt.current&&(Ee!=null&&Ee.summary)&&He(Ee.summary)}).catch(()=>{})}}else He(null)}else Me.current=C.entry_uid,N(new Set([C.entry_uid])),He(C)},[m,P,He,a]),B=c.useCallback(C=>{b(C)},[]),A=c.useCallback(()=>{b(null)},[]),D=c.useCallback(()=>{a&&Bl(a).then(ie)},[a]),F=c.useCallback((C,z)=>{v===C?b(z):v!=null&&v.startsWith(C+"/")&&b(z+v.slice(C.length))},[v]),H=c.useCallback(C=>{(v===C||v!=null&&v.startsWith(C+"/"))&&b(null)},[v]),ke=c.useCallback((C,z)=>{p(W=>new Map(W).set(C,z));const M=zt.current.get(C);M&&zt.current.set(C,{...M,title:z}),x(W=>W.map(G=>G.entry_uid===C?{...G,title:z}:G)),E(W=>W&&W.entry_uid===C?{...W,title:z}:W),st(W=>W&&W.summary.entry_uid===C?{...W,summary:{...W.summary,title:z}}:W)},[]),he=c.useCallback(()=>{if(!a||!k)return;const C=++Ze.current;Mr(a,k.entry_uid).then(z=>{C===Ze.current&&st(z)}).catch(()=>{})},[a,k]),Re=c.useCallback(C=>{const z=m.some(M=>M.entry_uid===C);S(M=>{const W=new Set(M);return W.add(C),W}),x(M=>M.filter(W=>W.entry_uid!==C)),E(M=>(M==null?void 0:M.entry_uid)===C?null:M),h(M=>M===C?null:M),N(M=>{const W=new Set(M);return W.delete(C),W}),z||et(a,q,v,u)},[m,a,q,v,u,et]),ye=c.useCallback(C=>{const z=new Set(m.map(W=>W.entry_uid)),M=[...C].some(W=>!z.has(W));S(W=>{const G=new Set(W);return C.forEach(ue=>G.add(ue)),G}),x(W=>W.filter(G=>!C.has(G.entry_uid))),N(new Set),E(null),h(null),M&&et(a,q,v,u)},[m,a,q,v,u,et]);c.useEffect(()=>{if(P.size>=2)h(null),E(null);else if(P.size===1){const[C]=P;h(C)}else h(null),E(null)},[P]);const Fe=c.useMemo(()=>m.filter(C=>P.has(C.entry_uid)),[m,P]);c.useEffect(()=>{if(!f||k)return;const C=m.find(z=>z.entry_uid===f);C&&E(C)},[m,f,k]),c.useEffect(()=>{if(Ir)return;const C=new URLSearchParams(window.location.search).get("archive"),z=new URLSearchParams;q&&z.set("q",q),L==="archive"&&v&&z.set("tag",v),L==="archive"&&f&&z.set("entry",f),L==="archive"&&u?(z.set("collection",u),a&&z.set("archive",a)):C&&a&&z.set("archive",a);const M=z.toString(),W=window.location.pathname+(M?"?"+M:"");window.location.pathname+window.location.search!==W&&history.replaceState(null,"",W)},[q,v,f,u,a,L]),c.useEffect(()=>{const C=z=>{var ue,Ee,We,je;const M=z.key==="/"&&!z.metaKey&&!z.ctrlKey&&!z.altKey,W=(z.metaKey||z.ctrlKey)&&z.key==="k";if(!M&&!W)return;const G=(ue=document.activeElement)==null?void 0:ue.tagName;M&&(G==="INPUT"||G==="TEXTAREA"||G==="SELECT")||M&&((Ee=document.activeElement)!=null&&Ee.isContentEditable)||(z.preventDefault(),L==="archive"?((We=$.current)==null||We.focus(),(je=$.current)==null||je.select()):(Z.current=!0,X("archive")))};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[L]),c.useEffect(()=>{const C=z=>{var ae,me;if(z.metaKey||z.ctrlKey||z.altKey||z.key!=="j"&&z.key!=="k")return;const M=(ae=document.activeElement)==null?void 0:ae.tagName;if(M==="INPUT"||M==="TEXTAREA"||M==="SELECT"||(me=document.activeElement)!=null&&me.isContentEditable)return;const W=[...document.querySelectorAll("#entries-body [data-entry-uid]")];if(W.length===0)return;const[G]=P.size===1?P:[null],ue=G?W.findIndex($e=>$e.dataset.entryUid===G):-1,Ee=z.key==="j"?Math.min(ue+1,W.length-1):Math.max(ue-1,0);if(Ee===ue&&ue!==-1)return;const We=W[Ee<0?0:Ee],je=We.dataset.entryUid;Me.current=je;const T=++Rt.current;N(new Set([je]));const J=zt.current.get(je)??m.find($e=>$e.entry_uid===je)??null;J?He(J):Mr(a,je).then($e=>{T===Rt.current&&($e!=null&&$e.summary)&&He($e.summary)}).catch(()=>{}),We.scrollIntoView({block:"nearest"}),z.preventDefault()};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[P,m,He,a]),c.useEffect(()=>{L==="archive"&&Z.current&&(Z.current=!1,requestAnimationFrame(()=>{var C,z;(C=$.current)==null||C.focus(),(z=$.current)==null||z.select()}))},[L]);const ce=c.useCallback(()=>{Ne(!0)},[]),it=c.useCallback(()=>{Ne(!1)},[]),dt=c.useCallback(()=>{if(a)return Promise.allSettled([et(a,q,v,u),Ni(a).then(ee)])},[a,q,v,u,et]),Nr=c.useCallback((C,z,M="error",W=null)=>{if(M==="warning"&&Lt&&z)return;const G=++te.current;U(ue=>[...ue,{id:G,text:C,locator:z,type:M,headline:W}])},[Lt]),Ws=c.useCallback(C=>{U(z=>z.filter(M=>M.id!==C))},[]),Vs=c.useCallback(C=>{Nr(C,null,"error","Reorder failed")},[Nr]),kl=c.useCallback(()=>{sessionStorage.setItem("ublockWarningIgnored","true"),yt(!0),U(C=>C.filter(z=>!(z.type==="warning"&&z.locator)))},[]),Ks=c.useCallback(C=>{Ue(z=>[...z,C])},[]),Qs=c.useCallback(C=>{Ue(z=>z.filter(M=>M.id!==C))},[]),[Kn,Qn]=c.useState(null),[Pn,jl]=c.useState(null),qs=c.useCallback(()=>{k&&Qn(k.entry_uid)},[k]),Xs=c.useCallback(()=>Qn(null),[]),Js=c.useCallback((C,z)=>{jl({src:C,entry:z})},[]),Gs=c.useCallback(()=>jl(null),[]);return c.useEffect(()=>{Qn(null)},[k]),c.useEffect(()=>{const C=z=>{var W,G,ue;if(z.key!=="Escape"||Y||Kn)return;const M=(W=document.activeElement)==null?void 0:W.tagName;M==="INPUT"||M==="TEXTAREA"||M==="SELECT"||P.size>0&&(z.preventDefault(),N(new Set),(ue=(G=document.activeElement)==null?void 0:G.blur)==null||ue.call(G))};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[Y,Kn,P]),c.useEffect(()=>(document.body.classList.toggle("has-audio-bar",!!Pn),()=>document.body.classList.remove("has-audio-bar")),[Pn]),Ir?s.jsx(Jg,{archiveId:Ir.archiveId,entryUid:Ir.entryUid}):e==="loading"?s.jsx("div",{className:"auth-loading",children:"Loading\\u2026"}):e==="setup"?s.jsx(Wm,{onComplete:()=>t("login")}):e==="login"?s.jsx(Hm,{onLogin:C=>{r(C),t("authenticated")}}):s.jsx(Hs.Provider,{value:{currentUser:n,setCurrentUser:r},children:s.jsxs(s.Fragment,{children:[s.jsx(Vm,{archives:l,archiveId:a,onArchiveChange:Xt,view:L,onViewChange:an,onCaptureClick:ce,collections:y,selectedCollectionUid:u,onCollectionChange:$t,isPublicSession:!n,onSignInClick:()=>t("login")}),s.jsxs("main",{className:"app-shell",children:[s.jsxs("div",{className:"workspace",children:[L==="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:$,className:"search-input",type:"search","aria-label":"Search archive","aria-busy":I,placeholder:"Search titles, URLs, types, tags…",value:q,onChange:C=>fe(C.target.value)}),s.jsx("span",{className:"kbd",children:"⌘K"})]}),s.jsxs("span",{className:"result-count",children:[Le&&s.jsxs(s.Fragment,{children:[s.jsx("b",{children:Le.split(" ")[0]})," ",Le.split(" ").slice(1).join(" ")]}),v&&s.jsxs("button",{className:"tag-filter-badge",onClick:A,children:["× ",It?pf(v):v]})]})]}),L==="archive"&&s.jsx(ig,{entries:m,selectedUids:P,onRowClick:j,archiveId:a,pendingCaptures:re,deletedUids:w,renamedTitles:_,isPublicSession:!n,canReorder:!!(n!=null&&n.can_reorder_children),onChildReorderError:Vs}),L==="runs"&&s.jsx(ug,{runs:K}),L==="admin"&&s.jsx(dg,{archives:l}),L==="tags"&&s.jsx(fg,{archiveId:a,tagNodes:se,tagFilter:v,onTagFilterSet:B,onViewChange:an,onTagRenamed:F,onTagDeleted:H,onTagsRefresh:D,humanizeTags:It}),L==="collections"&&s.jsx(hg,{archiveId:a}),L==="settings"&&s.jsx(yg,{tab:Q,onTabChange:ne,archiveId:a})]}),s.jsx(bg,{archiveId:a,selectedEntry:k,selectedUids:P,selectedEntries:Fe,detail:Ie,onTagFilterSet:B,tagNodes:se,onTagsRefresh:D,onEntryTitleChange:ke,onEntryDeleted:Re,onBulkDeleted:ye,humanizeTags:It,onDetailRefresh:he,onOpenPreview:qs,onPlay:Js,isPublicSession:!n})]}),Kn&&k&&k.entry_uid===Kn&&s.jsx(qg,{archiveId:a,entry:k,detail:Ie,onClose:Xs}),Pn&&s.jsx(Xg,{entry:Pn.entry,src:Pn.src,archiveId:a,onClose:Gs}),s.jsx(Xm,{open:Y,archiveId:a,onClose:it,onCaptured:dt,onToast:Nr,activeJobs:re,onJobStarted:Ks,onJobSettled:Qs}),s.jsx(Yg,{toasts:pe,onDismiss:Ws,onIgnoreUblock:kl})]})})}of(document.getElementById("root")).render(s.jsx(c.StrictMode,{children:s.jsx(ly,{})})); diff --git a/crates/archivr-server/static/assets/index-CQKWq7vB.css b/crates/archivr-server/static/assets/index-CQKWq7vB.css deleted file mode 100644 index 448f473..0000000 --- a/crates/archivr-server/static/assets/index-CQKWq7vB.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-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}.child-reorder-controls{display:inline-flex;align-items:center;gap:4px;flex-shrink:0;transition:opacity .15s}.child-drag-handle{display:none;cursor:grab;padding:0 3px;font-size:.8em;letter-spacing:-2px;-webkit-user-select:none;user-select:none;color:var(--muted)}.child-drag-handle:active{cursor:grabbing}.child-move-btn{width:28px;height:28px;padding:0;border:none;background:none;color:inherit;font-size:.9em;line-height:1;cursor:pointer}.child-move-btn:disabled{opacity:.3;cursor:default}.child-move-btn:focus{outline:none}.child-move-btn:focus-visible{outline:2px solid var(--accent);outline-offset:1px;border-radius:2px}@media (hover: hover) and (pointer: fine) and (min-width: 641px){.child-reorder-controls{gap:1px;opacity:.3}.child-entry-row:hover .child-reorder-controls,.child-entry-row:focus-within .child-reorder-controls{opacity:1}.child-drag-handle{display:inline}.child-move-btn{display:none}}.child-entry-row.is-dragging{opacity:.4}.child-entry-row.is-drop-before{box-shadow:inset 0 2px 0 var(--accent)}.child-entry-row.is-drop-after{box-shadow:inset 0 -2px 0 var(--accent)}.child-entries[aria-busy=true] .child-entry-row{cursor:progress}.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/index.html b/crates/archivr-server/static/index.html index a8b7f0e..8f14403 100644 --- a/crates/archivr-server/static/index.html +++ b/crates/archivr-server/static/index.html @@ -6,8 +6,8 @@ Archivr - - + +
From b4bce15f6625c2fa6f6e35f69960216c78849c48 Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Tue, 13 Oct 2026 14:42:35 +0200 Subject: [PATCH 08/14] fix: preserve SRT subtitles in entry export bundles --- crates/archivr-core/src/export/html.rs | 27 +++++++++++++++++ crates/archivr-core/src/export/mod.rs | 39 +++++++++++++++++++++++++ crates/archivr-core/src/export/model.rs | 6 ++-- 3 files changed, 69 insertions(+), 3 deletions(-) diff --git a/crates/archivr-core/src/export/html.rs b/crates/archivr-core/src/export/html.rs index 96ae341..ddaeaa6 100644 --- a/crates/archivr-core/src/export/html.rs +++ b/crates/archivr-core/src/export/html.rs @@ -335,6 +335,8 @@ fn render_video( .unwrap_or_default(); let tracks: String = subtitles .iter() + // SRT files stay in the ZIP, but HTML video tracks require WebVTT. + .filter(|sub| ext_of_s(&sub.name) == "vtt") .enumerate() .map(|(i, sub)| { let sub_src = asset_src(mode, sub); @@ -560,3 +562,28 @@ fn render_container( s.push_str(""); s } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn video_tracks_use_vtt_only_even_when_srt_precedes_it() { + let asset = |name: &str| Asset { + source: PathBuf::new(), + name: name.to_string(), + byte_size: 0, + }; + let html = render_video( + &asset("video.mp4"), + AssetMode::Bundle, + &std::collections::HashMap::new(), + &[asset("captions.srt"), asset("captions.vtt")], + ); + + assert_eq!(html.matches("")); + assert!(!html.contains("captions.srt")); + } +} diff --git a/crates/archivr-core/src/export/mod.rs b/crates/archivr-core/src/export/mod.rs index 36687ff..b9f68c8 100644 --- a/crates/archivr-core/src/export/mod.rs +++ b/crates/archivr-core/src/export/mod.rs @@ -922,6 +922,45 @@ mod tests { assert!(count <= 1, "child title at most once; found {count}"); } + #[test] + fn srt_subtitle_of_child_is_preserved_in_html_and_markdown_bundles() { + let ctx = TestCtx::new(); + let (parent_uid, child_uid) = ctx.add_container_entry("Playlist", "Video"); + let conn = ctx.conn(); + let entry_id = database::entry_id_for_uid(&conn, &child_uid) + .unwrap() + .unwrap(); + let relpath = "raw/captions.srt"; + let srt = "1\n00:00:00,000 --> 00:00:02,000\nCaption text.\n"; + std::fs::write(ctx.paths.store_path.join(relpath), srt).unwrap(); + database::add_entry_artifact( + &conn, + &database::NewArtifact { + entry_id, + artifact_role: "subtitle".to_string(), + storage_area: "raw".to_string(), + relpath: relpath.to_string(), + blob_id: None, + logical_path: None, + metadata_json: None, + }, + ) + .unwrap(); + + for format in [ExportFormat::Html, ExportFormat::Markdown] { + let opts = ExportOptions { + format, + layout: ExportLayout::Together, + include_credit: false, + caller_bits: u32::MAX, + }; + let export = + export_entries(&ctx.paths, std::slice::from_ref(&parent_uid), &opts).unwrap(); + let (file, _, _, _) = export.open().unwrap(); + assert_eq!(read_zip_entry(file, "assets/captions.srt"), srt); + } + } + #[test] fn test_validation_empty() { let ctx = TestCtx::new(); diff --git a/crates/archivr-core/src/export/model.rs b/crates/archivr-core/src/export/model.rs index d4ea2d6..7417d29 100644 --- a/crates/archivr-core/src/export/model.rs +++ b/crates/archivr-core/src/export/model.rs @@ -72,7 +72,7 @@ pub(crate) enum ExportBody { #[derive(Debug)] pub(crate) struct ExportEntry { pub summary: EntrySummary, - /// Subtitle `.vtt` assets in track order. + /// Subtitle `.vtt` and `.srt` assets in track order. pub subtitles: Vec, pub body: ExportBody, } @@ -192,10 +192,10 @@ pub(crate) fn load_entry( } } - // ----- subtitles (VTT only) ----- + // ----- subtitles ----- let subtitles: Vec = subtitle_artifacts .iter() - .filter(|a| a.relpath.to_lowercase().ends_with(".vtt")) + .filter(|a| matches!(ext_of_s(&a.relpath).as_str(), "vtt" | "srt")) .filter_map(|a| { archive::resolve_artifact_path(store_path, a) .map(|p| Asset { From e8767d221e7b13edb9e9bb6cf01072e8605c392c Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Tue, 13 Oct 2026 14:49:09 +0200 Subject: [PATCH 09/14] fix: close entry export dialog for public sessions --- frontend/src/components/ContextRail.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/components/ContextRail.jsx b/frontend/src/components/ContextRail.jsx index 9280fc3..591c7a3 100644 --- a/frontend/src/components/ContextRail.jsx +++ b/frontend/src/components/ContextRail.jsx @@ -1098,7 +1098,7 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se )} { if (!isBulk) return detail ? [detail.summary.entry_uid] : [] From cfc87e98597ddb489ffa99a690d38fbf5ad80298 Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Tue, 13 Oct 2026 14:52:40 +0200 Subject: [PATCH 10/14] fix: stop thread export traversal at visited posts --- crates/archivr-core/src/export/model.rs | 31 ++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/archivr-core/src/export/model.rs b/crates/archivr-core/src/export/model.rs index 7417d29..fa0986c 100644 --- a/crates/archivr-core/src/export/model.rs +++ b/crates/archivr-core/src/export/model.rs @@ -453,7 +453,9 @@ fn dfs( Some(s) => s, None => return, }; - conversation_ids.insert(id.to_string()); + if !conversation_ids.insert(id.to_string()) { + return; + } let post = parse_post(status, asset_map, Some(conversation_ids)); out.push(post); if let Some(children) = children_map.get(id) { @@ -718,3 +720,30 @@ fn decode_html_entities(s: &str) -> String { .replace(""", "\"") .replace("'", "'") } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn thread_export_visits_each_post_once_when_replies_cycle() { + for statuses in [ + vec![json!({"id_str": "1", "in_reply_to_status_id_str": "1"})], + vec![ + json!({"id_str": "1", "in_reply_to_status_id_str": "2"}), + json!({"id_str": "2", "in_reply_to_status_id_str": "1"}), + ], + ] { + let status_map: HashMap = statuses + .iter() + .map(|status| (tweet_id(status).unwrap(), status.clone())) + .collect(); + let posts = build_thread(&statuses, &status_map, Some("1"), &HashMap::new()); + let unique_ids: HashSet<&str> = posts.iter().map(|post| post._id.as_str()).collect(); + + assert_eq!(posts.len(), statuses.len()); + assert_eq!(unique_ids.len(), statuses.len()); + } + } +} From 8c8c084e9c0e0808bb13dba9907756c40330ef89 Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Tue, 13 Oct 2026 14:55:40 +0200 Subject: [PATCH 11/14] fix: fence plain text in Markdown exports --- crates/archivr-core/src/export/markdown.rs | 25 +++++++++++++-- crates/archivr-core/src/export/mod.rs | 36 +++++++++++++++++++++- crates/archivr-core/src/export/model.rs | 6 ++-- 3 files changed, 60 insertions(+), 7 deletions(-) diff --git a/crates/archivr-core/src/export/markdown.rs b/crates/archivr-core/src/export/markdown.rs index ea823d9..1079a39 100644 --- a/crates/archivr-core/src/export/markdown.rs +++ b/crates/archivr-core/src/export/markdown.rs @@ -55,6 +55,22 @@ fn poster_ref(poster: &std::path::Path) -> String { .unwrap_or_default() } +fn fenced_plain_text(text: &str) -> String { + let mut longest_run = 0; + let mut run = 0; + for byte in text.bytes() { + if byte == b'`' { + run += 1; + longest_run = longest_run.max(run); + } else { + run = 0; + } + } + let fence = "`".repeat((longest_run + 1).max(3)); + let trailing_newline = if text.ends_with('\n') { "" } else { "\n" }; + format!("{fence}\n{text}{trailing_newline}{fence}\n") +} + // --------------------------------------------------------------------------- // Public API // --------------------------------------------------------------------------- @@ -155,9 +171,12 @@ fn render_body_md( } ExportBody::Pdf(asset) => format!("[PDF document]({})\n", asset_ref(asset)), ExportBody::Page(asset) => format!("[Archived page snapshot]({})\n", asset_ref(asset)), - ExportBody::Text { text, .. } => { - // Verbatim text. - format!("{}\n", text) + ExportBody::Text { mime_markdown, text } => { + if *mime_markdown { + format!("{text}\n") + } else { + fenced_plain_text(text) + } } ExportBody::TextTooLarge(asset) | ExportBody::File(asset) => { let ext = ext_of_s(&asset.name).to_uppercase(); diff --git a/crates/archivr-core/src/export/mod.rs b/crates/archivr-core/src/export/mod.rs index b9f68c8..a047457 100644 --- a/crates/archivr-core/src/export/mod.rs +++ b/crates/archivr-core/src/export/mod.rs @@ -718,6 +718,15 @@ mod tests { /// Create a text entry with a .txt primary_media artifact. Returns entry_uid. fn add_text_entry(&self, title: &str, content: &str) -> String { + self.add_text_entry_with_extension(title, content, "txt") + } + + fn add_text_entry_with_extension( + &self, + title: &str, + content: &str, + extension: &str, + ) -> String { let conn = self.conn(); let n = self.si_counter.get(); self.si_counter.set(n + 1); @@ -746,7 +755,7 @@ mod tests { let hash = format!("{n:064x}"); let sub1 = &hash[0..1]; let sub2 = &hash[1..2]; - let relpath = format!("raw/{sub1}/{sub2}/{hash}.txt"); + let relpath = format!("raw/{sub1}/{sub2}/{hash}.{extension}"); let file_path = self.paths.store_path.join(&relpath); std::fs::create_dir_all(file_path.parent().unwrap()).unwrap(); std::fs::write(&file_path, content).unwrap(); @@ -904,6 +913,31 @@ mod tests { assert!(md.contains("# heading\n\nbody text"), "body verbatim"); } + #[test] + fn markdown_export_fences_plain_text_but_keeps_markdown_source_raw() { + let ctx = TestCtx::new(); + let source = "# heading\n[link](https://example.com)\n\n```\ninner\n```"; + let plain_uid = ctx.add_text_entry("Plain text", source); + let markdown_uid = ctx.add_text_entry_with_extension("Markdown", source, "md"); + let opts = ExportOptions { + format: ExportFormat::Markdown, + layout: ExportLayout::Together, + include_credit: false, + caller_bits: u32::MAX, + }; + + let plain = export_entries(&ctx.paths, &[plain_uid], &opts).unwrap(); + let (file, _, _, _) = plain.open().unwrap(); + let plain_md = read_zip_entry(file, "index.md"); + assert!(plain_md.contains(&format!("````\n{source}\n````"))); + + let markdown = export_entries(&ctx.paths, &[markdown_uid], &opts).unwrap(); + let (file, _, _, _) = markdown.open().unwrap(); + let markdown_md = read_zip_entry(file, "index.md"); + assert!(markdown_md.contains(&format!("\n\n{source}\n"))); + assert!(!markdown_md.contains("````\n")); + } + #[test] fn test_parent_child_dedupe() { let ctx = TestCtx::new(); diff --git a/crates/archivr-core/src/export/model.rs b/crates/archivr-core/src/export/model.rs index fa0986c..c2e6d60 100644 --- a/crates/archivr-core/src/export/model.rs +++ b/crates/archivr-core/src/export/model.rs @@ -59,7 +59,7 @@ pub(crate) enum ExportBody { Pdf(Asset), /// An HTML/HTM snapshot (SingleFile page). Page(Asset), - Text { _mime_markdown: bool, text: String }, + Text { mime_markdown: bool, text: String }, /// Text file > 5 MiB: offer a download link only. TextTooLarge(Asset), File(Asset), @@ -287,8 +287,8 @@ fn body_from_primary_media( match std::fs::read(&asset.source) { Ok(bytes) => { let text = String::from_utf8_lossy(&bytes).into_owned(); - let _mime_markdown = ext == "md" || ext == "markdown"; - ExportBody::Text { _mime_markdown, text } + let mime_markdown = ext == "md" || ext == "markdown"; + ExportBody::Text { mime_markdown, text } } Err(e) => { eprintln!("warn: export: failed to read text artifact: {e:#}"); From 0ec242e31d204c5dfa488c8b9a8372993f782d3b Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Tue, 13 Oct 2026 15:00:00 +0200 Subject: [PATCH 12/14] fix: scope active capture jobs to their creator --- crates/archivr-core/src/capture_jobs.rs | 12 ++++-- crates/archivr-server/src/jobs.rs | 57 +++++++++++++++++-------- frontend/src/App.jsx | 4 +- 3 files changed, 49 insertions(+), 24 deletions(-) diff --git a/crates/archivr-core/src/capture_jobs.rs b/crates/archivr-core/src/capture_jobs.rs index d6e4271..8a6426e 100644 --- a/crates/archivr-core/src/capture_jobs.rs +++ b/crates/archivr-core/src/capture_jobs.rs @@ -53,18 +53,22 @@ pub fn list_capture_jobs( Ok(rows) } -/// Lists all `pending` and `running` capture jobs for an archive, ordered oldest-first. -/// No creator scoping: any authorized user can see active jobs for cross-user skeleton display. -pub fn list_active_capture_jobs(conn: &Connection) -> Result> { +/// Lists `pending` and `running` capture jobs, ordered oldest-first. +/// `created_by = Some(uid)` limits the result to that user's jobs. +pub fn list_active_capture_jobs( + conn: &Connection, + created_by: Option<&str>, +) -> Result> { let mut stmt = conn.prepare( "SELECT job_uid, archive_id, run_uid, status, error_text, notes_json, created_at, updated_at, created_by FROM capture_jobs WHERE status IN ('pending', 'running') + AND (?1 IS NULL OR created_by = ?1) ORDER BY created_at ASC, id ASC", )?; let rows = stmt - .query_map([], |row| { + .query_map([created_by], |row| { Ok(CaptureJobSummary { job_uid: row.get(0)?, archive_id: row.get(1)?, diff --git a/crates/archivr-server/src/jobs.rs b/crates/archivr-server/src/jobs.rs index 283b2d2..377587e 100644 --- a/crates/archivr-server/src/jobs.rs +++ b/crates/archivr-server/src/jobs.rs @@ -67,14 +67,8 @@ async fn list_capture_jobs_handler( Query(q): Query, ) -> Result>, ApiError> { auth.require_role(ROLE_USER)?; - // `status=active` is a special value meaning all pending+running jobs, visible to every - // authorized user (no creator scoping). Used by other users to render in-progress skeletons. - if q.status.as_deref() == Some("active") { - let mounted = mounted_archive(&state, &archive_id)?; - let conn = database::open_or_initialize(&mounted.archive_path)?; - return Ok(Json(capture_jobs::list_active_capture_jobs(&conn)?)); - } if let Some(status) = q.status.as_deref() + && status != "active" && !capture_jobs::JOB_STATUSES.contains(&status) { return Err(ApiError::bad_request( @@ -103,6 +97,12 @@ async fn list_capture_jobs_handler( }; let conn = database::open_or_initialize(&mounted.archive_path)?; + if q.status.as_deref() == Some("active") { + return Ok(Json(capture_jobs::list_active_capture_jobs( + &conn, + owner.as_deref(), + )?)); + } Ok(Json(capture_jobs::list_capture_jobs( &conn, q.status.as_deref(), @@ -734,39 +734,60 @@ mod tests { } #[tokio::test] - async fn active_status_shows_pending_and_running_jobs_from_all_users() { + async fn active_status_keeps_job_metadata_scoped_to_creator() { let f = fixture(); let alice = make_role_session(&f.auth_path, "alice", &["user"]); let bob = make_role_session(&f.auth_path, "bob", &["user"]); + let admin = admin_session(&f.auth_path); let alice_uid = user_uid(&f.auth_path, "alice"); let bob_uid = user_uid(&f.auth_path, "bob"); let base = "/api/archives/test/capture_jobs"; - // Create pending jobs for alice and bob; set one running and one completed. - let (alice_pending, bob_running, alice_completed) = { + // Create active jobs for both users and a legacy job without a creator. + let (alice_pending, bob_running, alice_completed, legacy_pending) = { let conn = database::open_or_initialize(&f.archive_path).unwrap(); let a = database::create_capture_job_as(&conn, "test", Some(&alice_uid)).unwrap(); let b = database::create_capture_job_as(&conn, "test", Some(&bob_uid)).unwrap(); let c = database::create_capture_job_as(&conn, "test", Some(&alice_uid)).unwrap(); + let legacy = database::create_capture_job(&conn, "test").unwrap(); database::update_capture_job_status(&conn, &b, "running", None, None, None).unwrap(); database::update_capture_job_status(&conn, &c, "completed", Some("run-x"), None, None).unwrap(); - (a, b, c) + database::update_capture_job_notes( + &conn, + &b, + r#"{"locator":"https://private.example/?token=hidden"}"#, + ) + .unwrap(); + (a, b, c, legacy) }; - // Alice using status=active sees both the pending (own) and running (bob's) jobs, - // but not the completed one. + // Alice cannot see Bob's locator or even his active job's existence. let (s, list) = get(&f.router, &format!("{base}?status=active"), Some(&alice)).await; assert_eq!(s, StatusCode::OK); - let visible = uids(&list); - assert!(visible.contains(&alice_pending), "alice_pending should be visible"); - assert!(visible.contains(&bob_running), "bob_running should be visible"); - assert!(!visible.contains(&alice_completed), "completed should not appear"); + assert_eq!(uids(&list), vec![alice_pending.clone()]); + assert!(!list.to_string().contains("private.example")); - // Bob also sees both active jobs (including alice's pending). + // Bob sees his own active job and its notes. let (_, list) = get(&f.router, &format!("{base}?status=active"), Some(&bob)).await; + assert_eq!(uids(&list), vec![bob_running.clone()]); + assert!(list.to_string().contains("private.example")); + + // Explicit filters obey the same rule; admins can see all active jobs. + let (s, _) = get( + &f.router, + &format!("{base}?status=active&created_by={bob_uid}"), + Some(&alice), + ) + .await; + assert_eq!(s, StatusCode::FORBIDDEN); + let (_, list) = get(&f.router, &format!("{base}?status=active&created_by=all"), Some(&alice)).await; + assert_eq!(uids(&list), vec![alice_pending.clone()]); + let (_, list) = get(&f.router, &format!("{base}?status=active"), Some(&admin)).await; let visible = uids(&list); assert!(visible.contains(&alice_pending)); assert!(visible.contains(&bob_running)); + assert!(visible.contains(&legacy_pending)); + assert!(!visible.contains(&alice_completed)); // Regular (non-active) status=pending still scopes to own jobs only. let (_, list) = get(&f.router, &format!("{base}?status=pending"), Some(&alice)).await; diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index ec7319f..31a8291 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -167,8 +167,8 @@ export default function App() { sessionStorage.setItem('pendingCaptures', JSON.stringify(pendingCaptures)) }, [pendingCaptures]) - // Foreign captures: active jobs started by other users (or other tabs) that this session - // didn't submit. Polled every 3 s so all authorized viewers see in-progress skeletons. + // Active jobs this session didn't submit: other tabs for users, any user for admins. + // Poll every 3 s so their in-progress skeletons stay visible here too. const [foreignCaptures, setForeignCaptures] = useState([]) const pendingCapturesRef = useRef(pendingCaptures) useEffect(() => { pendingCapturesRef.current = pendingCaptures }, [pendingCaptures]) From 3779053f53cbfee4ceb54525f8326bddc693eaef Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Tue, 13 Oct 2026 15:49:00 +0200 Subject: [PATCH 13/14] Bundle extracted fonts in page exports --- crates/archivr-core/src/export/mod.rs | 167 +++++++++++++++++++++++- crates/archivr-core/src/export/model.rs | 25 +++- 2 files changed, 190 insertions(+), 2 deletions(-) diff --git a/crates/archivr-core/src/export/mod.rs b/crates/archivr-core/src/export/mod.rs index a047457..3920982 100644 --- a/crates/archivr-core/src/export/mod.rs +++ b/crates/archivr-core/src/export/mod.rs @@ -15,6 +15,8 @@ use std::time::Duration; use anyhow::{Context, Result, bail}; use chrono::Utc; +use regex::Regex; +use std::sync::LazyLock; use tempfile::TempDir; use crate::archive::{self, ArchivePaths, EntrySummary}; @@ -184,10 +186,13 @@ pub fn export_entries( let wpath = work_dir.path().to_path_buf(); // 5. Load all entries. - let entries: Vec = summaries + let mut entries: Vec = summaries .into_iter() .map(|s| model::load_entry(&conn, &paths.store_path, s, options.caller_bits, 0)) .collect::>>()?; + for entry in &mut entries { + localize_page_fonts(entry, &wpath)?; + } // 6. Generate posters when format requires them. let posters: HashMap = if options.format != ExportFormat::Markdown { @@ -209,6 +214,58 @@ pub fn export_entries( }) } +/// Rewrite extracted-font API URLs in an export copy of each captured page. +/// The page and its fonts are both placed directly under `assets/` in the ZIP. +fn localize_page_fonts(entry: &mut model::ExportEntry, work_dir: &Path) -> Result<()> { + static FONT_URL: LazyLock = LazyLock::new(|| { + Regex::new(r"url\(/api/archives/[^/)\s]+/blobs/([0-9a-f]{64})\)").unwrap() + }); + + match &mut entry.body { + model::ExportBody::Page(page) if !entry.fonts.is_empty() => { + let font_names: HashMap = entry + .fonts + .iter() + .filter_map(|font| { + let (hash, _) = font.name.rsplit_once('.')?; + (hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit())) + .then(|| (hash.to_ascii_lowercase(), font.name.clone())) + }) + .collect(); + let original = fs::read_to_string(&page.source) + .with_context(|| format!("failed to read page: {}", page.source.display()))?; + let rewritten = FONT_URL.replace_all(&original, |caps: ®ex::Captures| { + font_names + .get(&caps[1]) + .map_or_else(|| caps[0].to_string(), |name| format!("url(./{name})")) + }); + if rewritten != original { + let localized_name = format!( + "{}.{}", + crate::hash::hash_bytes(rewritten.as_bytes()), + model::ext_of_s(&page.name), + ); + let page_dir = work_dir + .join("localized-pages") + .join(crate::hash::hash_bytes(entry.summary.entry_uid.as_bytes())); + fs::create_dir_all(&page_dir)?; + let localized_path = page_dir.join(&localized_name); + fs::write(&localized_path, rewritten.as_bytes())?; + page.source = localized_path; + page.name = localized_name; + page.byte_size = rewritten.len() as u64; + } + } + model::ExportBody::Container(children) => { + for child in children { + localize_page_fonts(child, work_dir)?; + } + } + _ => {} + } + Ok(()) +} + // --------------------------------------------------------------------------- // Poster generation // --------------------------------------------------------------------------- @@ -529,6 +586,9 @@ fn collect_entry_assets( for sub in &entry.subtitles { out.push(sub.clone()); } + for font in &entry.fonts { + out.push(font.clone()); + } out } @@ -618,6 +678,9 @@ fn collect_entry_assets_into( for sub in &entry.subtitles { out.push(sub.clone()); } + for font in &entry.fonts { + out.push(font.clone()); + } } // --------------------------------------------------------------------------- @@ -774,6 +837,67 @@ mod tests { entry.entry_uid } + fn add_page_with_extracted_font(&self) -> (String, String, String, String) { + let conn = self.conn(); + let n = self.si_counter.get(); + self.si_counter.set(n + 1); + let si_id = database::upsert_source_identity( + &conn, "web", "page", Some(&format!("page-{n}")), None, + &format!("https://example.com/{n}"), + ).unwrap(); + let entry = database::create_archived_entry( + &conn, + &database::NewEntry { + source_identity_id: si_id, + archive_run_id: self.run_id, + parent_entry_id: None, + root_entry_id: None, + created_by_user_id: self.user_id, + owned_by_user_id: self.user_id, + source_kind: "web".to_string(), + entity_kind: "page".to_string(), + title: Some("Page with font".to_string()), + visibility: "public".to_string(), + representation_kind: "html".to_string(), + source_metadata_json: "{}".to_string(), + display_metadata_json: None, + }, + ).unwrap(); + let html = "

Page

"; + let (captured, fonts) = crate::downloader::font_extractor::extract_and_rewrite( + html, &self.paths.store_path, "test-archive", + ).unwrap(); + let page_name = format!("{}.html", crate::hash::hash_bytes(captured.as_bytes())); + let page_path = self.paths.store_path.join("raw").join(&page_name); + std::fs::write(&page_path, &captured).unwrap(); + database::add_entry_artifact( + &conn, + &database::NewArtifact { + entry_id: entry.id, + artifact_role: "primary_media".to_string(), + storage_area: "raw".to_string(), + relpath: format!("raw/{page_name}"), + blob_id: None, + logical_path: None, + metadata_json: None, + }, + ).unwrap(); + let font = &fonts[0]; + database::add_entry_artifact( + &conn, + &database::NewArtifact { + entry_id: entry.id, + artifact_role: "font".to_string(), + storage_area: "raw".to_string(), + relpath: font.raw_relpath.clone(), + blob_id: None, + logical_path: None, + metadata_json: None, + }, + ).unwrap(); + (entry.entry_uid, page_name, format!("{}{}", font.sha256, font.ext), captured) + } + /// Create a parent + child entry pair. Returns (parent_uid, child_uid). fn add_container_entry(&self, parent_title: &str, child_title: &str) -> (String, String) { let conn = self.conn(); @@ -995,6 +1119,47 @@ mod tests { } } + #[test] + fn extracted_fonts_are_localized_in_page_exports() { + let ctx = TestCtx::new(); + let (uid, page_name, font_name, captured) = ctx.add_page_with_extracted_font(); + let other_uid = ctx.add_text_entry("Other", "text"); + assert!(captured.contains("/api/archives/test-archive/blobs/")); + let localized = captured.replace( + &format!("/api/archives/test-archive/blobs/{}", font_name.trim_end_matches(".woff2")), + &format!("./{font_name}"), + ); + let localized_name = format!("{}.html", crate::hash::hash_bytes(localized.as_bytes())); + + for format in [ExportFormat::Html, ExportFormat::Markdown] { + for layout in [ExportLayout::Together, ExportLayout::Separate] { + let opts = ExportOptions { + format, + layout, + include_credit: false, + caller_bits: u32::MAX, + }; + let uids = if layout == ExportLayout::Separate { + vec![uid.clone(), other_uid.clone()] + } else { + vec![uid.clone()] + }; + let export = export_entries(&ctx.paths, &uids, &opts).unwrap(); + let (file, _, _, _) = export.open().unwrap(); + let page = read_zip_entry(file.try_clone().unwrap(), &format!("assets/{localized_name}")); + assert!(page.contains(&format!("url(./{font_name})"))); + assert!(!page.contains("/api/archives/test-archive/blobs/")); + assert_eq!( + read_zip_entry(file, &format!("assets/{font_name}")), + "WOFF2FAKEDATA", + ); + } + } + + let archived_page = std::fs::read_to_string(ctx.paths.store_path.join("raw").join(page_name)).unwrap(); + assert_eq!(archived_page, captured); + } + #[test] fn test_validation_empty() { let ctx = TestCtx::new(); diff --git a/crates/archivr-core/src/export/model.rs b/crates/archivr-core/src/export/model.rs index c2e6d60..12c88b9 100644 --- a/crates/archivr-core/src/export/model.rs +++ b/crates/archivr-core/src/export/model.rs @@ -74,6 +74,8 @@ pub(crate) struct ExportEntry { pub summary: EntrySummary, /// Subtitle `.vtt` and `.srt` assets in track order. pub subtitles: Vec, + /// Fonts extracted from a captured page. + pub fonts: Vec, pub body: ExportBody, } @@ -127,6 +129,7 @@ pub(crate) fn load_entry( return Ok(ExportEntry { summary, subtitles: vec![], + fonts: vec![], body: ExportBody::Empty, }); } @@ -136,6 +139,7 @@ pub(crate) fn load_entry( let mut asset_map: HashMap = HashMap::new(); let mut primary_media_artifact: Option = None; let mut subtitle_artifacts: Vec = Vec::new(); + let mut font_artifacts: Vec = Vec::new(); let mut raw_json_artifacts: Vec = Vec::new(); for artifact in &detail.artifacts { @@ -188,7 +192,8 @@ pub(crate) fn load_entry( } } "subtitle" => subtitle_artifacts.push(artifact.clone()), - _ => {} // favicon, font, etc. + "font" => font_artifacts.push(artifact.clone()), + _ => {} // favicon, etc. } } @@ -211,6 +216,23 @@ pub(crate) fn load_entry( }) .collect(); + let fonts: Vec = font_artifacts + .iter() + .filter_map(|a| { + archive::resolve_artifact_path(store_path, a) + .map(|p| Asset { + byte_size: a.byte_size.unwrap_or(0) as u64, + source: p, + name: file_name_of(&a.relpath), + }) + .map_err(|e| { + eprintln!("warn: export: font not found: {e:#}"); + e + }) + .ok() + }) + .collect(); + // ----- determine body ----- let ek = summary.entity_kind.as_str(); let sk = summary.source_kind.as_str(); @@ -251,6 +273,7 @@ pub(crate) fn load_entry( Ok(ExportEntry { summary, subtitles, + fonts, body, }) } From 7c5b4c033c4f420c49e6997146982e9b06b9a557 Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:58:54 +0200 Subject: [PATCH 14/14] feat: PUT /summary endpoint for agent-written and hand-edited summaries (#43) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds PUT /api/archives/:id/entries/:uid/summary so agents (via the MCP) and humans (via the web UI) can write or edit entry summaries without going through a server-side LLM provider. Core (archivr-core) - summarizer.rs: EXTERNAL_SUMMARY_KINDS, external_summary_text, normalize_external_model — full validation (trim, dedupe+lowercase tags, control-char checks, per-field length limits) + 13 unit tests. - database.rs: extract new_summary_uid(); add insert_completed_entry_summary — single-row INSERT with status='completed', prompt_version='external', input_sha256='external', all timestamps set to now. Server (archivr-server) - routes.rs: ExternalSummaryBody, put_entry_summary_handler. Checks: role (USER), entry visibility (hidden→404), kind in [agent|manual], model validation, text validation, manual-requires-existing-summary (409). Returns 201 + the new EntrySummaryRecord. Route registered alongside existing GET+POST. - entry_access.rs: PUT /summary added to the hidden-entry gate test. - Three new tokio tests: agent creates and becomes latest, manual requires existing summary, body and role validation. Frontend - api.js: saveEntrySummary (PUT, kind:'manual'). - ContextRail.jsx: SUMMARY_SOURCE_LABEL (agent/manual labels), three new state vars, handleSaveSummary (scoped to selected entry), edit form (TL;DR/summary/tags + Save/Cancel), provider controls hidden while editing. - styles.css: rail-summary-edit-btn, rail-summary-editor and sub-classes. Companion MCP PR: thegeneralist01/archivr-mcp#1 --- crates/archivr-core/src/database.rs | 41 ++- crates/archivr-core/src/summarizer.rs | 186 +++++++++++++ crates/archivr-server/src/entry_access.rs | 10 + crates/archivr-server/src/routes.rs | 319 +++++++++++++++++++++- crates/archivr-server/static/index.html | 4 +- frontend/src/api.js | 22 ++ frontend/src/components/ContextRail.jsx | 104 ++++++- frontend/src/styles.css | 42 +++ 8 files changed, 720 insertions(+), 8 deletions(-) diff --git a/crates/archivr-core/src/database.rs b/crates/archivr-core/src/database.rs index a74ceb2..d792ed6 100644 --- a/crates/archivr-core/src/database.rs +++ b/crates/archivr-core/src/database.rs @@ -1960,6 +1960,10 @@ pub fn entry_source_info(conn: &Connection, entry_uid: &str) -> Result String { + format!("sum_{}", &Uuid::new_v4().simple().to_string()[..10]) +} + /// Creates a fresh pending summary attempt for one cache key. /// /// Attempts are intentionally not unique by cache key: a forced regeneration @@ -1972,7 +1976,7 @@ pub fn upsert_pending_entry_summary( prompt_version: &str, input_sha256: &str, ) -> Result { - let summary_uid = format!("sum_{}", &Uuid::new_v4().simple().to_string()[..10]); + let summary_uid = new_summary_uid(); let now = now_timestamp(); let model = provider_model.unwrap_or(""); conn.execute( @@ -2012,6 +2016,41 @@ pub fn update_entry_summary_completed( Ok(()) } +/// Inserts an already-completed summary written outside the provider pipeline +/// (an agent via the API, or a hand edit). Returns the new `summary_uid`. +pub fn insert_completed_entry_summary( + conn: &Connection, + entry_id: i64, + provider_kind: &str, + model: Option<&str>, + prompt_version: &str, + input_sha256: &str, + summary_text: &str, +) -> Result { + let summary_uid = new_summary_uid(); + let now = now_timestamp(); + conn.execute( + "INSERT INTO entry_summaries + (summary_uid, entry_id, provider_kind, provider_model, prompt_version, + input_sha256, status, summary_text, resolved_model, error_text, + created_at, updated_at, completed_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'completed', ?7, ?8, NULL, ?9, ?9, ?9)", + rusqlite::params![ + summary_uid, + entry_id, + provider_kind, + model.unwrap_or(""), + prompt_version, + input_sha256, + summary_text, + model, + now + ], + )?; + Ok(summary_uid) +} + + /// Moves a summary row through `running` → `completed` / `failed`. /// `completed_at` is stamped only on the terminal `completed` transition. pub fn update_entry_summary_status( diff --git a/crates/archivr-core/src/summarizer.rs b/crates/archivr-core/src/summarizer.rs index 1dc1bd8..721770b 100644 --- a/crates/archivr-core/src/summarizer.rs +++ b/crates/archivr-core/src/summarizer.rs @@ -1270,6 +1270,81 @@ pub fn normalize_summary_json(raw: &str) -> String { .to_string() } +// ── External (agent / hand-edited) summary constants ──────────────────────── + +pub const EXTERNAL_SUMMARY_KINDS: [&str; 2] = ["agent", "manual"]; +pub const EXTERNAL_SUMMARY_PROMPT_VERSION: &str = "external"; +pub const EXTERNAL_SUMMARY_INPUT_SHA256: &str = "external"; +pub const MAX_EXTERNAL_TLDR_CHARS: usize = 300; +pub const MAX_EXTERNAL_SUMMARY_CHARS: usize = 20_000; +pub const MAX_EXTERNAL_SUMMARY_TAGS: usize = 10; +pub const MAX_EXTERNAL_TAG_CHARS: usize = 50; +pub const MAX_EXTERNAL_MODEL_CHARS: usize = 100; + +/// Validates and normalizes a caller-written summary into the persisted +/// `{"tldr","summary","tags"}` JSON (same shape as provider output). +/// +/// Counts Unicode scalar values (`.chars().count()`), runs every check on the +/// trimmed value, normalises tags to lowercase, and dedupes in first-seen +/// order. +pub fn external_summary_text(tldr: &str, summary: &str, tags: &[String]) -> Result { + // tldr + let t = tldr.trim(); + if t.chars().any(|c| c.is_control()) { + bail!("tldr must be a single line without control characters"); + } + if t.chars().count() > MAX_EXTERNAL_TLDR_CHARS { + bail!("tldr is longer than 300 characters"); + } + + // summary + let s = summary.trim(); + if s.is_empty() { + bail!("summary must not be empty"); + } + if s.chars().any(|c| c.is_control() && c != '\n' && c != '\r' && c != '\t') { + bail!("summary contains control characters"); + } + if s.chars().count() > MAX_EXTERNAL_SUMMARY_CHARS { + bail!("summary is longer than 20000 characters"); + } + + // tags: trim, lowercase, dedupe, validate + let mut seen = std::collections::HashSet::new(); + let mut out: Vec = Vec::new(); + for raw in tags { + let tag = raw.trim().to_lowercase(); + if tag.is_empty() { + continue; + } + if tag.chars().any(|c| c.is_control()) || tag.chars().count() > MAX_EXTERNAL_TAG_CHARS { + bail!("tags must be 1-50 characters without control characters"); + } + if seen.insert(tag.clone()) { + out.push(tag); + } + } + if out.len() > MAX_EXTERNAL_SUMMARY_TAGS { + bail!("at most 10 tags are allowed"); + } + + Ok(serde_json::json!({"tldr": t, "summary": s, "tags": out}).to_string()) +} + +/// Trims a self-reported model label. Returns `None` when absent or empty. +pub fn normalize_external_model(model: Option<&str>) -> Result> { + let Some(raw) = model else { return Ok(None) }; + let m = raw.trim(); + if m.is_empty() { + return Ok(None); + } + if m.chars().any(|c| c.is_control()) || m.chars().count() > MAX_EXTERNAL_MODEL_CHARS { + bail!("model is longer than 100 characters or contains control characters"); + } + Ok(Some(m.to_string())) +} + + /// Full manual summarization pass for one entry, persisting the result. /// /// Owns the whole row lifecycle (`pending` → `running` → `completed`/`failed`) @@ -2766,4 +2841,115 @@ mod tests { ); assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1); } + + // ── external_summary_text / normalize_external_model tests ────────────── + + #[test] + fn external_summary_tag_normalization() { + let tags: Vec = vec![ + " Rust ".to_string(), + "rust".to_string(), + "".to_string(), + "CLI".to_string(), + ]; + let json_str = external_summary_text("T", "Some summary.", &tags).unwrap(); + let v: serde_json::Value = serde_json::from_str(&json_str).unwrap(); + assert_eq!(v["tags"], serde_json::json!(["rust", "cli"])); + } + + #[test] + fn external_summary_empty_tldr_is_accepted() { + let result = external_summary_text("", "Some summary.", &[]); + assert!(result.is_ok(), "empty tldr should be accepted: {result:?}"); + } + + #[test] + fn external_summary_tldr_control_char_rejected() { + let err = external_summary_text("line1\nline2", "S.", &[]).unwrap_err(); + assert_eq!(format!("{err}"), "tldr must be a single line without control characters"); + } + + #[test] + fn external_summary_tldr_too_long_rejected() { + let long = "x".repeat(301); + let err = external_summary_text(&long, "S.", &[]).unwrap_err(); + assert_eq!(format!("{err}"), "tldr is longer than 300 characters"); + } + + #[test] + fn external_summary_empty_summary_rejected() { + let err = external_summary_text("T", " ", &[]).unwrap_err(); + assert_eq!(format!("{err}"), "summary must not be empty"); + } + + #[test] + fn external_summary_control_char_in_summary_rejected() { + let s = "hello\x01world"; + let err = external_summary_text("T", s, &[]).unwrap_err(); + assert_eq!(format!("{err}"), "summary contains control characters"); + } + + #[test] + fn external_summary_summary_too_long_rejected() { + let long = "x".repeat(20_001); + let err = external_summary_text("T", &long, &[]).unwrap_err(); + assert_eq!(format!("{err}"), "summary is longer than 20000 characters"); + } + + #[test] + fn external_summary_tag_control_char_rejected() { + let tags = vec!["bad\x01tag".to_string()]; + let err = external_summary_text("T", "S.", &tags).unwrap_err(); + assert_eq!(format!("{err}"), "tags must be 1-50 characters without control characters"); + } + + #[test] + fn external_summary_tag_too_long_rejected() { + let tags = vec!["x".repeat(51)]; + let err = external_summary_text("T", "S.", &tags).unwrap_err(); + assert_eq!(format!("{err}"), "tags must be 1-50 characters without control characters"); + } + + #[test] + fn external_summary_too_many_tags_rejected() { + let tags: Vec = (0..11).map(|i| format!("tag{i}")).collect(); + let err = external_summary_text("T", "S.", &tags).unwrap_err(); + assert_eq!(format!("{err}"), "at most 10 tags are allowed"); + } + + #[test] + fn external_summary_output_has_exactly_three_keys() { + let json_str = external_summary_text("TL;DR", "A full summary.", &["rust".to_string()]) + .unwrap(); + let v: serde_json::Map = + serde_json::from_str(&json_str).unwrap(); + assert_eq!(v.len(), 3); + assert!(v.contains_key("tldr")); + assert!(v.contains_key("summary")); + assert!(v.contains_key("tags")); + } + + #[test] + fn normalize_external_model_trims_and_returns_none_for_empty() { + assert_eq!(normalize_external_model(None).unwrap(), None); + assert_eq!(normalize_external_model(Some("")).unwrap(), None); + assert_eq!(normalize_external_model(Some(" ")).unwrap(), None); + assert_eq!( + normalize_external_model(Some(" claude-opus-4-5 ")).unwrap(), + Some("claude-opus-4-5".to_string()) + ); + } + + #[test] + fn normalize_external_model_control_char_rejected() { + let err = normalize_external_model(Some("bad\x01model")).unwrap_err(); + assert_eq!(format!("{err}"), "model is longer than 100 characters or contains control characters"); + } + + #[test] + fn normalize_external_model_too_long_rejected() { + let long = "x".repeat(101); + let err = normalize_external_model(Some(&long)).unwrap_err(); + assert_eq!(format!("{err}"), "model is longer than 100 characters or contains control characters"); + } } diff --git a/crates/archivr-server/src/entry_access.rs b/crates/archivr-server/src/entry_access.rs index f41bad0..fc22d20 100644 --- a/crates/archivr-server/src/entry_access.rs +++ b/crates/archivr-server/src/entry_access.rs @@ -125,6 +125,12 @@ async fn hidden_entry_is_not_found_on_every_by_uid_endpoint() { ("DELETE", "", None, StatusCode::NO_CONTENT), ("POST", "/tags", Some(json!({"tag_path": "/secret"})), StatusCode::CREATED), ("POST", "/rearchive", None, StatusCode::ACCEPTED), + ( + "PUT", + "/summary", + Some(json!({"kind": "agent", "summary": "x"})), + StatusCode::CREATED, + ), ]); for (method, suffix, body, _) in &cases { let uri = entry_path(hidden, suffix); @@ -149,6 +155,10 @@ async fn hidden_entry_is_not_found_on_every_by_uid_endpoint() { .query_row("SELECT COUNT(*) FROM capture_jobs", [], |r| r.get(0)) .unwrap(); assert_eq!(jobs, 2, "rearchive of a hidden entry must not create a job"); + let summaries: i64 = conn + .query_row("SELECT COUNT(*) FROM entry_summaries", [], |r| r.get(0)) + .unwrap(); + assert_eq!(summaries, 0, "PUT summary on hidden entry must not create a row"); // The tag-removal route is gated too (the tag need not exist for the gate to answer). let (status, json) = send_json( diff --git a/crates/archivr-server/src/routes.rs b/crates/archivr-server/src/routes.rs index 836464f..728cede 100644 --- a/crates/archivr-server/src/routes.rs +++ b/crates/archivr-server/src/routes.rs @@ -291,7 +291,7 @@ pub fn app_with_state(state: AppState) -> Router { ) .route( "/api/archives/:archive_id/entries/:entry_uid/summary", - get(entry_summary_handler).post(request_entry_summary_handler), + get(entry_summary_handler).post(request_entry_summary_handler).put(put_entry_summary_handler), ) .route( "/api/summary/transcription-engines", @@ -845,6 +845,68 @@ fn summary_failure_error_text(error: &anyhow::Error) -> String { } } +/// `PUT /api/archives/:id/entries/:uid/summary` +/// +/// Inserts a new completed summary row written by an agent (`kind:"agent"`) +/// or by a human editing an existing summary (`kind:"manual"`). +/// +/// The newest completed row is displayed; earlier rows are retained. A +/// provider attempt running concurrently will supersede this row when it +/// completes — that is the existing regeneration semantics. +#[derive(Debug, serde::Deserialize)] +struct ExternalSummaryBody { + kind: String, + #[serde(default)] + tldr: String, + summary: String, + #[serde(default)] + tags: Vec, + #[serde(default)] + model: Option, +} + +async fn put_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 conn = database::open_or_initialize(&mounted.archive_path)?; + ensure_entry_visible(&conn, &auth_user, &entry_uid)?; + let entry_id = database::entry_id_for_uid(&conn, &entry_uid)? + .ok_or(ApiError::not_found("entry not found"))?; + if !summarizer::EXTERNAL_SUMMARY_KINDS.contains(&body.kind.as_str()) { + return Err(ApiError::bad_request("kind must be 'agent' or 'manual'")); + } + let model = summarizer::normalize_external_model(body.model.as_deref()) + .map_err(|e| ApiError::bad_request(&format!("{e:#}")))?; + if body.kind == "manual" && model.is_some() { + return Err(ApiError::bad_request("model is only accepted for kind 'agent'")); + } + let text = summarizer::external_summary_text(&body.tldr, &body.summary, &body.tags) + .map_err(|e| ApiError::bad_request(&format!("{e:#}")))?; + if body.kind == "manual" + && database::latest_completed_entry_summary(&conn, entry_id)?.is_none() + { + return Err(ApiError::conflict("no summary to edit")); + } + let summary_uid = database::insert_completed_entry_summary( + &conn, + entry_id, + &body.kind, + model.as_deref(), + summarizer::EXTERNAL_SUMMARY_PROMPT_VERSION, + summarizer::EXTERNAL_SUMMARY_INPUT_SHA256, + &text, + )?; + let record = database::get_entry_summary_by_uid(&conn, &summary_uid)? + .ok_or_else(|| anyhow::anyhow!("inserted summary not found"))?; + Ok((StatusCode::CREATED, Json(serde_json::to_value(record)?))) +} + + /// `GET /api/summary/transcription-engines` /// /// Local transcription engines that are enabled (`ARCHIVR_TRANSCRIBE_ENGINES`) @@ -5172,6 +5234,261 @@ mod tests { assert_ne!(input_hashes[0], input_hashes[1]); } + async fn put_summary( + registry: ServerRegistry, + auth_path: std::path::PathBuf, + entry_uid: &str, + cookie: Option<&str>, + token: Option<&str>, + payload: serde_json::Value, + ) -> axum::response::Response { + let mut builder = Request::builder() + .method("PUT") + .uri(format!("/api/archives/test/entries/{entry_uid}/summary")) + .header("content-type", "application/json"); + if let Some(c) = cookie { + builder = builder.header("cookie", c); + } + if let Some(t) = token { + builder = builder.header("authorization", format!("Bearer {t}")); + } + app(registry, auth_path) + .oneshot(builder.body(json_body(&payload)).unwrap()) + .await + .unwrap() + } + + #[tokio::test] + async fn put_agent_summary_creates_completed_row_that_becomes_latest() { + 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); + + // Seed a pre-existing codex_cli completed row. + let conn = database::open_or_initialize(&archive_path).unwrap(); + let old_uid = database::upsert_pending_entry_summary( + &conn, + entry.id, + "codex_cli", + None, + summarizer::PROMPT_VERSION, + "prior-sha", + ) + .unwrap(); + database::update_entry_summary_status(&conn, &old_uid, "completed", Some("old summary"), None) + .unwrap(); + drop(conn); + + let resp = put_summary( + registry.clone(), + auth_path.clone(), + &entry.entry_uid, + Some(&session), + None, + serde_json::json!({ + "kind": "agent", + "tldr": "T", + "summary": " S ", + "tags": ["Rust", "rust", " cli "], + "model": " claude-x " + }), + ) + .await; + assert_eq!(resp.status(), StatusCode::CREATED); + let body = body_json(resp).await; + assert_eq!(body["provider_kind"], "agent"); + assert_eq!(body["provider_model"], "claude-x"); + assert_eq!(body["resolved_model"], "claude-x"); + assert_eq!(body["prompt_version"], "external"); + assert_eq!(body["status"], "completed"); + let text: serde_json::Value = serde_json::from_str(body["summary_text"].as_str().unwrap()).unwrap(); + assert_eq!(text, serde_json::json!({"tldr": "T", "summary": "S", "tags": ["rust", "cli"]})); + + // GET /summary now returns this uid as summary and attempt null. + let new_uid = body["summary_uid"].as_str().unwrap().to_string(); + let get_resp = 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 get_body = body_json(get_resp).await; + assert_eq!(get_body["summary"]["summary_uid"], new_uid); + assert!(get_body["attempt"].is_null()); + + // Both rows retained. + let conn = database::open_or_initialize(&archive_path).unwrap(); + let count: i64 = conn + .query_row("SELECT COUNT(*) FROM entry_summaries", [], |r| r.get(0)) + .unwrap(); + assert_eq!(count, 2); + } + + #[tokio::test] + async fn put_manual_summary_requires_existing_summary() { + 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); + + // 409 on a fresh entry. + let resp = put_summary( + registry.clone(), + auth_path.clone(), + &entry.entry_uid, + Some(&session), + None, + serde_json::json!({"kind": "manual", "summary": "S"}), + ) + .await; + assert_eq!(resp.status(), StatusCode::CONFLICT); + assert_eq!(body_json(resp).await["error"], "no summary to edit"); + + // No row was created. + let conn = database::open_or_initialize(&archive_path).unwrap(); + let count: i64 = conn + .query_row("SELECT COUNT(*) FROM entry_summaries", [], |r| r.get(0)) + .unwrap(); + assert_eq!(count, 0); + drop(conn); + + // After an agent PUT the manual PUT succeeds. + put_summary( + registry.clone(), + auth_path.clone(), + &entry.entry_uid, + Some(&session), + None, + serde_json::json!({"kind": "agent", "summary": "Agent S", "tldr": ""}), + ) + .await; + let resp2 = put_summary( + registry.clone(), + auth_path.clone(), + &entry.entry_uid, + Some(&session), + None, + serde_json::json!({"kind": "manual", "summary": "S"}), + ) + .await; + assert_eq!(resp2.status(), StatusCode::CREATED); + let b2 = body_json(resp2).await; + assert_eq!(b2["provider_kind"], "manual"); + assert!(b2["resolved_model"].is_null()); + + // model with kind=manual → 400. + let resp3 = put_summary( + registry.clone(), + auth_path.clone(), + &entry.entry_uid, + Some(&session), + None, + serde_json::json!({"kind": "manual", "summary": "S", "model": "m"}), + ) + .await; + assert_eq!(resp3.status(), StatusCode::BAD_REQUEST); + assert_eq!(body_json(resp3).await["error"], "model is only accepted for kind 'agent'"); + } + + #[tokio::test] + async fn put_summary_validates_body_and_role() { + use crate::test_support::{guest_session, make_api_token}; + 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); + + // Bad kind. + let r1 = put_summary( + registry.clone(), + auth_path.clone(), + &entry.entry_uid, + Some(&session), + None, + serde_json::json!({"kind": "anthropic_http", "summary": "S"}), + ) + .await; + assert_eq!(r1.status(), StatusCode::BAD_REQUEST); + assert_eq!(body_json(r1).await["error"], "kind must be 'agent' or 'manual'"); + + // Empty summary. + let r2 = put_summary( + registry.clone(), + auth_path.clone(), + &entry.entry_uid, + Some(&session), + None, + serde_json::json!({"kind": "agent", "summary": ""}), + ) + .await; + assert_eq!(r2.status(), StatusCode::BAD_REQUEST); + assert_eq!(body_json(r2).await["error"], "summary must not be empty"); + + // Too many tags. + let tags: Vec = (0..11_u8).map(|i| format!("tag{i}")).collect(); + let r3 = put_summary( + registry.clone(), + auth_path.clone(), + &entry.entry_uid, + Some(&session), + None, + serde_json::json!({"kind": "agent", "summary": "S", "tags": tags}), + ) + .await; + assert_eq!(r3.status(), StatusCode::BAD_REQUEST); + assert_eq!(body_json(r3).await["error"], "at most 10 tags are allowed"); + + // Guest → 403. + let guest = guest_session(&auth_path); + let r4 = put_summary( + registry.clone(), + auth_path.clone(), + &entry.entry_uid, + Some(&guest), + None, + serde_json::json!({"kind": "agent", "summary": "S"}), + ) + .await; + assert_eq!(r4.status(), StatusCode::FORBIDDEN); + + // No cookie → 401. + let r5 = put_summary( + registry.clone(), + auth_path.clone(), + &entry.entry_uid, + None, + None, + serde_json::json!({"kind": "agent", "summary": "S"}), + ) + .await; + assert_eq!(r5.status(), StatusCode::UNAUTHORIZED); + + // Read-scope token → 403. + let read_token = make_api_token(&auth_path, "testowner", None, "read"); + let r6 = put_summary( + registry.clone(), + auth_path.clone(), + &entry.entry_uid, + None, + Some(&read_token), + serde_json::json!({"kind": "agent", "summary": "S"}), + ) + .await; + assert_eq!(r6.status(), StatusCode::FORBIDDEN); + + // No rows created by any of the above. + let conn = database::open_or_initialize(&archive_path).unwrap(); + let count: i64 = conn + .query_row("SELECT COUNT(*) FROM entry_summaries", [], |r| r.get(0)) + .unwrap(); + assert_eq!(count, 0); + } + #[tokio::test] async fn archives_endpoint_lists_mounted_archives() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/archivr-server/static/index.html b/crates/archivr-server/static/index.html index 8f14403..8de283c 100644 --- a/crates/archivr-server/static/index.html +++ b/crates/archivr-server/static/index.html @@ -6,8 +6,8 @@ Archivr - - + +
diff --git a/frontend/src/api.js b/frontend/src/api.js index 5b97a55..d602c09 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -77,6 +77,28 @@ export async function requestEntrySummary(archiveId, entryUid, { provider, force return resp.json(); } +// Saves a hand-edited summary as a new completed row (kind "manual"). The +// server refuses (409) when the entry has no summary yet: edit-only by design. +export async function saveEntrySummary(archiveId, entryUid, { tldr, summary, tags, signal } = {}) { + const resp = await fetch( + `/api/archives/${archiveId}/entries/${entryUid}/summary`, + { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ kind: 'manual', tldr, summary, tags }), + signal, + } + ); + if (!resp.ok) { + const detail = await resp.text(); + let message = detail.trim(); + try { message = JSON.parse(detail).error || message } catch { /* non-JSON body */ } + throw new Error(message || `Summary save failed (${resp.status})`); + } + return resp.json(); +} + + // Text artifacts are served by the same entry-artifact endpoint as previews. // Keep credentials explicit because this helper is also used by public/private // archive views, and preserve the previous concise HTTP error contract. diff --git a/frontend/src/components/ContextRail.jsx b/frontend/src/components/ContextRail.jsx index 591c7a3..b481106 100644 --- a/frontend/src/components/ContextRail.jsx +++ b/frontend/src/components/ContextRail.jsx @@ -1,5 +1,5 @@ import { useState, useEffect, useLayoutEffect, useRef } from 'react' -import { fetchEntryTags, assignTag, removeTag, listEntryCollections, listCollections, addEntryToCollection, updateEntryTitle, generateThreadTitle, deleteEntry, rearchiveEntry, pollCaptureJob, fetchEntrySummary, requestEntrySummary, fetchTranscriptionEngines } from '../api' +import { fetchEntryTags, assignTag, removeTag, listEntryCollections, listCollections, addEntryToCollection, updateEntryTitle, generateThreadTitle, deleteEntry, rearchiveEntry, pollCaptureJob, fetchEntrySummary, requestEntrySummary, saveEntrySummary, fetchTranscriptionEngines } from '../api' import ExportDialog from './ExportDialog' import { formatTimestamp, formatBytes, valueText, sourceIconSvg, displayPath } from '../utils' @@ -14,6 +14,7 @@ const SUMMARY_PROVIDERS = [ { value: 'codex_cli', label: 'Codex CLI' }, ] const PROVIDER_LABEL = Object.fromEntries(SUMMARY_PROVIDERS.map(p => [p.value, p.label])) +const SUMMARY_SOURCE_LABEL = { ...PROVIDER_LABEL, agent: 'Agent', manual: 'Edited by hand' } const SUMMARY_PROVIDER_KEY = 'archivr:summary:provider' const SUMMARY_TRANSCRIBE_ENGINE_KEY = 'archivr:summary:transcribe-engine' const SUMMARY_POLL_MS = 1500 @@ -103,6 +104,9 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se return sessionStorage.getItem(SUMMARY_TRANSCRIBE_ENGINE_KEY) || '' } catch { return '' } }) + const [editingSummary, setEditingSummary] = useState(false) + const [summaryDraft, setSummaryDraft] = useState({ tldr: '', summary: '', tags: '' }) + const [summarySaving, setSummarySaving] = useState(false) const summaryPollRef = useRef(null) const summaryPollAbortRef = useRef(null) const summaryGenerateAbortRef = useRef(null) @@ -206,6 +210,8 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se setSummaryError('') setSummaryBusy(false) setIncludeSummaryImages(false) + setEditingSummary(false) + setSummarySaving(false) }, [archiveId, selectedEntry?.entry_uid, detail?.summary?.entry_uid]) // Poll only while a replacement attempt is non-terminal. Anchoring the effect @@ -323,6 +329,34 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se } } + async function handleSaveSummary() { + if (!archiveId || !detail?.summary?.entry_uid || summarySaving) return + const entryUid = detail.summary.entry_uid + const selectionKey = `${archiveId}:${entryUid}` + if (summarySelectionRef.current !== selectionKey) return + setSummarySaving(true) + setSummaryError('') + try { + const tags = summaryDraft.tags.split(',').map(t => t.trim()).filter(Boolean) + const res = await saveEntrySummary(archiveId, entryUid, { + tldr: summaryDraft.tldr, + summary: summaryDraft.summary, + tags, + }) + if (summarySelectionRef.current !== selectionKey) return + setSummary(res) + setSummaryAttempt(null) + setEditingSummary(false) + onDetailRefresh?.() + } catch (e) { + if (summarySelectionRef.current !== selectionKey) return + setSummaryError(e.message || 'Summary save failed') + } finally { + setSummarySaving(false) + } + } + + function handleProviderChange(value) { setSummaryProvider(value) if (value === 'claude_cli') setIncludeSummaryImages(false) @@ -810,15 +844,77 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se )}

- {PROVIDER_LABEL[summary.provider_kind] || summary.provider_kind} + {SUMMARY_SOURCE_LABEL[summary.provider_kind] || summary.provider_kind} {summary.resolved_model || summary.provider_model ? ` \u00b7 ${summary.resolved_model || summary.provider_model}` : ''}

+ {!isPublicSession && !running && !editingSummary && ( + + )} )} - {running && ( + {editingSummary && ( +
+ +