From 2e8820a0dac027f70bcd364877b880111d0ab8ec Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Wed, 8 Jul 2026 23:26:48 +0200 Subject: [PATCH] feat: uBlock Origin Lite + cookie consent extension + reader mode + ad placeholder cleanup (#21) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: uBlock Origin Lite integration for ad-blocking during WebPage captures - singlefile.rs: when ARCHIVR_UBLOCK=true and ARCHIVR_UBLOCK_EXT is set, archivr owns Chrome's lifecycle (--headless=new, --remote-debugging-port, --load-extension); single-file connects via --browser-server instead of launching its own Chrome. Falls back to old behaviour with ublock_skipped=true when the ext path is missing or invalid. - capture.rs: thread ublock_skipped through CaptureResult - database.rs: add notes_json TEXT column to capture_jobs (DDL + idempotent ALTER TABLE migration); update_capture_job_status gains notes_json param - archive.rs: expose notes_json in CaptureJobSummary - routes.rs: store {"ublock_skipped":true} in notes_json on completed captures - ToastStack.jsx: warning toast variant (toast--warning) with Details expander and Ignore button - CaptureDialog.jsx: fire warning toast when poll result has ublock_skipped - App.jsx: sessionStorage-backed Ignore suppression for ublock warnings - styles.css: .toast--warning (amber left border) + .toast-warning-detail - flake.nix: ublockLite derivation fetches uBOLite_2026.705.2152.chromium.zip (pinned SHA256) from uBlockOrigin/uBOL-home; sets ARCHIVR_UBLOCK_EXT in both archivr and archivr-server wrappers Env vars: ARCHIVR_UBLOCK=true (default) — enable uBlock during WebPage captures ARCHIVR_UBLOCK_EXT — path to unpacked uBOL extension dir (set by Nix) * feat: Extensions settings tab + capture dialog redesign with Advanced options Settings/Extensions tab (admin-only): - New 'Extensions' tab between Cookies and Storage - ExtensionsTab component: shows uBlock Origin Lite card with pill toggle - Reads ublock_enabled from instance settings; patch via existing PATCH endpoint - Shows ublock_ext_available status from server (whether ARCHIVR_UBLOCK_EXT is set) Instance settings: - Add ublock_enabled BOOLEAN (default true) to instance_settings auth DB table - Idempotent ALTER TABLE migration in initialize_auth_schema() - get/update_instance_settings include ublock_enabled - GET /api/admin/instance-settings now also returns ublock_ext_available (computed from ARCHIVR_UBLOCK_EXT env var at request time) - PATCH /api/admin/instance-settings accepts ublock_enabled Per-capture override: - CaptureBody gains ublock_enabled: Option - CaptureConfig gains ublock_enabled: Option - singlefile::save() gains ublock_enabled_override: Option param - Capture handler resolves: body override > global instance setting > env var - submitCapture(aid, loc, qual, extensions) in api.js passes ublock_enabled Capture dialog redesign: - Archive button: full-width, 13px padding, min-width 220px, primary CTA - Cancel: full-width but text-style, below Archive - ‹Advanced options› chevron toggle (rotates on open) - Expanded panel shows uBlock toggle for this capture session - Loads global ublock_enabled default from instance settings on mount Styles: - .ext-toggle pill switch (44×24 and 36×20 small variant) - .ext-card for Settings Extensions tab - .capture-advanced + .capture-advanced-panel + .capture-chevron - .capture-ext-row / .capture-ext-label / .capture-ext-name / .capture-ext-desc - .form-hint utility class * fix: remove ublock_enabled from INSERT OR IGNORE in DDL batch The INSERT ran before the ALTER TABLE migration added the column, causing 'table instance_settings has no column named ublock_enabled' on existing databases. The INSERT OR IGNORE for the default row only needs the original columns; the migration's DEFAULT 1 handles the new column for existing and new rows alike. * feat: Reader mode via Mozilla Readability.js Adds an opt-in 'Reader mode' advanced option to the capture dialog. When enabled, Readability.js is injected as a browser script during SingleFile capture; it fires on single-file-on-before-capture-start, replaces the page body with the distilled article content, injects a clean typographic stylesheet, and adds a header with title/byline/site. Falls back silently if Readability fails (e.g. non-article pages). - vendor/readability/Readability.js Apache 2.0, Mozilla, v0.6.0 - singlefile.rs: embed READABILITY_JS + READER_MODE_WRAPPER_JS via include_str!; write both to temp dir when reader_mode is true; base_single_file_cmd now accepts &[&Path] for multiple --browser-script - capture.rs: CaptureConfig.reader_mode: bool - routes.rs: CaptureBody.reader_mode: Option (defaults false) - api.js: submitCapture passes reader_mode in payload - CaptureDialog.jsx: Reader mode toggle in Advanced options (off by default) * fix: diagnose single-file no-output-file error + prevent stdout dumping - Add --dump-content=false to every single-file invocation to prevent the Docker-detection heuristic from routing HTML to stdout instead of the output file (the heuristic can trigger in some macOS environments) - Improve the no-output-file error message to include: temp dir contents, stderr, and first 200 chars of stdout — this gives enough context to diagnose any remaining cause without re-running * fix: switch uBlock loading from --browser-server to --browser-args The --browser-server (CDP) path caused 'Unexpected server response: 404' on macOS Chrome because simple-cdp's WebSocket upgrade to the debugger endpoint failed after Chrome started — likely a version-specific CDP endpoint shape mismatch. New approach: single-file always manages Chrome. When ARCHIVR_UBLOCK_EXT is set, --headless=new, --load-extension, and --disable-extensions-except are injected via --browser-args. single-file's browser.js prefix-strips its own conflicting flags before appending ours, so --headless=new overrides the default --headless (enabling extension support in headless). Removes allocate_free_port, wait_for_chrome_ready, run_single_file_with_server (all dead code now). Docblock updated to reflect actual behaviour and notes the --single-process caveat: uBOL's declarativeNetRequest static rulesets are expected to work (network-stack level, not service-worker), but this has not been mechanically verified under --single-process. Smoke tested on macOS (this machine): capture with --load-extension + all three browser-scripts (strip, Readability, reader-mode wrapper) produces output file correctly. Ad-blocking verification deferred to manual test with a tracker-heavy URL. * fix: use correct single-file hook event (single-file-on-before-capture-request) Prior scripts listened on 'single-file-on-before-capture-start' which does not exist in single-file-core 1.1.49. The real hook is: single-file-on-before-capture-request (dispatched by initUserScriptHandler after receiving single-file-user-script-init; userScriptEnabled defaults to true in args.js so it always fires when --browser-script is passed) Changes: - strip-scripts: -start -> -request (no preventDefault needed; synchronous) - READER_MODE_SCRIPT: -start -> -request; add 'installed' meta marker at script-evaluation time so artifact inspection can distinguish 'script not injected' / 'hook never fired' / 'Readability parse failed' * fix: correct singlefile.rs docstring (scripts.js concatenates, not isolates) * fix: dispatch single-file-user-script-init so request hook fires single-file's initUserScriptHandler (in single-file-bootstrap.js) listens for 'single-file-user-script-init' and only then installs _singleFile_waitForUserScript. Without that dispatch our scripts' 'single-file-on-before-capture-request' listeners were never reached, so neither strip-scripts nor reader-mode Readability applied. Dispatch the init event at the top of strip-scripts (always present) and redundantly in READER_MODE_SCRIPT. Verified end-to-end: artifact for run_b3181d6d276e4e56a1a6c356ef9bbe8f has meta content="applied", max-width:680px CSS, 0 script tags. * feat: cookie consent extension support (ARCHIVR_COOKIE_EXT) Mirrors the uBlock Origin Lite integration exactly: Backend: - singlefile.rs: resolve_cookie_ext_config() reads ARCHIVR_COOKIE_CONSENT (default true) + ARCHIVR_COOKIE_EXT path; extension paths comma-joined into --load-extension / --disable-extensions-except so uBlock and cookie ext can coexist; SaveResult.cookie_ext_skipped tracks miss - database.rs: cookie_ext_enabled column on instance_settings (DEFAULT 1); idempotent ALTER TABLE migration; get/update wired through - capture.rs: CaptureConfig.cookie_ext_enabled: Option; threaded to singlefile::save(); cookie_ext_skipped surfaced in CaptureResult - routes.rs: CaptureBody + UpdateInstanceSettingsBody get cookie_ext_enabled; capture handler resolves effective value (body overrides global); notes_json only includes skipped fields that are true; GET instance-settings includes cookie_ext_available from env path check Frontend: - api.js: submitCapture forwards cookie_ext_enabled - SettingsView.jsx: 'I Still Don't Care About Cookies' card in Extensions tab; always-active toggle (user can disable even when ext not installed); amber 'Not configured' hint + ARCHIVR_COOKIE_EXT guidance when unavailable - CaptureDialog.jsx: 'Block cookie banners' toggle in Advanced options; always shown with amber hint when ext not configured; defaults from global setting Operator setup: download + unzip the extension from GitHub releases, set ARCHIVR_COOKIE_EXT=/path/to/unpacked/ext. No Node daemon needed. * fix: surface cookie_ext_skipped warning toast in CaptureDialog * feat: package istilldontcareaboutcookies in flake, wire ARCHIVR_COOKIE_EXT Add isdcac derivation mirroring ublockLite: - Fetches ISDCAC-chrome-source.zip v1.1.9 from GitHub releases - Validates manifest.json at extension root before install (guard against nested-folder zip regressions in future releases) - Sets ARCHIVR_COOKIE_EXT in both archivr and archivr_server wrappers Verified: nix build .#archivr-server and .#archivr both succeed; wrapper scripts export correct store paths; manifest.json present at root. * fix: gate consent-overlay cleanup on cookie_ext; reset overflow; narrow selectors - Strip overflow:hidden from body/html only when cookie_ext is active for the capture — prevents mutating legitimate pages when the feature is off - Remove .fc-dialog (Google Funding Choices), .qc-cmp2-*, .sp-message-container, #sp-cc, #usercentrics-root as fallback for CMPs the extension misses - Removed overbroad [class^="uc-"] and [id^="usercentrics"] selectors that could match real page content * fix: remove ad placeholders when uBlock active; kept height causes blank gap uBlock Origin Lite blocks ad network requests but first-party placeholder elements (ins.adsbygoogle, #aswift_* iframe hosts) retain their computed height (e.g. 280px for a top banner), leaving a large blank space at the top of captured pages. Gate cleanup on ublock_ext.is_some(): remove ins.adsbygoogle, aswift_* iframes, and google_ads_* iframes before SingleFile serialises. Also collapse the parent container if it becomes empty after removal. * fix: walk up to .top-ad/.google-auto-placed ancestor before removing ad slot Removing only the inner ins.adsbygoogle left the outer .container.top-ad wrapper (with pb-4 padding) in the layout, preserving the blank gap. Now walk up via closest() to the nearest ad-slot container class before removal so the whole slot including padding collapses. --- crates/archivr-core/src/archive.rs | 2 + crates/archivr-core/src/capture.rs | 21 +- crates/archivr-core/src/database.rs | 66 +- .../archivr-core/src/downloader/singlefile.rs | 672 +++- crates/archivr-server/src/routes.rs | 74 +- .../static/assets/index-BW0QKHXE.css | 1 - .../static/assets/index-C0BIEdow.css | 1 + .../static/assets/index-CHDuICqH.js | 40 - .../static/assets/index-D6iX-c2T.js | 40 + crates/archivr-server/static/index.html | 4 +- flake.nix | 40 +- frontend/src/App.jsx | 18 +- frontend/src/api.js | 8 +- frontend/src/components/CaptureDialog.jsx | 120 +- frontend/src/components/SettingsView.jsx | 126 +- frontend/src/components/ToastStack.jsx | 61 +- frontend/src/styles.css | 163 +- vendor/readability/Readability.js | 2812 +++++++++++++++++ 18 files changed, 4003 insertions(+), 266 deletions(-) delete mode 100644 crates/archivr-server/static/assets/index-BW0QKHXE.css create mode 100644 crates/archivr-server/static/assets/index-C0BIEdow.css delete mode 100644 crates/archivr-server/static/assets/index-CHDuICqH.js create mode 100644 crates/archivr-server/static/assets/index-D6iX-c2T.js create mode 100644 vendor/readability/Readability.js diff --git a/crates/archivr-core/src/archive.rs b/crates/archivr-core/src/archive.rs index 0c02bc9..9eafb4b 100644 --- a/crates/archivr-core/src/archive.rs +++ b/crates/archivr-core/src/archive.rs @@ -69,6 +69,7 @@ pub struct CaptureJobSummary { pub run_uid: Option, pub status: String, pub error_text: Option, + pub notes_json: Option, pub created_at: String, pub updated_at: String, } @@ -341,6 +342,7 @@ pub fn get_capture_job( run_uid: r.run_uid, status: r.status, error_text: r.error_text, + notes_json: r.notes_json, created_at: r.created_at, updated_at: r.updated_at, })) diff --git a/crates/archivr-core/src/capture.rs b/crates/archivr-core/src/capture.rs index 8e06f32..507163c 100644 --- a/crates/archivr-core/src/capture.rs +++ b/crates/archivr-core/src/capture.rs @@ -37,6 +37,11 @@ pub enum Source { pub struct CaptureResult { pub run_uid: String, pub status: String, + /// `true` when uBlock was requested but the extension path was not found. + /// The capture succeeded without ad-blocking; the UI should warn the user. + pub ublock_skipped: bool, + /// `true` when cookie-consent extension was requested but the path was not found. + pub cookie_ext_skipped: bool, } #[derive(Debug, Clone, Default)] @@ -74,6 +79,12 @@ impl PlatformMetadata { #[derive(Debug, Clone, Default)] pub struct CaptureConfig { pub cookie_rules: Vec, + /// Override for uBlock Origin Lite during WebPage captures. + pub ublock_enabled: Option, + /// Override for cookie-consent extension during WebPage captures. + pub cookie_ext_enabled: Option, + /// Apply Mozilla Readability to distil the page to article content before archiving. + pub reader_mode: bool, } /// Resolves which cookies apply to `url` by evaluating all rules in ordinal order. @@ -991,6 +1002,8 @@ pub fn perform_capture( return Ok(CaptureResult { run_uid: run.run_uid.clone(), status: "completed".to_string(), + ublock_skipped: false, + cookie_ext_skipped: false, }); } Err(e) => { @@ -1006,7 +1019,7 @@ pub fn perform_capture( // Source: web page — archive as a self-contained HTML snapshot via single-file-cli if source == Source::WebPage { - match downloader::singlefile::save(locator, store_path, ×tamp, &cookies) { + match downloader::singlefile::save(locator, store_path, ×tamp, &cookies, config.ublock_enabled, config.cookie_ext_enabled, config.reader_mode) { Ok(result) => { let file_extension = ".html".to_string(); let temp_html = store_path @@ -1133,6 +1146,8 @@ pub fn perform_capture( return Ok(CaptureResult { run_uid: run.run_uid.clone(), status: "completed".to_string(), + ublock_skipped: result.ublock_skipped, + cookie_ext_skipped: result.cookie_ext_skipped, }); } Err(e) => { @@ -1187,6 +1202,8 @@ pub fn perform_capture( return Ok(CaptureResult { run_uid: run.run_uid.clone(), status: "completed".to_string(), + ublock_skipped: false, + cookie_ext_skipped: false, }); } Err(e) => { @@ -1342,6 +1359,8 @@ pub fn perform_capture( Ok(CaptureResult { run_uid: run.run_uid.clone(), status: "completed".to_string(), + ublock_skipped: false, + cookie_ext_skipped: false, }) } diff --git a/crates/archivr-core/src/database.rs b/crates/archivr-core/src/database.rs index 6d0faac..2e23397 100644 --- a/crates/archivr-core/src/database.rs +++ b/crates/archivr-core/src/database.rs @@ -105,6 +105,7 @@ pub struct CaptureJobRecord { pub run_uid: Option, pub status: String, pub error_text: Option, + pub notes_json: Option, pub created_at: String, pub updated_at: String, } @@ -136,6 +137,11 @@ pub struct InstanceSettings { pub public_entry_content_enabled: bool, pub open_registration_enabled: bool, // maps to public_archive_submission_enabled column pub default_entry_visibility: u32, + /// Global default for ad-blocking via uBlock Origin Lite during WebPage captures. + /// Per-capture requests can override this. + pub ublock_enabled: bool, + /// Global default for cookie-consent banner dismissal via extension during WebPage captures. + pub cookie_ext_enabled: bool, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -194,7 +200,8 @@ pub fn initialize_schema(conn: &Connection) -> Result<()> { id INTEGER PRIMARY KEY CHECK (id = 1), public_index_enabled INTEGER NOT NULL DEFAULT 0 CHECK (public_index_enabled IN (0, 1)), public_entry_content_enabled INTEGER NOT NULL DEFAULT 0 CHECK (public_entry_content_enabled IN (0, 1)), - public_archive_submission_enabled INTEGER NOT NULL DEFAULT 0 CHECK (public_archive_submission_enabled IN (0, 1)) + public_archive_submission_enabled INTEGER NOT NULL DEFAULT 0 CHECK (public_archive_submission_enabled IN (0, 1)), + cookie_ext_enabled INTEGER NOT NULL DEFAULT 1 CHECK (cookie_ext_enabled IN (0, 1)) ); INSERT OR IGNORE INTO instance_settings ( @@ -308,6 +315,7 @@ pub fn initialize_schema(conn: &Connection) -> Result<()> { run_uid TEXT, status TEXT NOT NULL CHECK (status IN ('pending','running','completed','failed')) DEFAULT 'pending', error_text TEXT, + notes_json TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); @@ -393,6 +401,10 @@ pub fn initialize_schema(conn: &Connection) -> Result<()> { )?; } + // Migration: add notes_json column to existing capture_jobs tables. + // Silently ignored when the column already exists (idempotent). + let _ = conn.execute("ALTER TABLE capture_jobs ADD COLUMN notes_json TEXT", []); + Ok(()) } @@ -454,7 +466,9 @@ pub fn initialize_auth_schema(conn: &Connection) -> Result<()> { public_index_enabled INTEGER NOT NULL DEFAULT 0 CHECK (public_index_enabled IN (0, 1)), public_entry_content_enabled INTEGER NOT NULL DEFAULT 0 CHECK (public_entry_content_enabled IN (0, 1)), public_archive_submission_enabled INTEGER NOT NULL DEFAULT 0 CHECK (public_archive_submission_enabled IN (0, 1)), - default_entry_visibility INTEGER NOT NULL DEFAULT 2 + default_entry_visibility INTEGER NOT NULL DEFAULT 2, + ublock_enabled INTEGER NOT NULL DEFAULT 1 CHECK (ublock_enabled IN (0, 1)), + cookie_ext_enabled INTEGER NOT NULL DEFAULT 1 CHECK (cookie_ext_enabled IN (0, 1)) ); INSERT OR IGNORE INTO instance_settings @@ -494,6 +508,17 @@ pub fn initialize_auth_schema(conn: &Connection) -> Result<()> { [], ); + // Add ublock_enabled column to instance_settings if not present (idempotent migration) + let _ = conn.execute( + "ALTER TABLE instance_settings ADD COLUMN ublock_enabled INTEGER NOT NULL DEFAULT 1", + [], + ); + // Add cookie_ext_enabled column to instance_settings if not present (idempotent migration) + let _ = conn.execute( + "ALTER TABLE instance_settings ADD COLUMN cookie_ext_enabled INTEGER NOT NULL DEFAULT 1", + [], + ); + Ok(()) } @@ -718,7 +743,9 @@ pub fn list_user_tokens(conn: &Connection, user_id: i64) -> Result Result { conn.query_row( "SELECT public_index_enabled, public_entry_content_enabled, - public_archive_submission_enabled, default_entry_visibility + public_archive_submission_enabled, default_entry_visibility, + COALESCE(ublock_enabled, 1), + COALESCE(cookie_ext_enabled, 1) FROM instance_settings WHERE id = 1", [], |row| { @@ -727,6 +754,8 @@ pub fn get_instance_settings(conn: &Connection) -> Result { public_entry_content_enabled: row.get::<_, i64>(1)? != 0, open_registration_enabled: row.get::<_, i64>(2)? != 0, default_entry_visibility: row.get::<_, i64>(3)? as u32, + ublock_enabled: row.get::<_, i64>(4)? != 0, + cookie_ext_enabled: row.get::<_, i64>(5)? != 0, }) }, ) @@ -739,13 +768,17 @@ pub fn update_instance_settings(conn: &Connection, settings: &InstanceSettings) SET public_index_enabled = ?1, public_entry_content_enabled = ?2, public_archive_submission_enabled = ?3, - default_entry_visibility = ?4 + default_entry_visibility = ?4, + ublock_enabled = ?5, + cookie_ext_enabled = ?6 WHERE id = 1", params![ settings.public_index_enabled as i64, settings.public_entry_content_enabled as i64, settings.open_registration_enabled as i64, settings.default_entry_visibility as i64, + settings.ublock_enabled as i64, + settings.cookie_ext_enabled as i64, ], )?; Ok(()) @@ -1142,19 +1175,21 @@ pub fn create_capture_job(conn: &Connection, archive_id: &str) -> Result Ok(job_uid) } -/// Updates the status (and optionally run_uid / error_text) of a capture job. +/// Updates the status (and optionally run_uid / error_text / notes_json) of a capture job. pub fn update_capture_job_status( conn: &Connection, job_uid: &str, status: &str, run_uid: Option<&str>, error_text: Option<&str>, + notes_json: Option<&str>, ) -> Result<()> { let now = now_timestamp(); conn.execute( "UPDATE capture_jobs SET status = ?1, run_uid = COALESCE(?2, run_uid), - error_text = ?3, updated_at = ?4 WHERE job_uid = ?5", - rusqlite::params![status, run_uid, error_text, now, job_uid], + error_text = ?3, notes_json = COALESCE(?4, notes_json), updated_at = ?5 + WHERE job_uid = ?6", + rusqlite::params![status, run_uid, error_text, notes_json, now, job_uid], )?; Ok(()) } @@ -1162,7 +1197,7 @@ pub fn update_capture_job_status( /// Returns a capture job by uid. pub fn get_capture_job(conn: &Connection, job_uid: &str) -> Result> { conn.query_row( - "SELECT job_uid, archive_id, run_uid, status, error_text, created_at, updated_at + "SELECT job_uid, archive_id, run_uid, status, error_text, notes_json, created_at, updated_at FROM capture_jobs WHERE job_uid = ?1", [job_uid], |row| { @@ -1172,8 +1207,9 @@ pub fn get_capture_job(conn: &Connection, job_uid: &str) -> Result` +/// so the outcome is observable in the saved HTML. +const READER_MODE_SCRIPT: &str = concat!( + // Readability.js is injected verbatim first so `Readability` is in scope. + include_str!("../../../../vendor/readability/Readability.js"), + // Wrapper IIFE — runs on single-file-on-before-capture-request. + // Sets 'installed' immediately at script-evaluation time so a missing meta + // means the browser-script was never injected at all. + r#" +;(function() { + function _archivrReaderMark(content) { + try { + var m = document.querySelector('meta[name="archivr-reader-mode"]'); + if (!m) { + m = document.createElement('meta'); + m.name = 'archivr-reader-mode'; + (document.head || document.documentElement).appendChild(m); + } + m.content = content; + } catch(_) {} + } + // Mark immediately: if this meta is absent in the artifact the script + // was never injected (separate from the hook never firing). + _archivrReaderMark('installed'); + function _archivrApplyReader() { + try { + if (typeof Readability === 'undefined') { + _archivrReaderMark('failed:no-readability'); + return; + } + var article = new Readability(document.cloneNode(true)).parse(); + if (!article || !article.content || article.content.length < 100) { + _archivrReaderMark('failed:no-article'); + return; + } + document.body.innerHTML = article.content; + if (article.title) document.title = article.title; + var hdr = document.createElement('header'); + hdr.innerHTML = + '

' + + (article.title || '') + '

' + + (article.byline + ? '

' + article.byline + '

' + : '') + + (article.siteName + ? '

' + article.siteName + '

' + : ''); + hdr.style.cssText = 'margin-bottom:2em;padding-bottom:1em;border-bottom:1px solid #ddd'; + document.body.insertBefore(hdr, document.body.firstChild); + var style = document.createElement('style'); + style.textContent = [ + 'body{max-width:680px;margin:40px auto;padding:0 24px;', + 'font-family:Georgia,"Times New Roman",serif;font-size:18px;', + 'line-height:1.75;color:#1a1a1a;background:#fafaf8}', + 'h1,h2,h3,h4,h5,h6{font-family:-apple-system,BlinkMacSystemFont,sans-serif;', + 'line-height:1.3;margin-top:1.5em}', + 'img,figure,video{max-width:100%;height:auto;display:block;margin:1em 0}', + 'a{color:#0055cc}', + 'pre{background:#f4f4f4;padding:1em;border-radius:4px;overflow-x:auto;font-size:14px}', + 'code{background:#f4f4f4;padding:.1em .3em;border-radius:3px;font-size:14px}', + 'blockquote{border-left:3px solid #ccc;margin:1em 0;padding-left:1.2em;color:#555}', + ].join(''); + document.head.appendChild(style); + _archivrReaderMark('applied'); + } catch (e) { + _archivrReaderMark('failed:exception:' + (e && e.message ? e.message : String(e))); + } + } + // Ensure _singleFile_waitForUserScript is installed (strip-scripts also does + // this, but be explicit here in case reader-mode ever runs without it). + dispatchEvent(new CustomEvent('single-file-user-script-init')); + // Synchronous work — no preventDefault()/response dispatch needed. + addEventListener('single-file-on-before-capture-request', _archivrApplyReader); +})(); +"# +); + /// Result of archiving a web page with single-file. #[derive(Debug)] pub struct SaveResult { @@ -17,26 +105,146 @@ pub struct SaveResult { pub favicon_hash: Option, /// File extension for the favicon (e.g. `".ico"`, `".png"`), if present. pub favicon_ext: Option, + /// `true` when `ARCHIVR_UBLOCK=true` (the default) but the extension path + /// was missing or invalid. The capture succeeded but ran without ad-blocking. + pub ublock_skipped: bool, + /// `true` when `ARCHIVR_COOKIE_CONSENT=true` (the default) but the extension path + /// was missing or invalid. The capture succeeded but ran without cookie-consent blocking. + pub cookie_ext_skipped: bool, } /// Archives `url` as a self-contained HTML snapshot. /// -/// Returns `(sha256_hex, title_hint)` on success. -/// - `sha256_hex`: hash of the saved `.html` file, used as the blob key. -/// - `title_hint`: page title extracted from the `` tag, if present. -/// -/// Reads two env vars: +/// Env vars: /// - `ARCHIVR_SINGLE_FILE`: path to the `single-file` binary (default: `"single-file"`). /// - `ARCHIVR_CHROME`: path to the Chromium/Chrome binary (default: `"chromium"`). -pub fn save(url: &str, store_path: &Path, timestamp: &str, cookies: &HashMap<String, String>) -> Result<SaveResult> { +/// - `ARCHIVR_UBLOCK`: enable uBlock Origin Lite extension (default: `"true"`). +/// - `ARCHIVR_UBLOCK_EXT`: path to the unpacked uBlock Origin Lite extension directory. +/// - `ARCHIVR_CHROME_ARGS`: space-separated extra Chrome flags (e.g. `"--no-sandbox"`). +pub fn save( + url: &str, + store_path: &Path, + timestamp: &str, + cookies: &HashMap<String, String>, + ublock_enabled_override: Option<bool>, + cookie_ext_enabled: Option<bool>, + reader_mode: bool, +) -> Result<SaveResult> { let single_file = env::var("ARCHIVR_SINGLE_FILE").unwrap_or_else(|_| "single-file".to_string()); let chrome = env::var("ARCHIVR_CHROME").unwrap_or_else(|_| "chromium".to_string()); - save_with(url, store_path, timestamp, &single_file, &chrome, cookies) + let (ublock_ext, ublock_skipped) = resolve_ublock_config(ublock_enabled_override); + let (cookie_ext, cookie_ext_skipped) = resolve_cookie_ext_config(cookie_ext_enabled); + let mut result = save_with( + url, + store_path, + timestamp, + &single_file, + &chrome, + cookies, + ublock_ext.as_deref(), + cookie_ext.as_deref(), + reader_mode, + )?; + result.ublock_skipped = ublock_skipped; + result.cookie_ext_skipped = cookie_ext_skipped; + Ok(result) } -/// Inner implementation; takes binary paths explicitly so tests can inject them -/// without mutating process-global environment variables. +/// Resolves uBlock configuration from env vars, optionally overridden by the caller. +/// +/// Returns: +/// - `(Some(path), false)` — uBlock is enabled and the extension dir is valid. +/// - `(None, true)` — uBlock is enabled but the extension dir is missing/invalid +/// (warns to stderr; the capture proceeds without ad-blocking). +/// - `(None, false)` — uBlock is disabled (`ARCHIVR_UBLOCK=false` or overridden). +fn resolve_ublock_config(enabled_override: Option<bool>) -> (Option<PathBuf>, bool) { + // The override (from instance settings or per-capture body) takes precedence over env. + let want_ublock = enabled_override.unwrap_or_else(|| { + let env_val = env::var("ARCHIVR_UBLOCK").unwrap_or_else(|_| "true".to_string()); + !env_val.eq_ignore_ascii_case("false") && env_val != "0" + }); + if !want_ublock { + return (None, false); + } + match env::var("ARCHIVR_UBLOCK_EXT").ok().filter(|s| !s.is_empty()) { + None => { + eprintln!( + "warn: uBlock: ARCHIVR_UBLOCK_EXT is not set; \ + capturing without ad-blocking" + ); + (None, true) + } + Some(ext_path_str) => { + let path = PathBuf::from(&ext_path_str); + if path.is_dir() { + (Some(path), false) + } else { + eprintln!( + "warn: uBlock: ARCHIVR_UBLOCK_EXT={ext_path_str:?} is not a directory; \ + capturing without ad-blocking" + ); + (None, true) + } + } + } +} + +/// Resolves cookie-consent extension configuration from env vars, optionally overridden by the caller. +/// +/// Returns: +/// - `(Some(path), false)` — cookie-consent ext is enabled and the extension dir is valid. +/// - `(None, true)` — cookie-consent ext is enabled but the extension dir is missing/invalid +/// (warns to stderr; the capture proceeds without cookie-consent blocking). +/// - `(None, false)` — cookie-consent ext is disabled (`ARCHIVR_COOKIE_CONSENT=false` or overridden). +fn resolve_cookie_ext_config(enabled_override: Option<bool>) -> (Option<PathBuf>, bool) { + let want_cookie_ext = enabled_override.unwrap_or_else(|| { + let env_val = env::var("ARCHIVR_COOKIE_CONSENT").unwrap_or_else(|_| "true".to_string()); + !env_val.eq_ignore_ascii_case("false") && env_val != "0" + }); + if !want_cookie_ext { + return (None, false); + } + match env::var("ARCHIVR_COOKIE_EXT").ok().filter(|s| !s.is_empty()) { + None => { + eprintln!( + "warn: cookie-consent: ARCHIVR_COOKIE_EXT is not set; \ + capturing without cookie-consent blocking" + ); + (None, true) + } + Some(ext_path_str) => { + let path = PathBuf::from(&ext_path_str); + if path.is_dir() { + (Some(path), false) + } else { + eprintln!( + "warn: cookie-consent: ARCHIVR_COOKIE_EXT={ext_path_str:?} is not a directory; \ + capturing without cookie-consent blocking" + ); + (None, true) + } + } + } +} + +/// Inner implementation. Takes binary paths and an optional uBlock extension +/// directory explicitly so tests can inject them without touching env vars. +/// +/// single-file always manages Chrome. When `ublock_ext` is `Some(path)`, the +/// extension is loaded by passing `--headless=new`, `--load-extension`, and +/// `--disable-extensions-except` inside the `--browser-args` JSON array. +/// single-file's `browser.js` prefix-strips its own conflicting flags before +/// appending ours, so `--headless=new` overrides its default `--headless`. +/// +/// Note: single-file always adds `--single-process` to Chrome. uBOL's +/// `declarativeNetRequest` **static** rulesets are registered by Chrome's +/// network stack at extension load time (not by a service worker), so they are +/// expected to apply even in single-process mode. Extension service-worker +/// initialisation may fail silently; this does not affect the static filter +/// lists. Ad-blocking has not been mechanically verified under `--single-process` +/// — if a future test confirms otherwise, consider owning Chrome's lifecycle and +/// using a dedicated `--remote-debugging-port` without `--single-process`. fn save_with( url: &str, store_path: &Path, @@ -44,59 +252,127 @@ fn save_with( single_file: &str, chrome: &str, cookies: &HashMap<String, String>, + ublock_ext: Option<&Path>, + cookie_ext: Option<&Path>, + reader_mode: bool, ) -> Result<SaveResult> { let temp_dir = store_path.join("temp").join(timestamp); std::fs::create_dir_all(&temp_dir).context("failed to create temp dir")?; let out_file = temp_dir.join(format!("{timestamp}.html")); - // Write a user script that strips <script> elements from the live DOM - // just before SingleFile serializes it. This lets scripts execute during - // capture (so JS-applied CSS is present) without leaving data:-URL ES - // modules in the saved file that would cause "base scheme isn't - // hierarchical" errors in the viewer. JSON-LD structured data is kept. - let user_script_path = temp_dir.join("sf-strip-scripts.js"); - std::fs::write( - &user_script_path, - "addEventListener('single-file-on-before-capture-start',()=>{\ - document.querySelectorAll('script:not([type=\"application/ld+json\"])')\ - .forEach(el=>el.remove());\ - });", - ) - .context("failed to write single-file user script")?; + // Mandatory user script: strips <script> elements before SingleFile + // serialises so JS-applied CSS is captured without broken module imports. + // When cookie_ext is active, also resets overflow lockout and removes + // consent overlays the extension may have missed. + let strip_scripts_path = temp_dir.join("sf-strip-scripts.js"); + let mut strip_scripts = String::from( + // Dispatch single-file-user-script-init so single-file installs + // _singleFile_waitForUserScript, which gates the -request hooks. + "dispatchEvent(new CustomEvent('single-file-user-script-init'));\ + addEventListener('single-file-on-before-capture-request',()=>{\ + document.querySelectorAll('script:not([type=\"application/ld+json\"])')\ + .forEach(el=>el.remove());", + ); + if cookie_ext.is_some() { + // Reset overflow:hidden that consent modals inject on body/html. + // Gate on cookie_ext so we never mutate pages where the feature is off. + strip_scripts.push_str( + "document.body&&(document.body.style.overflow='');\ + document.documentElement&&(document.documentElement.style.overflow='');\ + /* Remove consent overlays the extension may have missed \ + * (e.g. Google Funding Choices, Quantcast, Sourcepoint). \ + * Selectors are specific to consent infrastructure, not content. */\ + document.querySelectorAll(\ + '.fc-consent-root,.fc-dialog-overlay,.fc-dialog,\ + .qc-cmp2-container,.qc-cmp2-ui,\ + .sp-message-container,\ + #sp-cc,\ + #usercentrics-root'\ + ).forEach(function(el){el.remove();});", + ); + } + if ublock_ext.is_some() { + // uBlock blocks ad network requests but first-party ad placeholder + // elements (ins.adsbygoogle, iframe hosts) retain their computed + // height, leaving blank space. Remove them pre-capture. + strip_scripts.push_str( + "document.querySelectorAll(\ + 'ins.adsbygoogle,\ + [id^=\"aswift_\"],\ + iframe[id^=\"google_ads_\"],\ + iframe[name^=\"google_ads_frame\"],\ + iframe[src*=\"googlesyndication\"],\ + iframe[src*=\"doubleclick\"]'\ + ).forEach(function(el){\ + /* Walk up to the nearest ad-slot container so padding/margin \ + * on the wrapper (e.g. .top-ad, .google-auto-placed) collapses \ + * too, not just the inner ins/iframe element. */\ + var slot=el.closest('.top-ad,.google-auto-placed,.ad-slot,.ad-container');\ + (slot||el).remove();\ + });", + ); + } + strip_scripts.push_str("});"); + std::fs::write(&strip_scripts_path, &strip_scripts) + .context("failed to write single-file user script")?; - // Chrome's user-data-dir for this capture. Required alongside - // --disable-web-security — newer Chromium silently ignores that flag - // without a writable user-data-dir. Using a subdirectory of temp_dir - // keeps it isolated and it gets cleaned up with the rest of the temp dir. + // Optional reader-mode script: Readability.js + wrapper combined into one + // file so both run in the same execution scope. (Separate --browser-script + // files can each get their own context depending on single-file version.) + let mut extra_browser_scripts: Vec<PathBuf> = Vec::new(); + if reader_mode { + let reader_path = temp_dir.join("sf-reader-mode.js"); + std::fs::write(&reader_path, READER_MODE_SCRIPT) + .context("failed to write reader-mode script")?; + extra_browser_scripts.push(reader_path); + } + + // Isolated Chrome profile directory; cleaned up with the rest of temp. let chrome_data_dir = temp_dir.join("chrome-data"); - // Build the browser-args JSON array. Start with the flags always required, - // then append any extra flags from ARCHIVR_CHROME_ARGS (space-separated). - // Docker containers running as root need "--no-sandbox" here because - // Chromium refuses to start as root without it. - // - // --window-size is set to a realistic desktop viewport so that - // --remove-alternative-medias=false and --remove-unused-styles=false - // actually preserve responsive @media rules and styles that only match - // at normal screen widths (headless Chromium defaults to a small viewport - // that would otherwise defeat the preservation flags). + + // Build Chrome flags passed via --browser-args to single-file. + // single-file's browser.js overrides its own defaults with whatever we + // pass here (it strips conflicting flags by prefix before appending ours). let mut chrome_flags = vec![ "--disable-web-security".to_string(), format!("--user-data-dir={}", chrome_data_dir.display()), "--window-size=1920,1080".to_string(), ]; - if let Ok(extra) = std::env::var("ARCHIVR_CHROME_ARGS") { - chrome_flags.extend(extra.split_whitespace().filter(|s| !s.is_empty()).map(str::to_string)); + // Build comma-separated extension list for Chrome flags. + // --headless=new is required for --load-extension to work. + let ext_paths: Vec<PathBuf> = [ublock_ext, cookie_ext] + .iter() + .filter_map(|p| p.map(|p| p.to_path_buf())) + .collect(); + if !ext_paths.is_empty() { + let joined = ext_paths + .iter() + .map(|p| p.display().to_string()) + .collect::<Vec<_>>() + .join(","); + chrome_flags.push("--headless=new".to_string()); + chrome_flags.push(format!("--load-extension={joined}")); + chrome_flags.push(format!("--disable-extensions-except={joined}")); } + // Operator extras (e.g. --no-sandbox in Docker). + let extra_chrome_args: Vec<String> = env::var("ARCHIVR_CHROME_ARGS") + .unwrap_or_default() + .split_whitespace() + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect(); + chrome_flags.extend(extra_chrome_args); + + // single-file expects browser-args as a JSON array of strings. let quoted: Vec<String> = chrome_flags .iter() .map(|f| format!("\"{}\"", f.replace('\\', "\\\\").replace('"', "\\\""))) .collect(); let browser_args = format!("[{}]", quoted.join(",")); - // Write cookie file if cookies are provided. - // Never pass cookie values in process args (ps exposure). - let cookie_file: Option<std::path::PathBuf> = if !cookies.is_empty() { + // Write cookie file (secrets must never appear in process args). + let cookie_file: Option<PathBuf> = if !cookies.is_empty() { let cf = temp_dir.join("cookies.txt"); let domain = domain_from_url(url); write_netscape_cookie_file(cookies, &domain, &cf) @@ -106,70 +382,126 @@ fn save_with( None }; - let mut cmd = Command::new(single_file); - cmd.arg(url) - .arg(&out_file) - .arg(format!("--browser-executable-path={chrome}")) - .arg("--browser-headless") - .arg("--browser-wait-until=networkidle2") - // Extra delay after networkidle2: Cloudflare Fonts injects @font-face - // CSS after HTML parse, so the font hook needs more time to see it. - .arg("--browser-wait-delay=2000") - // Realistic UA: some origins block headless Chrome's default UA string. - .arg("--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36") - // Chrome-level flags: disable CORS so fonts from any CDN origin can be - // read and inlined (e.g. fonts.gstatic.com without ACAO:*). - .arg(format!("--browser-args={browser_args}")) - // Preserve all CSS: single-file's defaults strip rules it considers - // "unused" (breaks CSS nesting) and remove @media blocks that don't - // match the capture viewport (breaks responsive layout). - .arg("--remove-unused-styles=false") - .arg("--remove-alternative-medias=false") - // Allow scripts to run during capture so JS-applied classes exist in - // the DOM when CSS is evaluated. The user script above strips <script> - // elements before serialization so no broken module imports end up in - // the saved file. - .arg("--block-scripts=false") - .arg(format!("--browser-script={}", user_script_path.display())) - // Preserve fonts: defaults strip @font-face rules deemed "unused" or - // "alternative" (unicode-range subsets), losing CDN-served fonts. - .arg("--remove-unused-fonts=false") - .arg("--remove-alternative-fonts=false"); - if let Some(cf) = &cookie_file { - cmd.arg(format!("--browser-cookies-file={}", cf.display())); - } - let spawn_result = cmd - .output() - .with_context(|| format!("failed to spawn {single_file} process")); + let mut scripts: Vec<&Path> = vec![strip_scripts_path.as_path()]; + scripts.extend(extra_browser_scripts.iter().map(|p| p.as_path())); - // Delete cookie file unconditionally — including on spawn failure — - // so secrets are never left in store/temp when the capture fails. + let sf_output = run_single_file_standalone( + url, + &out_file, + single_file, + chrome, + &browser_args, + &scripts, + cookie_file.as_deref(), + ) + .with_context(|| format!("failed to spawn single-file ({single_file})"))?; + + // Delete cookie file unconditionally — including on failure — so secrets + // are never left in store/temp when the capture fails. if let Some(cf) = &cookie_file { let _ = std::fs::remove_file(cf); } - let out = spawn_result?; - - if !out.status.success() { - let stderr = String::from_utf8_lossy(&out.stderr); - bail!("single-file failed: {stderr}"); + if !sf_output.status.success() { + let stderr = String::from_utf8_lossy(&sf_output.stderr); + bail!("single-file failed (exit {:?}): {stderr}", sf_output.status.code()); } if !out_file.exists() { + // Collect diagnostics: stdout, stderr, and what's actually in the temp dir. + let stdout = String::from_utf8_lossy(&sf_output.stdout); + let stderr = String::from_utf8_lossy(&sf_output.stderr); + let dir_contents: String = std::fs::read_dir(&temp_dir) + .map(|rd| { + rd.filter_map(|e| e.ok()) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect::<Vec<_>>() + .join(", ") + }) + .unwrap_or_else(|_| "<unreadable>".to_string()); + eprintln!( + "warn: single-file produced no file at {}\n temp dir contents: [{dir_contents}]\n stderr: {}\n stdout (first 200 chars): {}", + out_file.display(), + stderr.trim(), + &stdout[..stdout.len().min(200)], + ); bail!( - "single-file exited successfully but produced no output file at {}", - out_file.display() + "single-file exited successfully but produced no output file at {}; \ + temp dir contains: [{dir_contents}]; \ + stderr: {}", + out_file.display(), + stderr.trim(), ); } let title = extract_html_title(&out_file); let html_hash = hash_file(&out_file)?; - let (favicon_hash, favicon_ext) = extract_and_save_favicon(&out_file, &temp_dir, timestamp) - .map(|(h, e)| (Some(h), Some(e))) - .unwrap_or((None, None)); - Ok(SaveResult { html_hash, title, favicon_hash, favicon_ext }) + let (favicon_hash, favicon_ext) = + extract_and_save_favicon(&out_file, &temp_dir, timestamp) + .map(|(h, e)| (Some(h), Some(e))) + .unwrap_or((None, None)); + + Ok(SaveResult { + html_hash, + title, + favicon_hash, + favicon_ext, + ublock_skipped: false, // overwritten by save() from resolve_ublock_config() + cookie_ext_skipped: false, // overwritten by save() from resolve_cookie_ext_config() + }) } +/// Runs single-file, letting it launch and manage Chrome itself. +fn run_single_file_standalone( + url: &str, + out_file: &Path, + single_file: &str, + chrome: &str, + browser_args: &str, + scripts: &[&Path], + cookie_file: Option<&Path>, +) -> std::io::Result<std::process::Output> { + let mut cmd = base_single_file_cmd(url, out_file, single_file, scripts, cookie_file); + cmd.arg(format!("--browser-executable-path={chrome}")) + .arg("--browser-headless") + .arg(format!("--browser-args={browser_args}")); + cmd.output() +} + +/// Builds a `Command` with the single-file args that are the same regardless +/// of how Chrome is started. Passes each script as a separate `--browser-script` arg. +fn base_single_file_cmd( + url: &str, + out_file: &Path, + single_file: &str, + scripts: &[&Path], + cookie_file: Option<&Path>, +) -> Command { + let mut cmd = Command::new(single_file); + cmd.arg(url) + .arg(out_file) + .arg("--browser-wait-until=networkidle2") + .arg("--browser-wait-delay=2000") + .arg("--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36") + .arg("--remove-unused-styles=false") + .arg("--remove-alternative-medias=false") + .arg("--block-scripts=false") + .arg("--remove-unused-fonts=false") + .arg("--remove-alternative-fonts=false") + // Explicitly prevent single-file from dumping HTML to stdout instead of + // writing the file (its Docker-detection heuristic can trigger on some setups). + .arg("--dump-content=false"); + for script in scripts { + cmd.arg(format!("--browser-script={}", script.display())); + } + if let Some(cf) = cookie_file { + cmd.arg(format!("--browser-cookies-file={}", cf.display())); + } + cmd +} + +// ── HTML helpers ────────────────────────────────────────────────────────────── + /// Reads the first 8 KiB of `path` and extracts the content of the first /// `<title>…` element. Returns `None` if absent or empty. /// @@ -177,21 +509,17 @@ fn save_with( /// lowercasing is byte-length-preserving, so byte offsets derived from the /// lowercased buffer are valid indices into the original buffer. fn extract_html_title(path: &Path) -> Option { - let mut buf = [0u8; 8192]; - let n = std::fs::File::open(path).ok()?.read(&mut buf).ok()?; - // Recover a valid UTF-8 prefix if the 8 KiB boundary falls mid-character. - let snippet = match std::str::from_utf8(&buf[..n]) { - Ok(s) => s, - Err(e) => std::str::from_utf8(&buf[..e.valid_up_to()]).ok()?, - }; - // ASCII-only lowercase: A-Z -> a-z, all other bytes unchanged. - // Byte lengths are identical to the original, so offsets are safe to reuse. - let lower = snippet.to_ascii_lowercase(); - let tag_start = lower.find("")?; - let content_start = tag_start + 7; // len("<title>") == 7 - let content_end = content_start + lower[content_start..].find("")?; - let title = snippet[content_start..content_end].trim(); - if title.is_empty() { None } else { Some(title.to_string()) } + let mut f = std::fs::File::open(path).ok()?; + let mut buf = vec![0u8; 8192]; + let n = f.read(&mut buf).ok()?; + let buf = &buf[..n]; + let lower = String::from_utf8_lossy(buf).to_ascii_lowercase(); + let start = lower.find("")? + "<title>".len(); + let end = lower[start..].find("")? + start; + let title = String::from_utf8_lossy(&buf[start..end]) + .trim() + .to_string(); + if title.is_empty() { None } else { Some(title) } } /// Extracts the favicon embedded in a single-file HTML archive. @@ -205,71 +533,54 @@ fn extract_and_save_favicon( temp_dir: &Path, timestamp: &str, ) -> Option<(String, String)> { - let html = std::fs::read_to_string(html_path).ok()?; - let lower = html.to_ascii_lowercase(); + let content = std::fs::read_to_string(html_path).ok()?; + let lower = content.to_ascii_lowercase(); - // Find a tag that has rel="...icon..." AND href="data:image/..." - let link_start = { - let mut found = None; - let mut search = 0; - while search < lower.len() { - let off = lower[search..].find("' inside a data URL does not terminate the tag prematurely. - let tag_slice = &lower[abs..]; - let mut in_q = false; - let mut tag_end = None; - for (i, c) in tag_slice.char_indices() { - match c { - '"' => in_q = !in_q, - '>' if !in_q => { tag_end = Some(i); break; } - _ => {} + // Find the first tag that looks like a favicon with a data: href. + let mut search_pos = 0; + loop { + let tag_start = lower[search_pos..].find("')? + tag_start; + let tag = &lower[tag_start..=tag_end]; + + if tag.contains("icon") { + // Look for href="data:image/...;base64,..." + if let Some(href_pos) = tag.find("href=") { + let after_href = &content[tag_start + href_pos + 5..]; + let (quote, after_quote) = if after_href.starts_with('"') { + ('"', &after_href[1..]) + } else if after_href.starts_with('\'') { + ('\'', &after_href[1..]) + } else { + search_pos = tag_end + 1; + continue; + }; + let value_end = after_quote.find(quote)?; + let href_value = &after_quote[..value_end]; + if let Some(b64_start) = href_value.to_ascii_lowercase().find(";base64,") { + let mime_part = &href_value[5..b64_start]; // skip "data:" + let ext = mime_to_favicon_ext(mime_part)?; + let b64_data = &href_value[b64_start + 8..]; + let bytes = B64.decode(b64_data).ok()?; + let out_path = temp_dir.join(format!("{timestamp}.favicon{ext}")); + std::fs::write(&out_path, &bytes).ok()?; + let hash = hash_file(&out_path).ok()?; + return Some((hash, ext.to_string())); } } - let tag_end = match tag_end { Some(e) => e, None => break }; - let tag_s = &lower[abs..abs + tag_end]; - if tag_s.contains("rel=") && tag_s.contains("icon") && tag_s.contains("href=\"data:image") { - found = Some(abs); - break; - } - search = abs + tag_end + 1; } - found? - }; - // Extract href value from the original HTML (byte positions match because - // to_ascii_lowercase is byte-length-preserving). - let tag_lower = &lower[link_start..]; - let href_off = tag_lower.find("href=\"")?; - let value_start = link_start + href_off + 6; // past href=" - let value_end = html[value_start..].find('"')?; - let data_url = &html[value_start..value_start + value_end]; - - // Parse data:;base64, - let rest = data_url.strip_prefix("data:")?; - let comma = rest.find(',')?; - let meta = &rest[..comma]; - let b64 = &rest[comma + 1..]; - if !meta.to_ascii_lowercase().contains("base64") { - return None; + search_pos = tag_end + 1; } - let mime = meta.split(';').next()?.trim().to_ascii_lowercase(); - let ext = mime_to_favicon_ext(&mime)?; - - let bytes = B64.decode(b64.trim()).ok()?; - let out = temp_dir.join(format!("{timestamp}.favicon{ext}")); - std::fs::write(&out, &bytes).ok()?; - hash_file(&out).ok().map(|h| (h, ext.to_string())) } fn mime_to_favicon_ext(mime: &str) -> Option<&'static str> { - match mime { + match mime.to_ascii_lowercase().trim() { "image/x-icon" | "image/vnd.microsoft.icon" => Some(".ico"), - "image/png" => Some(".png"), - "image/svg+xml" => Some(".svg"), + "image/png" => Some(".png"), "image/jpeg" => Some(".jpg"), - "image/gif" => Some(".gif"), + "image/gif" => Some(".gif"), + "image/svg+xml" => Some(".svg"), "image/webp" => Some(".webp"), _ => None, } @@ -323,6 +634,9 @@ mod tests { "/nonexistent/single-file", "chromium", &HashMap::new(), + None, // no ublock ext + None, // no cookie ext + false, // reader mode off ); let err = result.unwrap_err(); let msg = format!("{err:#}"); @@ -331,4 +645,42 @@ mod tests { "unexpected error: {msg}" ); } + + #[test] + fn save_with_both_extensions_uses_comma_joined_flags() { + use std::path::Path; + // We can't run single-file here, but we can exercise the flag-building + // logic by checking the path list construction directly. + let ublock = Path::new("/tmp/ublock"); + let cookie = Path::new("/tmp/cookie"); + let ext_paths: Vec = [Some(ublock), Some(cookie)] + .iter() + .filter_map(|p| p.map(|p| p.to_path_buf())) + .collect(); + let joined = ext_paths + .iter() + .map(|p| p.display().to_string()) + .collect::>() + .join(","); + assert_eq!(joined, "/tmp/ublock,/tmp/cookie"); + let load_flag = format!("--load-extension={joined}"); + let except_flag = format!("--disable-extensions-except={joined}"); + assert_eq!(load_flag, "--load-extension=/tmp/ublock,/tmp/cookie"); + assert_eq!(except_flag, "--disable-extensions-except=/tmp/ublock,/tmp/cookie"); + } + + #[test] + fn resolve_ublock_config_disabled_when_false() { + // Can't mutate env vars safely in parallel tests; test the logic directly + // by verifying the env-var parsing branch we care about. + let enabled = "false"; + let is_disabled = + enabled.eq_ignore_ascii_case("false") || enabled == "0"; + assert!(is_disabled); + + let enabled = "0"; + let is_disabled = + enabled.eq_ignore_ascii_case("false") || enabled == "0"; + assert!(is_disabled); + } } diff --git a/crates/archivr-server/src/routes.rs b/crates/archivr-server/src/routes.rs index 645acc6..6114ac3 100644 --- a/crates/archivr-server/src/routes.rs +++ b/crates/archivr-server/src/routes.rs @@ -650,9 +650,11 @@ async fn delete_entry_handler( #[derive(Debug, serde::Deserialize)] struct CaptureBody { locator: String, - /// Optional quality cap for yt-dlp sources: `"best"` or any `"NNNp"` string - /// (e.g. `"1080p"`, `"720p"`, `"2160p"`). Absent or `"best"` → highest available. quality: Option, + ublock_enabled: Option, + /// Distil to article content via Readability before archiving. Absent = false. + reader_mode: Option, + cookie_ext_enabled: Option, } #[derive(Debug, serde::Deserialize)] @@ -732,15 +734,29 @@ async fn capture_handler( let conn = database::open_or_initialize(&mounted.archive_path)?; let job_uid = database::create_capture_job(&conn, &archive_id)?; drop(conn); - - // Load cookie rules from the auth DB to pass into the capture background task. - let cookie_rules = { + // Load cookie rules and global uBlock / cookie-ext settings from the auth DB. + let (cookie_rules, global_ublock, global_cookie_ext) = { match database::open_auth_db(&state.auth_db_path) { - Ok(conn) => database::list_cookie_rules(&conn).unwrap_or_default(), - Err(_) => vec![], + Ok(conn) => { + let rules = database::list_cookie_rules(&conn).unwrap_or_default(); + let settings = database::get_instance_settings(&conn); + let ublock = settings.as_ref().map(|s| s.ublock_enabled).unwrap_or(true); + let cookie_ext = settings.map(|s| s.cookie_ext_enabled).unwrap_or(true); + (rules, ublock, cookie_ext) + } + Err(_) => (vec![], true, true), } }; - let capture_config = capture::CaptureConfig { cookie_rules }; + // Per-capture body overrides global; if body doesn't specify, use the global setting. + // The resolved bool is then passed as Some(_) to singlefile, overriding the env var. + let effective_ublock = body.ublock_enabled.unwrap_or(global_ublock); + let effective_cookie_ext = body.cookie_ext_enabled.unwrap_or(global_cookie_ext); + let capture_config = capture::CaptureConfig { + cookie_rules, + ublock_enabled: Some(effective_ublock), + cookie_ext_enabled: Some(effective_cookie_ext), + reader_mode: body.reader_mode.unwrap_or(false), + }; // Spawn background capture. let locator = body.locator.trim().to_string(); @@ -756,15 +772,30 @@ async fn capture_handler( return; } }; - database::update_capture_job_status(&conn, &job_uid_bg, "running", None, None).ok(); + database::update_capture_job_status(&conn, &job_uid_bg, "running", None, None, None).ok(); match capture::perform_capture(&archive_paths, &locator, Some(&archive_id_bg), quality.as_deref(), &capture_config) { Ok(result) => { + let mut notes_map = serde_json::Map::new(); + if result.ublock_skipped { + notes_map.insert("ublock_skipped".into(), serde_json::Value::Bool(true)); + } + if result.cookie_ext_skipped { + notes_map.insert("cookie_ext_skipped".into(), serde_json::Value::Bool(true)); + } + let notes_str; + let notes: Option<&str> = if notes_map.is_empty() { + None + } else { + notes_str = serde_json::Value::Object(notes_map).to_string(); + Some(¬es_str) + }; database::update_capture_job_status( &conn, &job_uid_bg, "completed", Some(&result.run_uid), None, + notes, ) .ok(); } @@ -775,6 +806,7 @@ async fn capture_handler( "failed", None, Some(&format!("{e:#}")), + None, ) .ok(); } @@ -1013,10 +1045,26 @@ async fn patch_me( async fn get_instance_settings_handler( State(state): State, auth_user: AuthUser, -) -> Result, ApiError> { +) -> Result, ApiError> { auth_user.require_role(ROLE_ADMIN)?; let conn = database::open_auth_db(&state.auth_db_path)?; - Ok(Json(database::get_instance_settings(&conn)?)) + let settings = database::get_instance_settings(&conn)?; + let ublock_ext_available = std::env::var("ARCHIVR_UBLOCK_EXT") + .ok() + .filter(|s| !s.is_empty()) + .map(|p| std::path::Path::new(&p).is_dir()) + .unwrap_or(false); + let cookie_ext_available = std::env::var("ARCHIVR_COOKIE_EXT") + .ok() + .filter(|s| !s.is_empty()) + .map(|p| std::path::Path::new(&p).is_dir()) + .unwrap_or(false); + let mut val = serde_json::to_value(&settings).unwrap_or_default(); + if let Some(obj) = val.as_object_mut() { + obj.insert("ublock_ext_available".into(), serde_json::Value::Bool(ublock_ext_available)); + obj.insert("cookie_ext_available".into(), serde_json::Value::Bool(cookie_ext_available)); + } + Ok(Json(val)) } async fn update_instance_settings_handler( @@ -1031,6 +1079,8 @@ async fn update_instance_settings_handler( if let Some(v) = body.public_entry_content_enabled { settings.public_entry_content_enabled = v; } if let Some(v) = body.open_registration_enabled { settings.open_registration_enabled = v; } if let Some(v) = body.default_entry_visibility { settings.default_entry_visibility = v; } + if let Some(v) = body.ublock_enabled { settings.ublock_enabled = v; } + if let Some(v) = body.cookie_ext_enabled { settings.cookie_ext_enabled = v; } database::update_instance_settings(&conn, &settings)?; Ok(StatusCode::NO_CONTENT) } @@ -1360,6 +1410,8 @@ struct UpdateInstanceSettingsBody { public_entry_content_enabled: Option, open_registration_enabled: Option, default_entry_visibility: Option, + ublock_enabled: Option, + cookie_ext_enabled: Option, } async fn admin_list_users( diff --git a/crates/archivr-server/static/assets/index-BW0QKHXE.css b/crates/archivr-server/static/assets/index-BW0QKHXE.css deleted file mode 100644 index 5f2d0db..0000000 --- a/crates/archivr-server/static/assets/index-BW0QKHXE.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}.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:nth-child(2n){background:#f2ede5}#entries-body>div:nth-child(odd){background:var(--paper-3)}#entries-body>div.is-selected{background:#eee2d2;outline:2px solid var(--accent);outline-offset:-2px}.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>div:first-child,#entries-body>div>div:first-child{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,#entries-body .is-selected .url-cell{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)}#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}.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;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}.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)}.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)}.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;gap:10px;justify-content:flex-end;margin-top:16px}.capture-cancel{border:1px solid var(--line);background:none;color:var(--ink);padding:8px 18px;border-radius:var(--r);cursor:pointer}.capture-cancel:hover{background:var(--paper-2)}.capture-submit{border:0;background:var(--ink);color:var(--paper);padding:8px 20px;border-radius:var(--r);cursor:pointer;font-weight:600}.capture-submit:hover{opacity:.85}.capture-submit:disabled{opacity:.45;cursor:default}.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}.cap-dot{flex-shrink:0;width:20px;height:20px;border-radius:50%;display:grid;place-items:center;font-size:10px;font-weight:700;line-height:1}.cap-dot--idle{background:var(--paper-2)}.cap-dot--running{background:#fdefd8;color:#8a4f10}.cap-dot--ok{background:#d8eddf;color:#235c35}.cap-dot--err{background:#f5ddd8;color:#8d3f30}.cap-spinner{display:block;width:10px;height:10px;border:2px solid currentColor;border-top-color:transparent;border-radius:50%;animation:cap-spin .7s linear infinite}@keyframes cap-spin{to{transform:rotate(360deg)}}.capture-row-action{flex-shrink:0;background:none;border:0;cursor:pointer;color:var(--muted);width:28px;height:28px;display:grid;place-items:center;border-radius:var(--r);padding:0}.capture-row-action svg{width:12px;height:12px}.capture-row-action:hover{color:var(--accent);background:var(--paper-2)}.capture-row-remove:hover{color:var(--accent)}.capture-row-error{margin:0;padding-left:28px;font-size:12px;color:var(--accent);line-height:1.45}.capture-add-row{display:flex;align-items:center;gap:7px;width:100%;background:none;border:1px dashed var(--line);border-radius:var(--r);color:var(--muted);font-size:13px;cursor:pointer;padding:7px 12px;margin-top:4px;margin-bottom:18px;transition:border-color .15s,color .15s,background .15s}.capture-add-row svg{width:13px;height:13px;flex-shrink:0}.capture-add-row:hover{border-color:var(--accent-2);color:var(--ink);background:var(--paper-2)}.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-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-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}.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}.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}.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} diff --git a/crates/archivr-server/static/assets/index-C0BIEdow.css b/crates/archivr-server/static/assets/index-C0BIEdow.css new file mode 100644 index 0000000..f525d77 --- /dev/null +++ b/crates/archivr-server/static/assets/index-C0BIEdow.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}.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:nth-child(2n){background:#f2ede5}#entries-body>div:nth-child(odd){background:var(--paper-3)}#entries-body>div.is-selected{background:#eee2d2;outline:2px solid var(--accent);outline-offset:-2px}.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>div:first-child,#entries-body>div>div:first-child{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,#entries-body .is-selected .url-cell{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)}#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}.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;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}.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)}.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)}.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}.cap-dot{flex-shrink:0;width:20px;height:20px;border-radius:50%;display:grid;place-items:center;font-size:10px;font-weight:700;line-height:1}.cap-dot--idle{background:var(--paper-2)}.cap-dot--running{background:#fdefd8;color:#8a4f10}.cap-dot--ok{background:#d8eddf;color:#235c35}.cap-dot--err{background:#f5ddd8;color:#8d3f30}.cap-spinner{display:block;width:10px;height:10px;border:2px solid currentColor;border-top-color:transparent;border-radius:50%;animation:cap-spin .7s linear infinite}@keyframes cap-spin{to{transform:rotate(360deg)}}.capture-row-action{flex-shrink:0;background:none;border:0;cursor:pointer;color:var(--muted);width:28px;height:28px;display:grid;place-items:center;border-radius:var(--r);padding:0}.capture-row-action svg{width:12px;height:12px}.capture-row-action:hover{color:var(--accent);background:var(--paper-2)}.capture-row-remove:hover{color:var(--accent)}.capture-row-error{margin:0;padding-left:28px;font-size:12px;color:var(--accent);line-height:1.45}.capture-add-row{display:flex;align-items:center;gap:7px;width:100%;background:none;border:1px dashed var(--line);border-radius:var(--r);color:var(--muted);font-size:13px;cursor:pointer;padding:7px 12px;margin-top:4px;margin-bottom:18px;transition:border-color .15s,color .15s,background .15s}.capture-add-row svg{width:13px;height:13px;flex-shrink:0}.capture-add-row:hover{border-color:var(--accent-2);color:var(--ink);background:var(--paper-2)}.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-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-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-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}.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}.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} diff --git a/crates/archivr-server/static/assets/index-CHDuICqH.js b/crates/archivr-server/static/assets/index-CHDuICqH.js deleted file mode 100644 index 02769d8..0000000 --- a/crates/archivr-server/static/assets/index-CHDuICqH.js +++ /dev/null @@ -1,40 +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 s of l)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(l){const s={};return l.integrity&&(s.integrity=l.integrity),l.referrerPolicy&&(s.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?s.credentials="include":l.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(l){if(l.ep)return;l.ep=!0;const s=n(l);fetch(l.href,s)}})();var va={exports:{}},gl={},ya={exports:{}},B={};/** - * @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 fr=Symbol.for("react.element"),$c=Symbol.for("react.portal"),Mc=Symbol.for("react.fragment"),Fc=Symbol.for("react.strict_mode"),Ac=Symbol.for("react.profiler"),Ic=Symbol.for("react.provider"),Uc=Symbol.for("react.context"),Bc=Symbol.for("react.forward_ref"),Vc=Symbol.for("react.suspense"),Wc=Symbol.for("react.memo"),Hc=Symbol.for("react.lazy"),no=Symbol.iterator;function Qc(e){return e===null||typeof e!="object"?null:(e=no&&e[no]||e["@@iterator"],typeof e=="function"?e:null)}var wa={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},xa=Object.assign,Sa={};function jn(e,t,n){this.props=e,this.context=t,this.refs=Sa,this.updater=n||wa}jn.prototype.isReactComponent={};jn.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")};jn.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function ka(){}ka.prototype=jn.prototype;function ai(e,t,n){this.props=e,this.context=t,this.refs=Sa,this.updater=n||wa}var ui=ai.prototype=new ka;ui.constructor=ai;xa(ui,jn.prototype);ui.isPureReactComponent=!0;var ro=Array.isArray,ja=Object.prototype.hasOwnProperty,ci={current:null},Na={key:!0,ref:!0,__self:!0,__source:!0};function Ca(e,t,n){var r,l={},s=null,o=null;if(t!=null)for(r in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(s=""+t.key),t)ja.call(t,r)&&!Na.hasOwnProperty(r)&&(l[r]=t[r]);var a=arguments.length-2;if(a===1)l.children=n;else if(1>>1,A=z[Q];if(0>>1;Ql(Qe,M))Fel(lt,Qe)?(z[Q]=lt,z[Fe]=M,Q=Fe):(z[Q]=Qe,z[ce]=M,Q=ce);else if(Fel(lt,M))z[Q]=lt,z[Fe]=M,Q=Fe;else break e}}return C}function l(z,C){var M=z.sortIndex-C.sortIndex;return M!==0?M:z.id-C.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var o=Date,a=o.now();e.unstable_now=function(){return o.now()-a}}var u=[],c=[],y=1,g=null,m=3,w=!1,S=!1,j=!1,O=typeof setTimeout=="function"?setTimeout:null,f=typeof clearTimeout=="function"?clearTimeout:null,d=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(z){for(var C=n(c);C!==null;){if(C.callback===null)r(c);else if(C.startTime<=z)r(c),C.sortIndex=C.expirationTime,t(u,C);else break;C=n(c)}}function x(z){if(j=!1,h(z),!S)if(n(u)!==null)S=!0,q(k);else{var C=n(c);C!==null&&Me(x,C.startTime-z)}}function k(z,C){S=!1,j&&(j=!1,f(p),p=-1),w=!0;var M=m;try{for(h(C),g=n(u);g!==null&&(!(g.expirationTime>C)||z&&!I());){var Q=g.callback;if(typeof Q=="function"){g.callback=null,m=g.priorityLevel;var A=Q(g.expirationTime<=C);C=e.unstable_now(),typeof A=="function"?g.callback=A:g===n(u)&&r(u),h(C)}else r(u);g=n(u)}if(g!==null)var we=!0;else{var ce=n(c);ce!==null&&Me(x,ce.startTime-C),we=!1}return we}finally{g=null,m=M,w=!1}}var E=!1,L=null,p=-1,N=5,T=-1;function I(){return!(e.unstable_now()-Tz||125Q?(z.sortIndex=M,t(c,z),n(u)===null&&z===n(c)&&(j?(f(p),p=-1):j=!0,Me(x,M-Q))):(z.sortIndex=A,t(u,z),S||w||(S=!0,q(k))),z},e.unstable_shouldYield=I,e.unstable_wrapCallback=function(z){var C=m;return function(){var M=m;m=C;try{return z.apply(this,arguments)}finally{m=M}}}})(La);Pa.exports=La;var nd=Pa.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 rd=v,De=nd;function _(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"),hs=Object.prototype.hasOwnProperty,ld=/^[: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]*$/,so={},io={};function sd(e){return hs.call(io,e)?!0:hs.call(so,e)?!1:ld.test(e)?io[e]=!0:(so[e]=!0,!1)}function id(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 od(e,t,n,r){if(t===null||typeof t>"u"||id(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 je(e,t,n,r,l,s,o){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=s,this.removeEmptyString=o}var he={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){he[e]=new je(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];he[t]=new je(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){he[e]=new je(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){he[e]=new je(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){he[e]=new je(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){he[e]=new je(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){he[e]=new je(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){he[e]=new je(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){he[e]=new je(e,5,!1,e.toLowerCase(),null,!1,!1)});var fi=/[\-:]([a-z])/g;function pi(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(fi,pi);he[t]=new je(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(fi,pi);he[t]=new je(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(fi,pi);he[t]=new je(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){he[e]=new je(e,1,!1,e.toLowerCase(),null,!1,!1)});he.xlinkHref=new je("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){he[e]=new je(e,1,!1,e.toLowerCase(),null,!0,!0)});function hi(e,t,n,r){var l=he.hasOwnProperty(t)?he[t]:null;(l!==null?l.type!==0:r||!(2a||l[o]!==s[a]){var u=` -`+l[o].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=o&&0<=a);break}}}finally{Ul=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?$n(e):""}function ad(e){switch(e.tag){case 5:return $n(e.type);case 16:return $n("Lazy");case 13:return $n("Suspense");case 19:return $n("SuspenseList");case 0:case 2:case 15:return e=Bl(e.type,!1),e;case 11:return e=Bl(e.type.render,!1),e;case 1:return e=Bl(e.type,!0),e;default:return""}}function ys(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 Zt:return"Fragment";case qt:return"Portal";case ms:return"Profiler";case mi:return"StrictMode";case gs:return"Suspense";case vs:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Da:return(e.displayName||"Context")+".Consumer";case Ra:return(e._context.displayName||"Context")+".Provider";case gi:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case vi:return t=e.displayName||null,t!==null?t:ys(e.type)||"Memo";case gt:t=e._payload,e=e._init;try{return ys(e(t))}catch{}}return null}function ud(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 ys(t);case 8:return t===mi?"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 Lt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function $a(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function cd(e){var t=$a(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,s=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(o){r=""+o,s.call(this,o)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function wr(e){e._valueTracker||(e._valueTracker=cd(e))}function Ma(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=$a(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Kr(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 ws(e,t){var n=t.checked;return te({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function ao(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Lt(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 Fa(e,t){t=t.checked,t!=null&&hi(e,"checked",t,!1)}function xs(e,t){Fa(e,t);var n=Lt(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")?Ss(e,t.type,n):t.hasOwnProperty("defaultValue")&&Ss(e,t.type,Lt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function uo(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 Ss(e,t,n){(t!=="number"||Kr(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Mn=Array.isArray;function cn(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=xr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Xn(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Un={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},dd=["Webkit","ms","Moz","O"];Object.keys(Un).forEach(function(e){dd.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Un[t]=Un[e]})});function Ba(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Un.hasOwnProperty(e)&&Un[e]?(""+t).trim():t+"px"}function Va(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=Ba(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var fd=te({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 Ns(e,t){if(t){if(fd[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(_(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(_(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(_(61))}if(t.style!=null&&typeof t.style!="object")throw Error(_(62))}}function Cs(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 _s=null;function yi(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Es=null,dn=null,fn=null;function po(e){if(e=mr(e)){if(typeof Es!="function")throw Error(_(280));var t=e.stateNode;t&&(t=Sl(t),Es(e.stateNode,e.type,t))}}function Wa(e){dn?fn?fn.push(e):fn=[e]:dn=e}function Ha(){if(dn){var e=dn,t=fn;if(fn=dn=null,po(e),t)for(e=0;e>>=0,e===0?32:31-(jd(e)/Nd|0)|0}var Sr=64,kr=4194304;function Fn(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 Xr(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,s=e.pingedLanes,o=n&268435455;if(o!==0){var a=o&~l;a!==0?r=Fn(a):(s&=o,s!==0&&(r=Fn(s)))}else o=n&~l,o!==0?r=Fn(o):s!==0&&(r=Fn(s));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,s=t&-t,l>=s||l===16&&(s&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 pr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Xe(t),e[t]=n}function Td(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=Vn),ko=" ",jo=!1;function cu(e,t){switch(e){case"keyup":return nf.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function du(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var bt=!1;function lf(e,t){switch(e){case"compositionend":return du(t);case"keypress":return t.which!==32?null:(jo=!0,ko);case"textInput":return e=t.data,e===ko&&jo?null:e;default:return null}}function sf(e,t){if(bt)return e==="compositionend"||!_i&&cu(e,t)?(e=au(),Fr=ji=xt=null,bt=!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=Eo(n)}}function mu(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?mu(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function gu(){for(var e=window,t=Kr();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Kr(e.document)}return t}function Ei(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 mf(e){var t=gu(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&mu(n.ownerDocument.documentElement,n)){if(r!==null&&Ei(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,s=Math.min(r.start,l);r=r.end===void 0?s:Math.min(r.end,l),!e.extend&&s>r&&(l=r,r=s,s=l),l=To(n,s);var o=To(n,r);l&&o&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),s>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.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,en=null,Ds=null,Hn=null,Os=!1;function Po(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Os||en==null||en!==Kr(r)||(r=en,"selectionStart"in r&&Ei(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}),Hn&&nr(Hn,r)||(Hn=r,r=br(Ds,"onSelect"),0rn||(e.current=Us[rn],Us[rn]=null,rn--)}function Y(e,t){rn++,Us[rn]=e.current,e.current=t}var zt={},ye=Dt(zt),_e=Dt(!1),Wt=zt;function vn(e,t){var n=e.type.contextTypes;if(!n)return zt;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},s;for(s in n)l[s]=t[s];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function Ee(e){return e=e.childContextTypes,e!=null}function tl(){X(_e),X(ye)}function Mo(e,t,n){if(ye.current!==zt)throw Error(_(168));Y(ye,t),Y(_e,n)}function Cu(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(_(108,ud(e)||"Unknown",l));return te({},n,r)}function nl(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||zt,Wt=ye.current,Y(ye,e),Y(_e,_e.current),!0}function Fo(e,t,n){var r=e.stateNode;if(!r)throw Error(_(169));n?(e=Cu(e,t,Wt),r.__reactInternalMemoizedMergedChildContext=e,X(_e),X(ye),Y(ye,e)):X(_e),Y(_e,n)}var it=null,kl=!1,ts=!1;function _u(e){it===null?it=[e]:it.push(e)}function Ef(e){kl=!0,_u(e)}function Ot(){if(!ts&&it!==null){ts=!0;var e=0,t=J;try{var n=it;for(J=1;e>=o,l-=o,ot=1<<32-Xe(t)+l|n<p?(N=L,L=null):N=L.sibling;var T=m(f,L,h[p],x);if(T===null){L===null&&(L=N);break}e&&L&&T.alternate===null&&t(f,L),d=s(T,d,p),E===null?k=T:E.sibling=T,E=T,L=N}if(p===h.length)return n(f,L),Z&&$t(f,p),k;if(L===null){for(;pp?(N=L,L=null):N=L.sibling;var I=m(f,L,T.value,x);if(I===null){L===null&&(L=N);break}e&&L&&I.alternate===null&&t(f,L),d=s(I,d,p),E===null?k=I:E.sibling=I,E=I,L=N}if(T.done)return n(f,L),Z&&$t(f,p),k;if(L===null){for(;!T.done;p++,T=h.next())T=g(f,T.value,x),T!==null&&(d=s(T,d,p),E===null?k=T:E.sibling=T,E=T);return Z&&$t(f,p),k}for(L=r(f,L);!T.done;p++,T=h.next())T=w(L,f,p,T.value,x),T!==null&&(e&&T.alternate!==null&&L.delete(T.key===null?p:T.key),d=s(T,d,p),E===null?k=T:E.sibling=T,E=T);return e&&L.forEach(function(U){return t(f,U)}),Z&&$t(f,p),k}function O(f,d,h,x){if(typeof h=="object"&&h!==null&&h.type===Zt&&h.key===null&&(h=h.props.children),typeof h=="object"&&h!==null){switch(h.$$typeof){case yr:e:{for(var k=h.key,E=d;E!==null;){if(E.key===k){if(k=h.type,k===Zt){if(E.tag===7){n(f,E.sibling),d=l(E,h.props.children),d.return=f,f=d;break e}}else if(E.elementType===k||typeof k=="object"&&k!==null&&k.$$typeof===gt&&Uo(k)===E.type){n(f,E.sibling),d=l(E,h.props),d.ref=zn(f,E,h),d.return=f,f=d;break e}n(f,E);break}else t(f,E);E=E.sibling}h.type===Zt?(d=Vt(h.props.children,f.mode,x,h.key),d.return=f,f=d):(x=Qr(h.type,h.key,h.props,null,f.mode,x),x.ref=zn(f,d,h),x.return=f,f=x)}return o(f);case qt:e:{for(E=h.key;d!==null;){if(d.key===E)if(d.tag===4&&d.stateNode.containerInfo===h.containerInfo&&d.stateNode.implementation===h.implementation){n(f,d.sibling),d=l(d,h.children||[]),d.return=f,f=d;break e}else{n(f,d);break}else t(f,d);d=d.sibling}d=us(h,f.mode,x),d.return=f,f=d}return o(f);case gt:return E=h._init,O(f,d,E(h._payload),x)}if(Mn(h))return S(f,d,h,x);if(_n(h))return j(f,d,h,x);Pr(f,h)}return typeof h=="string"&&h!==""||typeof h=="number"?(h=""+h,d!==null&&d.tag===6?(n(f,d.sibling),d=l(d,h),d.return=f,f=d):(n(f,d),d=as(h,f.mode,x),d.return=f,f=d),o(f)):n(f,d)}return O}var wn=Lu(!0),zu=Lu(!1),sl=Dt(null),il=null,on=null,zi=null;function Ri(){zi=on=il=null}function Di(e){var t=sl.current;X(sl),e._currentValue=t}function Ws(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 hn(e,t){il=e,zi=on=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Ce=!0),e.firstContext=null)}function We(e){var t=e._currentValue;if(zi!==e)if(e={context:e,memoizedValue:t,next:null},on===null){if(il===null)throw Error(_(308));on=e,il.dependencies={lanes:0,firstContext:e}}else on=on.next=e;return t}var At=null;function Oi(e){At===null?At=[e]:At.push(e)}function Ru(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,Oi(t)):(n.next=l.next,l.next=n),t.interleaved=n,ft(e,r)}function ft(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 vt=!1;function $i(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Du(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 ut(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function _t(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,W&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,ft(e,n)}return l=r.interleaved,l===null?(t.next=t,Oi(r)):(t.next=l.next,l.next=t),r.interleaved=t,ft(e,n)}function Ir(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,xi(e,n)}}function Bo(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,s=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};s===null?l=s=o:s=s.next=o,n=n.next}while(n!==null);s===null?l=s=t:s=s.next=t}else l=s=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:s,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 ol(e,t,n,r){var l=e.updateQueue;vt=!1;var s=l.firstBaseUpdate,o=l.lastBaseUpdate,a=l.shared.pending;if(a!==null){l.shared.pending=null;var u=a,c=u.next;u.next=null,o===null?s=c:o.next=c,o=u;var y=e.alternate;y!==null&&(y=y.updateQueue,a=y.lastBaseUpdate,a!==o&&(a===null?y.firstBaseUpdate=c:a.next=c,y.lastBaseUpdate=u))}if(s!==null){var g=l.baseState;o=0,y=c=u=null,a=s;do{var m=a.lane,w=a.eventTime;if((r&m)===m){y!==null&&(y=y.next={eventTime:w,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var S=e,j=a;switch(m=t,w=n,j.tag){case 1:if(S=j.payload,typeof S=="function"){g=S.call(w,g,m);break e}g=S;break e;case 3:S.flags=S.flags&-65537|128;case 0:if(S=j.payload,m=typeof S=="function"?S.call(w,g,m):S,m==null)break e;g=te({},g,m);break e;case 2:vt=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,m=l.effects,m===null?l.effects=[a]:m.push(a))}else w={eventTime:w,lane:m,tag:a.tag,payload:a.payload,callback:a.callback,next:null},y===null?(c=y=w,u=g):y=y.next=w,o|=m;if(a=a.next,a===null){if(a=l.shared.pending,a===null)break;m=a,a=m.next,m.next=null,l.lastBaseUpdate=m,l.shared.pending=null}}while(!0);if(y===null&&(u=g),l.baseState=u,l.firstBaseUpdate=c,l.lastBaseUpdate=y,t=l.shared.interleaved,t!==null){l=t;do o|=l.lane,l=l.next;while(l!==t)}else s===null&&(l.shared.lanes=0);Kt|=o,e.lanes=o,e.memoizedState=g}}function Vo(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=rs.transition;rs.transition={};try{e(!1),t()}finally{J=n,rs.transition=r}}function Xu(){return He().memoizedState}function zf(e,t,n){var r=Tt(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},qu(e))Zu(t,n);else if(n=Ru(e,t,n,r),n!==null){var l=Se();qe(n,e,r,l),bu(n,t,r)}}function Rf(e,t,n){var r=Tt(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(qu(e))Zu(t,l);else{var s=e.alternate;if(e.lanes===0&&(s===null||s.lanes===0)&&(s=t.lastRenderedReducer,s!==null))try{var o=t.lastRenderedState,a=s(o,n);if(l.hasEagerState=!0,l.eagerState=a,Ze(a,o)){var u=t.interleaved;u===null?(l.next=l,Oi(t)):(l.next=u.next,u.next=l),t.interleaved=l;return}}catch{}finally{}n=Ru(e,t,l,r),n!==null&&(l=Se(),qe(n,e,r,l),bu(n,t,r))}}function qu(e){var t=e.alternate;return e===ee||t!==null&&t===ee}function Zu(e,t){Qn=ul=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function bu(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,xi(e,n)}}var cl={readContext:We,useCallback:me,useContext:me,useEffect:me,useImperativeHandle:me,useInsertionEffect:me,useLayoutEffect:me,useMemo:me,useReducer:me,useRef:me,useState:me,useDebugValue:me,useDeferredValue:me,useTransition:me,useMutableSource:me,useSyncExternalStore:me,useId:me,unstable_isNewReconciler:!1},Df={readContext:We,useCallback:function(e,t){return et().memoizedState=[e,t===void 0?null:t],e},useContext:We,useEffect:Ho,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Br(4194308,4,Qu.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Br(4194308,4,e,t)},useInsertionEffect:function(e,t){return Br(4,2,e,t)},useMemo:function(e,t){var n=et();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=et();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=zf.bind(null,ee,e),[r.memoizedState,e]},useRef:function(e){var t=et();return e={current:e},t.memoizedState=e},useState:Wo,useDebugValue:Wi,useDeferredValue:function(e){return et().memoizedState=e},useTransition:function(){var e=Wo(!1),t=e[0];return e=Lf.bind(null,e[1]),et().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=ee,l=et();if(Z){if(n===void 0)throw Error(_(407));n=n()}else{if(n=t(),ae===null)throw Error(_(349));Qt&30||Fu(r,t,n)}l.memoizedState=n;var s={value:n,getSnapshot:t};return l.queue=s,Ho(Iu.bind(null,r,s,e),[e]),r.flags|=2048,cr(9,Au.bind(null,r,s,n,t),void 0,null),n},useId:function(){var e=et(),t=ae.identifierPrefix;if(Z){var n=at,r=ot;n=(r&~(1<<32-Xe(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=ar++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(n,{is:r.is}):(e=o.createElement(n),n==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,n),e[tt]=t,e[sr]=r,uc(e,t,!1,!1),t.stateNode=e;e:{switch(o=Cs(n,r),n){case"dialog":G("cancel",e),G("close",e),l=r;break;case"iframe":case"object":case"embed":G("load",e),l=r;break;case"video":case"audio":for(l=0;lkn&&(t.flags|=128,r=!0,Rn(s,!1),t.lanes=4194304)}else{if(!r)if(e=al(o),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Rn(s,!0),s.tail===null&&s.tailMode==="hidden"&&!o.alternate&&!Z)return ge(t),null}else 2*re()-s.renderingStartTime>kn&&n!==1073741824&&(t.flags|=128,r=!0,Rn(s,!1),t.lanes=4194304);s.isBackwards?(o.sibling=t.child,t.child=o):(n=s.last,n!==null?n.sibling=o:t.child=o,s.last=o)}return s.tail!==null?(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=re(),t.sibling=null,n=b.current,Y(b,r?n&1|2:n&1),t):(ge(t),null);case 22:case 23:return Gi(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Le&1073741824&&(ge(t),t.subtreeFlags&6&&(t.flags|=8192)):ge(t),null;case 24:return null;case 25:return null}throw Error(_(156,t.tag))}function Bf(e,t){switch(Pi(t),t.tag){case 1:return Ee(t.type)&&tl(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return xn(),X(_e),X(ye),Ai(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Fi(t),null;case 13:if(X(b),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(_(340));yn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return X(b),null;case 4:return xn(),null;case 10:return Di(t.type._context),null;case 22:case 23:return Gi(),null;case 24:return null;default:return null}}var zr=!1,ve=!1,Vf=typeof WeakSet=="function"?WeakSet:Set,D=null;function an(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){ne(e,t,r)}else n.current=null}function Zs(e,t,n){try{n()}catch(r){ne(e,t,r)}}var ta=!1;function Wf(e,t){if($s=qr,e=gu(),Ei(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,s=r.focusNode;r=r.focusOffset;try{n.nodeType,s.nodeType}catch{n=null;break e}var o=0,a=-1,u=-1,c=0,y=0,g=e,m=null;t:for(;;){for(var w;g!==n||l!==0&&g.nodeType!==3||(a=o+l),g!==s||r!==0&&g.nodeType!==3||(u=o+r),g.nodeType===3&&(o+=g.nodeValue.length),(w=g.firstChild)!==null;)m=g,g=w;for(;;){if(g===e)break t;if(m===n&&++c===l&&(a=o),m===s&&++y===r&&(u=o),(w=g.nextSibling)!==null)break;g=m,m=g.parentNode}g=w}n=a===-1||u===-1?null:{start:a,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(Ms={focusedElem:e,selectionRange:n},qr=!1,D=t;D!==null;)if(t=D,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,D=e;else for(;D!==null;){t=D;try{var S=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(S!==null){var j=S.memoizedProps,O=S.memoizedState,f=t.stateNode,d=f.getSnapshotBeforeUpdate(t.elementType===t.type?j:Je(t.type,j),O);f.__reactInternalSnapshotBeforeUpdate=d}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(_(163))}}catch(x){ne(t,t.return,x)}if(e=t.sibling,e!==null){e.return=t.return,D=e;break}D=t.return}return S=ta,ta=!1,S}function Kn(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 s=l.destroy;l.destroy=void 0,s!==void 0&&Zs(t,n,s)}l=l.next}while(l!==r)}}function Cl(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 bs(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 fc(e){var t=e.alternate;t!==null&&(e.alternate=null,fc(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[tt],delete t[sr],delete t[Is],delete t[Cf],delete t[_f])),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 pc(e){return e.tag===5||e.tag===3||e.tag===4}function na(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||pc(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 ei(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=el));else if(r!==4&&(e=e.child,e!==null))for(ei(e,t,n),e=e.sibling;e!==null;)ei(e,t,n),e=e.sibling}function ti(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(ti(e,t,n),e=e.sibling;e!==null;)ti(e,t,n),e=e.sibling}var fe=null,Ye=!1;function mt(e,t,n){for(n=n.child;n!==null;)hc(e,t,n),n=n.sibling}function hc(e,t,n){if(nt&&typeof nt.onCommitFiberUnmount=="function")try{nt.onCommitFiberUnmount(vl,n)}catch{}switch(n.tag){case 5:ve||an(n,t);case 6:var r=fe,l=Ye;fe=null,mt(e,t,n),fe=r,Ye=l,fe!==null&&(Ye?(e=fe,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):fe.removeChild(n.stateNode));break;case 18:fe!==null&&(Ye?(e=fe,n=n.stateNode,e.nodeType===8?es(e.parentNode,n):e.nodeType===1&&es(e,n),er(e)):es(fe,n.stateNode));break;case 4:r=fe,l=Ye,fe=n.stateNode.containerInfo,Ye=!0,mt(e,t,n),fe=r,Ye=l;break;case 0:case 11:case 14:case 15:if(!ve&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var s=l,o=s.destroy;s=s.tag,o!==void 0&&(s&2||s&4)&&Zs(n,t,o),l=l.next}while(l!==r)}mt(e,t,n);break;case 1:if(!ve&&(an(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){ne(n,t,a)}mt(e,t,n);break;case 21:mt(e,t,n);break;case 22:n.mode&1?(ve=(r=ve)||n.memoizedState!==null,mt(e,t,n),ve=r):mt(e,t,n);break;default:mt(e,t,n)}}function ra(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Vf),t.forEach(function(r){var l=Zf.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function Ke(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=o),r&=~s}if(r=l,r=re()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Qf(r/1960))-r,10e?16:e,St===null)var r=!1;else{if(e=St,St=null,pl=0,W&6)throw Error(_(331));var l=W;for(W|=4,D=e.current;D!==null;){var s=D,o=s.child;if(D.flags&16){var a=s.deletions;if(a!==null){for(var u=0;ure()-Ji?Bt(e,0):Ki|=n),Te(e,t)}function kc(e,t){t===0&&(e.mode&1?(t=kr,kr<<=1,!(kr&130023424)&&(kr=4194304)):t=1);var n=Se();e=ft(e,t),e!==null&&(pr(e,t,n),Te(e,n))}function qf(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),kc(e,n)}function Zf(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(_(314))}r!==null&&r.delete(t),kc(e,n)}var jc;jc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||_e.current)Ce=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Ce=!1,If(e,t,n);Ce=!!(e.flags&131072)}else Ce=!1,Z&&t.flags&1048576&&Eu(t,ll,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Vr(e,t),e=t.pendingProps;var l=vn(t,ye.current);hn(t,n),l=Ui(null,t,r,e,l,n);var s=Bi();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,Ee(r)?(s=!0,nl(t)):s=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,$i(t),l.updater=Nl,t.stateNode=l,l._reactInternals=t,Qs(t,r,e,n),t=Ys(null,t,r,!0,s,n)):(t.tag=0,Z&&s&&Ti(t),xe(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Vr(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=ep(r),e=Je(r,e),l){case 0:t=Js(null,t,r,e,n);break e;case 1:t=Zo(null,t,r,e,n);break e;case 11:t=Xo(null,t,r,e,n);break e;case 14:t=qo(null,t,r,Je(r.type,e),n);break e}throw Error(_(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Je(r,l),Js(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Je(r,l),Zo(e,t,r,l,n);case 3:e:{if(ic(t),e===null)throw Error(_(387));r=t.pendingProps,s=t.memoizedState,l=s.element,Du(e,t),ol(t,r,null,n);var o=t.memoizedState;if(r=o.element,s.isDehydrated)if(s={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=s,t.memoizedState=s,t.flags&256){l=Sn(Error(_(423)),t),t=bo(e,t,r,n,l);break e}else if(r!==l){l=Sn(Error(_(424)),t),t=bo(e,t,r,n,l);break e}else for(ze=Ct(t.stateNode.containerInfo.firstChild),Re=t,Z=!0,Ge=null,n=zu(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(yn(),r===l){t=pt(e,t,n);break e}xe(e,t,r,n)}t=t.child}return t;case 5:return Ou(t),e===null&&Vs(t),r=t.type,l=t.pendingProps,s=e!==null?e.memoizedProps:null,o=l.children,Fs(r,l)?o=null:s!==null&&Fs(r,s)&&(t.flags|=32),sc(e,t),xe(e,t,o,n),t.child;case 6:return e===null&&Vs(t),null;case 13:return oc(e,t,n);case 4:return Mi(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=wn(t,null,r,n):xe(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Je(r,l),Xo(e,t,r,l,n);case 7:return xe(e,t,t.pendingProps,n),t.child;case 8:return xe(e,t,t.pendingProps.children,n),t.child;case 12:return xe(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,s=t.memoizedProps,o=l.value,Y(sl,r._currentValue),r._currentValue=o,s!==null)if(Ze(s.value,o)){if(s.children===l.children&&!_e.current){t=pt(e,t,n);break e}}else for(s=t.child,s!==null&&(s.return=t);s!==null;){var a=s.dependencies;if(a!==null){o=s.child;for(var u=a.firstContext;u!==null;){if(u.context===r){if(s.tag===1){u=ut(-1,n&-n),u.tag=2;var c=s.updateQueue;if(c!==null){c=c.shared;var y=c.pending;y===null?u.next=u:(u.next=y.next,y.next=u),c.pending=u}}s.lanes|=n,u=s.alternate,u!==null&&(u.lanes|=n),Ws(s.return,n,t),a.lanes|=n;break}u=u.next}}else if(s.tag===10)o=s.type===t.type?null:s.child;else if(s.tag===18){if(o=s.return,o===null)throw Error(_(341));o.lanes|=n,a=o.alternate,a!==null&&(a.lanes|=n),Ws(o,n,t),o=s.sibling}else o=s.child;if(o!==null)o.return=s;else for(o=s;o!==null;){if(o===t){o=null;break}if(s=o.sibling,s!==null){s.return=o.return,o=s;break}o=o.return}s=o}xe(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,hn(t,n),l=We(l),r=r(l),t.flags|=1,xe(e,t,r,n),t.child;case 14:return r=t.type,l=Je(r,t.pendingProps),l=Je(r.type,l),qo(e,t,r,l,n);case 15:return rc(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Je(r,l),Vr(e,t),t.tag=1,Ee(r)?(e=!0,nl(t)):e=!1,hn(t,n),ec(t,r,l),Qs(t,r,l,n),Ys(null,t,r,!0,e,n);case 19:return ac(e,t,n);case 22:return lc(e,t,n)}throw Error(_(156,t.tag))};function Nc(e,t){return qa(e,t)}function bf(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 Be(e,t,n,r){return new bf(e,t,n,r)}function qi(e){return e=e.prototype,!(!e||!e.isReactComponent)}function ep(e){if(typeof e=="function")return qi(e)?1:0;if(e!=null){if(e=e.$$typeof,e===gi)return 11;if(e===vi)return 14}return 2}function Pt(e,t){var n=e.alternate;return n===null?(n=Be(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 Qr(e,t,n,r,l,s){var o=2;if(r=e,typeof e=="function")qi(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case Zt:return Vt(n.children,l,s,t);case mi:o=8,l|=8;break;case ms:return e=Be(12,n,t,l|2),e.elementType=ms,e.lanes=s,e;case gs:return e=Be(13,n,t,l),e.elementType=gs,e.lanes=s,e;case vs:return e=Be(19,n,t,l),e.elementType=vs,e.lanes=s,e;case Oa:return El(n,l,s,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Ra:o=10;break e;case Da:o=9;break e;case gi:o=11;break e;case vi:o=14;break e;case gt:o=16,r=null;break e}throw Error(_(130,e==null?e:typeof e,""))}return t=Be(o,n,t,l),t.elementType=e,t.type=r,t.lanes=s,t}function Vt(e,t,n,r){return e=Be(7,e,r,t),e.lanes=n,e}function El(e,t,n,r){return e=Be(22,e,r,t),e.elementType=Oa,e.lanes=n,e.stateNode={isHidden:!1},e}function as(e,t,n){return e=Be(6,e,null,t),e.lanes=n,e}function us(e,t,n){return t=Be(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function tp(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=Wl(0),this.expirationTimes=Wl(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Wl(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Zi(e,t,n,r,l,s,o,a,u){return e=new tp(e,t,n,a,u),t===1?(t=1,s===!0&&(t|=8)):t=0,s=Be(3,null,null,t),e.current=s,s.stateNode=e,s.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},$i(s),e}function np(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Tc)}catch(e){console.error(e)}}Tc(),Ta.exports=Oe;var op=Ta.exports,Pc,da=op;Pc=da.createRoot,da.hydrateRoot;async function ue(e){const t=await fetch(e);if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);return t.json()}async function ap(){return ue("/api/archives")}async function up(e){return ue(`/api/archives/${e}/entries`)}async function cp(e,t,n){const r=new URLSearchParams;return t&&r.set("q",t),n&&r.set("tag",n),ue(`/api/archives/${e}/entries/search?${r}`)}async function dp(e,t){return ue(`/api/archives/${e}/entries/${t}`)}async function fp(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 cs(e,t){return ue(`/api/archives/${e}/entries/${t}/tags`)}async function pp(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 hp(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 mp(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 gp(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 vp(e,t){const n=await fetch(`/api/archives/${e}/tags/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(await n.text())}async function fa(e){return ue(`/api/archives/${e}/runs`)}async function ds(e){return ue(`/api/archives/${e}/tags`)}async function yp(e,t,n=null){const r={locator:t};n&&n!=="best"&&(r.quality=n);const l=await fetch(`/api/archives/${e}/captures`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!l.ok){const s=await l.json().catch(()=>({}));throw new Error(s.error||`HTTP ${l.status}`)}return l.json()}async function wp(e,t){return ue(`/api/archives/${e}/captures/probe?locator=${encodeURIComponent(t)}`)}async function xp(e,t){return ue(`/api/archives/${e}/capture_jobs/${t}`)}async function Sp(){return(await(await fetch("/api/auth/setup")).json()).setup_required===!0}async function kp(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 jp(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 Np(){await fetch("/api/auth/logout",{method:"POST"})}async function Cp(){const e=await fetch("/api/auth/me");return e.status===401?null:e.json()}async function _p(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 Ep(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 Tp(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 Pp(){return ue("/api/auth/tokens")}async function Lp(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 zp(e){const t=await fetch(`/api/auth/tokens/${e}`,{method:"DELETE"});if(!t.ok)throw new Error(await t.text())}async function Rp(){return ue("/api/admin/instance-settings")}async function Dp(e){const t=await fetch("/api/admin/instance-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function Op(){return ue("/api/admin/users")}async function $p(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 Mp(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 Fp(){return ue("/api/admin/roles")}async function Ap(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 Ip(e){return ue(`/api/archives/${e}/collections`)}async function Up(e,t,n,r=2){const l=await fetch(`/api/archives/${e}/collections`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:t,slug:n,default_visibility_bits:r})});if(!l.ok){const s=await l.json().catch(()=>({error:l.statusText}));throw new Error(s.error||l.statusText)}return l.json()}async function Bp(e,t){return ue(`/api/archives/${e}/collections/${t}`)}async function Vp(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 s=await l.json().catch(()=>({error:l.statusText}));throw new Error(s.error||l.statusText)}}async function Wp(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 Hp(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 s=await l.json().catch(()=>({error:l.statusText}));throw new Error(s.error||l.statusText)}}async function Qp(e,t){return ue(`/api/archives/${e}/entries/${t}/collections`)}async function pa(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 Kp(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 Jp(e){return ue(`/api/archives/${e}/blob-cleanup`)}async function Yp(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 Gp(){return ue("/api/admin/cookie-rules")}async function Xp(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 qp(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 Zp(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}`)}}const bp=window.fetch;window.fetch=async(...e)=>{var n;const t=await bp(...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 eh({onLogin:e}){const[t,n]=v.useState(""),[r,l]=v.useState(""),[s,o]=v.useState(null),[a,u]=v.useState(!1);async function c(y){y.preventDefault(),o(null),u(!0);try{const g=await jp(t,r);e(g)}catch(g){o(g.message)}finally{u(!1)}}return i.jsx("div",{className:"login-page",children:i.jsxs("div",{className:"login-card",children:[i.jsx("h1",{className:"login-brand",children:"Archivr"}),i.jsx("p",{className:"login-tagline",children:"Sign in to your archive"}),i.jsxs("form",{onSubmit:c,children:[i.jsxs("div",{className:"login-field",children:[i.jsx("label",{className:"login-label",htmlFor:"login-username",children:"Username"}),i.jsx("input",{className:"login-input",id:"login-username",type:"text",value:t,onChange:y=>n(y.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),i.jsxs("div",{className:"login-field",children:[i.jsx("label",{className:"login-label",htmlFor:"login-password",children:"Password"}),i.jsx("input",{className:"login-input",id:"login-password",type:"password",value:r,onChange:y=>l(y.target.value),required:!0,autoComplete:"current-password"})]}),s&&i.jsx("p",{className:"login-error",children:s}),i.jsx("button",{className:"login-submit",type:"submit",disabled:a,children:a?"Signing in…":"Sign in"})]})]})})}function th({onComplete:e}){const[t,n]=v.useState(""),[r,l]=v.useState(""),[s,o]=v.useState(""),[a,u]=v.useState(null),[c,y]=v.useState(!1);async function g(m){if(m.preventDefault(),r!==s){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 kp(t,r),e()}catch(w){u(w.message)}finally{y(!1)}}return i.jsx("div",{className:"setup-page",children:i.jsxs("div",{className:"setup-card",children:[i.jsx("h1",{className:"setup-brand",children:"Archivr"}),i.jsx("p",{className:"setup-tagline",children:"Create your owner account to get started."}),i.jsxs("form",{onSubmit:g,children:[i.jsxs("div",{className:"setup-field",children:[i.jsx("label",{className:"setup-label",htmlFor:"setup-username",children:"Username"}),i.jsx("input",{className:"setup-input",id:"setup-username",type:"text",value:t,onChange:m=>n(m.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),i.jsxs("div",{className:"setup-field",children:[i.jsx("label",{className:"setup-label",htmlFor:"setup-password",children:"Password"}),i.jsx("input",{className:"setup-input",id:"setup-password",type:"password",value:r,onChange:m=>l(m.target.value),required:!0,autoComplete:"new-password"})]}),i.jsxs("div",{className:"setup-field",children:[i.jsx("label",{className:"setup-label",htmlFor:"setup-confirm",children:"Confirm password"}),i.jsx("input",{className:"setup-input",id:"setup-confirm",type:"password",value:s,onChange:m=>o(m.target.value),required:!0,autoComplete:"new-password"})]}),a&&i.jsx("p",{className:"setup-error",children:a}),i.jsx("button",{className:"setup-submit",type:"submit",disabled:c,children:c?"Creating account…":"Create account"})]})]})})}function nh({archives:e,archiveId:t,onArchiveChange:n,view:r,onViewChange:l,onCaptureClick:s}){const{currentUser:o,setCurrentUser:a}=v.useContext(Rl)??{},[u,c]=v.useState(!1);async function y(){c(!0),await Np(),a(null),window.location.reload()}return i.jsxs("header",{className:"topbar",children:[i.jsx("div",{className:"brand",children:"Archivr"}),i.jsx("div",{className:"switcher",children:i.jsx("select",{"aria-label":"Select archive",value:t??"",onChange:g=>n(g.target.value),children:e.map(g=>i.jsx("option",{value:g.id,children:g.label},g.id))})}),i.jsx("nav",{className:"nav","aria-label":"Primary",children:["archive","tags","collections","runs","admin","settings"].map(g=>i.jsx("button",{className:`nav-link${r===g?" is-active":""}`,onClick:()=>l(g),children:g.charAt(0).toUpperCase()+g.slice(1)},g))}),i.jsx("button",{className:"capture-button",onClick:s,children:"Capture"}),o&&i.jsxs("div",{className:"user-menu",children:[i.jsx("span",{className:"user-name",children:o.display_name||o.username}),i.jsx("button",{className:"logout-btn",onClick:y,disabled:u,children:u?"Logging out…":"Log out"})]})]})}let ii=1;function Lc(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/")}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 On(e=""){return{id:ii++,locator:e,quality:"best",probeState:"idle",probeQualities:null,probeHasAudio:!1,status:"idle",error:null,jobUid:null,archiveId:null}}function ha(e){return e.some(t=>t.status==="submitting"||t.status==="running")}function rh({open:e,archiveId:t,onClose:n,onCaptured:r,onToast:l}){const s=v.useRef(null),o=v.useRef(!0),a=v.useRef(new Map),u=v.useRef(new Map),c=v.useRef(t);v.useEffect(()=>{c.current=t},[t]);const y=v.useRef(r),g=v.useRef(l);v.useEffect(()=>{y.current=r},[r]),v.useEffect(()=>{g.current=l},[l]);const[m,w]=v.useState(()=>{try{const p=JSON.parse(sessionStorage.getItem("captureItems")||"null");if(Array.isArray(p)&&p.length>0)return p.forEach(N=>{N.id>=ii&&(ii=N.id+1)}),p}catch{}return[On()]});v.useEffect(()=>{sessionStorage.setItem("captureItems",JSON.stringify(m))},[m]),v.useEffect(()=>{["captureDialogLocator","captureDialogError","captureDialogBusy","captureDialogJobStatus","captureDialogJobUid"].forEach(p=>sessionStorage.removeItem(p)),w(p=>p.map(N=>N.status==="submitting"?{...N,status:"idle",error:null}:N)),m.forEach(p=>{p.status==="running"&&p.jobUid&&p.archiveId&&!a.current.has(p.jobUid)&&S(p.id,p.jobUid,p.locator,p.archiveId)})},[]),v.useEffect(()=>{const p=s.current;if(!p)return;const N=()=>{u.current.forEach(T=>clearTimeout(T)),u.current.clear(),n()};return p.addEventListener("close",N),()=>p.removeEventListener("close",N)},[n]),v.useEffect(()=>{const p=s.current;p&&(e?(!o.current&&!ha(m)&&w([On()]),o.current=!1,p.open||p.showModal()):(u.current.forEach(N=>clearTimeout(N)),u.current.clear(),p.open&&p.close()))},[e]),v.useEffect(()=>()=>{a.current.forEach(p=>clearInterval(p)),u.current.forEach(p=>clearTimeout(p))},[]);function S(p,N,T,I){if(a.current.has(N))return;const U=setInterval(async()=>{try{const P=await xp(I,N);if(P.status==="completed")clearInterval(a.current.get(N)),a.current.delete(N),w(F=>F.map(H=>H.id===p?{...H,status:"completed"}:H)),setTimeout(()=>{w(F=>{const H=F.filter(q=>q.id!==p);return H.length===0?[On()]:H})},1400),y.current();else if(P.status==="failed"){clearInterval(a.current.get(N)),a.current.delete(N);const F=P.error_text||"Capture failed.";w(H=>H.map(q=>q.id===p?{...q,status:"failed",error:F}:q)),g.current(F,T)}}catch(P){clearInterval(a.current.get(N)),a.current.delete(N);const F=P.message||"Network error";w(H=>H.map(q=>q.id===p?{...q,status:"failed",error:F}:q)),g.current(F,T)}},500);a.current.set(N,U)}async function j(p){if(!p.locator.trim())return;const N=t,T=p.locator.trim(),I=p.quality||"best";w(U=>U.map(P=>P.id===p.id?{...P,status:"submitting",error:null}:P));try{const U=await yp(N,T,I);w(P=>P.map(F=>F.id===p.id?{...F,status:"running",jobUid:U.job_uid,archiveId:N}:F)),S(p.id,U.job_uid,T,N)}catch(U){const P=U.message||"Submission failed.";w(F=>F.map(H=>H.id===p.id?{...H,status:"failed",error:P}:H)),g.current(P,T)}}function O(){m.filter(N=>N.status==="idle"&&N.locator.trim()).forEach(N=>j(N))}function f(){w(p=>[...p,On()])}function d(p){clearTimeout(u.current.get(p)),u.current.delete(p),w(N=>{const T=N.filter(I=>I.id!==p);return T.length===0?[On()]:T})}function h(p){w(N=>N.map(T=>T.id===p?{...T,status:"idle",error:null}:T))}function x(p,N){if(clearTimeout(u.current.get(p)),w(I=>I.map(U=>U.id===p?{...U,locator:N,probeState:"idle",probeQualities:null,probeHasAudio:!1,quality:"best"}:U)),!Lc(N))return;const T=setTimeout(async()=>{u.current.delete(p),w(I=>I.map(U=>U.id===p?{...U,probeState:"probing"}:U));try{const I=await wp(c.current,N.trim());w(U=>U.map(P=>{if(P.id!==p||P.locator!==N)return P;const F=I.qualities??[],H=I.has_audio??!1,q=F.length===0&&H?"audio":"best";return{...P,probeState:"done",probeQualities:F,probeHasAudio:H,quality:q}}))}catch{w(I=>I.map(U=>U.id===p?{...U,probeState:"idle",probeQualities:null}:U))}},600);u.current.set(p,T)}function k(p,N){w(T=>T.map(I=>I.id===p?{...I,quality:N}:I))}const E=m.filter(p=>p.status==="idle"&&p.locator.trim()).length,L=ha(m);return i.jsx("dialog",{ref:s,className:"capture-dialog",children:i.jsxs("div",{className:"capture-dialog-inner",children:[i.jsxs("div",{className:"capture-dialog-header",children:[i.jsx("h2",{className:"capture-dialog-title",children:"Capture"}),i.jsx("button",{type:"button",className:"capture-dialog-close",onClick:()=>{var p;return(p=s.current)==null?void 0:p.close()},"aria-label":"Close",children:i.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[i.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),i.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),i.jsx("div",{className:"capture-rows",children:m.map((p,N)=>i.jsx(lh,{item:p,autoFocus:N===m.length-1&&p.status==="idle",onLocatorChange:T=>x(p.id,T),onQualityChange:T=>k(p.id,T),onRemove:()=>d(p.id),onReset:()=>h(p.id),onSubmit:O},p.id))}),i.jsxs("button",{type:"button",className:"capture-add-row",onClick:f,children:[i.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[i.jsx("line",{x1:"8",y1:"2",x2:"8",y2:"14"}),i.jsx("line",{x1:"2",y1:"8",x2:"14",y2:"8"})]}),"Add another"]}),i.jsxs("div",{className:"capture-actions",children:[i.jsx("button",{type:"button",className:"capture-cancel",onClick:()=>{var p;return(p=s.current)==null?void 0:p.close()},children:L?"Close":"Cancel"}),i.jsx("button",{type:"button",className:"capture-submit",onClick:O,disabled:E===0,children:E>1?`Archive ${E}`:"Archive"})]})]})})}function lh({item:e,autoFocus:t,onLocatorChange:n,onQualityChange:r,onRemove:l,onReset:s,onSubmit:o}){const a=v.useRef(null),u=e.status==="submitting"||e.status==="running";v.useEffect(()=>{var y;t&&e.status==="idle"&&((y=a.current)==null||y.focus())},[t]);const c=(()=>{if(e.status==="completed"||u||!Lc(e.locator))return null;if(e.probeState==="probing")return i.jsx("span",{className:"capture-quality-probing","aria-label":"Checking available qualities",children:"…"});if(e.probeState==="done"){const y=e.probeQualities??[],g=e.probeHasAudio??!1;return y.length===0&&!g?i.jsx("span",{className:"capture-quality-hint",children:"No media detected"}):y.length===0&&g?i.jsx("select",{className:"capture-quality",value:"audio",onChange:m=>r(m.target.value),"aria-label":"Video quality",children:i.jsx("option",{value:"audio",children:"Audio only"})}):i.jsxs("select",{className:"capture-quality",value:e.quality||"best",onChange:m=>r(m.target.value),"aria-label":"Video quality",children:[i.jsx("option",{value:"best",children:"Best quality"}),y.map(m=>i.jsx("option",{value:m,children:m},m)),g&&i.jsx("option",{value:"audio",children:"Audio only"})]})}return null})();return i.jsxs("div",{className:`capture-row capture-row--${e.status}`,children:[i.jsxs("div",{className:"capture-row-main",children:[i.jsx(sh,{status:e.status}),i.jsx("input",{ref:a,className:"capture-input",type:"text",placeholder:"https://… · yt:ID · ytm:ID · tweet:ID · x:ID",value:e.locator,onChange:y=>n(y.target.value),onKeyDown:y=>{y.key==="Enter"&&o()},disabled:u||e.status==="completed",autoComplete:"off",spellCheck:!1}),c,e.status==="failed"&&i.jsx("button",{type:"button",className:"capture-row-action",onClick:s,title:"Retry",children:i.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("path",{d:"M13 2.5A7 7 0 1 1 6.5 1"}),i.jsx("polyline",{points:"6.5 1 4 3.5 6.5 6"})]})}),!u&&e.status!=="completed"&&e.status!=="failed"&&i.jsx("button",{type:"button",className:"capture-row-action capture-row-remove",onClick:l,"aria-label":"Remove",children:i.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[i.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),i.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),e.error&&i.jsx("p",{className:"capture-row-error",children:e.error})]})}function sh({status:e}){return e==="submitting"||e==="running"?i.jsx("span",{className:"cap-dot cap-dot--running","aria-label":"Running",children:i.jsx("span",{className:"cap-spinner"})}):e==="completed"?i.jsx("span",{className:"cap-dot cap-dot--ok","aria-label":"Done",children:"✓"}):e==="failed"?i.jsx("span",{className:"cap-dot cap-dot--err","aria-label":"Failed",children:"✕"}):i.jsx("span",{className:"cap-dot cap-dot--idle","aria-hidden":"true"})}function oi(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 Ut(e){return ih(e)??""}function zc(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 ma={youtube:'',youtube_music:'',spotify:'',x:'',instagram:'',facebook:'',tiktok:'',reddit:'',snapchat:'',local:'',web:'',other:'?'};function Rc(e){return ma[e]??ma.other}function Dc(e){return e.split("/").map(t=>t?t.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"").join("/")}function oh({entry:e,archiveId:t,isSelected:n,onSelect:r}){const[l,s]=v.useState(!1),a=e.source_kind==="web"&&e.entity_kind==="page"&&e.has_favicon&&t&&!l?i.jsx("img",{src:`/api/archives/${t}/entries/${e.entry_uid}/favicon`,width:"16",height:"16",alt:"",onError:()=>s(!0),style:{objectFit:"contain"}}):i.jsx("span",{dangerouslySetInnerHTML:{__html:Rc(e.source_kind)}});return i.jsxs("div",{className:n?"is-selected":void 0,tabIndex:0,"data-entry-uid":e.entry_uid,onClick:r,onKeyDown:u=>{u.key==="Enter"&&r()},children:[i.jsx("div",{className:"col-added",children:zc(e.archived_at)}),i.jsxs("div",{className:"col-title",children:[i.jsx("span",{className:"source-icon",children:a}),i.jsx("span",{className:"entry-title",children:Ut(e.title)||Ut(e.entry_uid)})]}),i.jsx("div",{className:"col-type",children:i.jsx("span",{className:"type-pill",children:Ut(e.entity_kind)})}),i.jsxs("div",{className:"col-size",children:[i.jsx("span",{className:"size-total",children:oi(e.total_artifact_bytes)}),e.cached_bytes>0&&e.total_artifact_bytes>0&&i.jsxs("span",{className:"size-cached-pct",title:`${oi(e.cached_bytes)} already on disk from an earlier entry`,children:[Math.round(e.cached_bytes/e.total_artifact_bytes*100),"% cached"]})]}),i.jsx("div",{className:"url-cell col-url",children:Ut(e.original_url)})]})}function ah({entries:e,selectedEntryUid:t,onSelectEntry:n,archiveId:r}){return i.jsx("section",{id:"archive-view",className:"view is-active",children:i.jsxs("div",{className:"entry-table",children:[i.jsxs("div",{className:"entry-header-row",children:[i.jsx("div",{className:"col-added",children:"Added"}),i.jsx("div",{className:"col-title",children:"Title"}),i.jsx("div",{className:"col-type",children:"Type"}),i.jsx("div",{className:"col-size",children:"Size"}),i.jsx("div",{className:"col-url",children:"Original URL"})]}),i.jsx("div",{id:"entries-body",children:e.map(l=>i.jsx(oh,{entry:l,archiveId:r,isSelected:l.entry_uid===t,onSelect:()=>n(l)},l.entry_uid))})]})})}function uh(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 ch({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 i.jsx("span",{className:`run-status ${t}`,children:n})}function dh({runs:e}){const[t,n]=v.useState(null);function r(l){n(s=>s===l?null:l)}return i.jsx("section",{id:"runs-view",className:"view is-active",children:i.jsxs("table",{className:"entry-table",children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Started"}),i.jsx("th",{children:"Status"}),i.jsx("th",{children:"Requested"}),i.jsx("th",{children:"Completed"}),i.jsx("th",{children:"Failed"})]})}),i.jsx("tbody",{children:e.length===0?i.jsx("tr",{children:i.jsx("td",{colSpan:5,style:{color:"var(--muted)",padding:"24px 16px",textAlign:"center"},children:"No runs yet."})}):e.map(l=>{const s=l.status==="failed"&&l.error_summary,o=t===l.run_uid;return[i.jsxs("tr",{className:s?"run-row run-row--failed":"run-row",onClick:s?()=>r(l.run_uid):void 0,title:s?o?"Click to hide error":"Click to view error":void 0,children:[i.jsx("td",{children:uh(l.started_at)}),i.jsxs("td",{children:[i.jsx(ch,{status:l.status}),s&&i.jsx("span",{className:"run-expand-hint","aria-hidden":"true",children:o?"▴":"▾"})]}),i.jsx("td",{children:l.requested_count??"—"}),i.jsx("td",{children:l.completed_count??"—"}),i.jsx("td",{children:l.failed_count??"—"})]},l.run_uid),s&&o&&i.jsx("tr",{className:"run-error-row",children:i.jsx("td",{colSpan:5,children:i.jsx("pre",{className:"run-error-detail",children:l.error_summary})})},`${l.run_uid}-detail`)]})})]})})}const fh=4;function ph({archives:e}){const{currentUser:t}=v.useContext(Rl)??{},n=t&&(t.role_bits&fh)!==0,[r,l]=v.useState("users"),[s,o]=v.useState([]),[a,u]=v.useState([]),[c,y]=v.useState(!1),[g,m]=v.useState(null),[w,S]=v.useState(""),[j,O]=v.useState(""),[f,d]=v.useState(""),[h,x]=v.useState(null),[k,E]=v.useState(!1),[L,p]=v.useState(""),[N,T]=v.useState(""),[I,U]=v.useState(null),[P,F]=v.useState(!1),H=v.useCallback(async()=>{if(n){y(!0),m(null);try{const[C,M]=await Promise.all([Op(),Fp()]);o(C),u(M)}catch(C){m(C.message)}finally{y(!1)}}},[n]);v.useEffect(()=>{H()},[H]);async function q(C){const M=C.status==="active"?"disabled":"active";try{await Mp(C.user_uid,M),o(Q=>Q.map(A=>A.user_uid===C.user_uid?{...A,status:M}:A))}catch(Q){m(Q.message)}}async function Me(C){if(C.preventDefault(),!w.trim()||!j){x("Username and password required");return}E(!0),x(null);try{await $p(w.trim(),j,f.trim()||void 0),S(""),O(""),d(""),await H()}catch(M){x(M.message)}finally{E(!1)}}async function z(C){if(C.preventDefault(),!L.trim()||!N.trim()){U("Slug and name required");return}F(!0),U(null);try{await Ap(L.trim(),N.trim()),p(""),T(""),await H()}catch(M){U(M.message)}finally{F(!1)}}return n?i.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[i.jsx("h1",{children:"Admin"}),i.jsxs("div",{className:"view-tabs",children:[i.jsx("button",{className:`view-tab${r==="users"?" is-active":""}`,onClick:()=>l("users"),children:"Users"}),i.jsx("button",{className:`view-tab${r==="roles"?" is-active":""}`,onClick:()=>l("roles"),children:"Roles"}),i.jsx("button",{className:`view-tab${r==="archives"?" is-active":""}`,onClick:()=>l("archives"),children:"Archives"})]}),g&&i.jsx("div",{className:"form-msg form-msg--err",children:g}),r==="users"&&i.jsxs("div",{className:"admin-section",children:[i.jsx("h2",{children:"Users"}),c?i.jsx("p",{className:"muted",children:"Loading…"}):i.jsxs("table",{className:"admin-table",children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Username"}),i.jsx("th",{children:"Email"}),i.jsx("th",{children:"Roles"}),i.jsx("th",{children:"Status"}),i.jsx("th",{children:"Actions"})]})}),i.jsx("tbody",{children:s.map(C=>i.jsxs("tr",{className:C.status==="disabled"?"admin-row-disabled":"",children:[i.jsx("td",{children:C.username}),i.jsx("td",{className:"muted",children:C.email||"—"}),i.jsx("td",{children:C.role_slugs.join(", ")||"—"}),i.jsx("td",{children:i.jsx("span",{className:`status-badge status-${C.status}`,children:C.status})}),i.jsx("td",{children:i.jsx("button",{className:"admin-action-btn",onClick:()=>q(C),children:C.status==="active"?"Ban":"Unban"})})]},C.user_uid))})]}),i.jsx("h3",{children:"Create User"}),i.jsxs("form",{className:"admin-form",onSubmit:Me,children:[i.jsx("input",{className:"admin-input",placeholder:"Username",value:w,onChange:C=>S(C.target.value),required:!0}),i.jsx("input",{className:"admin-input",type:"password",placeholder:"Password (min 8 chars)",value:j,onChange:C=>O(C.target.value),required:!0}),i.jsx("input",{className:"admin-input",type:"email",placeholder:"Email (optional)",value:f,onChange:C=>d(C.target.value)}),h&&i.jsx("div",{className:"form-msg form-msg--err",children:h}),i.jsx("button",{className:"btn-primary",type:"submit",disabled:k,children:k?"Creating…":"Create User"})]})]}),r==="roles"&&i.jsxs("div",{className:"admin-section",children:[i.jsx("h2",{children:"Roles"}),c?i.jsx("p",{className:"muted",children:"Loading…"}):i.jsxs("table",{className:"admin-table",children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Slug"}),i.jsx("th",{children:"Name"}),i.jsx("th",{children:"Level"}),i.jsx("th",{children:"Bit"}),i.jsx("th",{children:"Built-in"})]})}),i.jsx("tbody",{children:a.map(C=>i.jsxs("tr",{children:[i.jsx("td",{children:i.jsx("code",{children:C.slug})}),i.jsx("td",{children:C.name}),i.jsx("td",{children:C.level}),i.jsx("td",{children:C.bit_position}),i.jsx("td",{children:C.is_builtin?"✓":""})]},C.role_uid))})]}),i.jsx("h3",{children:"Create Custom Role"}),i.jsxs("form",{className:"admin-form",onSubmit:z,children:[i.jsx("input",{className:"admin-input",placeholder:"Slug (e.g. moderator)",value:L,onChange:C=>p(C.target.value),required:!0}),i.jsx("input",{className:"admin-input",placeholder:"Display Name (e.g. Moderator)",value:N,onChange:C=>T(C.target.value),required:!0}),I&&i.jsx("div",{className:"form-msg form-msg--err",children:I}),i.jsx("button",{className:"btn-primary",type:"submit",disabled:P,children:P?"Creating…":"Create Role"})]})]}),r==="archives"&&i.jsxs("div",{className:"admin-section",children:[i.jsx("h2",{children:"Mounted Archives"}),i.jsx("div",{className:"admin-list",children:e.map(C=>i.jsxs("div",{className:"admin-archive",children:[i.jsx("strong",{children:C.label}),i.jsx("div",{className:"muted",children:C.archive_path})]},C.id))})]})]}):i.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[i.jsx("h1",{children:"Admin"}),i.jsx("p",{className:"muted",children:"You need admin privileges to access this panel."}),i.jsx("h2",{children:"Mounted Archives"}),i.jsx("div",{className:"admin-list",children:e.map(C=>i.jsxs("div",{className:"admin-archive",children:[i.jsx("strong",{children:C.label}),i.jsx("div",{className:"muted",children:C.archive_path})]},C.id))})]})}function Oc({node:e,archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:s,onTagDeleted:o,onTagsRefresh:a,humanizeTags:u}){var x;const c=n===e.tag.full_path,[y,g]=v.useState(!1),[m,w]=v.useState(""),S=v.useRef(!1);function j(){if(y)return;const k=c?null:e.tag.full_path;r(k),l("archive")}function O(k){k.stopPropagation(),w(e.tag.slug),g(!0)}async function f(){const k=m.trim();if(!k||k===e.tag.slug){g(!1);return}try{const E=await gp(t,e.tag.tag_uid,k);s(e.tag.full_path,E.full_path),a()}catch{}finally{g(!1)}}async function d(k){var L;k.stopPropagation();const E=((L=e.children)==null?void 0:L.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(E))try{await vp(t,e.tag.tag_uid),o(e.tag.full_path),a()}catch{}}const h={archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:s,onTagDeleted:o,onTagsRefresh:a,humanizeTags:u};return i.jsxs("li",{children:[i.jsxs("div",{className:"tag-node-row",children:[y?i.jsx("input",{className:"tag-rename-input",autoFocus:!0,value:m,onChange:k=>w(k.target.value),onKeyDown:k=>{k.key==="Enter"&&k.currentTarget.blur(),k.key==="Escape"&&(S.current=!0,k.currentTarget.blur())},onBlur:()=>{S.current?(S.current=!1,g(!1)):f()}}):i.jsxs("button",{className:`tag-node-btn${c?" is-active":""}`,title:e.tag.full_path,onClick:j,onDoubleClick:O,children:[u?e.tag.name:e.tag.slug,i.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",onClick:k=>{k.stopPropagation(),O(k)},children:i.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),i.jsx("button",{className:"remove tag-node-delete",title:`Delete tag ${e.tag.full_path}`,onClick:d,"aria-label":`Delete tag ${e.tag.full_path}`,children:"×"})]}),((x=e.children)==null?void 0:x.length)>0&&i.jsx("div",{className:"tag-children",children:i.jsx("ul",{className:"tag-tree-list",children:e.children.map(k=>i.jsx(Oc,{node:k,...h},k.tag.tag_uid))})})]})}function hh({archiveId:e,tagNodes:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:s,onTagDeleted:o,onTagsRefresh:a,humanizeTags:u}){return i.jsx("section",{id:"tags-view",className:"view is-active",children:i.jsxs("div",{className:"tag-tree",children:[i.jsxs("div",{className:"tag-tree-header",children:[i.jsx("span",{className:"tag-tree-title",children:"Tags"}),n&&i.jsxs("span",{className:"tag-tree-active",children:["Filtering: ",n]})]}),t.length===0?i.jsx("p",{className:"muted",style:{padding:"8px 0"},children:"No tags yet."}):i.jsx("ul",{className:"tag-tree-list",children:t.map(c=>i.jsx(Oc,{node:c,archiveId:e,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:s,onTagDeleted:o,onTagsRefresh:a,humanizeTags:u},c.tag.tag_uid))})]})})}const In=[{value:0,label:"Private"},{value:2,label:"Users only"},{value:3,label:"Public"}],mh=e=>{var t;return((t=In.find(n=>n.value===e))==null?void 0:t.label)??String(e)};function gh({archiveId:e}){const[t,n]=v.useState([]),[r,l]=v.useState(!1),[s,o]=v.useState(null),[a,u]=v.useState(null),[c,y]=v.useState(null),[g,m]=v.useState(!1),[w,S]=v.useState(null),[j,O]=v.useState(""),[f,d]=v.useState(""),[h,x]=v.useState(2),[k,E]=v.useState(!1),[L,p]=v.useState(null),[N,T]=v.useState(""),[I,U]=v.useState(2),[P,F]=v.useState(!1),[H,q]=v.useState(null),[Me,z]=v.useState(!1),[C,M]=v.useState(""),Q=v.useRef(null),A=t.find(R=>R.collection_uid===a)??null,we=(A==null?void 0:A.slug)==="_default_",ce=v.useCallback(async()=>{if(e){l(!0),o(null);try{const R=await Ip(e);n(R)}catch(R){o(R.message)}finally{l(!1)}}},[e]),Qe=v.useCallback(async R=>{if(!R){y(null);return}m(!0),S(null);try{const V=await Bp(e,R);y(V)}catch(V){S(V.message)}finally{m(!1)}},[e]);v.useEffect(()=>{ce()},[ce]),v.useEffect(()=>{Qe(a)},[a,Qe]),v.useEffect(()=>{Me&&Q.current&&Q.current.focus()},[Me]);async function Fe(R){R.preventDefault();const V=j.trim(),Pe=f.trim();if(!(!V||!Pe)){E(!0),p(null);try{const $=await Up(e,V,Pe,h);O(""),d(""),x(2),await ce(),u($.collection_uid)}catch($){p($.message)}finally{E(!1)}}}async function lt(){const R=C.trim();if(!R||!A){z(!1);return}try{await pa(e,A.collection_uid,{name:R}),await ce(),y(V=>V&&{...V,name:R})}catch(V){o(V.message)}finally{z(!1)}}async function Dl(R){if(A)try{await pa(e,A.collection_uid,{default_visibility_bits:R}),await ce(),y(V=>V&&{...V,default_visibility_bits:R})}catch(V){o(V.message)}}async function Ol(){if(A&&window.confirm(`Delete collection "${A.name}"? Entries will not be deleted.`))try{await Kp(e,A.collection_uid),u(null),y(null),await ce()}catch(R){o(R.message)}}async function $l(R){R.preventDefault();const V=N.trim();if(!(!V||!A)){F(!0),q(null);try{await Vp(e,A.collection_uid,V,I),T(""),await Qe(A.collection_uid)}catch(Pe){q(Pe.message)}finally{F(!1)}}}async function Ml(R){if(A)try{await Wp(e,A.collection_uid,R),await Qe(A.collection_uid)}catch(V){S(V.message)}}async function Fl(R,V){if(A)try{await Hp(e,A.collection_uid,R,V),y(Pe=>Pe&&{...Pe,entries:Pe.entries.map($=>$.entry_uid===R?{...$,collection_visibility_bits:V}:$)})}catch(Pe){S(Pe.message)}}return e?i.jsxs("div",{className:"collections-view",children:[i.jsx("h2",{className:"collections-heading",children:"Collections"}),r&&i.jsx("div",{className:"muted",children:"Loading…"}),s&&i.jsxs("div",{className:"collections-error",children:[s," ",i.jsx("button",{onClick:()=>o(null),className:"coll-dismiss",children:"×"})]}),i.jsxs("div",{className:"collections-layout",children:[i.jsxs("div",{className:"collections-sidebar",children:[t.map(R=>i.jsxs("button",{className:`coll-sidebar-row${a===R.collection_uid?" is-active":""}`,onClick:()=>u(R.collection_uid),children:[i.jsx("span",{className:"coll-row-name",children:R.name}),i.jsx("span",{className:"coll-row-meta",children:mh(R.default_visibility_bits)})]},R.collection_uid)),t.length===0&&!r&&i.jsx("div",{className:"muted",style:{padding:"8px 12px"},children:"No collections yet."})]}),A?i.jsxs("div",{className:"coll-detail",children:[i.jsxs("div",{className:"coll-detail-header",children:[Me?i.jsx("input",{ref:Q,className:"coll-rename-input",value:C,onChange:R=>M(R.target.value),onBlur:lt,onKeyDown:R=>{R.key==="Enter"&<(),R.key==="Escape"&&z(!1)}}):i.jsxs("h3",{className:`coll-detail-name${we?"":" coll-detail-name--editable"}`,title:we?void 0:"Click to rename",onClick:()=>{we||(M(A.name),z(!0))},children:[(c==null?void 0:c.name)??A.name,!we&&i.jsx("span",{className:"coll-edit-hint",children:" ✎"})]}),!we&&i.jsx("button",{className:"coll-delete-btn",onClick:Ol,title:"Delete collection",children:"Delete"})]}),i.jsxs("div",{className:"coll-detail-vis",children:[i.jsx("span",{className:"coll-vis-label",children:"Default visibility"}),i.jsx("select",{className:"coll-vis-select",value:(c==null?void 0:c.default_visibility_bits)??A.default_visibility_bits,onChange:R=>Dl(Number(R.target.value)),disabled:we,children:In.map(R=>i.jsx("option",{value:R.value,children:R.label},R.value))})]}),i.jsxs("div",{className:"coll-entries-section",children:[i.jsx("div",{className:"coll-section-heading",children:"Entries"}),g&&i.jsx("div",{className:"muted",children:"Loading…"}),w&&i.jsx("div",{className:"collections-error",children:w}),!g&&c&&(c.entries.length===0?i.jsx("div",{className:"muted",children:"No entries in this collection."}):i.jsx("ul",{className:"coll-entries-list",children:c.entries.map(R=>i.jsxs("li",{className:"coll-entry-row",children:[i.jsxs("div",{className:"coll-entry-info",children:[i.jsx("span",{className:"coll-entry-title",children:R.title||R.entry_uid}),i.jsx("span",{className:"coll-entry-kind muted",children:R.source_kind})]}),i.jsxs("div",{className:"coll-entry-actions",children:[i.jsx("select",{className:"coll-entry-vis-select",value:R.collection_visibility_bits,onChange:V=>Fl(R.entry_uid,Number(V.target.value)),children:In.map(V=>i.jsx("option",{value:V.value,children:V.label},V.value))}),!we&&i.jsx("button",{className:"coll-entry-remove",onClick:()=>Ml(R.entry_uid),title:"Remove from collection",children:"×"})]})]},R.entry_uid))}))]}),!we&&i.jsxs("form",{className:"coll-add-entry-form",onSubmit:$l,children:[i.jsx("div",{className:"coll-section-heading",children:"Add entry"}),i.jsxs("div",{className:"coll-add-entry-row",children:[i.jsx("input",{className:"coll-add-entry-input",type:"text",value:N,onChange:R=>T(R.target.value),placeholder:"entry_uid",required:!0}),i.jsx("select",{className:"coll-vis-select",value:I,onChange:R=>U(Number(R.target.value)),children:In.map(R=>i.jsx("option",{value:R.value,children:R.label},R.value))}),i.jsx("button",{className:"coll-add-btn",type:"submit",disabled:P,children:P?"…":"Add"})]}),H&&i.jsx("div",{className:"collections-error",style:{marginTop:4},children:H})]})]}):i.jsx("div",{className:"coll-detail coll-detail--empty",children:i.jsx("div",{className:"muted",children:"Select a collection to view details."})})]}),i.jsxs("details",{className:"coll-create-details",children:[i.jsx("summary",{children:"+ Create collection"}),i.jsxs("form",{className:"coll-create-form",onSubmit:Fe,children:[i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",htmlFor:"coll-name",children:"Name"}),i.jsx("input",{className:"capture-input",id:"coll-name",type:"text",value:j,onChange:R=>{O(R.target.value),f||d(R.target.value.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""))},placeholder:"My Collection",required:!0})]}),i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",htmlFor:"coll-slug",children:"Slug"}),i.jsx("input",{className:"capture-input",id:"coll-slug",type:"text",value:f,onChange:R=>d(R.target.value),placeholder:"my-collection",required:!0})]}),i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",htmlFor:"coll-vis",children:"Default visibility"}),i.jsx("select",{className:"capture-input",id:"coll-vis",style:{height:42},value:h,onChange:R=>x(Number(R.target.value)),children:In.map(R=>i.jsx("option",{value:R.value,children:R.label},R.value))})]}),L&&i.jsx("div",{className:"collections-error",children:L}),i.jsx("button",{className:"btn-primary",type:"submit",disabled:k,children:k?"Creating…":"Create collection"})]})]})]}):i.jsx("div",{className:"view-placeholder",children:"Select an archive."})}const vh=4;function yh({tab:e,onTabChange:t,archiveId:n}){const{currentUser:r,setCurrentUser:l}=v.useContext(Rl)??{},s=r&&(r.role_bits&vh)!==0,o=["profile","tokens",...s?["instance","cookies","storage"]:[]],a={profile:"Profile",tokens:"API Tokens",instance:"Instance",cookies:"Cookies",storage:"Storage"};return i.jsxs("section",{className:"admin-view",children:[i.jsx("h1",{children:"Settings"}),i.jsx("div",{className:"view-tabs",children:o.map(u=>i.jsx("button",{className:`view-tab${e===u?" is-active":""}`,onClick:()=>t(u),children:a[u]},u))}),e==="profile"&&i.jsx(wh,{currentUser:r,setCurrentUser:l}),e==="tokens"&&i.jsx(xh,{}),e==="instance"&&s&&i.jsx(Sh,{}),e==="cookies"&&s&&i.jsx(jh,{}),e==="storage"&&s&&i.jsx(kh,{archiveId:n})]})}function wh({currentUser:e,setCurrentUser:t}){const[n,r]=v.useState((e==null?void 0:e.display_name)??""),[l,s]=v.useState(!1),[o,a]=v.useState(null),[u,c]=v.useState(""),[y,g]=v.useState(""),[m,w]=v.useState(""),[S,j]=v.useState(!1),[O,f]=v.useState(null);async function d(x){x.preventDefault(),s(!0),a(null);try{await _p(n),t(k=>({...k,display_name:n||null})),a({ok:!0,text:"Saved."})}catch(k){a({ok:!1,text:k.message})}finally{s(!1)}}async function h(x){if(x.preventDefault(),y!==m){f({ok:!1,text:"Passwords do not match."});return}j(!0),f(null);try{await Tp(u,y),c(""),g(""),w(""),f({ok:!0,text:"Password changed."})}catch(k){f({ok:!1,text:k.message})}finally{j(!1)}}return i.jsxs("div",{style:{maxWidth:440},children:[i.jsxs("div",{className:"form-section",children:[i.jsx("h2",{children:"Display Name"}),i.jsxs("form",{onSubmit:d,children:[i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",htmlFor:"display-name",children:"Name shown in the UI"}),i.jsx("input",{className:"field-input",id:"display-name",placeholder:(e==null?void 0:e.username)??"",value:n,onChange:x=>r(x.target.value)})]}),o&&i.jsx("div",{className:`form-msg form-msg--${o.ok?"ok":"err"}`,children:o.text}),i.jsx("button",{className:"btn-primary",type:"submit",disabled:l,children:l?"Saving…":"Save"})]})]}),i.jsxs("div",{className:"form-section",children:[i.jsx("h2",{children:"Display Preferences"}),i.jsxs("label",{className:"checkbox-row",children:[i.jsx("input",{type:"checkbox",checked:(e==null?void 0:e.humanize_slugs)??!1,onChange:async x=>{const k=x.target.checked;try{await Ep({humanize_slugs:k}),t(E=>({...E,humanize_slugs:k}))}catch{}}}),i.jsx("span",{className:"form-label",style:{margin:0},children:"Humanize tag display"})]}),i.jsx("p",{className:"muted",style:{fontSize:13,margin:"4px 0 0"},children:'When on, tag paths show as "X / Articles" instead of "x/articles".'})]}),i.jsxs("div",{className:"form-section",children:[i.jsx("h2",{children:"Change Password"}),i.jsxs("form",{onSubmit:h,children:[i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",htmlFor:"cur-pw",children:"Current password"}),i.jsx("input",{className:"field-input",id:"cur-pw",type:"password",value:u,onChange:x=>c(x.target.value),required:!0})]}),i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",htmlFor:"new-pw",children:"New password"}),i.jsx("input",{className:"field-input",id:"new-pw",type:"password",value:y,onChange:x=>g(x.target.value),required:!0})]}),i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",htmlFor:"confirm-pw",children:"Confirm new password"}),i.jsx("input",{className:"field-input",id:"confirm-pw",type:"password",value:m,onChange:x=>w(x.target.value),required:!0})]}),O&&i.jsx("div",{className:`form-msg form-msg--${O.ok?"ok":"err"}`,children:O.text}),i.jsx("button",{className:"btn-primary",type:"submit",disabled:S,children:S?"Changing…":"Change Password"})]})]})]})}function xh(){const[e,t]=v.useState([]),[n,r]=v.useState(!0),[l,s]=v.useState(null),[o,a]=v.useState(""),[u,c]=v.useState(!1),[y,g]=v.useState(null),m=v.useCallback(async()=>{r(!0),s(null);try{t(await Pp())}catch(j){s(j.message)}finally{r(!1)}},[]);v.useEffect(()=>{m()},[m]);async function w(j){if(j.preventDefault(),!!o.trim()){c(!0);try{const O=await Lp(o.trim());g(O),a(""),m()}catch(O){s(O.message)}finally{c(!1)}}}async function S(j){try{await zp(j),t(O=>O.filter(f=>f.token_uid!==j))}catch(O){s(O.message)}}return i.jsx("div",{style:{maxWidth:600},children:i.jsxs("div",{className:"form-section",children:[i.jsx("h2",{children:"API Tokens"}),y&&i.jsxs("div",{className:"token-banner",children:[i.jsx("strong",{children:"Token created."})," Copy it now — it won't be shown again.",i.jsx("code",{children:y.raw_token}),i.jsx("button",{className:"token-dismiss",onClick:()=>g(null),children:"Dismiss"})]}),i.jsxs("form",{className:"token-create-row",onSubmit:w,children:[i.jsx("input",{className:"field-input field-input--flex",placeholder:"Token name",value:o,onChange:j=>a(j.target.value),required:!0}),i.jsx("button",{className:"btn-primary",type:"submit",disabled:u,children:u?"Creating…":"Create token"})]}),l&&i.jsx("div",{className:"form-msg form-msg--err",children:l}),n?i.jsx("div",{className:"muted",children:"Loading…"}):i.jsxs("div",{children:[e.length===0&&i.jsx("div",{className:"muted",children:"No tokens yet."}),e.map(j=>i.jsxs("div",{className:"token-row",children:[i.jsxs("div",{className:"token-row-info",children:[i.jsx("strong",{children:j.name}),i.jsxs("div",{className:"muted",children:["Created ",j.created_at.slice(0,10),j.last_used_at&&` · Last used ${j.last_used_at.slice(0,10)}`]})]}),i.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"4px 10px"},onClick:()=>S(j.token_uid),children:"Revoke"})]},j.token_uid))]})]})})}function Sh(){const[e,t]=v.useState(null),[n,r]=v.useState(!0),[l,s]=v.useState(null),[o,a]=v.useState(!1),[u,c]=v.useState(null);v.useEffect(()=>{(async()=>{try{t(await Rp())}catch(g){s(g.message)}finally{r(!1)}})()},[]);async function y(g){g.preventDefault(),a(!0),c(null);try{await Dp(e),c({ok:!0,text:"Saved."})}catch(m){c({ok:!1,text:m.message})}finally{a(!1)}}return n?i.jsx("div",{className:"muted",children:"Loading…"}):l?i.jsx("div",{className:"form-msg form-msg--err",children:l}):e?i.jsx("div",{style:{maxWidth:440},children:i.jsxs("div",{className:"form-section",children:[i.jsx("h2",{children:"Instance Settings"}),i.jsxs("form",{onSubmit:y,children:[[["public_index_enabled","Public index (unauthenticated browsing)"],["public_entry_content_enabled","Public entry content"],["open_registration_enabled","Open registration"]].map(([g,m])=>i.jsxs("label",{className:"checkbox-row",children:[i.jsx("input",{type:"checkbox",checked:!!e[g],onChange:w=>t(S=>({...S,[g]:w.target.checked}))}),m]},g)),i.jsxs("div",{className:"form-field",style:{marginTop:4},children:[i.jsx("label",{className:"form-label",children:"Default entry visibility"}),i.jsxs("select",{className:"field-input",value:e.default_entry_visibility,onChange:g=>t(m=>({...m,default_entry_visibility:Number(g.target.value)})),children:[i.jsx("option",{value:0,children:"Private"}),i.jsx("option",{value:2,children:"Unlisted"}),i.jsx("option",{value:3,children:"Public"})]})]}),u&&i.jsx("div",{className:`form-msg form-msg--${u.ok?"ok":"err"}`,children:u.text}),i.jsx("button",{className:"btn-primary",type:"submit",disabled:o,children:o?"Saving…":"Save Settings"})]})]})}):null}function fs(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 kh({archiveId:e}){const[t,n]=v.useState("idle"),[r,l]=v.useState(null),[s,o]=v.useState(null),[a,u]=v.useState(null);function c(){n("idle"),l(null),o(null),u(null)}async function y(){n("scanning"),u(null),l(null);try{const w=await Jp(e);l(w),n("scanned")}catch(w){u(w.message),n("error")}}async function g(){n("deleting"),u(null);try{const w=await Yp(e);o(w),n("done")}catch(w){u(w.message),n("error")}}const m=r&&r.deletable_files===0&&r.orphaned_blob_rows===0;return i.jsx("div",{style:{maxWidth:440},children:i.jsxs("div",{className:"form-section",children:[i.jsx("h2",{children:"Orphan Cleanup"}),i.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."," ",i.jsx("strong",{children:"Cleanup is blocked while captures are running."})]}),!e&&i.jsx("div",{className:"muted",children:"No archive selected."}),e&&t==="idle"&&i.jsx("button",{className:"btn-ghost",onClick:y,children:"Scan for orphaned blobs"}),t==="scanning"&&i.jsx("div",{className:"muted",children:"Scanning…"}),t==="scanned"&&r&&m&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"form-msg form-msg--ok",children:"Archive is clean — nothing to remove."}),i.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Done"})]}),t==="scanned"&&r&&!m&&i.jsxs("div",{children:[i.jsxs("div",{style:{marginBottom:14,lineHeight:1.6},children:["Found ",i.jsx("strong",{children:r.deletable_files})," unreferenced file",r.deletable_files!==1?"s":""," ","and ",i.jsx("strong",{children:r.orphaned_blob_rows})," orphaned DB record",r.orphaned_blob_rows!==1?"s":""," ","— ",i.jsx("strong",{children:fs(r.total_bytes)})," recoverable."]}),i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsxs("button",{className:"btn-danger",onClick:g,children:["Delete (",fs(r.total_bytes),")"]}),i.jsx("button",{className:"btn-ghost",onClick:c,children:"Cancel"})]})]}),t==="deleting"&&i.jsx("div",{className:"muted",children:"Deleting…"}),t==="done"&&s&&i.jsxs("div",{children:[i.jsxs("div",{className:"form-msg form-msg--ok",children:["Freed ",i.jsx("strong",{children:fs(s.freed_bytes)})," ","— removed ",s.deleted_files," file",s.deleted_files!==1?"s":""," ","and ",s.deleted_blob_rows," DB record",s.deleted_blob_rows!==1?"s":"","."]}),s.errors&&s.errors.length>0&&i.jsxs("div",{className:"form-msg form-msg--err",style:{marginTop:6},children:[s.errors.length," file",s.errors.length!==1?"s":""," could not be deleted."]}),i.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Scan again"})]}),t==="error"&&i.jsxs("div",{children:[i.jsx("div",{className:"form-msg form-msg--err",children:a}),i.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Try again"})]})]})})}function jh(){const[e,t]=v.useState(null),[n,r]=v.useState(!0),[l,s]=v.useState(null),[o,a]=v.useState("global"),[u,c]=v.useState(""),[y,g]=v.useState("{}"),[m,w]=v.useState(null),[S,j]=v.useState(!1),[O,f]=v.useState({});v.useEffect(()=>{d()},[]);async function d(){r(!0),s(null);try{t(await Gp())}catch(p){s(p.message)}finally{r(!1)}}async function h(p){p.preventDefault();try{JSON.parse(y)}catch{w({ok:!1,text:'cookies must be valid JSON, e.g. {"session": "abc"}'});return}j(!0),w(null);try{await Xp(o==="global"?null:u.trim(),o,y),c(""),g("{}"),a("global"),w({ok:!0,text:"Rule added."}),await d()}catch(N){w({ok:!1,text:N.message})}finally{j(!1)}}async function x(p){try{await Zp(p),await d()}catch(N){s(N.message)}}function k(p){f(N=>({...N,[p.rule_uid]:{cookiesInput:p.cookies_json,saving:!1,msg:null}}))}function E(p){f(N=>{const T={...N};return delete T[p],T})}async function L(p){const N=O[p.rule_uid];try{JSON.parse(N.cookiesInput)}catch{f(T=>({...T,[p.rule_uid]:{...T[p.rule_uid],msg:{ok:!1,text:"Invalid JSON"}}}));return}f(T=>({...T,[p.rule_uid]:{...T[p.rule_uid],saving:!0,msg:null}}));try{await qp(p.rule_uid,{cookies_json:N.cookiesInput}),E(p.rule_uid),await d()}catch(T){f(I=>({...I,[p.rule_uid]:{...I[p.rule_uid],saving:!1,msg:{ok:!1,text:T.message}}}))}}return n?i.jsx("div",{className:"muted",children:"Loading…"}):l?i.jsx("div",{className:"form-msg form-msg--err",children:l}):i.jsx("div",{style:{maxWidth:560},children:i.jsxs("div",{className:"form-section",children:[i.jsx("h2",{children:"Cookie Rules"}),i.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?i.jsxs("table",{className:"data-table",style:{width:"100%",marginBottom:16},children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Pattern"}),i.jsx("th",{children:"Cookies"}),i.jsx("th",{style:{width:100},children:"Actions"})]})}),i.jsx("tbody",{children:e.map(p=>{const N=O[p.rule_uid],T=p.url_pattern?i.jsxs(i.Fragment,{children:[i.jsxs("span",{className:"muted",children:[p.pattern_kind,":"]})," ",i.jsx("code",{children:p.url_pattern})]}):i.jsx("span",{className:"muted",children:"global (all URLs)"});return i.jsxs("tr",{children:[i.jsx("td",{children:T}),i.jsx("td",{children:N?i.jsxs(i.Fragment,{children:[i.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:12,width:"100%",minHeight:60},value:N.cookiesInput,onChange:I=>f(U=>({...U,[p.rule_uid]:{...U[p.rule_uid],cookiesInput:I.target.value}}))}),N.msg&&i.jsx("div",{className:`form-msg form-msg--${N.msg.ok?"ok":"err"}`,children:N.msg.text}),i.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[i.jsx("button",{className:"btn-primary",style:{fontSize:12,padding:"2px 8px"},disabled:N.saving,onClick:()=>L(p),children:N.saving?"Saving…":"Save"}),i.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>E(p.rule_uid),children:"Cancel"})]})]}):i.jsx("code",{style:{fontSize:12,wordBreak:"break-all"},children:p.cookies_json})}),i.jsx("td",{children:!N&&i.jsxs("div",{style:{display:"flex",gap:6},children:[i.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>k(p),children:"Edit"}),i.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"2px 8px"},onClick:()=>x(p.rule_uid),children:"Del"})]})})]},p.rule_uid)})})]}):i.jsx("p",{className:"muted",style:{marginBottom:16},children:"No cookie rules defined."}),i.jsx("h3",{style:{marginBottom:8},children:"Add Rule"}),i.jsxs("form",{onSubmit:h,children:[i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",children:"Pattern type"}),i.jsxs("select",{className:"field-input",value:o,onChange:p=>a(p.target.value),children:[i.jsx("option",{value:"global",children:"Global (all URLs)"}),i.jsx("option",{value:"wildcard",children:"Wildcard (e.g. *.youtube.com)"}),i.jsx("option",{value:"regex",children:"Regex (matched against full URL)"})]})]}),o!=="global"&&i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",children:o==="wildcard"?"URL/hostname pattern":"Regex pattern"}),i.jsx("input",{className:"field-input",type:"text",value:u,onChange:p=>c(p.target.value),placeholder:o==="wildcard"?"*.youtube.com or https://example.com/*":".*\\.youtube\\.com.*",required:!0})]}),i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",children:"Cookies (JSON object)"}),i.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:13,minHeight:70},value:y,onChange:p=>g(p.target.value),placeholder:'{"SESSION": "abc123", "token": "xyz"}',required:!0})]}),m&&i.jsx("div",{className:`form-msg form-msg--${m.ok?"ok":"err"}`,children:m.text}),i.jsx("button",{className:"btn-primary",type:"submit",disabled:S,children:S?"Adding…":"Add Rule"})]})]})})}const ga={0:"Private",1:"Public",2:"Users only",3:"Public"},Nh=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"M7 17 17 7M9 7h8v8"})});function Ch({archiveId:e,selectedEntry:t,onTagFilterSet:n,tagNodes:r,onTagsRefresh:l,onEntryTitleChange:s,onEntryDeleted:o,humanizeTags:a}){const[u,c]=v.useState(null),[y,g]=v.useState([]),[m,w]=v.useState(""),[S,j]=v.useState([]),[O,f]=v.useState(""),d=v.useRef(0),h=v.useRef(!1),[x,k]=v.useState(!1),[E,L]=v.useState("");v.useEffect(()=>{if(!t||!e){c(null),g([]),j([]);return}k(!1),L(""),h.current=!1;const P=++d.current;c(null),g([]),Promise.all([dp(e,t.entry_uid),cs(e,t.entry_uid),Qp(e,t.entry_uid)]).then(([F,H,q])=>{P===d.current&&(c(F),g(H),j(q))}).catch(()=>{})},[t,e]);async function p(){const P=E.trim()||null;try{await fp(e,t.entry_uid,P),c(F=>F&&{...F,summary:{...F.summary,title:P}}),s==null||s(t.entry_uid,P)}catch{}finally{k(!1)}}async function N(){const P=m.trim();if(!(!P||!t))try{await pp(e,t.entry_uid,P),w(""),f("");const F=await cs(e,t.entry_uid);g(F),l()}catch(F){f(F.message)}}async function T(P){try{await hp(e,t.entry_uid,P);const F=await cs(e,t.entry_uid);g(F),l()}catch{}}async function I(){if(!(!t||!e)&&window.confirm("Delete this entry? This cannot be undone."))try{await mp(e,t.entry_uid),o==null||o(t.entry_uid)}catch{}}const U=u?[["Added",zc(u.summary.archived_at)],["Source",u.summary.source_kind],["Type",u.summary.entity_kind],["Visibility",ga[u.summary.visibility]??u.summary.visibility],["Root",u.structured_root_relpath]]:[];return i.jsxs("aside",{className:"context-rail",children:[i.jsx("div",{className:"rail-eyebrow",children:"Context"}),t?u?i.jsxs(i.Fragment,{children:[x?i.jsx("input",{className:"rail-title-input",autoFocus:!0,value:E,onChange:P=>L(P.target.value),onKeyDown:P=>{P.key==="Enter"&&P.currentTarget.blur(),P.key==="Escape"&&(h.current=!0,P.currentTarget.blur())},onBlur:()=>{h.current?k(!1):p(),h.current=!1}}):i.jsxs("h2",{className:"rail-title rail-title--editable",title:"Click to rename",onClick:()=>{L(u.summary.title??""),k(!0)},children:[Ut(u.summary.title)||Ut(u.summary.entry_uid),i.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:i.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),u.summary.original_url&&i.jsxs("a",{className:"url-tile",href:u.summary.original_url,target:"_blank",rel:"noopener noreferrer",children:[i.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:Rc(u.summary.source_kind)}}),i.jsx("span",{className:"u-text",children:u.summary.original_url}),i.jsx("span",{className:"ext",children:i.jsx(Nh,{})})]}),i.jsx("div",{className:"meta-list",children:U.filter(([,P])=>P!=null&&P!=="").map(([P,F])=>i.jsxs("div",{className:"meta-item",children:[i.jsx("span",{className:"meta-k",children:P}),i.jsx("span",{className:`meta-v${P==="Root"?" mono":""}`,children:Ut(F)})]},P))}),u.artifacts.length>0&&i.jsxs("div",{className:"rail-section",children:[i.jsxs("div",{className:"rail-section-heading",children:["Artifacts ",i.jsx("span",{className:"num",children:u.artifacts.length})]}),i.jsx("ul",{className:"artifact-list",children:u.artifacts.map((P,F)=>i.jsx("li",{children:i.jsxs("a",{href:`/api/archives/${e}/entries/${u.summary.entry_uid}/artifacts/${F}`,target:"_blank",rel:"noopener noreferrer",className:"artifact-link",children:[i.jsx("span",{className:"artifact-name",children:P.artifact_role.replace(/_/g," ")}),i.jsx("span",{className:"artifact-size",children:P.byte_size!=null?oi(P.byte_size):"—"})]})},F))})]})]}):i.jsx("p",{className:"tags-empty",children:"Loading…"}):i.jsx("p",{className:"tags-empty",children:"Select an entry."}),t&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"rail-section",children:[i.jsx("div",{className:"rail-section-heading",children:"Tags"}),y.length===0?i.jsx("p",{className:"tags-empty",children:"No tags yet."}):i.jsx("div",{className:"tags-wrap",children:y.map(P=>i.jsxs("span",{className:"tag-pill",title:P.full_path,children:[a?Dc(P.full_path):P.full_path,i.jsx("button",{className:"remove",title:`Remove tag ${P.full_path}`,onClick:()=>T(P.tag_uid),children:"×"})]},P.tag_uid))}),O&&i.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:O}),i.jsxs("div",{className:"tag-input-wrap",children:[i.jsx("span",{className:"hash",children:"/"}),i.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:m,onChange:P=>w(P.target.value),onKeyDown:P=>{P.key==="Enter"&&N()}}),i.jsx("button",{className:"tag-add-btn",onClick:N,children:"Add"})]})]}),S.length>0&&i.jsxs("div",{className:"rail-section",children:[i.jsx("div",{className:"rail-section-heading",children:"Collections"}),S.map(P=>i.jsxs("div",{className:"coll-row",children:[i.jsx("span",{className:"coll-name",children:P.collection_uid}),i.jsx("span",{className:"vis-badge",children:ga[P.visibility_bits]??`bits:${P.visibility_bits}`})]},P.collection_uid))]}),i.jsx("div",{className:"rail-delete-zone",children:i.jsx("button",{className:"rail-delete-btn",onClick:I,children:"Delete entry"})})]})]})}const _h=7e3;function Eh({toasts:e,onDismiss:t}){return e.length?i.jsx("div",{className:"toast-stack",role:"log","aria-live":"polite","aria-label":"Notifications",children:e.map(n=>i.jsx(Th,{toast:n,onDismiss:t},n.id))}):null}function Th({toast:e,onDismiss:t}){const[n,r]=v.useState(!1);v.useEffect(()=>{if(n)return;const s=setTimeout(()=>t(e.id),_h);return()=>clearTimeout(s)},[n,e.id,t]);const l=e.locator?e.locator.length>48?e.locator.slice(0,45)+"…":e.locator:null;return i.jsxs("div",{className:"toast toast--error",role:"alert","aria-atomic":"true",children:[i.jsxs("div",{className:"toast-top",children:[i.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✕"}),i.jsxs("div",{className:"toast-body",children:[i.jsx("span",{className:"toast-headline",children:"Capture failed"}),l&&i.jsx("span",{className:"toast-locator",children:l})]}),i.jsxs("div",{className:"toast-btns",children:[e.errorText&&i.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>r(s=>!s),children:n?"Hide":"View error"}),i.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),n&&e.errorText&&i.jsx("pre",{className:"toast-error-detail",children:e.errorText})]})}const Rl=v.createContext(null),Ph=["archive","tags","collections","runs","admin","settings"],Lh=["profile","tokens","instance","storage"];function ps(){const e=window.location.pathname.split("/").filter(Boolean),t=Ph.includes(e[0])?e[0]:"archive",n=t==="settings"&&Lh.includes(e[1])?e[1]:"profile";return{view:t,settingsTab:n}}function zh(e,t){return e==="archive"?"/":e==="settings"?`/settings/${t}`:`/${e}`}function Rh(){const[e,t]=v.useState("loading"),[n,r]=v.useState(null);v.useEffect(()=>{(async()=>{if(await Sp()){t("setup");return}const K=await Cp();if(!K){t("login");return}r(K),t("authenticated")})()},[]),v.useEffect(()=>{const $=()=>{r(null),t("login")};return window.addEventListener("auth:expired",$),()=>window.removeEventListener("auth:expired",$)},[]),v.useEffect(()=>{const $=()=>{const{view:K,settingsTab:de}=ps();f(K),h(de)};return window.addEventListener("popstate",$),()=>window.removeEventListener("popstate",$)},[]);const[l,s]=v.useState([]),[o,a]=v.useState(null),[u,c]=v.useState([]),[y,g]=v.useState(null),[m,w]=v.useState(null),[S,j]=v.useState(null),[O,f]=v.useState(()=>ps().view),[d,h]=v.useState(()=>ps().settingsTab),[x,k]=v.useState(""),[E,L]=v.useState(""),[p,N]=v.useState(!1),[T,I]=v.useState([]),[U,P]=v.useState([]),[F,H]=v.useState(()=>sessionStorage.getItem("captureDialogOpen")==="true"),[q,Me]=v.useState([]),z=v.useRef(0),C=(n==null?void 0:n.humanize_slugs)??!1;v.useEffect(()=>{sessionStorage.setItem("captureDialogOpen",F)},[F]);const M=v.useCallback(async($,K,de)=>{if($){N(!0);try{let Ae;K||de?Ae=await cp($,K,de):Ae=await up($),c(Ae),L(Ae.length===0?"No results":`${Ae.length} result${Ae.length===1?"":"s"}`)}catch{c([]),L("Search failed. Try again.")}finally{N(!1)}}},[]);v.useEffect(()=>{e==="authenticated"&&ap().then($=>{if(s($),$.length>0){const K=$[0].id;a(K)}})},[e]),v.useEffect(()=>{o&&(j(null),w(null),g(null),Promise.all([M(o,"",null),fa(o).then(I),ds(o).then(P)]))},[o]),v.useEffect(()=>{if(o===null)return;const $=setTimeout(()=>{M(o,x,S)},300);return()=>clearTimeout($)},[x,o]),v.useEffect(()=>{o!==null&&(S!==null&&f("archive"),M(o,x,S))},[S,o]);const Q=v.useCallback($=>{a($)},[]),A=v.useCallback($=>{f($),$==="tags"&&o&&ds(o).then(P)},[o]);v.useEffect(()=>{const $=zh(O,d);window.location.pathname!==$&&history.pushState(null,"",$)},[O,d]);const we=v.useCallback($=>{g($?$.entry_uid:null),w($)},[]),ce=v.useCallback($=>{j($)},[]),Qe=v.useCallback(()=>{j(null)},[]),Fe=v.useCallback(()=>{o&&ds(o).then(P)},[o]),lt=v.useCallback(($,K)=>{S===$?j(K):S!=null&&S.startsWith($+"/")&&j(K+S.slice($.length))},[S]),Dl=v.useCallback($=>{(S===$||S!=null&&S.startsWith($+"/"))&&j(null)},[S]),Ol=v.useCallback(($,K)=>{c(de=>de.map(Ae=>Ae.entry_uid===$?{...Ae,title:K}:Ae)),w(de=>de&&de.entry_uid===$?{...de,title:K}:de)},[]),$l=v.useCallback($=>{c(K=>K.filter(de=>de.entry_uid!==$)),w(K=>(K==null?void 0:K.entry_uid)===$?null:K),g(K=>K===$?null:K)},[]),Ml=v.useCallback(()=>{H(!0)},[]),Fl=v.useCallback(()=>{H(!1)},[]),R=v.useCallback(()=>{o&&Promise.all([M(o,x,S),fa(o).then(I)])},[o,x,S,M]),V=v.useCallback(($,K)=>{const de=++z.current;Me(Ae=>[...Ae,{id:de,errorText:$,locator:K}])},[]),Pe=v.useCallback($=>{Me(K=>K.filter(de=>de.id!==$))},[]);return e==="loading"?i.jsx("div",{className:"auth-loading",children:"Loading\\u2026"}):e==="setup"?i.jsx(th,{onComplete:()=>t("login")}):e==="login"?i.jsx(eh,{onLogin:$=>{r($),t("authenticated")}}):i.jsx(Rl.Provider,{value:{currentUser:n,setCurrentUser:r},children:i.jsxs(i.Fragment,{children:[i.jsx(nh,{archives:l,archiveId:o,onArchiveChange:Q,view:O,onViewChange:A,onCaptureClick:Ml}),i.jsxs("main",{className:"app-shell",children:[i.jsxs("div",{className:"workspace",children:[O==="archive"&&i.jsxs("div",{className:"toolbar",children:[i.jsxs("div",{className:"search-field",children:[i.jsx("span",{className:"ico","aria-hidden":"true",children:i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[i.jsx("circle",{cx:"11",cy:"11",r:"7"}),i.jsx("line",{x1:"16.5",y1:"16.5",x2:"21",y2:"21"})]})}),i.jsx("input",{className:"search-input",type:"search","aria-label":"Search archive","aria-busy":p,placeholder:"Search titles, URLs, types, tags…",value:x,onChange:$=>k($.target.value)}),i.jsx("span",{className:"kbd",children:"⌘K"})]}),i.jsxs("span",{className:"result-count",children:[E&&i.jsxs(i.Fragment,{children:[i.jsx("b",{children:E.split(" ")[0]})," ",E.split(" ").slice(1).join(" ")]}),S&&i.jsxs("button",{className:"tag-filter-badge",onClick:Qe,children:["× ",C?Dc(S):S]})]})]}),O==="archive"&&i.jsx(ah,{entries:u,selectedEntryUid:y,onSelectEntry:we,archiveId:o,tagFilter:S,onClearTagFilter:Qe,searchQuery:x,onSearchChange:k,resultCount:E,searchBusy:p}),O==="runs"&&i.jsx(dh,{runs:T}),O==="admin"&&i.jsx(ph,{archives:l}),O==="tags"&&i.jsx(hh,{archiveId:o,tagNodes:U,tagFilter:S,onTagFilterSet:ce,onViewChange:A,onTagRenamed:lt,onTagDeleted:Dl,onTagsRefresh:Fe,humanizeTags:C}),O==="collections"&&i.jsx(gh,{archiveId:o}),O==="settings"&&i.jsx(yh,{tab:d,onTabChange:h,archiveId:o})]}),i.jsx(Ch,{archiveId:o,selectedEntry:m,onTagFilterSet:ce,tagNodes:U,onTagsRefresh:Fe,onEntryTitleChange:Ol,onEntryDeleted:$l,humanizeTags:C})]}),i.jsx(rh,{open:F,archiveId:o,onClose:Fl,onCaptured:R,onToast:V}),i.jsx(Eh,{toasts:q,onDismiss:Pe})]})})}Pc(document.getElementById("root")).render(i.jsx(v.StrictMode,{children:i.jsx(Rh,{})})); diff --git a/crates/archivr-server/static/assets/index-D6iX-c2T.js b/crates/archivr-server/static/assets/index-D6iX-c2T.js new file mode 100644 index 0000000..9088806 --- /dev/null +++ b/crates/archivr-server/static/assets/index-D6iX-c2T.js @@ -0,0 +1,40 @@ +(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 s of l)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(l){const s={};return l.integrity&&(s.integrity=l.integrity),l.referrerPolicy&&(s.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?s.credentials="include":l.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(l){if(l.ep)return;l.ep=!0;const s=n(l);fetch(l.href,s)}})();var wo={exports:{}},yl={},ko={exports:{}},U={};/** + * @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 pr=Symbol.for("react.element"),Bc=Symbol.for("react.portal"),Vc=Symbol.for("react.fragment"),Wc=Symbol.for("react.strict_mode"),Hc=Symbol.for("react.profiler"),Qc=Symbol.for("react.provider"),Kc=Symbol.for("react.context"),bc=Symbol.for("react.forward_ref"),Jc=Symbol.for("react.suspense"),Xc=Symbol.for("react.memo"),Yc=Symbol.for("react.lazy"),sa=Symbol.iterator;function Gc(e){return e===null||typeof e!="object"?null:(e=sa&&e[sa]||e["@@iterator"],typeof e=="function"?e:null)}var So={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},jo=Object.assign,No={};function Nn(e,t,n){this.props=e,this.context=t,this.refs=No,this.updater=n||So}Nn.prototype.isReactComponent={};Nn.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")};Nn.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Co(){}Co.prototype=Nn.prototype;function ci(e,t,n){this.props=e,this.context=t,this.refs=No,this.updater=n||So}var di=ci.prototype=new Co;di.constructor=ci;jo(di,Nn.prototype);di.isPureReactComponent=!0;var ia=Array.isArray,_o=Object.prototype.hasOwnProperty,fi={current:null},Eo={key:!0,ref:!0,__self:!0,__source:!0};function To(e,t,n){var r,l={},s=null,a=null;if(t!=null)for(r in t.ref!==void 0&&(a=t.ref),t.key!==void 0&&(s=""+t.key),t)_o.call(t,r)&&!Eo.hasOwnProperty(r)&&(l[r]=t[r]);var o=arguments.length-2;if(o===1)l.children=n;else if(1>>1,R=P[M];if(0>>1;Ml(V,C))Wl(re,V)?(P[M]=re,P[W]=C,M=W):(P[M]=V,P[A]=C,M=A);else if(Wl(re,C))P[M]=re,P[W]=C,M=W;else break e}}return p}function l(P,p){var C=P.sortIndex-p.sortIndex;return C!==0?C:P.id-p.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var a=Date,o=a.now();e.unstable_now=function(){return a.now()-o}}var u=[],c=[],y=1,m=null,g=3,x=!1,k=!1,S=!1,D=typeof setTimeout=="function"?setTimeout:null,f=typeof clearTimeout=="function"?clearTimeout:null,d=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function v(P){for(var p=n(c);p!==null;){if(p.callback===null)r(c);else if(p.startTime<=P)r(c),p.sortIndex=p.expirationTime,t(u,p);else break;p=n(c)}}function w(P){if(S=!1,v(P),!k)if(n(u)!==null)k=!0,Ee(j);else{var p=n(c);p!==null&&he(w,p.startTime-P)}}function j(P,p){k=!1,S&&(S=!1,f(N),N=-1),x=!0;var C=g;try{for(v(p),m=n(u);m!==null&&(!(m.expirationTime>p)||P&&!J());){var M=m.callback;if(typeof M=="function"){m.callback=null,g=m.priorityLevel;var R=M(m.expirationTime<=p);p=e.unstable_now(),typeof R=="function"?m.callback=R:m===n(u)&&r(u),v(p)}else r(u);m=n(u)}if(m!==null)var B=!0;else{var A=n(c);A!==null&&he(w,A.startTime-p),B=!1}return B}finally{m=null,g=C,x=!1}}var E=!1,T=null,N=-1,F=5,$=-1;function J(){return!(e.unstable_now()-$P||125M?(P.sortIndex=C,t(c,P),n(u)===null&&P===n(c)&&(S?(f(N),N=-1):S=!0,he(w,C-M))):(P.sortIndex=R,t(u,P),k||x||(k=!0,Ee(j))),P},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(P){var p=g;return function(){var C=g;g=p;try{return P.apply(this,arguments)}finally{g=C}}}})(Do);zo.exports=Do;var od=zo.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 ud=h,Fe=od;function _(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"),ms=Object.prototype.hasOwnProperty,cd=/^[: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]*$/,oa={},ua={};function dd(e){return ms.call(ua,e)?!0:ms.call(oa,e)?!1:cd.test(e)?ua[e]=!0:(oa[e]=!0,!1)}function fd(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 pd(e,t,n,r){if(t===null||typeof t>"u"||fd(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 _e(e,t,n,r,l,s,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=s,this.removeEmptyString=a}var ve={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){ve[e]=new _e(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];ve[t]=new _e(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){ve[e]=new _e(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){ve[e]=new _e(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){ve[e]=new _e(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){ve[e]=new _e(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){ve[e]=new _e(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){ve[e]=new _e(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){ve[e]=new _e(e,5,!1,e.toLowerCase(),null,!1,!1)});var hi=/[\-:]([a-z])/g;function mi(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(hi,mi);ve[t]=new _e(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(hi,mi);ve[t]=new _e(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(hi,mi);ve[t]=new _e(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){ve[e]=new _e(e,1,!1,e.toLowerCase(),null,!1,!1)});ve.xlinkHref=new _e("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){ve[e]=new _e(e,1,!1,e.toLowerCase(),null,!0,!0)});function gi(e,t,n,r){var l=ve.hasOwnProperty(t)?ve[t]:null;(l!==null?l.type!==0:r||!(2o||l[a]!==s[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{Bl=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Mn(e):""}function hd(e){switch(e.tag){case 5:return Mn(e.type);case 16:return Mn("Lazy");case 13:return Mn("Suspense");case 19:return Mn("SuspenseList");case 0:case 2:case 15:return e=Vl(e.type,!1),e;case 11:return e=Vl(e.type.render,!1),e;case 1:return e=Vl(e.type,!0),e;default:return""}}function xs(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 Zt:return"Fragment";case qt:return"Portal";case gs:return"Profiler";case vi:return"StrictMode";case vs:return"Suspense";case ys:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Mo:return(e.displayName||"Context")+".Consumer";case $o:return(e._context.displayName||"Context")+".Provider";case yi:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case xi:return t=e.displayName||null,t!==null?t:xs(e.type)||"Memo";case vt:t=e._payload,e=e._init;try{return xs(e(t))}catch{}}return null}function md(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 xs(t);case 8:return t===vi?"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 Rt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Io(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function gd(e){var t=Io(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,s=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(a){r=""+a,s.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 kr(e){e._valueTracker||(e._valueTracker=gd(e))}function Ao(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=Io(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Jr(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 ws(e,t){var n=t.checked;return ne({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function da(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Rt(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 Uo(e,t){t=t.checked,t!=null&&gi(e,"checked",t,!1)}function ks(e,t){Uo(e,t);var n=Rt(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")?Ss(e,t.type,n):t.hasOwnProperty("defaultValue")&&Ss(e,t.type,Rt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function fa(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 Ss(e,t,n){(t!=="number"||Jr(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Fn=Array.isArray;function dn(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=Sr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Gn(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Bn={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},vd=["Webkit","ms","Moz","O"];Object.keys(Bn).forEach(function(e){vd.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Bn[t]=Bn[e]})});function Ho(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Bn.hasOwnProperty(e)&&Bn[e]?(""+t).trim():t+"px"}function Qo(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=Ho(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var yd=ne({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 Cs(e,t){if(t){if(yd[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(_(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(_(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(_(61))}if(t.style!=null&&typeof t.style!="object")throw Error(_(62))}}function _s(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 Es=null;function wi(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Ts=null,fn=null,pn=null;function ma(e){if(e=gr(e)){if(typeof Ts!="function")throw Error(_(280));var t=e.stateNode;t&&(t=jl(t),Ts(e.stateNode,e.type,t))}}function Ko(e){fn?pn?pn.push(e):pn=[e]:fn=e}function bo(){if(fn){var e=fn,t=pn;if(pn=fn=null,ma(e),t)for(e=0;e>>=0,e===0?32:31-(Pd(e)/Ld|0)|0}var jr=64,Nr=4194304;function In(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 qr(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,s=e.pingedLanes,a=n&268435455;if(a!==0){var o=a&~l;o!==0?r=In(o):(s&=a,s!==0&&(r=In(s)))}else a=n&~l,a!==0?r=In(a):s!==0&&(r=In(s));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,s=t&-t,l>=s||l===16&&(s&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 hr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ge(t),e[t]=n}function Od(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=Wn),Na=" ",Ca=!1;function pu(e,t){switch(e){case"keyup":return uf.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function hu(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var en=!1;function df(e,t){switch(e){case"compositionend":return hu(t);case"keypress":return t.which!==32?null:(Ca=!0,Na);case"textInput":return e=t.data,e===Na&&Ca?null:e;default:return null}}function ff(e,t){if(en)return e==="compositionend"||!Ti&&pu(e,t)?(e=du(),Ar=Ci=kt=null,en=!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=Pa(n)}}function yu(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?yu(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function xu(){for(var e=window,t=Jr();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Jr(e.document)}return t}function Pi(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 kf(e){var t=xu(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&yu(n.ownerDocument.documentElement,n)){if(r!==null&&Pi(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,s=Math.min(r.start,l);r=r.end===void 0?s:Math.min(r.end,l),!e.extend&&s>r&&(l=r,r=s,s=l),l=La(n,s);var a=La(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(),s>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,tn=null,Os=null,Qn=null,$s=!1;function Ra(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;$s||tn==null||tn!==Jr(r)||(r=tn,"selectionStart"in r&&Pi(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}),Qn&&rr(Qn,r)||(Qn=r,r=tl(Os,"onSelect"),0ln||(e.current=Bs[ln],Bs[ln]=null,ln--)}function Y(e,t){ln++,Bs[ln]=e.current,e.current=t}var zt={},Se=Ot(zt),Le=Ot(!1),Ht=zt;function yn(e,t){var n=e.type.contextTypes;if(!n)return zt;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},s;for(s in n)l[s]=t[s];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function Re(e){return e=e.childContextTypes,e!=null}function rl(){q(Le),q(Se)}function Ia(e,t,n){if(Se.current!==zt)throw Error(_(168));Y(Se,t),Y(Le,n)}function Tu(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(_(108,md(e)||"Unknown",l));return ne({},n,r)}function ll(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||zt,Ht=Se.current,Y(Se,e),Y(Le,Le.current),!0}function Aa(e,t,n){var r=e.stateNode;if(!r)throw Error(_(169));n?(e=Tu(e,t,Ht),r.__reactInternalMemoizedMergedChildContext=e,q(Le),q(Se),Y(Se,e)):q(Le),Y(Le,n)}var at=null,Nl=!1,ns=!1;function Pu(e){at===null?at=[e]:at.push(e)}function Df(e){Nl=!0,Pu(e)}function $t(){if(!ns&&at!==null){ns=!0;var e=0,t=X;try{var n=at;for(X=1;e>=a,l-=a,ot=1<<32-Ge(t)+l|n<N?(F=T,T=null):F=T.sibling;var $=g(f,T,v[N],w);if($===null){T===null&&(T=F);break}e&&T&&$.alternate===null&&t(f,T),d=s($,d,N),E===null?j=$:E.sibling=$,E=$,T=F}if(N===v.length)return n(f,T),Z&&Mt(f,N),j;if(T===null){for(;NN?(F=T,T=null):F=T.sibling;var J=g(f,T,$.value,w);if(J===null){T===null&&(T=F);break}e&&T&&J.alternate===null&&t(f,T),d=s(J,d,N),E===null?j=J:E.sibling=J,E=J,T=F}if($.done)return n(f,T),Z&&Mt(f,N),j;if(T===null){for(;!$.done;N++,$=v.next())$=m(f,$.value,w),$!==null&&(d=s($,d,N),E===null?j=$:E.sibling=$,E=$);return Z&&Mt(f,N),j}for(T=r(f,T);!$.done;N++,$=v.next())$=x(T,f,N,$.value,w),$!==null&&(e&&$.alternate!==null&&T.delete($.key===null?N:$.key),d=s($,d,N),E===null?j=$:E.sibling=$,E=$);return e&&T.forEach(function(se){return t(f,se)}),Z&&Mt(f,N),j}function D(f,d,v,w){if(typeof v=="object"&&v!==null&&v.type===Zt&&v.key===null&&(v=v.props.children),typeof v=="object"&&v!==null){switch(v.$$typeof){case wr:e:{for(var j=v.key,E=d;E!==null;){if(E.key===j){if(j=v.type,j===Zt){if(E.tag===7){n(f,E.sibling),d=l(E,v.props.children),d.return=f,f=d;break e}}else if(E.elementType===j||typeof j=="object"&&j!==null&&j.$$typeof===vt&&Va(j)===E.type){n(f,E.sibling),d=l(E,v.props),d.ref=zn(f,E,v),d.return=f,f=d;break e}n(f,E);break}else t(f,E);E=E.sibling}v.type===Zt?(d=Wt(v.props.children,f.mode,w,v.key),d.return=f,f=d):(w=br(v.type,v.key,v.props,null,f.mode,w),w.ref=zn(f,d,v),w.return=f,f=w)}return a(f);case qt:e:{for(E=v.key;d!==null;){if(d.key===E)if(d.tag===4&&d.stateNode.containerInfo===v.containerInfo&&d.stateNode.implementation===v.implementation){n(f,d.sibling),d=l(d,v.children||[]),d.return=f,f=d;break e}else{n(f,d);break}else t(f,d);d=d.sibling}d=cs(v,f.mode,w),d.return=f,f=d}return a(f);case vt:return E=v._init,D(f,d,E(v._payload),w)}if(Fn(v))return k(f,d,v,w);if(En(v))return S(f,d,v,w);Rr(f,v)}return typeof v=="string"&&v!==""||typeof v=="number"?(v=""+v,d!==null&&d.tag===6?(n(f,d.sibling),d=l(d,v),d.return=f,f=d):(n(f,d),d=us(v,f.mode,w),d.return=f,f=d),a(f)):n(f,d)}return D}var wn=Du(!0),Ou=Du(!1),al=Ot(null),ol=null,on=null,Di=null;function Oi(){Di=on=ol=null}function $i(e){var t=al.current;q(al),e._currentValue=t}function Hs(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 mn(e,t){ol=e,Di=on=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Pe=!0),e.firstContext=null)}function Qe(e){var t=e._currentValue;if(Di!==e)if(e={context:e,memoizedValue:t,next:null},on===null){if(ol===null)throw Error(_(308));on=e,ol.dependencies={lanes:0,firstContext:e}}else on=on.next=e;return t}var At=null;function Mi(e){At===null?At=[e]:At.push(e)}function $u(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,Mi(t)):(n.next=l.next,l.next=n),t.interleaved=n,pt(e,r)}function pt(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 yt=!1;function Fi(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Mu(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 ct(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Et(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Q&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,pt(e,n)}return l=r.interleaved,l===null?(t.next=t,Mi(r)):(t.next=l.next,l.next=t),r.interleaved=t,pt(e,n)}function Br(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,Si(e,n)}}function Wa(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,s=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};s===null?l=s=a:s=s.next=a,n=n.next}while(n!==null);s===null?l=s=t:s=s.next=t}else l=s=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:s,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 ul(e,t,n,r){var l=e.updateQueue;yt=!1;var s=l.firstBaseUpdate,a=l.lastBaseUpdate,o=l.shared.pending;if(o!==null){l.shared.pending=null;var u=o,c=u.next;u.next=null,a===null?s=c:a.next=c,a=u;var y=e.alternate;y!==null&&(y=y.updateQueue,o=y.lastBaseUpdate,o!==a&&(o===null?y.firstBaseUpdate=c:o.next=c,y.lastBaseUpdate=u))}if(s!==null){var m=l.baseState;a=0,y=c=u=null,o=s;do{var g=o.lane,x=o.eventTime;if((r&g)===g){y!==null&&(y=y.next={eventTime:x,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var k=e,S=o;switch(g=t,x=n,S.tag){case 1:if(k=S.payload,typeof k=="function"){m=k.call(x,m,g);break e}m=k;break e;case 3:k.flags=k.flags&-65537|128;case 0:if(k=S.payload,g=typeof k=="function"?k.call(x,m,g):k,g==null)break e;m=ne({},m,g);break e;case 2:yt=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,g=l.effects,g===null?l.effects=[o]:g.push(o))}else x={eventTime:x,lane:g,tag:o.tag,payload:o.payload,callback:o.callback,next:null},y===null?(c=y=x,u=m):y=y.next=x,a|=g;if(o=o.next,o===null){if(o=l.shared.pending,o===null)break;g=o,o=g.next,g.next=null,l.lastBaseUpdate=g,l.shared.pending=null}}while(!0);if(y===null&&(u=m),l.baseState=u,l.firstBaseUpdate=c,l.lastBaseUpdate=y,t=l.shared.interleaved,t!==null){l=t;do a|=l.lane,l=l.next;while(l!==t)}else s===null&&(l.shared.lanes=0);bt|=a,e.lanes=a,e.memoizedState=m}}function Ha(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=ls.transition;ls.transition={};try{e(!1),t()}finally{X=n,ls.transition=r}}function Zu(){return Ke().memoizedState}function Ff(e,t,n){var r=Pt(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},ec(e))tc(t,n);else if(n=$u(e,t,n,r),n!==null){var l=Ne();qe(n,e,r,l),nc(n,t,r)}}function If(e,t,n){var r=Pt(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(ec(e))tc(t,l);else{var s=e.alternate;if(e.lanes===0&&(s===null||s.lanes===0)&&(s=t.lastRenderedReducer,s!==null))try{var a=t.lastRenderedState,o=s(a,n);if(l.hasEagerState=!0,l.eagerState=o,Ze(o,a)){var u=t.interleaved;u===null?(l.next=l,Mi(t)):(l.next=u.next,u.next=l),t.interleaved=l;return}}catch{}finally{}n=$u(e,t,l,r),n!==null&&(l=Ne(),qe(n,e,r,l),nc(n,t,r))}}function ec(e){var t=e.alternate;return e===te||t!==null&&t===te}function tc(e,t){Kn=dl=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function nc(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Si(e,n)}}var fl={readContext:Qe,useCallback:xe,useContext:xe,useEffect:xe,useImperativeHandle:xe,useInsertionEffect:xe,useLayoutEffect:xe,useMemo:xe,useReducer:xe,useRef:xe,useState:xe,useDebugValue:xe,useDeferredValue:xe,useTransition:xe,useMutableSource:xe,useSyncExternalStore:xe,useId:xe,unstable_isNewReconciler:!1},Af={readContext:Qe,useCallback:function(e,t){return tt().memoizedState=[e,t===void 0?null:t],e},useContext:Qe,useEffect:Ka,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Wr(4194308,4,Ju.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Wr(4194308,4,e,t)},useInsertionEffect:function(e,t){return Wr(4,2,e,t)},useMemo:function(e,t){var n=tt();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=tt();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=Ff.bind(null,te,e),[r.memoizedState,e]},useRef:function(e){var t=tt();return e={current:e},t.memoizedState=e},useState:Qa,useDebugValue:Qi,useDeferredValue:function(e){return tt().memoizedState=e},useTransition:function(){var e=Qa(!1),t=e[0];return e=Mf.bind(null,e[1]),tt().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=te,l=tt();if(Z){if(n===void 0)throw Error(_(407));n=n()}else{if(n=t(),fe===null)throw Error(_(349));Kt&30||Uu(r,t,n)}l.memoizedState=n;var s={value:n,getSnapshot:t};return l.queue=s,Ka(Vu.bind(null,r,s,e),[e]),r.flags|=2048,dr(9,Bu.bind(null,r,s,n,t),void 0,null),n},useId:function(){var e=tt(),t=fe.identifierPrefix;if(Z){var n=ut,r=ot;n=(r&~(1<<32-Ge(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=ur++,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[nt]=t,e[ir]=r,fc(e,t,!1,!1),t.stateNode=e;e:{switch(a=_s(n,r),n){case"dialog":G("cancel",e),G("close",e),l=r;break;case"iframe":case"object":case"embed":G("load",e),l=r;break;case"video":case"audio":for(l=0;ljn&&(t.flags|=128,r=!0,Dn(s,!1),t.lanes=4194304)}else{if(!r)if(e=cl(a),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Dn(s,!0),s.tail===null&&s.tailMode==="hidden"&&!a.alternate&&!Z)return we(t),null}else 2*ie()-s.renderingStartTime>jn&&n!==1073741824&&(t.flags|=128,r=!0,Dn(s,!1),t.lanes=4194304);s.isBackwards?(a.sibling=t.child,t.child=a):(n=s.last,n!==null?n.sibling=a:t.child=a,s.last=a)}return s.tail!==null?(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=ie(),t.sibling=null,n=ee.current,Y(ee,r?n&1|2:n&1),t):(we(t),null);case 22:case 23:return Gi(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Oe&1073741824&&(we(t),t.subtreeFlags&6&&(t.flags|=8192)):we(t),null;case 24:return null;case 25:return null}throw Error(_(156,t.tag))}function bf(e,t){switch(Ri(t),t.tag){case 1:return Re(t.type)&&rl(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return kn(),q(Le),q(Se),Ui(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Ai(t),null;case 13:if(q(ee),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(_(340));xn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return q(ee),null;case 4:return kn(),null;case 10:return $i(t.type._context),null;case 22:case 23:return Gi(),null;case 24:return null;default:return null}}var Dr=!1,ke=!1,Jf=typeof WeakSet=="function"?WeakSet:Set,z=null;function un(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){le(e,t,r)}else n.current=null}function Zs(e,t,n){try{n()}catch(r){le(e,t,r)}}var ro=!1;function Xf(e,t){if(Ms=Zr,e=xu(),Pi(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,s=r.focusNode;r=r.focusOffset;try{n.nodeType,s.nodeType}catch{n=null;break e}var a=0,o=-1,u=-1,c=0,y=0,m=e,g=null;t:for(;;){for(var x;m!==n||l!==0&&m.nodeType!==3||(o=a+l),m!==s||r!==0&&m.nodeType!==3||(u=a+r),m.nodeType===3&&(a+=m.nodeValue.length),(x=m.firstChild)!==null;)g=m,m=x;for(;;){if(m===e)break t;if(g===n&&++c===l&&(o=a),g===s&&++y===r&&(u=a),(x=m.nextSibling)!==null)break;m=g,g=m.parentNode}m=x}n=o===-1||u===-1?null:{start:o,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(Fs={focusedElem:e,selectionRange:n},Zr=!1,z=t;z!==null;)if(t=z,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,z=e;else for(;z!==null;){t=z;try{var k=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(k!==null){var S=k.memoizedProps,D=k.memoizedState,f=t.stateNode,d=f.getSnapshotBeforeUpdate(t.elementType===t.type?S:Je(t.type,S),D);f.__reactInternalSnapshotBeforeUpdate=d}break;case 3:var v=t.stateNode.containerInfo;v.nodeType===1?v.textContent="":v.nodeType===9&&v.documentElement&&v.removeChild(v.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(_(163))}}catch(w){le(t,t.return,w)}if(e=t.sibling,e!==null){e.return=t.return,z=e;break}z=t.return}return k=ro,ro=!1,k}function bn(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 s=l.destroy;l.destroy=void 0,s!==void 0&&Zs(t,n,s)}l=l.next}while(l!==r)}}function El(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 ei(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 mc(e){var t=e.alternate;t!==null&&(e.alternate=null,mc(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[nt],delete t[ir],delete t[Us],delete t[Rf],delete t[zf])),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 gc(e){return e.tag===5||e.tag===3||e.tag===4}function lo(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||gc(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 ti(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=nl));else if(r!==4&&(e=e.child,e!==null))for(ti(e,t,n),e=e.sibling;e!==null;)ti(e,t,n),e=e.sibling}function ni(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(ni(e,t,n),e=e.sibling;e!==null;)ni(e,t,n),e=e.sibling}var me=null,Xe=!1;function gt(e,t,n){for(n=n.child;n!==null;)vc(e,t,n),n=n.sibling}function vc(e,t,n){if(rt&&typeof rt.onCommitFiberUnmount=="function")try{rt.onCommitFiberUnmount(xl,n)}catch{}switch(n.tag){case 5:ke||un(n,t);case 6:var r=me,l=Xe;me=null,gt(e,t,n),me=r,Xe=l,me!==null&&(Xe?(e=me,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):me.removeChild(n.stateNode));break;case 18:me!==null&&(Xe?(e=me,n=n.stateNode,e.nodeType===8?ts(e.parentNode,n):e.nodeType===1&&ts(e,n),tr(e)):ts(me,n.stateNode));break;case 4:r=me,l=Xe,me=n.stateNode.containerInfo,Xe=!0,gt(e,t,n),me=r,Xe=l;break;case 0:case 11:case 14:case 15:if(!ke&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var s=l,a=s.destroy;s=s.tag,a!==void 0&&(s&2||s&4)&&Zs(n,t,a),l=l.next}while(l!==r)}gt(e,t,n);break;case 1:if(!ke&&(un(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){le(n,t,o)}gt(e,t,n);break;case 21:gt(e,t,n);break;case 22:n.mode&1?(ke=(r=ke)||n.memoizedState!==null,gt(e,t,n),ke=r):gt(e,t,n);break;default:gt(e,t,n)}}function so(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Jf),t.forEach(function(r){var l=lp.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function be(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=a),r&=~s}if(r=l,r=ie()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Gf(r/1960))-r,10e?16:e,St===null)var r=!1;else{if(e=St,St=null,ml=0,Q&6)throw Error(_(331));var l=Q;for(Q|=4,z=e.current;z!==null;){var s=z,a=s.child;if(z.flags&16){var o=s.deletions;if(o!==null){for(var u=0;uie()-Xi?Vt(e,0):Ji|=n),ze(e,t)}function Cc(e,t){t===0&&(e.mode&1?(t=Nr,Nr<<=1,!(Nr&130023424)&&(Nr=4194304)):t=1);var n=Ne();e=pt(e,t),e!==null&&(hr(e,t,n),ze(e,n))}function rp(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Cc(e,n)}function lp(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(_(314))}r!==null&&r.delete(t),Cc(e,n)}var _c;_c=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Le.current)Pe=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Pe=!1,Qf(e,t,n);Pe=!!(e.flags&131072)}else Pe=!1,Z&&t.flags&1048576&&Lu(t,il,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Hr(e,t),e=t.pendingProps;var l=yn(t,Se.current);mn(t,n),l=Vi(null,t,r,e,l,n);var s=Wi();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,Re(r)?(s=!0,ll(t)):s=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,Fi(t),l.updater=_l,t.stateNode=l,l._reactInternals=t,Ks(t,r,e,n),t=Xs(null,t,r,!0,s,n)):(t.tag=0,Z&&s&&Li(t),je(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Hr(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=ip(r),e=Je(r,e),l){case 0:t=Js(null,t,r,e,n);break e;case 1:t=eo(null,t,r,e,n);break e;case 11:t=qa(null,t,r,e,n);break e;case 14:t=Za(null,t,r,Je(r.type,e),n);break e}throw Error(_(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Je(r,l),Js(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Je(r,l),eo(e,t,r,l,n);case 3:e:{if(uc(t),e===null)throw Error(_(387));r=t.pendingProps,s=t.memoizedState,l=s.element,Mu(e,t),ul(t,r,null,n);var a=t.memoizedState;if(r=a.element,s.isDehydrated)if(s={element:r,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},t.updateQueue.baseState=s,t.memoizedState=s,t.flags&256){l=Sn(Error(_(423)),t),t=to(e,t,r,n,l);break e}else if(r!==l){l=Sn(Error(_(424)),t),t=to(e,t,r,n,l);break e}else for($e=_t(t.stateNode.containerInfo.firstChild),Me=t,Z=!0,Ye=null,n=Ou(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(xn(),r===l){t=ht(e,t,n);break e}je(e,t,r,n)}t=t.child}return t;case 5:return Fu(t),e===null&&Ws(t),r=t.type,l=t.pendingProps,s=e!==null?e.memoizedProps:null,a=l.children,Is(r,l)?a=null:s!==null&&Is(r,s)&&(t.flags|=32),oc(e,t),je(e,t,a,n),t.child;case 6:return e===null&&Ws(t),null;case 13:return cc(e,t,n);case 4:return Ii(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=wn(t,null,r,n):je(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Je(r,l),qa(e,t,r,l,n);case 7:return je(e,t,t.pendingProps,n),t.child;case 8:return je(e,t,t.pendingProps.children,n),t.child;case 12:return je(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,s=t.memoizedProps,a=l.value,Y(al,r._currentValue),r._currentValue=a,s!==null)if(Ze(s.value,a)){if(s.children===l.children&&!Le.current){t=ht(e,t,n);break e}}else for(s=t.child,s!==null&&(s.return=t);s!==null;){var o=s.dependencies;if(o!==null){a=s.child;for(var u=o.firstContext;u!==null;){if(u.context===r){if(s.tag===1){u=ct(-1,n&-n),u.tag=2;var c=s.updateQueue;if(c!==null){c=c.shared;var y=c.pending;y===null?u.next=u:(u.next=y.next,y.next=u),c.pending=u}}s.lanes|=n,u=s.alternate,u!==null&&(u.lanes|=n),Hs(s.return,n,t),o.lanes|=n;break}u=u.next}}else if(s.tag===10)a=s.type===t.type?null:s.child;else if(s.tag===18){if(a=s.return,a===null)throw Error(_(341));a.lanes|=n,o=a.alternate,o!==null&&(o.lanes|=n),Hs(a,n,t),a=s.sibling}else a=s.child;if(a!==null)a.return=s;else for(a=s;a!==null;){if(a===t){a=null;break}if(s=a.sibling,s!==null){s.return=a.return,a=s;break}a=a.return}s=a}je(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,mn(t,n),l=Qe(l),r=r(l),t.flags|=1,je(e,t,r,n),t.child;case 14:return r=t.type,l=Je(r,t.pendingProps),l=Je(r.type,l),Za(e,t,r,l,n);case 15:return ic(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Je(r,l),Hr(e,t),t.tag=1,Re(r)?(e=!0,ll(t)):e=!1,mn(t,n),rc(t,r,l),Ks(t,r,l,n),Xs(null,t,r,!0,e,n);case 19:return dc(e,t,n);case 22:return ac(e,t,n)}throw Error(_(156,t.tag))};function Ec(e,t){return eu(e,t)}function sp(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 We(e,t,n,r){return new sp(e,t,n,r)}function Zi(e){return e=e.prototype,!(!e||!e.isReactComponent)}function ip(e){if(typeof e=="function")return Zi(e)?1:0;if(e!=null){if(e=e.$$typeof,e===yi)return 11;if(e===xi)return 14}return 2}function Lt(e,t){var n=e.alternate;return n===null?(n=We(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 br(e,t,n,r,l,s){var a=2;if(r=e,typeof e=="function")Zi(e)&&(a=1);else if(typeof e=="string")a=5;else e:switch(e){case Zt:return Wt(n.children,l,s,t);case vi:a=8,l|=8;break;case gs:return e=We(12,n,t,l|2),e.elementType=gs,e.lanes=s,e;case vs:return e=We(13,n,t,l),e.elementType=vs,e.lanes=s,e;case ys:return e=We(19,n,t,l),e.elementType=ys,e.lanes=s,e;case Fo:return Pl(n,l,s,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case $o:a=10;break e;case Mo:a=9;break e;case yi:a=11;break e;case xi:a=14;break e;case vt:a=16,r=null;break e}throw Error(_(130,e==null?e:typeof e,""))}return t=We(a,n,t,l),t.elementType=e,t.type=r,t.lanes=s,t}function Wt(e,t,n,r){return e=We(7,e,r,t),e.lanes=n,e}function Pl(e,t,n,r){return e=We(22,e,r,t),e.elementType=Fo,e.lanes=n,e.stateNode={isHidden:!1},e}function us(e,t,n){return e=We(6,e,null,t),e.lanes=n,e}function cs(e,t,n){return t=We(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function ap(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=Hl(0),this.expirationTimes=Hl(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Hl(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function ea(e,t,n,r,l,s,a,o,u){return e=new ap(e,t,n,o,u),t===1?(t=1,s===!0&&(t|=8)):t=0,s=We(3,null,null,t),e.current=s,s.stateNode=e,s.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Fi(s),e}function op(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Rc)}catch(e){console.error(e)}}Rc(),Ro.exports=Ie;var pp=Ro.exports,zc,ho=pp;zc=ho.createRoot,ho.hydrateRoot;async function pe(e){const t=await fetch(e);if(!t.ok)throw new Error(`${t.status} ${t.statusText}`);return t.json()}async function hp(){return pe("/api/archives")}async function mp(e){return pe(`/api/archives/${e}/entries`)}async function gp(e,t,n){const r=new URLSearchParams;return t&&r.set("q",t),n&&r.set("tag",n),pe(`/api/archives/${e}/entries/search?${r}`)}async function vp(e,t){return pe(`/api/archives/${e}/entries/${t}`)}async function yp(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 ds(e,t){return pe(`/api/archives/${e}/entries/${t}/tags`)}async function xp(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 wp(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 kp(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 Sp(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 jp(e,t){const n=await fetch(`/api/archives/${e}/tags/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(await n.text())}async function mo(e){return pe(`/api/archives/${e}/runs`)}async function fs(e){return pe(`/api/archives/${e}/tags`)}async function Np(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));const s=await fetch(`/api/archives/${e}/captures`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!s.ok){const a=await s.json().catch(()=>({}));throw new Error(a.error||`HTTP ${s.status}`)}return s.json()}async function Cp(e,t){return pe(`/api/archives/${e}/captures/probe?locator=${encodeURIComponent(t)}`)}async function _p(e,t){return pe(`/api/archives/${e}/capture_jobs/${t}`)}async function Ep(){return(await(await fetch("/api/auth/setup")).json()).setup_required===!0}async function Tp(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 Pp(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 Lp(){await fetch("/api/auth/logout",{method:"POST"})}async function Rp(){const e=await fetch("/api/auth/me");return e.status===401?null:e.json()}async function zp(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 Dp(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 Op(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 $p(){return pe("/api/auth/tokens")}async function Mp(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 Fp(e){const t=await fetch(`/api/auth/tokens/${e}`,{method:"DELETE"});if(!t.ok)throw new Error(await t.text())}async function la(){return pe("/api/admin/instance-settings")}async function ai(e){const t=await fetch("/api/admin/instance-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(await t.text())}async function Ip(){return pe("/api/admin/users")}async function Ap(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 Up(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 Bp(){return pe("/api/admin/roles")}async function Vp(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 Wp(e){return pe(`/api/archives/${e}/collections`)}async function Hp(e,t,n,r=2){const l=await fetch(`/api/archives/${e}/collections`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:t,slug:n,default_visibility_bits:r})});if(!l.ok){const s=await l.json().catch(()=>({error:l.statusText}));throw new Error(s.error||l.statusText)}return l.json()}async function Qp(e,t){return pe(`/api/archives/${e}/collections/${t}`)}async function Kp(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 s=await l.json().catch(()=>({error:l.statusText}));throw new Error(s.error||l.statusText)}}async function bp(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 Jp(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 s=await l.json().catch(()=>({error:l.statusText}));throw new Error(s.error||l.statusText)}}async function Xp(e,t){return pe(`/api/archives/${e}/entries/${t}/collections`)}async function go(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 Yp(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 Gp(e){return pe(`/api/archives/${e}/blob-cleanup`)}async function qp(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 Zp(){return pe("/api/admin/cookie-rules")}async function eh(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 th(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 nh(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}`)}}const rh=window.fetch;window.fetch=async(...e)=>{var n;const t=await rh(...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 lh({onLogin:e}){const[t,n]=h.useState(""),[r,l]=h.useState(""),[s,a]=h.useState(null),[o,u]=h.useState(!1);async function c(y){y.preventDefault(),a(null),u(!0);try{const m=await Pp(t,r);e(m)}catch(m){a(m.message)}finally{u(!1)}}return i.jsx("div",{className:"login-page",children:i.jsxs("div",{className:"login-card",children:[i.jsx("h1",{className:"login-brand",children:"Archivr"}),i.jsx("p",{className:"login-tagline",children:"Sign in to your archive"}),i.jsxs("form",{onSubmit:c,children:[i.jsxs("div",{className:"login-field",children:[i.jsx("label",{className:"login-label",htmlFor:"login-username",children:"Username"}),i.jsx("input",{className:"login-input",id:"login-username",type:"text",value:t,onChange:y=>n(y.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),i.jsxs("div",{className:"login-field",children:[i.jsx("label",{className:"login-label",htmlFor:"login-password",children:"Password"}),i.jsx("input",{className:"login-input",id:"login-password",type:"password",value:r,onChange:y=>l(y.target.value),required:!0,autoComplete:"current-password"})]}),s&&i.jsx("p",{className:"login-error",children:s}),i.jsx("button",{className:"login-submit",type:"submit",disabled:o,children:o?"Signing in…":"Sign in"})]})]})})}function sh({onComplete:e}){const[t,n]=h.useState(""),[r,l]=h.useState(""),[s,a]=h.useState(""),[o,u]=h.useState(null),[c,y]=h.useState(!1);async function m(g){if(g.preventDefault(),r!==s){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 Tp(t,r),e()}catch(x){u(x.message)}finally{y(!1)}}return i.jsx("div",{className:"setup-page",children:i.jsxs("div",{className:"setup-card",children:[i.jsx("h1",{className:"setup-brand",children:"Archivr"}),i.jsx("p",{className:"setup-tagline",children:"Create your owner account to get started."}),i.jsxs("form",{onSubmit:m,children:[i.jsxs("div",{className:"setup-field",children:[i.jsx("label",{className:"setup-label",htmlFor:"setup-username",children:"Username"}),i.jsx("input",{className:"setup-input",id:"setup-username",type:"text",value:t,onChange:g=>n(g.target.value),autoFocus:!0,required:!0,autoComplete:"username"})]}),i.jsxs("div",{className:"setup-field",children:[i.jsx("label",{className:"setup-label",htmlFor:"setup-password",children:"Password"}),i.jsx("input",{className:"setup-input",id:"setup-password",type:"password",value:r,onChange:g=>l(g.target.value),required:!0,autoComplete:"new-password"})]}),i.jsxs("div",{className:"setup-field",children:[i.jsx("label",{className:"setup-label",htmlFor:"setup-confirm",children:"Confirm password"}),i.jsx("input",{className:"setup-input",id:"setup-confirm",type:"password",value:s,onChange:g=>a(g.target.value),required:!0,autoComplete:"new-password"})]}),o&&i.jsx("p",{className:"setup-error",children:o}),i.jsx("button",{className:"setup-submit",type:"submit",disabled:c,children:c?"Creating account…":"Create account"})]})]})})}function ih({archives:e,archiveId:t,onArchiveChange:n,view:r,onViewChange:l,onCaptureClick:s}){const{currentUser:a,setCurrentUser:o}=h.useContext(Ol)??{},[u,c]=h.useState(!1);async function y(){c(!0),await Lp(),o(null),window.location.reload()}return i.jsxs("header",{className:"topbar",children:[i.jsx("div",{className:"brand",children:"Archivr"}),i.jsx("div",{className:"switcher",children:i.jsx("select",{"aria-label":"Select archive",value:t??"",onChange:m=>n(m.target.value),children:e.map(m=>i.jsx("option",{value:m.id,children:m.label},m.id))})}),i.jsx("nav",{className:"nav","aria-label":"Primary",children:["archive","tags","collections","runs","admin","settings"].map(m=>i.jsx("button",{className:`nav-link${r===m?" is-active":""}`,onClick:()=>l(m),children:m.charAt(0).toUpperCase()+m.slice(1)},m))}),i.jsx("button",{className:"capture-button",onClick:s,children:"Capture"}),a&&i.jsxs("div",{className:"user-menu",children:[i.jsx("span",{className:"user-name",children:a.display_name||a.username}),i.jsx("button",{className:"logout-btn",onClick:y,disabled:u,children:u?"Logging out…":"Log out"})]})]})}let oi=1;function Dc(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/")}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 $n(e=""){return{id:oi++,locator:e,quality:"best",probeState:"idle",probeQualities:null,probeHasAudio:!1,status:"idle",error:null,jobUid:null,archiveId:null}}function vo(e){return e.some(t=>t.status==="submitting"||t.status==="running")}function ah({open:e,archiveId:t,onClose:n,onCaptured:r,onToast:l}){const s=h.useRef(null),a=h.useRef(!0),o=h.useRef(new Map),u=h.useRef(new Map),c=h.useRef(t);h.useEffect(()=>{c.current=t},[t]);const y=h.useRef(r),m=h.useRef(l);h.useEffect(()=>{y.current=r},[r]),h.useEffect(()=>{m.current=l},[l]);const[g,x]=h.useState(()=>{try{const p=JSON.parse(sessionStorage.getItem("captureItems")||"null");if(Array.isArray(p)&&p.length>0)return p.forEach(C=>{C.id>=oi&&(oi=C.id+1)}),p}catch{}return[$n()]});h.useEffect(()=>{sessionStorage.setItem("captureItems",JSON.stringify(g))},[g]);const[k,S]=h.useState(!1),[D,f]=h.useState(null),[d,v]=h.useState(null),[w,j]=h.useState(!0);h.useEffect(()=>{la().then(p=>{v(p),j(p.cookie_ext_enabled??!0)}).catch(()=>v({}))},[]);const E=D!==null?D:(d==null?void 0:d.ublock_enabled)??!0,[T,N]=h.useState(!1);h.useEffect(()=>{["captureDialogLocator","captureDialogError","captureDialogBusy","captureDialogJobStatus","captureDialogJobUid"].forEach(p=>sessionStorage.removeItem(p)),x(p=>p.map(C=>C.status==="submitting"?{...C,status:"idle",error:null}:C)),g.forEach(p=>{p.status==="running"&&p.jobUid&&p.archiveId&&!o.current.has(p.jobUid)&&F(p.id,p.jobUid,p.locator,p.archiveId)})},[]),h.useEffect(()=>{const p=s.current;if(!p)return;const C=()=>{u.current.forEach(M=>clearTimeout(M)),u.current.clear(),n()};return p.addEventListener("close",C),()=>p.removeEventListener("close",C)},[n]),h.useEffect(()=>{const p=s.current;p&&(e?(!a.current&&!vo(g)&&x([$n()]),a.current=!1,p.open||p.showModal()):(u.current.forEach(C=>clearTimeout(C)),u.current.clear(),p.open&&p.close()))},[e]),h.useEffect(()=>()=>{o.current.forEach(p=>clearInterval(p)),u.current.forEach(p=>clearTimeout(p))},[]);function F(p,C,M,R){if(o.current.has(C))return;const B=setInterval(async()=>{try{const A=await _p(R,C);if(A.status==="completed"){clearInterval(o.current.get(C)),o.current.delete(C),x(V=>V.map(W=>W.id===p?{...W,status:"completed"}:W)),setTimeout(()=>{x(V=>{const W=V.filter(re=>re.id!==p);return W.length===0?[$n()]:W})},1400),y.current();try{const V=A.notes_json?JSON.parse(A.notes_json):null;(V!=null&&V.ublock_skipped||V!=null&&V.cookie_ext_skipped)&&m.current(null,M,"warning")}catch{}}else if(A.status==="failed"){clearInterval(o.current.get(C)),o.current.delete(C);const V=A.error_text||"Capture failed.";x(W=>W.map(re=>re.id===p?{...re,status:"failed",error:V}:re)),m.current(V,M)}}catch(A){clearInterval(o.current.get(C)),o.current.delete(C);const V=A.message||"Network error";x(W=>W.map(re=>re.id===p?{...re,status:"failed",error:V}:re)),m.current(V,M)}},500);o.current.set(C,B)}async function $(p){if(!p.locator.trim())return;const C=t,M=p.locator.trim(),R=p.quality||"best";x(B=>B.map(A=>A.id===p.id?{...A,status:"submitting",error:null}:A));try{const A=await Np(C,M,R,{ublock_enabled:E,reader_mode:T,cookie_ext_enabled:w});x(V=>V.map(W=>W.id===p.id?{...W,status:"running",jobUid:A.job_uid,archiveId:C}:W)),F(p.id,A.job_uid,M,C)}catch(B){const A=B.message||"Submission failed.";x(V=>V.map(W=>W.id===p.id?{...W,status:"failed",error:A}:W)),m.current(A,M)}}function J(){g.filter(C=>C.status==="idle"&&C.locator.trim()).forEach(C=>$(C))}function se(){x(p=>[...p,$n()])}function O(p){clearTimeout(u.current.get(p)),u.current.delete(p),x(C=>{const M=C.filter(R=>R.id!==p);return M.length===0?[$n()]:M})}function K(p){x(C=>C.map(M=>M.id===p?{...M,status:"idle",error:null}:M))}function ye(p,C){if(clearTimeout(u.current.get(p)),x(R=>R.map(B=>B.id===p?{...B,locator:C,probeState:"idle",probeQualities:null,probeHasAudio:!1,quality:"best"}:B)),!Dc(C))return;const M=setTimeout(async()=>{u.current.delete(p),x(R=>R.map(B=>B.id===p?{...B,probeState:"probing"}:B));try{const R=await Cp(c.current,C.trim());x(B=>B.map(A=>{if(A.id!==p||A.locator!==C)return A;const V=R.qualities??[],W=R.has_audio??!1,re=V.length===0&&W?"audio":"best";return{...A,probeState:"done",probeQualities:V,probeHasAudio:W,quality:re}}))}catch{x(R=>R.map(B=>B.id===p?{...B,probeState:"idle",probeQualities:null}:B))}},600);u.current.set(p,M)}function Ee(p,C){x(M=>M.map(R=>R.id===p?{...R,quality:C}:R))}const he=g.filter(p=>p.status==="idle"&&p.locator.trim()).length,P=vo(g);return i.jsx("dialog",{ref:s,className:"capture-dialog",children:i.jsxs("div",{className:"capture-dialog-inner",children:[i.jsxs("div",{className:"capture-dialog-header",children:[i.jsx("h2",{className:"capture-dialog-title",children:"Capture"}),i.jsx("button",{type:"button",className:"capture-dialog-close",onClick:()=>{var p;return(p=s.current)==null?void 0:p.close()},"aria-label":"Close",children:i.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[i.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),i.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),i.jsx("div",{className:"capture-rows",children:g.map((p,C)=>i.jsx(oh,{item:p,autoFocus:C===g.length-1&&p.status==="idle",onLocatorChange:M=>ye(p.id,M),onQualityChange:M=>Ee(p.id,M),onRemove:()=>O(p.id),onReset:()=>K(p.id),onSubmit:J},p.id))}),i.jsxs("button",{type:"button",className:"capture-add-row",onClick:se,children:[i.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[i.jsx("line",{x1:"8",y1:"2",x2:"8",y2:"14"}),i.jsx("line",{x1:"2",y1:"8",x2:"14",y2:"8"})]}),"Add another"]}),i.jsxs("div",{className:"capture-advanced",children:[i.jsxs("button",{type:"button",className:"capture-advanced-toggle",onClick:()=>S(p=>!p),"aria-expanded":k,children:[i.jsx("svg",{className:`capture-chevron${k?" capture-chevron--open":""}`,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("polyline",{points:"4 6 8 10 12 6"})}),"Advanced options"]}),k&&i.jsxs("div",{className:"capture-advanced-panel",children:[i.jsxs("label",{className:"capture-ext-row",children:[i.jsxs("span",{className:"capture-ext-label",children:[i.jsx("span",{className:"capture-ext-name",children:"uBlock Origin Lite"}),i.jsx("span",{className:"capture-ext-desc",children:"Block ads during this capture"})]}),i.jsx("button",{type:"button",role:"switch","aria-checked":E,className:`ext-toggle ext-toggle--sm${E?" ext-toggle--on":""}`,onClick:()=>f(p=>p===null?!E:!p),"aria-label":"Toggle uBlock for this capture",children:i.jsx("span",{className:"ext-toggle-knob"})})]}),i.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[i.jsxs("span",{className:"capture-ext-label",children:[i.jsx("span",{className:"capture-ext-name",children:"Block cookie banners"}),i.jsx("span",{className:"capture-ext-desc",children:"Dismiss cookie consent banners during this capture"}),!(d!=null&&d.cookie_ext_available)&&i.jsxs("span",{className:"capture-ext-hint",children:["Not configured — set ",i.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})]})]}),i.jsx("button",{type:"button",role:"switch","aria-checked":w,className:`ext-toggle ext-toggle--sm${w?" ext-toggle--on":""}`,onClick:()=>j(p=>!p),"aria-label":"Toggle cookie banner blocking for this capture",children:i.jsx("span",{className:"ext-toggle-knob"})})]}),i.jsxs("label",{className:"capture-ext-row",style:{marginTop:8},children:[i.jsxs("span",{className:"capture-ext-label",children:[i.jsx("span",{className:"capture-ext-name",children:"Reader mode"}),i.jsx("span",{className:"capture-ext-desc",children:"Distil to article text via Readability (off by default)"})]}),i.jsx("button",{type:"button",role:"switch","aria-checked":T,className:`ext-toggle ext-toggle--sm${T?" ext-toggle--on":""}`,onClick:()=>N(p=>!p),"aria-label":"Toggle reader mode for this capture",children:i.jsx("span",{className:"ext-toggle-knob"})})]})]})]}),i.jsxs("div",{className:"capture-actions",children:[i.jsx("button",{type:"button",className:"capture-submit",onClick:J,disabled:he===0,children:he>1?`Archive ${he}`:"Archive"}),i.jsx("button",{type:"button",className:"capture-cancel",onClick:()=>{var p;return(p=s.current)==null?void 0:p.close()},children:P?"Close":"Cancel"})]})]})})}function oh({item:e,autoFocus:t,onLocatorChange:n,onQualityChange:r,onRemove:l,onReset:s,onSubmit:a}){const o=h.useRef(null),u=e.status==="submitting"||e.status==="running";h.useEffect(()=>{var y;t&&e.status==="idle"&&((y=o.current)==null||y.focus())},[t]);const c=(()=>{if(e.status==="completed"||u||!Dc(e.locator))return null;if(e.probeState==="probing")return i.jsx("span",{className:"capture-quality-probing","aria-label":"Checking available qualities",children:"…"});if(e.probeState==="done"){const y=e.probeQualities??[],m=e.probeHasAudio??!1;return y.length===0&&!m?i.jsx("span",{className:"capture-quality-hint",children:"No media detected"}):y.length===0&&m?i.jsx("select",{className:"capture-quality",value:"audio",onChange:g=>r(g.target.value),"aria-label":"Video quality",children:i.jsx("option",{value:"audio",children:"Audio only"})}):i.jsxs("select",{className:"capture-quality",value:e.quality||"best",onChange:g=>r(g.target.value),"aria-label":"Video quality",children:[i.jsx("option",{value:"best",children:"Best quality"}),y.map(g=>i.jsx("option",{value:g,children:g},g)),m&&i.jsx("option",{value:"audio",children:"Audio only"})]})}return null})();return i.jsxs("div",{className:`capture-row capture-row--${e.status}`,children:[i.jsxs("div",{className:"capture-row-main",children:[i.jsx(uh,{status:e.status}),i.jsx("input",{ref:o,className:"capture-input",type:"text",placeholder:"https://… · yt:ID · ytm:ID · tweet:ID · x:ID",value:e.locator,onChange:y=>n(y.target.value),onKeyDown:y=>{y.key==="Enter"&&a()},disabled:u||e.status==="completed",autoComplete:"off",spellCheck:!1}),c,e.status==="failed"&&i.jsx("button",{type:"button",className:"capture-row-action",onClick:s,title:"Retry",children:i.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("path",{d:"M13 2.5A7 7 0 1 1 6.5 1"}),i.jsx("polyline",{points:"6.5 1 4 3.5 6.5 6"})]})}),!u&&e.status!=="completed"&&e.status!=="failed"&&i.jsx("button",{type:"button",className:"capture-row-action capture-row-remove",onClick:l,"aria-label":"Remove",children:i.jsxs("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[i.jsx("line",{x1:"3",y1:"3",x2:"13",y2:"13"}),i.jsx("line",{x1:"13",y1:"3",x2:"3",y2:"13"})]})})]}),e.error&&i.jsx("p",{className:"capture-row-error",children:e.error})]})}function uh({status:e}){return e==="submitting"||e==="running"?i.jsx("span",{className:"cap-dot cap-dot--running","aria-label":"Running",children:i.jsx("span",{className:"cap-spinner"})}):e==="completed"?i.jsx("span",{className:"cap-dot cap-dot--ok","aria-label":"Done",children:"✓"}):e==="failed"?i.jsx("span",{className:"cap-dot cap-dot--err","aria-label":"Failed",children:"✕"}):i.jsx("span",{className:"cap-dot cap-dot--idle","aria-hidden":"true"})}function ui(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 Bt(e){return ch(e)??""}function Oc(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 yo={youtube:'',youtube_music:'',spotify:'',x:'',instagram:'',facebook:'',tiktok:'',reddit:'',snapchat:'',local:'',web:'',other:'?'};function $c(e){return yo[e]??yo.other}function Mc(e){return e.split("/").map(t=>t?t.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):"").join("/")}function dh({entry:e,archiveId:t,isSelected:n,onSelect:r}){const[l,s]=h.useState(!1),o=e.source_kind==="web"&&e.entity_kind==="page"&&e.has_favicon&&t&&!l?i.jsx("img",{src:`/api/archives/${t}/entries/${e.entry_uid}/favicon`,width:"16",height:"16",alt:"",onError:()=>s(!0),style:{objectFit:"contain"}}):i.jsx("span",{dangerouslySetInnerHTML:{__html:$c(e.source_kind)}});return i.jsxs("div",{className:n?"is-selected":void 0,tabIndex:0,"data-entry-uid":e.entry_uid,onClick:r,onKeyDown:u=>{u.key==="Enter"&&r()},children:[i.jsx("div",{className:"col-added",children:Oc(e.archived_at)}),i.jsxs("div",{className:"col-title",children:[i.jsx("span",{className:"source-icon",children:o}),i.jsx("span",{className:"entry-title",children:Bt(e.title)||Bt(e.entry_uid)})]}),i.jsx("div",{className:"col-type",children:i.jsx("span",{className:"type-pill",children:Bt(e.entity_kind)})}),i.jsxs("div",{className:"col-size",children:[i.jsx("span",{className:"size-total",children:ui(e.total_artifact_bytes)}),e.cached_bytes>0&&e.total_artifact_bytes>0&&i.jsxs("span",{className:"size-cached-pct",title:`${ui(e.cached_bytes)} already on disk from an earlier entry`,children:[Math.round(e.cached_bytes/e.total_artifact_bytes*100),"% cached"]})]}),i.jsx("div",{className:"url-cell col-url",children:Bt(e.original_url)})]})}function fh({entries:e,selectedEntryUid:t,onSelectEntry:n,archiveId:r}){return i.jsx("section",{id:"archive-view",className:"view is-active",children:i.jsxs("div",{className:"entry-table",children:[i.jsxs("div",{className:"entry-header-row",children:[i.jsx("div",{className:"col-added",children:"Added"}),i.jsx("div",{className:"col-title",children:"Title"}),i.jsx("div",{className:"col-type",children:"Type"}),i.jsx("div",{className:"col-size",children:"Size"}),i.jsx("div",{className:"col-url",children:"Original URL"})]}),i.jsx("div",{id:"entries-body",children:e.map(l=>i.jsx(dh,{entry:l,archiveId:r,isSelected:l.entry_uid===t,onSelect:()=>n(l)},l.entry_uid))})]})})}function ph(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 hh({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 i.jsx("span",{className:`run-status ${t}`,children:n})}function mh({runs:e}){const[t,n]=h.useState(null);function r(l){n(s=>s===l?null:l)}return i.jsx("section",{id:"runs-view",className:"view is-active",children:i.jsxs("table",{className:"entry-table",children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Started"}),i.jsx("th",{children:"Status"}),i.jsx("th",{children:"Requested"}),i.jsx("th",{children:"Completed"}),i.jsx("th",{children:"Failed"})]})}),i.jsx("tbody",{children:e.length===0?i.jsx("tr",{children:i.jsx("td",{colSpan:5,style:{color:"var(--muted)",padding:"24px 16px",textAlign:"center"},children:"No runs yet."})}):e.map(l=>{const s=l.status==="failed"&&l.error_summary,a=t===l.run_uid;return[i.jsxs("tr",{className:s?"run-row run-row--failed":"run-row",onClick:s?()=>r(l.run_uid):void 0,title:s?a?"Click to hide error":"Click to view error":void 0,children:[i.jsx("td",{children:ph(l.started_at)}),i.jsxs("td",{children:[i.jsx(hh,{status:l.status}),s&&i.jsx("span",{className:"run-expand-hint","aria-hidden":"true",children:a?"▴":"▾"})]}),i.jsx("td",{children:l.requested_count??"—"}),i.jsx("td",{children:l.completed_count??"—"}),i.jsx("td",{children:l.failed_count??"—"})]},l.run_uid),s&&a&&i.jsx("tr",{className:"run-error-row",children:i.jsx("td",{colSpan:5,children:i.jsx("pre",{className:"run-error-detail",children:l.error_summary})})},`${l.run_uid}-detail`)]})})]})})}const gh=4;function vh({archives:e}){const{currentUser:t}=h.useContext(Ol)??{},n=t&&(t.role_bits&gh)!==0,[r,l]=h.useState("users"),[s,a]=h.useState([]),[o,u]=h.useState([]),[c,y]=h.useState(!1),[m,g]=h.useState(null),[x,k]=h.useState(""),[S,D]=h.useState(""),[f,d]=h.useState(""),[v,w]=h.useState(null),[j,E]=h.useState(!1),[T,N]=h.useState(""),[F,$]=h.useState(""),[J,se]=h.useState(null),[O,K]=h.useState(!1),ye=h.useCallback(async()=>{if(n){y(!0),g(null);try{const[p,C]=await Promise.all([Ip(),Bp()]);a(p),u(C)}catch(p){g(p.message)}finally{y(!1)}}},[n]);h.useEffect(()=>{ye()},[ye]);async function Ee(p){const C=p.status==="active"?"disabled":"active";try{await Up(p.user_uid,C),a(M=>M.map(R=>R.user_uid===p.user_uid?{...R,status:C}:R))}catch(M){g(M.message)}}async function he(p){if(p.preventDefault(),!x.trim()||!S){w("Username and password required");return}E(!0),w(null);try{await Ap(x.trim(),S,f.trim()||void 0),k(""),D(""),d(""),await ye()}catch(C){w(C.message)}finally{E(!1)}}async function P(p){if(p.preventDefault(),!T.trim()||!F.trim()){se("Slug and name required");return}K(!0),se(null);try{await Vp(T.trim(),F.trim()),N(""),$(""),await ye()}catch(C){se(C.message)}finally{K(!1)}}return n?i.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[i.jsx("h1",{children:"Admin"}),i.jsxs("div",{className:"view-tabs",children:[i.jsx("button",{className:`view-tab${r==="users"?" is-active":""}`,onClick:()=>l("users"),children:"Users"}),i.jsx("button",{className:`view-tab${r==="roles"?" is-active":""}`,onClick:()=>l("roles"),children:"Roles"}),i.jsx("button",{className:`view-tab${r==="archives"?" is-active":""}`,onClick:()=>l("archives"),children:"Archives"})]}),m&&i.jsx("div",{className:"form-msg form-msg--err",children:m}),r==="users"&&i.jsxs("div",{className:"admin-section",children:[i.jsx("h2",{children:"Users"}),c?i.jsx("p",{className:"muted",children:"Loading…"}):i.jsxs("table",{className:"admin-table",children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Username"}),i.jsx("th",{children:"Email"}),i.jsx("th",{children:"Roles"}),i.jsx("th",{children:"Status"}),i.jsx("th",{children:"Actions"})]})}),i.jsx("tbody",{children:s.map(p=>i.jsxs("tr",{className:p.status==="disabled"?"admin-row-disabled":"",children:[i.jsx("td",{children:p.username}),i.jsx("td",{className:"muted",children:p.email||"—"}),i.jsx("td",{children:p.role_slugs.join(", ")||"—"}),i.jsx("td",{children:i.jsx("span",{className:`status-badge status-${p.status}`,children:p.status})}),i.jsx("td",{children:i.jsx("button",{className:"admin-action-btn",onClick:()=>Ee(p),children:p.status==="active"?"Ban":"Unban"})})]},p.user_uid))})]}),i.jsx("h3",{children:"Create User"}),i.jsxs("form",{className:"admin-form",onSubmit:he,children:[i.jsx("input",{className:"admin-input",placeholder:"Username",value:x,onChange:p=>k(p.target.value),required:!0}),i.jsx("input",{className:"admin-input",type:"password",placeholder:"Password (min 8 chars)",value:S,onChange:p=>D(p.target.value),required:!0}),i.jsx("input",{className:"admin-input",type:"email",placeholder:"Email (optional)",value:f,onChange:p=>d(p.target.value)}),v&&i.jsx("div",{className:"form-msg form-msg--err",children:v}),i.jsx("button",{className:"btn-primary",type:"submit",disabled:j,children:j?"Creating…":"Create User"})]})]}),r==="roles"&&i.jsxs("div",{className:"admin-section",children:[i.jsx("h2",{children:"Roles"}),c?i.jsx("p",{className:"muted",children:"Loading…"}):i.jsxs("table",{className:"admin-table",children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Slug"}),i.jsx("th",{children:"Name"}),i.jsx("th",{children:"Level"}),i.jsx("th",{children:"Bit"}),i.jsx("th",{children:"Built-in"})]})}),i.jsx("tbody",{children:o.map(p=>i.jsxs("tr",{children:[i.jsx("td",{children:i.jsx("code",{children:p.slug})}),i.jsx("td",{children:p.name}),i.jsx("td",{children:p.level}),i.jsx("td",{children:p.bit_position}),i.jsx("td",{children:p.is_builtin?"✓":""})]},p.role_uid))})]}),i.jsx("h3",{children:"Create Custom Role"}),i.jsxs("form",{className:"admin-form",onSubmit:P,children:[i.jsx("input",{className:"admin-input",placeholder:"Slug (e.g. moderator)",value:T,onChange:p=>N(p.target.value),required:!0}),i.jsx("input",{className:"admin-input",placeholder:"Display Name (e.g. Moderator)",value:F,onChange:p=>$(p.target.value),required:!0}),J&&i.jsx("div",{className:"form-msg form-msg--err",children:J}),i.jsx("button",{className:"btn-primary",type:"submit",disabled:O,children:O?"Creating…":"Create Role"})]})]}),r==="archives"&&i.jsxs("div",{className:"admin-section",children:[i.jsx("h2",{children:"Mounted Archives"}),i.jsx("div",{className:"admin-list",children:e.map(p=>i.jsxs("div",{className:"admin-archive",children:[i.jsx("strong",{children:p.label}),i.jsx("div",{className:"muted",children:p.archive_path})]},p.id))})]})]}):i.jsxs("section",{id:"admin-view",className:"view admin-view is-active",children:[i.jsx("h1",{children:"Admin"}),i.jsx("p",{className:"muted",children:"You need admin privileges to access this panel."}),i.jsx("h2",{children:"Mounted Archives"}),i.jsx("div",{className:"admin-list",children:e.map(p=>i.jsxs("div",{className:"admin-archive",children:[i.jsx("strong",{children:p.label}),i.jsx("div",{className:"muted",children:p.archive_path})]},p.id))})]})}function Fc({node:e,archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:s,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u}){var w;const c=n===e.tag.full_path,[y,m]=h.useState(!1),[g,x]=h.useState(""),k=h.useRef(!1);function S(){if(y)return;const j=c?null:e.tag.full_path;r(j),l("archive")}function D(j){j.stopPropagation(),x(e.tag.slug),m(!0)}async function f(){const j=g.trim();if(!j||j===e.tag.slug){m(!1);return}try{const E=await Sp(t,e.tag.tag_uid,j);s(e.tag.full_path,E.full_path),o()}catch{}finally{m(!1)}}async function d(j){var T;j.stopPropagation();const E=((T=e.children)==null?void 0:T.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(E))try{await jp(t,e.tag.tag_uid),a(e.tag.full_path),o()}catch{}}const v={archiveId:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:s,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u};return i.jsxs("li",{children:[i.jsxs("div",{className:"tag-node-row",children:[y?i.jsx("input",{className:"tag-rename-input",autoFocus:!0,value:g,onChange:j=>x(j.target.value),onKeyDown:j=>{j.key==="Enter"&&j.currentTarget.blur(),j.key==="Escape"&&(k.current=!0,j.currentTarget.blur())},onBlur:()=>{k.current?(k.current=!1,m(!1)):f()}}):i.jsxs("button",{className:`tag-node-btn${c?" is-active":""}`,title:e.tag.full_path,onClick:S,onDoubleClick:D,children:[u?e.tag.name:e.tag.slug,i.jsx("svg",{className:"edit-icon",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",onClick:j=>{j.stopPropagation(),D(j)},children:i.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),i.jsx("button",{className:"remove tag-node-delete",title:`Delete tag ${e.tag.full_path}`,onClick:d,"aria-label":`Delete tag ${e.tag.full_path}`,children:"×"})]}),((w=e.children)==null?void 0:w.length)>0&&i.jsx("div",{className:"tag-children",children:i.jsx("ul",{className:"tag-tree-list",children:e.children.map(j=>i.jsx(Fc,{node:j,...v},j.tag.tag_uid))})})]})}function yh({archiveId:e,tagNodes:t,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:s,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u}){return i.jsx("section",{id:"tags-view",className:"view is-active",children:i.jsxs("div",{className:"tag-tree",children:[i.jsxs("div",{className:"tag-tree-header",children:[i.jsx("span",{className:"tag-tree-title",children:"Tags"}),n&&i.jsxs("span",{className:"tag-tree-active",children:["Filtering: ",n]})]}),t.length===0?i.jsx("p",{className:"muted",style:{padding:"8px 0"},children:"No tags yet."}):i.jsx("ul",{className:"tag-tree-list",children:t.map(c=>i.jsx(Fc,{node:c,archiveId:e,tagFilter:n,onTagFilterSet:r,onViewChange:l,onTagRenamed:s,onTagDeleted:a,onTagsRefresh:o,humanizeTags:u},c.tag.tag_uid))})]})})}const Un=[{value:0,label:"Private"},{value:2,label:"Users only"},{value:3,label:"Public"}],xh=e=>{var t;return((t=Un.find(n=>n.value===e))==null?void 0:t.label)??String(e)};function wh({archiveId:e}){const[t,n]=h.useState([]),[r,l]=h.useState(!1),[s,a]=h.useState(null),[o,u]=h.useState(null),[c,y]=h.useState(null),[m,g]=h.useState(!1),[x,k]=h.useState(null),[S,D]=h.useState(""),[f,d]=h.useState(""),[v,w]=h.useState(2),[j,E]=h.useState(!1),[T,N]=h.useState(null),[F,$]=h.useState(""),[J,se]=h.useState(2),[O,K]=h.useState(!1),[ye,Ee]=h.useState(null),[he,P]=h.useState(!1),[p,C]=h.useState(""),M=h.useRef(null),R=t.find(L=>L.collection_uid===o)??null,B=(R==null?void 0:R.slug)==="_default_",A=h.useCallback(async()=>{if(e){l(!0),a(null);try{const L=await Wp(e);n(L)}catch(L){a(L.message)}finally{l(!1)}}},[e]),V=h.useCallback(async L=>{if(!L){y(null);return}g(!0),k(null);try{const H=await Qp(e,L);y(H)}catch(H){k(H.message)}finally{g(!1)}},[e]);h.useEffect(()=>{A()},[A]),h.useEffect(()=>{V(o)},[o,V]),h.useEffect(()=>{he&&M.current&&M.current.focus()},[he]);async function W(L){L.preventDefault();const H=S.trim(),De=f.trim();if(!(!H||!De)){E(!0),N(null);try{const st=await Hp(e,H,De,v);D(""),d(""),w(2),await A(),u(st.collection_uid)}catch(st){N(st.message)}finally{E(!1)}}}async function re(){const L=p.trim();if(!L||!R){P(!1);return}try{await go(e,R.collection_uid,{name:L}),await A(),y(H=>H&&{...H,name:L})}catch(H){a(H.message)}finally{P(!1)}}async function yr(L){if(R)try{await go(e,R.collection_uid,{default_visibility_bits:L}),await A(),y(H=>H&&{...H,default_visibility_bits:L})}catch(H){a(H.message)}}async function $l(){if(R&&window.confirm(`Delete collection "${R.name}"? Entries will not be deleted.`))try{await Yp(e,R.collection_uid),u(null),y(null),await A()}catch(L){a(L.message)}}async function Ml(L){L.preventDefault();const H=F.trim();if(!(!H||!R)){K(!0),Ee(null);try{await Kp(e,R.collection_uid,H,J),$(""),await V(R.collection_uid)}catch(De){Ee(De.message)}finally{K(!1)}}}async function Fl(L){if(R)try{await bp(e,R.collection_uid,L),await V(R.collection_uid)}catch(H){k(H.message)}}async function Il(L,H){if(R)try{await Jp(e,R.collection_uid,L,H),y(De=>De&&{...De,entries:De.entries.map(st=>st.entry_uid===L?{...st,collection_visibility_bits:H}:st)})}catch(De){k(De.message)}}return e?i.jsxs("div",{className:"collections-view",children:[i.jsx("h2",{className:"collections-heading",children:"Collections"}),r&&i.jsx("div",{className:"muted",children:"Loading…"}),s&&i.jsxs("div",{className:"collections-error",children:[s," ",i.jsx("button",{onClick:()=>a(null),className:"coll-dismiss",children:"×"})]}),i.jsxs("div",{className:"collections-layout",children:[i.jsxs("div",{className:"collections-sidebar",children:[t.map(L=>i.jsxs("button",{className:`coll-sidebar-row${o===L.collection_uid?" is-active":""}`,onClick:()=>u(L.collection_uid),children:[i.jsx("span",{className:"coll-row-name",children:L.name}),i.jsx("span",{className:"coll-row-meta",children:xh(L.default_visibility_bits)})]},L.collection_uid)),t.length===0&&!r&&i.jsx("div",{className:"muted",style:{padding:"8px 12px"},children:"No collections yet."})]}),R?i.jsxs("div",{className:"coll-detail",children:[i.jsxs("div",{className:"coll-detail-header",children:[he?i.jsx("input",{ref:M,className:"coll-rename-input",value:p,onChange:L=>C(L.target.value),onBlur:re,onKeyDown:L=>{L.key==="Enter"&&re(),L.key==="Escape"&&P(!1)}}):i.jsxs("h3",{className:`coll-detail-name${B?"":" coll-detail-name--editable"}`,title:B?void 0:"Click to rename",onClick:()=>{B||(C(R.name),P(!0))},children:[(c==null?void 0:c.name)??R.name,!B&&i.jsx("span",{className:"coll-edit-hint",children:" ✎"})]}),!B&&i.jsx("button",{className:"coll-delete-btn",onClick:$l,title:"Delete collection",children:"Delete"})]}),i.jsxs("div",{className:"coll-detail-vis",children:[i.jsx("span",{className:"coll-vis-label",children:"Default visibility"}),i.jsx("select",{className:"coll-vis-select",value:(c==null?void 0:c.default_visibility_bits)??R.default_visibility_bits,onChange:L=>yr(Number(L.target.value)),disabled:B,children:Un.map(L=>i.jsx("option",{value:L.value,children:L.label},L.value))})]}),i.jsxs("div",{className:"coll-entries-section",children:[i.jsx("div",{className:"coll-section-heading",children:"Entries"}),m&&i.jsx("div",{className:"muted",children:"Loading…"}),x&&i.jsx("div",{className:"collections-error",children:x}),!m&&c&&(c.entries.length===0?i.jsx("div",{className:"muted",children:"No entries in this collection."}):i.jsx("ul",{className:"coll-entries-list",children:c.entries.map(L=>i.jsxs("li",{className:"coll-entry-row",children:[i.jsxs("div",{className:"coll-entry-info",children:[i.jsx("span",{className:"coll-entry-title",children:L.title||L.entry_uid}),i.jsx("span",{className:"coll-entry-kind muted",children:L.source_kind})]}),i.jsxs("div",{className:"coll-entry-actions",children:[i.jsx("select",{className:"coll-entry-vis-select",value:L.collection_visibility_bits,onChange:H=>Il(L.entry_uid,Number(H.target.value)),children:Un.map(H=>i.jsx("option",{value:H.value,children:H.label},H.value))}),!B&&i.jsx("button",{className:"coll-entry-remove",onClick:()=>Fl(L.entry_uid),title:"Remove from collection",children:"×"})]})]},L.entry_uid))}))]}),!B&&i.jsxs("form",{className:"coll-add-entry-form",onSubmit:Ml,children:[i.jsx("div",{className:"coll-section-heading",children:"Add entry"}),i.jsxs("div",{className:"coll-add-entry-row",children:[i.jsx("input",{className:"coll-add-entry-input",type:"text",value:F,onChange:L=>$(L.target.value),placeholder:"entry_uid",required:!0}),i.jsx("select",{className:"coll-vis-select",value:J,onChange:L=>se(Number(L.target.value)),children:Un.map(L=>i.jsx("option",{value:L.value,children:L.label},L.value))}),i.jsx("button",{className:"coll-add-btn",type:"submit",disabled:O,children:O?"…":"Add"})]}),ye&&i.jsx("div",{className:"collections-error",style:{marginTop:4},children:ye})]})]}):i.jsx("div",{className:"coll-detail coll-detail--empty",children:i.jsx("div",{className:"muted",children:"Select a collection to view details."})})]}),i.jsxs("details",{className:"coll-create-details",children:[i.jsx("summary",{children:"+ Create collection"}),i.jsxs("form",{className:"coll-create-form",onSubmit:W,children:[i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",htmlFor:"coll-name",children:"Name"}),i.jsx("input",{className:"capture-input",id:"coll-name",type:"text",value:S,onChange:L=>{D(L.target.value),f||d(L.target.value.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""))},placeholder:"My Collection",required:!0})]}),i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",htmlFor:"coll-slug",children:"Slug"}),i.jsx("input",{className:"capture-input",id:"coll-slug",type:"text",value:f,onChange:L=>d(L.target.value),placeholder:"my-collection",required:!0})]}),i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",htmlFor:"coll-vis",children:"Default visibility"}),i.jsx("select",{className:"capture-input",id:"coll-vis",style:{height:42},value:v,onChange:L=>w(Number(L.target.value)),children:Un.map(L=>i.jsx("option",{value:L.value,children:L.label},L.value))})]}),T&&i.jsx("div",{className:"collections-error",children:T}),i.jsx("button",{className:"btn-primary",type:"submit",disabled:j,children:j?"Creating…":"Create collection"})]})]})]}):i.jsx("div",{className:"view-placeholder",children:"Select an archive."})}const kh=4;function Sh({tab:e,onTabChange:t,archiveId:n}){const{currentUser:r,setCurrentUser:l}=h.useContext(Ol)??{},s=r&&(r.role_bits&kh)!==0,a=["profile","tokens",...s?["instance","cookies","extensions","storage"]:[]],o={profile:"Profile",tokens:"API Tokens",instance:"Instance",cookies:"Cookies",extensions:"Extensions",storage:"Storage"};return i.jsxs("section",{className:"admin-view",children:[i.jsx("h1",{children:"Settings"}),i.jsx("div",{className:"view-tabs",children:a.map(u=>i.jsx("button",{className:`view-tab${e===u?" is-active":""}`,onClick:()=>t(u),children:o[u]},u))}),e==="profile"&&i.jsx(jh,{currentUser:r,setCurrentUser:l}),e==="tokens"&&i.jsx(Nh,{}),e==="instance"&&s&&i.jsx(Ch,{}),e==="cookies"&&s&&i.jsx(Eh,{}),e==="extensions"&&s&&i.jsx(Th,{}),e==="storage"&&s&&i.jsx(_h,{archiveId:n})]})}function jh({currentUser:e,setCurrentUser:t}){const[n,r]=h.useState((e==null?void 0:e.display_name)??""),[l,s]=h.useState(!1),[a,o]=h.useState(null),[u,c]=h.useState(""),[y,m]=h.useState(""),[g,x]=h.useState(""),[k,S]=h.useState(!1),[D,f]=h.useState(null);async function d(w){w.preventDefault(),s(!0),o(null);try{await zp(n),t(j=>({...j,display_name:n||null})),o({ok:!0,text:"Saved."})}catch(j){o({ok:!1,text:j.message})}finally{s(!1)}}async function v(w){if(w.preventDefault(),y!==g){f({ok:!1,text:"Passwords do not match."});return}S(!0),f(null);try{await Op(u,y),c(""),m(""),x(""),f({ok:!0,text:"Password changed."})}catch(j){f({ok:!1,text:j.message})}finally{S(!1)}}return i.jsxs("div",{style:{maxWidth:440},children:[i.jsxs("div",{className:"form-section",children:[i.jsx("h2",{children:"Display Name"}),i.jsxs("form",{onSubmit:d,children:[i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",htmlFor:"display-name",children:"Name shown in the UI"}),i.jsx("input",{className:"field-input",id:"display-name",placeholder:(e==null?void 0:e.username)??"",value:n,onChange:w=>r(w.target.value)})]}),a&&i.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text}),i.jsx("button",{className:"btn-primary",type:"submit",disabled:l,children:l?"Saving…":"Save"})]})]}),i.jsxs("div",{className:"form-section",children:[i.jsx("h2",{children:"Display Preferences"}),i.jsxs("label",{className:"checkbox-row",children:[i.jsx("input",{type:"checkbox",checked:(e==null?void 0:e.humanize_slugs)??!1,onChange:async w=>{const j=w.target.checked;try{await Dp({humanize_slugs:j}),t(E=>({...E,humanize_slugs:j}))}catch{}}}),i.jsx("span",{className:"form-label",style:{margin:0},children:"Humanize tag display"})]}),i.jsx("p",{className:"muted",style:{fontSize:13,margin:"4px 0 0"},children:'When on, tag paths show as "X / Articles" instead of "x/articles".'})]}),i.jsxs("div",{className:"form-section",children:[i.jsx("h2",{children:"Change Password"}),i.jsxs("form",{onSubmit:v,children:[i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",htmlFor:"cur-pw",children:"Current password"}),i.jsx("input",{className:"field-input",id:"cur-pw",type:"password",value:u,onChange:w=>c(w.target.value),required:!0})]}),i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",htmlFor:"new-pw",children:"New password"}),i.jsx("input",{className:"field-input",id:"new-pw",type:"password",value:y,onChange:w=>m(w.target.value),required:!0})]}),i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",htmlFor:"confirm-pw",children:"Confirm new password"}),i.jsx("input",{className:"field-input",id:"confirm-pw",type:"password",value:g,onChange:w=>x(w.target.value),required:!0})]}),D&&i.jsx("div",{className:`form-msg form-msg--${D.ok?"ok":"err"}`,children:D.text}),i.jsx("button",{className:"btn-primary",type:"submit",disabled:k,children:k?"Changing…":"Change Password"})]})]})]})}function Nh(){const[e,t]=h.useState([]),[n,r]=h.useState(!0),[l,s]=h.useState(null),[a,o]=h.useState(""),[u,c]=h.useState(!1),[y,m]=h.useState(null),g=h.useCallback(async()=>{r(!0),s(null);try{t(await $p())}catch(S){s(S.message)}finally{r(!1)}},[]);h.useEffect(()=>{g()},[g]);async function x(S){if(S.preventDefault(),!!a.trim()){c(!0);try{const D=await Mp(a.trim());m(D),o(""),g()}catch(D){s(D.message)}finally{c(!1)}}}async function k(S){try{await Fp(S),t(D=>D.filter(f=>f.token_uid!==S))}catch(D){s(D.message)}}return i.jsx("div",{style:{maxWidth:600},children:i.jsxs("div",{className:"form-section",children:[i.jsx("h2",{children:"API Tokens"}),y&&i.jsxs("div",{className:"token-banner",children:[i.jsx("strong",{children:"Token created."})," Copy it now — it won't be shown again.",i.jsx("code",{children:y.raw_token}),i.jsx("button",{className:"token-dismiss",onClick:()=>m(null),children:"Dismiss"})]}),i.jsxs("form",{className:"token-create-row",onSubmit:x,children:[i.jsx("input",{className:"field-input field-input--flex",placeholder:"Token name",value:a,onChange:S=>o(S.target.value),required:!0}),i.jsx("button",{className:"btn-primary",type:"submit",disabled:u,children:u?"Creating…":"Create token"})]}),l&&i.jsx("div",{className:"form-msg form-msg--err",children:l}),n?i.jsx("div",{className:"muted",children:"Loading…"}):i.jsxs("div",{children:[e.length===0&&i.jsx("div",{className:"muted",children:"No tokens yet."}),e.map(S=>i.jsxs("div",{className:"token-row",children:[i.jsxs("div",{className:"token-row-info",children:[i.jsx("strong",{children:S.name}),i.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)}`]})]}),i.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"4px 10px"},onClick:()=>k(S.token_uid),children:"Revoke"})]},S.token_uid))]})]})})}function Ch(){const[e,t]=h.useState(null),[n,r]=h.useState(!0),[l,s]=h.useState(null),[a,o]=h.useState(!1),[u,c]=h.useState(null);h.useEffect(()=>{(async()=>{try{t(await la())}catch(m){s(m.message)}finally{r(!1)}})()},[]);async function y(m){m.preventDefault(),o(!0),c(null);try{await ai(e),c({ok:!0,text:"Saved."})}catch(g){c({ok:!1,text:g.message})}finally{o(!1)}}return n?i.jsx("div",{className:"muted",children:"Loading…"}):l?i.jsx("div",{className:"form-msg form-msg--err",children:l}):e?i.jsx("div",{style:{maxWidth:440},children:i.jsxs("div",{className:"form-section",children:[i.jsx("h2",{children:"Instance Settings"}),i.jsxs("form",{onSubmit:y,children:[[["public_index_enabled","Public index (unauthenticated browsing)"],["public_entry_content_enabled","Public entry content"],["open_registration_enabled","Open registration"]].map(([m,g])=>i.jsxs("label",{className:"checkbox-row",children:[i.jsx("input",{type:"checkbox",checked:!!e[m],onChange:x=>t(k=>({...k,[m]:x.target.checked}))}),g]},m)),i.jsxs("div",{className:"form-field",style:{marginTop:4},children:[i.jsx("label",{className:"form-label",children:"Default entry visibility"}),i.jsxs("select",{className:"field-input",value:e.default_entry_visibility,onChange:m=>t(g=>({...g,default_entry_visibility:Number(m.target.value)})),children:[i.jsx("option",{value:0,children:"Private"}),i.jsx("option",{value:2,children:"Unlisted"}),i.jsx("option",{value:3,children:"Public"})]})]}),u&&i.jsx("div",{className:`form-msg form-msg--${u.ok?"ok":"err"}`,children:u.text}),i.jsx("button",{className:"btn-primary",type:"submit",disabled:a,children:a?"Saving…":"Save Settings"})]})]})}):null}function ps(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 _h({archiveId:e}){const[t,n]=h.useState("idle"),[r,l]=h.useState(null),[s,a]=h.useState(null),[o,u]=h.useState(null);function c(){n("idle"),l(null),a(null),u(null)}async function y(){n("scanning"),u(null),l(null);try{const x=await Gp(e);l(x),n("scanned")}catch(x){u(x.message),n("error")}}async function m(){n("deleting"),u(null);try{const x=await qp(e);a(x),n("done")}catch(x){u(x.message),n("error")}}const g=r&&r.deletable_files===0&&r.orphaned_blob_rows===0;return i.jsx("div",{style:{maxWidth:440},children:i.jsxs("div",{className:"form-section",children:[i.jsx("h2",{children:"Orphan Cleanup"}),i.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."," ",i.jsx("strong",{children:"Cleanup is blocked while captures are running."})]}),!e&&i.jsx("div",{className:"muted",children:"No archive selected."}),e&&t==="idle"&&i.jsx("button",{className:"btn-ghost",onClick:y,children:"Scan for orphaned blobs"}),t==="scanning"&&i.jsx("div",{className:"muted",children:"Scanning…"}),t==="scanned"&&r&&g&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"form-msg form-msg--ok",children:"Archive is clean — nothing to remove."}),i.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Done"})]}),t==="scanned"&&r&&!g&&i.jsxs("div",{children:[i.jsxs("div",{style:{marginBottom:14,lineHeight:1.6},children:["Found ",i.jsx("strong",{children:r.deletable_files})," unreferenced file",r.deletable_files!==1?"s":""," ","and ",i.jsx("strong",{children:r.orphaned_blob_rows})," orphaned DB record",r.orphaned_blob_rows!==1?"s":""," ","— ",i.jsx("strong",{children:ps(r.total_bytes)})," recoverable."]}),i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsxs("button",{className:"btn-danger",onClick:m,children:["Delete (",ps(r.total_bytes),")"]}),i.jsx("button",{className:"btn-ghost",onClick:c,children:"Cancel"})]})]}),t==="deleting"&&i.jsx("div",{className:"muted",children:"Deleting…"}),t==="done"&&s&&i.jsxs("div",{children:[i.jsxs("div",{className:"form-msg form-msg--ok",children:["Freed ",i.jsx("strong",{children:ps(s.freed_bytes)})," ","— removed ",s.deleted_files," file",s.deleted_files!==1?"s":""," ","and ",s.deleted_blob_rows," DB record",s.deleted_blob_rows!==1?"s":"","."]}),s.errors&&s.errors.length>0&&i.jsxs("div",{className:"form-msg form-msg--err",style:{marginTop:6},children:[s.errors.length," file",s.errors.length!==1?"s":""," could not be deleted."]}),i.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Scan again"})]}),t==="error"&&i.jsxs("div",{children:[i.jsx("div",{className:"form-msg form-msg--err",children:o}),i.jsx("button",{className:"btn-ghost",style:{marginTop:10},onClick:c,children:"Try again"})]})]})})}function Eh(){const[e,t]=h.useState(null),[n,r]=h.useState(!0),[l,s]=h.useState(null),[a,o]=h.useState("global"),[u,c]=h.useState(""),[y,m]=h.useState("{}"),[g,x]=h.useState(null),[k,S]=h.useState(!1),[D,f]=h.useState({});h.useEffect(()=>{d()},[]);async function d(){r(!0),s(null);try{t(await Zp())}catch(N){s(N.message)}finally{r(!1)}}async function v(N){N.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 eh(a==="global"?null:u.trim(),a,y),c(""),m("{}"),o("global"),x({ok:!0,text:"Rule added."}),await d()}catch(F){x({ok:!1,text:F.message})}finally{S(!1)}}async function w(N){try{await nh(N),await d()}catch(F){s(F.message)}}function j(N){f(F=>({...F,[N.rule_uid]:{cookiesInput:N.cookies_json,saving:!1,msg:null}}))}function E(N){f(F=>{const $={...F};return delete $[N],$})}async function T(N){const F=D[N.rule_uid];try{JSON.parse(F.cookiesInput)}catch{f($=>({...$,[N.rule_uid]:{...$[N.rule_uid],msg:{ok:!1,text:"Invalid JSON"}}}));return}f($=>({...$,[N.rule_uid]:{...$[N.rule_uid],saving:!0,msg:null}}));try{await th(N.rule_uid,{cookies_json:F.cookiesInput}),E(N.rule_uid),await d()}catch($){f(J=>({...J,[N.rule_uid]:{...J[N.rule_uid],saving:!1,msg:{ok:!1,text:$.message}}}))}}return n?i.jsx("div",{className:"muted",children:"Loading…"}):l?i.jsx("div",{className:"form-msg form-msg--err",children:l}):i.jsx("div",{style:{maxWidth:560},children:i.jsxs("div",{className:"form-section",children:[i.jsx("h2",{children:"Cookie Rules"}),i.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?i.jsxs("table",{className:"data-table",style:{width:"100%",marginBottom:16},children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{children:"Pattern"}),i.jsx("th",{children:"Cookies"}),i.jsx("th",{style:{width:100},children:"Actions"})]})}),i.jsx("tbody",{children:e.map(N=>{const F=D[N.rule_uid],$=N.url_pattern?i.jsxs(i.Fragment,{children:[i.jsxs("span",{className:"muted",children:[N.pattern_kind,":"]})," ",i.jsx("code",{children:N.url_pattern})]}):i.jsx("span",{className:"muted",children:"global (all URLs)"});return i.jsxs("tr",{children:[i.jsx("td",{children:$}),i.jsx("td",{children:F?i.jsxs(i.Fragment,{children:[i.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:12,width:"100%",minHeight:60},value:F.cookiesInput,onChange:J=>f(se=>({...se,[N.rule_uid]:{...se[N.rule_uid],cookiesInput:J.target.value}}))}),F.msg&&i.jsx("div",{className:`form-msg form-msg--${F.msg.ok?"ok":"err"}`,children:F.msg.text}),i.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[i.jsx("button",{className:"btn-primary",style:{fontSize:12,padding:"2px 8px"},disabled:F.saving,onClick:()=>T(N),children:F.saving?"Saving…":"Save"}),i.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>E(N.rule_uid),children:"Cancel"})]})]}):i.jsx("code",{style:{fontSize:12,wordBreak:"break-all"},children:N.cookies_json})}),i.jsx("td",{children:!F&&i.jsxs("div",{style:{display:"flex",gap:6},children:[i.jsx("button",{className:"btn-secondary",style:{fontSize:12,padding:"2px 8px"},onClick:()=>j(N),children:"Edit"}),i.jsx("button",{className:"btn-danger",style:{fontSize:12,padding:"2px 8px"},onClick:()=>w(N.rule_uid),children:"Del"})]})})]},N.rule_uid)})})]}):i.jsx("p",{className:"muted",style:{marginBottom:16},children:"No cookie rules defined."}),i.jsx("h3",{style:{marginBottom:8},children:"Add Rule"}),i.jsxs("form",{onSubmit:v,children:[i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",children:"Pattern type"}),i.jsxs("select",{className:"field-input",value:a,onChange:N=>o(N.target.value),children:[i.jsx("option",{value:"global",children:"Global (all URLs)"}),i.jsx("option",{value:"wildcard",children:"Wildcard (e.g. *.youtube.com)"}),i.jsx("option",{value:"regex",children:"Regex (matched against full URL)"})]})]}),a!=="global"&&i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",children:a==="wildcard"?"URL/hostname pattern":"Regex pattern"}),i.jsx("input",{className:"field-input",type:"text",value:u,onChange:N=>c(N.target.value),placeholder:a==="wildcard"?"*.youtube.com or https://example.com/*":".*\\.youtube\\.com.*",required:!0})]}),i.jsxs("div",{className:"form-field",children:[i.jsx("label",{className:"form-label",children:"Cookies (JSON object)"}),i.jsx("textarea",{className:"field-input",style:{fontFamily:"monospace",fontSize:13,minHeight:70},value:y,onChange:N=>m(N.target.value),placeholder:'{"SESSION": "abc123", "token": "xyz"}',required:!0})]}),g&&i.jsx("div",{className:`form-msg form-msg--${g.ok?"ok":"err"}`,children:g.text}),i.jsx("button",{className:"btn-primary",type:"submit",disabled:k,children:k?"Adding…":"Add Rule"})]})]})})}function Th(){const[e,t]=h.useState(null),[n,r]=h.useState(!0),[l,s]=h.useState(!1),[a,o]=h.useState(null);h.useEffect(()=>{(async()=>{try{t(await la())}catch(k){o({ok:!1,text:k.message})}finally{r(!1)}})()},[]);async function u(k){s(!0),o(null);try{await ai({ublock_enabled:k}),t(S=>({...S,ublock_enabled:k})),o({ok:!0,text:"Saved."})}catch(S){o({ok:!1,text:S.message})}finally{s(!1)}}async function c(k){s(!0),o(null);try{await ai({cookie_ext_enabled:k}),t(S=>({...S,cookie_ext_enabled:k})),o({ok:!0,text:"Saved."})}catch(S){o({ok:!1,text:S.message})}finally{s(!1)}}if(n)return i.jsx("div",{className:"muted",children:"Loading\\u2026"});const y=(e==null?void 0:e.ublock_ext_available)??!1,m=(e==null?void 0:e.ublock_enabled)??!0,g=(e==null?void 0:e.cookie_ext_available)??!1,x=(e==null?void 0:e.cookie_ext_enabled)??!0;return i.jsx("div",{style:{maxWidth:560},children:i.jsxs("div",{className:"form-section",children:[i.jsx("h2",{children:"Extensions"}),i.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."}),i.jsx("div",{className:"ext-card",children:i.jsxs("div",{className:"ext-card-header",children:[i.jsxs("div",{className:"ext-card-info",children:[i.jsx("span",{className:"ext-card-name",children:"uBlock Origin Lite"}),i.jsx("span",{className:"ext-card-desc",children:"Blocks ads, trackers, and other page clutter during archiving via Chrome’s declarativeNetRequest API (Manifest V3)."}),!y&&i.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",i.jsx("code",{children:"ARCHIVR_UBLOCK_EXT"})," to the unpacked extension directory to enable."]})]}),i.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:i.jsx("span",{className:"ext-toggle-knob"})})]})}),i.jsx("div",{className:"ext-card",children:i.jsxs("div",{className:"ext-card-header",children:[i.jsxs("div",{className:"ext-card-info",children:[i.jsx("span",{className:"ext-card-name",children:"I Still Don’t Care About Cookies"}),i.jsx("span",{className:"ext-card-desc",children:"Dismiss cookie consent banners during archiving."}),!g&&i.jsxs("span",{className:"ext-card-hint",children:["Not configured — set ",i.jsx("code",{children:"ARCHIVR_COOKIE_EXT"})," to the unpacked extension directory to enable."]})]}),i.jsx("button",{type:"button",role:"switch","aria-checked":x,className:`ext-toggle${x?" ext-toggle--on":""}`,onClick:()=>c(!x),disabled:l,"aria-label":"Toggle I Still Don't Care About Cookies",children:i.jsx("span",{className:"ext-toggle-knob"})})]})}),a&&i.jsx("div",{className:`form-msg form-msg--${a.ok?"ok":"err"}`,children:a.text})]})})}const xo={0:"Private",1:"Public",2:"Users only",3:"Public"},Ph=()=>i.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"M7 17 17 7M9 7h8v8"})});function Lh({archiveId:e,selectedEntry:t,onTagFilterSet:n,tagNodes:r,onTagsRefresh:l,onEntryTitleChange:s,onEntryDeleted:a,humanizeTags:o}){const[u,c]=h.useState(null),[y,m]=h.useState([]),[g,x]=h.useState(""),[k,S]=h.useState([]),[D,f]=h.useState(""),d=h.useRef(0),v=h.useRef(!1),[w,j]=h.useState(!1),[E,T]=h.useState("");h.useEffect(()=>{if(!t||!e){c(null),m([]),S([]);return}j(!1),T(""),v.current=!1;const O=++d.current;c(null),m([]),Promise.all([vp(e,t.entry_uid),ds(e,t.entry_uid),Xp(e,t.entry_uid)]).then(([K,ye,Ee])=>{O===d.current&&(c(K),m(ye),S(Ee))}).catch(()=>{})},[t,e]);async function N(){const O=E.trim()||null;try{await yp(e,t.entry_uid,O),c(K=>K&&{...K,summary:{...K.summary,title:O}}),s==null||s(t.entry_uid,O)}catch{}finally{j(!1)}}async function F(){const O=g.trim();if(!(!O||!t))try{await xp(e,t.entry_uid,O),x(""),f("");const K=await ds(e,t.entry_uid);m(K),l()}catch(K){f(K.message)}}async function $(O){try{await wp(e,t.entry_uid,O);const K=await ds(e,t.entry_uid);m(K),l()}catch{}}async function J(){if(!(!t||!e)&&window.confirm("Delete this entry? This cannot be undone."))try{await kp(e,t.entry_uid),a==null||a(t.entry_uid)}catch{}}const se=u?[["Added",Oc(u.summary.archived_at)],["Source",u.summary.source_kind],["Type",u.summary.entity_kind],["Visibility",xo[u.summary.visibility]??u.summary.visibility],["Root",u.structured_root_relpath]]:[];return i.jsxs("aside",{className:"context-rail",children:[i.jsx("div",{className:"rail-eyebrow",children:"Context"}),t?u?i.jsxs(i.Fragment,{children:[w?i.jsx("input",{className:"rail-title-input",autoFocus:!0,value:E,onChange:O=>T(O.target.value),onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur(),O.key==="Escape"&&(v.current=!0,O.currentTarget.blur())},onBlur:()=>{v.current?j(!1):N(),v.current=!1}}):i.jsxs("h2",{className:"rail-title rail-title--editable",title:"Click to rename",onClick:()=>{T(u.summary.title??""),j(!0)},children:[Bt(u.summary.title)||Bt(u.summary.entry_uid),i.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:i.jsx("path",{d:"M11.5 2.5a1.5 1.5 0 0 1 2 2L5 13l-3 1 1-3 8.5-8.5z"})})]}),u.summary.original_url&&i.jsxs("a",{className:"url-tile",href:u.summary.original_url,target:"_blank",rel:"noopener noreferrer",children:[i.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:$c(u.summary.source_kind)}}),i.jsx("span",{className:"u-text",children:u.summary.original_url}),i.jsx("span",{className:"ext",children:i.jsx(Ph,{})})]}),i.jsx("div",{className:"meta-list",children:se.filter(([,O])=>O!=null&&O!=="").map(([O,K])=>i.jsxs("div",{className:"meta-item",children:[i.jsx("span",{className:"meta-k",children:O}),i.jsx("span",{className:`meta-v${O==="Root"?" mono":""}`,children:Bt(K)})]},O))}),u.artifacts.length>0&&i.jsxs("div",{className:"rail-section",children:[i.jsxs("div",{className:"rail-section-heading",children:["Artifacts ",i.jsx("span",{className:"num",children:u.artifacts.length})]}),i.jsx("ul",{className:"artifact-list",children:u.artifacts.map((O,K)=>i.jsx("li",{children:i.jsxs("a",{href:`/api/archives/${e}/entries/${u.summary.entry_uid}/artifacts/${K}`,target:"_blank",rel:"noopener noreferrer",className:"artifact-link",children:[i.jsx("span",{className:"artifact-name",children:O.artifact_role.replace(/_/g," ")}),i.jsx("span",{className:"artifact-size",children:O.byte_size!=null?ui(O.byte_size):"—"})]})},K))})]})]}):i.jsx("p",{className:"tags-empty",children:"Loading…"}):i.jsx("p",{className:"tags-empty",children:"Select an entry."}),t&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"rail-section",children:[i.jsx("div",{className:"rail-section-heading",children:"Tags"}),y.length===0?i.jsx("p",{className:"tags-empty",children:"No tags yet."}):i.jsx("div",{className:"tags-wrap",children:y.map(O=>i.jsxs("span",{className:"tag-pill",title:O.full_path,children:[o?Mc(O.full_path):O.full_path,i.jsx("button",{className:"remove",title:`Remove tag ${O.full_path}`,onClick:()=>$(O.tag_uid),children:"×"})]},O.tag_uid))}),D&&i.jsx("p",{className:"form-msg form-msg--err",style:{margin:"0 0 8px"},children:D}),i.jsxs("div",{className:"tag-input-wrap",children:[i.jsx("span",{className:"hash",children:"/"}),i.jsx("input",{className:"tag-input",type:"text",placeholder:"science/cs",autoComplete:"off",value:g,onChange:O=>x(O.target.value),onKeyDown:O=>{O.key==="Enter"&&F()}}),i.jsx("button",{className:"tag-add-btn",onClick:F,children:"Add"})]})]}),k.length>0&&i.jsxs("div",{className:"rail-section",children:[i.jsx("div",{className:"rail-section-heading",children:"Collections"}),k.map(O=>i.jsxs("div",{className:"coll-row",children:[i.jsx("span",{className:"coll-name",children:O.collection_uid}),i.jsx("span",{className:"vis-badge",children:xo[O.visibility_bits]??`bits:${O.visibility_bits}`})]},O.collection_uid))]}),i.jsx("div",{className:"rail-delete-zone",children:i.jsx("button",{className:"rail-delete-btn",onClick:J,children:"Delete entry"})})]})]})}const Rh=7e3;function zh({toasts:e,onDismiss:t,onIgnoreUblock:n}){return e.length?i.jsx("div",{className:"toast-stack",role:"log","aria-live":"polite","aria-label":"Notifications",children:e.map(r=>i.jsx(Dh,{toast:r,onDismiss:t,onIgnoreUblock:n},r.id))}):null}function Dh({toast:e,onDismiss:t,onIgnoreUblock:n}){const[r,l]=h.useState(!1),s=e.type==="warning";h.useEffect(()=>{if(r)return;const o=setTimeout(()=>t(e.id),Rh);return()=>clearTimeout(o)},[r,e.id,t]);const a=e.locator?e.locator.length>48?e.locator.slice(0,45)+"…":e.locator:null;return s?i.jsxs("div",{className:"toast toast--warning",role:"alert","aria-atomic":"true",children:[i.jsxs("div",{className:"toast-top",children:[i.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"⚠"}),i.jsxs("div",{className:"toast-body",children:[i.jsx("span",{className:"toast-headline",children:"Ad-blocking unavailable"}),a&&i.jsx("span",{className:"toast-locator",children:a})]}),i.jsxs("div",{className:"toast-btns",children:[i.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(o=>!o),"aria-expanded":r,children:r?"Hide":"Details"}),i.jsx("button",{type:"button",className:"toast-view-btn toast-ignore-btn",onClick:()=>{n==null||n(),t(e.id)},children:"Ignore"}),i.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&i.jsx("p",{className:"toast-warning-detail",children:e.text||"ARCHIVR_UBLOCK=true but ARCHIVR_UBLOCK_EXT is not set or the path is invalid. The page was captured without ad-blocking. Set ARCHIVR_UBLOCK_EXT to the unpacked uBlock Origin Lite extension directory to enable ad-blocking, or set ARCHIVR_UBLOCK=false to silence this warning."})]}):i.jsxs("div",{className:"toast toast--error",role:"alert","aria-atomic":"true",children:[i.jsxs("div",{className:"toast-top",children:[i.jsx("span",{className:"toast-icon","aria-hidden":"true",children:"✕"}),i.jsxs("div",{className:"toast-body",children:[i.jsx("span",{className:"toast-headline",children:"Capture failed"}),a&&i.jsx("span",{className:"toast-locator",children:a})]}),i.jsxs("div",{className:"toast-btns",children:[e.text&&i.jsx("button",{type:"button",className:"toast-view-btn",onClick:()=>l(o=>!o),children:r?"Hide":"View error"}),i.jsx("button",{type:"button",className:"toast-dismiss",onClick:()=>t(e.id),"aria-label":"Dismiss",children:"×"})]})]}),r&&e.text&&i.jsx("pre",{className:"toast-error-detail",children:e.text})]})}const Ol=h.createContext(null),Oh=["archive","tags","collections","runs","admin","settings"],$h=["profile","tokens","instance","storage"];function hs(){const e=window.location.pathname.split("/").filter(Boolean),t=Oh.includes(e[0])?e[0]:"archive",n=t==="settings"&&$h.includes(e[1])?e[1]:"profile";return{view:t,settingsTab:n}}function Mh(e,t){return e==="archive"?"/":e==="settings"?`/settings/${t}`:`/${e}`}function Fh(){const[e,t]=h.useState("loading"),[n,r]=h.useState(null);h.useEffect(()=>{(async()=>{if(await Ep()){t("setup");return}const b=await Rp();if(!b){t("login");return}r(b),t("authenticated")})()},[]),h.useEffect(()=>{const I=()=>{r(null),t("login")};return window.addEventListener("auth:expired",I),()=>window.removeEventListener("auth:expired",I)},[]),h.useEffect(()=>{const I=()=>{const{view:b,settingsTab:ce}=hs();f(b),v(ce)};return window.addEventListener("popstate",I),()=>window.removeEventListener("popstate",I)},[]);const[l,s]=h.useState([]),[a,o]=h.useState(null),[u,c]=h.useState([]),[y,m]=h.useState(null),[g,x]=h.useState(null),[k,S]=h.useState(null),[D,f]=h.useState(()=>hs().view),[d,v]=h.useState(()=>hs().settingsTab),[w,j]=h.useState(""),[E,T]=h.useState(""),[N,F]=h.useState(!1),[$,J]=h.useState([]),[se,O]=h.useState([]),[K,ye]=h.useState(()=>sessionStorage.getItem("captureDialogOpen")==="true"),[Ee,he]=h.useState([]),P=h.useRef(0),[p,C]=h.useState(()=>sessionStorage.getItem("ublockWarningIgnored")==="true"),M=(n==null?void 0:n.humanize_slugs)??!1;h.useEffect(()=>{sessionStorage.setItem("captureDialogOpen",K)},[K]);const R=h.useCallback(async(I,b,ce)=>{if(I){F(!0);try{let Ue;b||ce?Ue=await gp(I,b,ce):Ue=await mp(I),c(Ue),T(Ue.length===0?"No results":`${Ue.length} result${Ue.length===1?"":"s"}`)}catch{c([]),T("Search failed. Try again.")}finally{F(!1)}}},[]);h.useEffect(()=>{e==="authenticated"&&hp().then(I=>{if(s(I),I.length>0){const b=I[0].id;o(b)}})},[e]),h.useEffect(()=>{a&&(S(null),x(null),m(null),Promise.all([R(a,"",null),mo(a).then(J),fs(a).then(O)]))},[a]),h.useEffect(()=>{if(a===null)return;const I=setTimeout(()=>{R(a,w,k)},300);return()=>clearTimeout(I)},[w,a]),h.useEffect(()=>{a!==null&&(k!==null&&f("archive"),R(a,w,k))},[k,a]);const B=h.useCallback(I=>{o(I)},[]),A=h.useCallback(I=>{f(I),I==="tags"&&a&&fs(a).then(O)},[a]);h.useEffect(()=>{const I=Mh(D,d);window.location.pathname!==I&&history.pushState(null,"",I)},[D,d]);const V=h.useCallback(I=>{m(I?I.entry_uid:null),x(I)},[]),W=h.useCallback(I=>{S(I)},[]),re=h.useCallback(()=>{S(null)},[]),yr=h.useCallback(()=>{a&&fs(a).then(O)},[a]),$l=h.useCallback((I,b)=>{k===I?S(b):k!=null&&k.startsWith(I+"/")&&S(b+k.slice(I.length))},[k]),Ml=h.useCallback(I=>{(k===I||k!=null&&k.startsWith(I+"/"))&&S(null)},[k]),Fl=h.useCallback((I,b)=>{c(ce=>ce.map(Ue=>Ue.entry_uid===I?{...Ue,title:b}:Ue)),x(ce=>ce&&ce.entry_uid===I?{...ce,title:b}:ce)},[]),Il=h.useCallback(I=>{c(b=>b.filter(ce=>ce.entry_uid!==I)),x(b=>(b==null?void 0:b.entry_uid)===I?null:b),m(b=>b===I?null:b)},[]),L=h.useCallback(()=>{ye(!0)},[]),H=h.useCallback(()=>{ye(!1)},[]),De=h.useCallback(()=>{a&&Promise.all([R(a,w,k),mo(a).then(J)])},[a,w,k,R]),st=h.useCallback((I,b,ce="error")=>{if(ce==="warning"&&p)return;const Ue=++P.current;he(Uc=>[...Uc,{id:Ue,text:I,locator:b,type:ce}])},[p]),Ic=h.useCallback(I=>{he(b=>b.filter(ce=>ce.id!==I))},[]),Ac=h.useCallback(()=>{sessionStorage.setItem("ublockWarningIgnored","true"),C(!0),he(I=>I.filter(b=>b.type!=="warning"))},[]);return e==="loading"?i.jsx("div",{className:"auth-loading",children:"Loading\\u2026"}):e==="setup"?i.jsx(sh,{onComplete:()=>t("login")}):e==="login"?i.jsx(lh,{onLogin:I=>{r(I),t("authenticated")}}):i.jsx(Ol.Provider,{value:{currentUser:n,setCurrentUser:r},children:i.jsxs(i.Fragment,{children:[i.jsx(ih,{archives:l,archiveId:a,onArchiveChange:B,view:D,onViewChange:A,onCaptureClick:L}),i.jsxs("main",{className:"app-shell",children:[i.jsxs("div",{className:"workspace",children:[D==="archive"&&i.jsxs("div",{className:"toolbar",children:[i.jsxs("div",{className:"search-field",children:[i.jsx("span",{className:"ico","aria-hidden":"true",children:i.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[i.jsx("circle",{cx:"11",cy:"11",r:"7"}),i.jsx("line",{x1:"16.5",y1:"16.5",x2:"21",y2:"21"})]})}),i.jsx("input",{className:"search-input",type:"search","aria-label":"Search archive","aria-busy":N,placeholder:"Search titles, URLs, types, tags…",value:w,onChange:I=>j(I.target.value)}),i.jsx("span",{className:"kbd",children:"⌘K"})]}),i.jsxs("span",{className:"result-count",children:[E&&i.jsxs(i.Fragment,{children:[i.jsx("b",{children:E.split(" ")[0]})," ",E.split(" ").slice(1).join(" ")]}),k&&i.jsxs("button",{className:"tag-filter-badge",onClick:re,children:["× ",M?Mc(k):k]})]})]}),D==="archive"&&i.jsx(fh,{entries:u,selectedEntryUid:y,onSelectEntry:V,archiveId:a,tagFilter:k,onClearTagFilter:re,searchQuery:w,onSearchChange:j,resultCount:E,searchBusy:N}),D==="runs"&&i.jsx(mh,{runs:$}),D==="admin"&&i.jsx(vh,{archives:l}),D==="tags"&&i.jsx(yh,{archiveId:a,tagNodes:se,tagFilter:k,onTagFilterSet:W,onViewChange:A,onTagRenamed:$l,onTagDeleted:Ml,onTagsRefresh:yr,humanizeTags:M}),D==="collections"&&i.jsx(wh,{archiveId:a}),D==="settings"&&i.jsx(Sh,{tab:d,onTabChange:v,archiveId:a})]}),i.jsx(Lh,{archiveId:a,selectedEntry:g,onTagFilterSet:W,tagNodes:se,onTagsRefresh:yr,onEntryTitleChange:Fl,onEntryDeleted:Il,humanizeTags:M})]}),i.jsx(ah,{open:K,archiveId:a,onClose:H,onCaptured:De,onToast:st}),i.jsx(zh,{toasts:Ee,onDismiss:Ic,onIgnoreUblock:Ac})]})})}zc(document.getElementById("root")).render(i.jsx(h.StrictMode,{children:i.jsx(Fh,{})})); diff --git a/crates/archivr-server/static/index.html b/crates/archivr-server/static/index.html index 0876e3e..1797684 100644 --- a/crates/archivr-server/static/index.html +++ b/crates/archivr-server/static/index.html @@ -4,8 +4,8 @@ Archivr - - + +
diff --git a/flake.nix b/flake.nix index 48ad04e..8a2d1bb 100644 --- a/flake.nix +++ b/flake.nix @@ -60,6 +60,40 @@ tweetPython = pkgs.python312.withPackages (ps: [ twitterApiClient ]); + # uBlock Origin Lite (MV3) — unpacked Chromium extension for headless ad-blocking. + # Fetched from the uBOL-home GitHub releases; update version + hash together. + ublockLite = pkgs.stdenv.mkDerivation { + pname = "ublock-origin-lite"; + version = "2026.705.2152"; + src = pkgs.fetchurl { + url = "https://github.com/uBlockOrigin/uBOL-home/releases/download/2026.705.2152/uBOLite_2026.705.2152.chromium.zip"; + hash = "sha256-4TbvDYbkOkDuVK17TeAbLDBcgf9O6f/vh2buGbLu4XQ="; + }; + nativeBuildInputs = [ pkgs.unzip ]; + sourceRoot = "."; + installPhase = '' + mkdir -p $out + cp -r . $out/ + ''; + }; + # I Still Don't Care About Cookies (MV3) — unpacked Chromium extension + # for dismissing cookie consent banners during headless captures. + # Fetched from GitHub releases; update version + hash together. + isdcac = pkgs.stdenv.mkDerivation { + pname = "istilldontcareaboutcookies"; + version = "1.1.9"; + src = pkgs.fetchurl { + url = "https://github.com/OhMyGuus/I-Still-Dont-Care-About-Cookies/releases/download/v1.1.9/ISDCAC-chrome-source.zip"; + hash = "sha256-j3CrlHyy0nT0AiqXD13Tzs2OwCsGDgUYe++e48sYu8s="; + }; + nativeBuildInputs = [ pkgs.unzip ]; + sourceRoot = "."; + installPhase = '' + test -f manifest.json || { echo "ERROR: manifest.json not at extension root; zip structure may have changed"; exit 1; } + mkdir -p $out + cp -r . $out/ + ''; + }; version = "0.1.0"; src = pkgs.lib.cleanSource ./.; cargoLock = { @@ -123,6 +157,8 @@ ${lib.optionalString pkgs.stdenv.isLinux "--set ARCHIVR_CHROME ${pkgs.chromium}/bin/chromium"} \ --set ARCHIVR_TWEET_PYTHON ${tweetPython}/bin/python3 \ --set ARCHIVR_TWEET_SCRAPER $out/libexec/archivr/scrape_user_tweet_contents.py \ + --set ARCHIVR_UBLOCK_EXT ${ublockLite} \ + --set ARCHIVR_COOKIE_EXT ${isdcac} \ --prefix PATH : ${ lib.makeBinPath ([ pkgs.yt-dlp @@ -149,7 +185,9 @@ --set ARCHIVR_SINGLE_FILE ${pkgs.single-file-cli}/bin/single-file \ ${lib.optionalString pkgs.stdenv.isLinux "--set ARCHIVR_CHROME ${pkgs.chromium}/bin/chromium"} \ --set ARCHIVR_TWEET_PYTHON ${tweetPython}/bin/python3 \ - --set ARCHIVR_TWEET_SCRAPER $out/libexec/archivr-server/scrape_user_tweet_contents.py + --set ARCHIVR_TWEET_SCRAPER $out/libexec/archivr-server/scrape_user_tweet_contents.py \ + --set ARCHIVR_UBLOCK_EXT ${ublockLite} \ + --set ARCHIVR_COOKIE_EXT ${isdcac} ''; }; archivr-all = pkgs.symlinkJoin { diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 614135c..b463ce2 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -85,6 +85,9 @@ export default function App() { const [toasts, setToasts] = useState([]) const toastIdRef = useRef(0) + const [ublockWarningIgnored, setUblockWarningIgnored] = useState( + () => sessionStorage.getItem('ublockWarningIgnored') === 'true' + ) const humanizeTags = currentUser?.humanize_slugs ?? false; @@ -238,15 +241,22 @@ export default function App() { ]) }, [archiveId, searchQuery, tagFilter, loadEntries]) - const handleToast = useCallback((errorText, locator) => { + const handleToast = useCallback((text, locator, type = 'error') => { + if (type === 'warning' && ublockWarningIgnored) return const id = ++toastIdRef.current - setToasts(prev => [...prev, { id, errorText, locator }]) - }, []) + setToasts(prev => [...prev, { id, text, locator, type }]) + }, [ublockWarningIgnored]) const handleDismissToast = useCallback((id) => { setToasts(prev => prev.filter(t => t.id !== id)) }, []) + const handleIgnoreUblock = useCallback(() => { + sessionStorage.setItem('ublockWarningIgnored', 'true') + setUblockWarningIgnored(true) + setToasts(prev => prev.filter(t => t.type !== 'warning')) + }, []) + if (authState === 'loading') return
Loading\u2026
; if (authState === 'setup') return setAuthState('login')} />; if (authState === 'login') return { setCurrentUser(user); setAuthState('authenticated'); }} />; @@ -347,7 +357,7 @@ export default function App() { onCaptured={handleCaptured} onToast={handleToast} /> - + ) diff --git a/frontend/src/api.js b/frontend/src/api.js index 118fa86..2279233 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -95,9 +95,15 @@ export async function fetchTags(archiveId) { return getJson(`/api/archives/${archiveId}/tags`); } -export async function submitCapture(archiveId, locator, quality = null) { +export async function submitCapture(archiveId, locator, quality = null, extensions = null) { const payload = { locator } if (quality && quality !== 'best') payload.quality = quality + // extensions: { ublock_enabled?: bool, reader_mode?: bool } — per-capture overrides + if (extensions) { + if (typeof extensions.ublock_enabled === 'boolean') payload.ublock_enabled = extensions.ublock_enabled + if (typeof extensions.reader_mode === 'boolean') payload.reader_mode = extensions.reader_mode + if (typeof extensions.cookie_ext_enabled === 'boolean') payload.cookie_ext_enabled = extensions.cookie_ext_enabled + } const res = await fetch(`/api/archives/${archiveId}/captures`, { method: "POST", headers: { "Content-Type": "application/json" }, diff --git a/frontend/src/components/CaptureDialog.jsx b/frontend/src/components/CaptureDialog.jsx index 3472664..c0105bb 100644 --- a/frontend/src/components/CaptureDialog.jsx +++ b/frontend/src/components/CaptureDialog.jsx @@ -1,5 +1,5 @@ -import { useRef, useEffect, useState } from 'react' -import { submitCapture, pollCaptureJob, probeCapture } from '../api' +import { useRef, useEffect, useState, useCallback } from 'react' +import { submitCapture, pollCaptureJob, probeCapture, getInstanceSettings } from '../api' let nextItemId = 1 @@ -112,6 +112,31 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on sessionStorage.setItem('captureItems', JSON.stringify(items)) }, [items]) + // Advanced options panel state + const [advancedOpen, setAdvancedOpen] = useState(false) + // null = use server default; true/false = per-session override + const [ublockOverride, setUblockOverride] = useState(null) + // Server-side global settings (loaded on mount, null until loaded) + const [globalSettings, setGlobalSettings] = useState(null) + // Cookie consent: session-level only, initialized from server default + const [cookieExtEnabled, setCookieExtEnabled] = useState(true) + + // Load global settings from server once on mount + useEffect(() => { + getInstanceSettings() + .then(s => { + setGlobalSettings(s) + setCookieExtEnabled(s.cookie_ext_enabled ?? true) + }) + .catch(() => setGlobalSettings({})) + }, []) + + // Effective uBlock for this session + const ublockEnabled = ublockOverride !== null ? ublockOverride : (globalSettings?.ublock_enabled ?? true) + + // Reader mode: off by default, per-session only + const [readerMode, setReaderMode] = useState(false) + // On mount: clean up old single-locator sessionStorage keys; reconnect running jobs useEffect(() => { ;['captureDialogLocator','captureDialogError','captureDialogBusy', @@ -186,6 +211,13 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on }) }, 1400) onCapturedRef.current() + // Warn if uBlock was requested but the extension wasn't available + try { + const notes = updated.notes_json ? JSON.parse(updated.notes_json) : null + if (notes?.ublock_skipped || notes?.cookie_ext_skipped) { + onToastRef.current(null, locator, 'warning') + } + } catch {} } else if (updated.status === 'failed') { clearInterval(pollIntervals.current.get(jobUid)) pollIntervals.current.delete(jobUid) @@ -216,7 +248,8 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on const qual = item.quality || 'best' setItems(prev => prev.map(it => it.id === item.id ? { ...it, status: 'submitting', error: null } : it)) try { - const job = await submitCapture(aid, loc, qual) + const extensions = { ublock_enabled: ublockEnabled, reader_mode: readerMode, cookie_ext_enabled: cookieExtEnabled } + const job = await submitCapture(aid, loc, qual, extensions) setItems(prev => prev.map(it => it.id === item.id ? { ...it, status: 'running', jobUid: job.job_uid, archiveId: aid } : it )) @@ -335,10 +368,82 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on Add another -
- + {advancedOpen && ( +
+ + + +
+ )} +
+ + {/* ── Primary action ──────────────────────────────── */} +
+
diff --git a/frontend/src/components/SettingsView.jsx b/frontend/src/components/SettingsView.jsx index 31b04cd..ddf361a 100644 --- a/frontend/src/components/SettingsView.jsx +++ b/frontend/src/components/SettingsView.jsx @@ -14,8 +14,8 @@ export default function SettingsView({ tab, onTabChange, archiveId }) { const { currentUser, setCurrentUser } = useContext(AuthContext) ?? {} const isAdmin = currentUser && ((currentUser.role_bits & ROLE_ADMIN) !== 0) - const tabs = ['profile', 'tokens', ...(isAdmin ? ['instance', 'cookies', 'storage'] : [])] - const tabLabels = { profile: 'Profile', tokens: 'API Tokens', instance: 'Instance', cookies: 'Cookies', storage: 'Storage' } + const tabs = ['profile', 'tokens', ...(isAdmin ? ['instance', 'cookies', 'extensions', 'storage'] : [])] + const tabLabels = { profile: 'Profile', tokens: 'API Tokens', instance: 'Instance', cookies: 'Cookies', extensions: 'Extensions', storage: 'Storage' } return (
@@ -34,6 +34,7 @@ export default function SettingsView({ tab, onTabChange, archiveId }) { {tab === 'tokens' && } {tab === 'instance' && isAdmin && } {tab === 'cookies' && isAdmin && } + {tab === 'extensions' && isAdmin && } {tab === 'storage' && isAdmin && }
) @@ -638,4 +639,125 @@ function CookiesTab() { ) +} + +function ExtensionsTab() { + const [settings, setSettings] = useState(null) + const [loading, setLoading] = useState(true) + const [saving, setSaving] = useState(false) + const [msg, setMsg] = useState(null) + + useEffect(() => { + (async () => { + try { setSettings(await getInstanceSettings()) } + catch (e) { setMsg({ ok: false, text: e.message }) } + finally { setLoading(false) } + })() + }, []) + + async function toggleUblock(val) { + setSaving(true) + setMsg(null) + try { + await updateInstanceSettings({ ublock_enabled: val }) + setSettings(s => ({ ...s, ublock_enabled: val })) + setMsg({ ok: true, text: 'Saved.' }) + } catch (e) { + setMsg({ ok: false, text: e.message }) + } finally { + setSaving(false) + } + } + + async function toggleCookieExt(val) { + setSaving(true) + setMsg(null) + try { + await updateInstanceSettings({ cookie_ext_enabled: val }) + setSettings(s => ({ ...s, cookie_ext_enabled: val })) + setMsg({ ok: true, text: 'Saved.' }) + } catch (e) { + setMsg({ ok: false, text: e.message }) + } finally { + setSaving(false) + } + } + + if (loading) return
Loading\u2026
+ + const extAvailable = settings?.ublock_ext_available ?? false + const extEnabled = settings?.ublock_enabled ?? true + const cookieExtAvailable = settings?.cookie_ext_available ?? false + const cookieExtEnabled = settings?.cookie_ext_enabled ?? true + + return ( +
+
+

Extensions

+

+ Extensions run inside the browser during WebPage captures and can block ads, + accept cookie banners, and more. Changes take effect on the next capture. +

+ +
+
+
+ uBlock Origin Lite + + Blocks ads, trackers, and other page clutter during archiving + via Chrome’s declarativeNetRequest API (Manifest V3). + + {!extAvailable && ( + + Not configured — set ARCHIVR_UBLOCK_EXT to the + unpacked extension directory to enable. + + )} +
+ +
+
+ +
+
+
+ I Still Don’t Care About Cookies + + Dismiss cookie consent banners during archiving. + + {!cookieExtAvailable && ( + + Not configured — set ARCHIVR_COOKIE_EXT to the + unpacked extension directory to enable. + + )} +
+ +
+
+ + {msg &&
{msg.text}
} +
+
+ ) } \ No newline at end of file diff --git a/frontend/src/components/ToastStack.jsx b/frontend/src/components/ToastStack.jsx index b9da5f9..9ea8d18 100644 --- a/frontend/src/components/ToastStack.jsx +++ b/frontend/src/components/ToastStack.jsx @@ -1,22 +1,23 @@ import { useState, useEffect } from 'react' -const TOAST_TTL = 7000 // ms before auto-dismiss; paused when error is expanded +const TOAST_TTL = 7000 // ms before auto-dismiss; paused when detail is expanded -export default function ToastStack({ toasts, onDismiss }) { +export default function ToastStack({ toasts, onDismiss, onIgnoreUblock }) { if (!toasts.length) return null return (
{toasts.map(t => ( - + ))}
) } -function Toast({ toast, onDismiss }) { +function Toast({ toast, onDismiss, onIgnoreUblock }) { const [expanded, setExpanded] = useState(false) + const isWarning = toast.type === 'warning' - // Auto-dismiss after TTL; paused while error detail is expanded + // Auto-dismiss after TTL; paused while detail is expanded useEffect(() => { if (expanded) return const timer = setTimeout(() => onDismiss(toast.id), TOAST_TTL) @@ -27,6 +28,50 @@ function Toast({ toast, onDismiss }) { ? (toast.locator.length > 48 ? toast.locator.slice(0, 45) + '\u2026' : toast.locator) : null + if (isWarning) { + return ( +
+
+ +
+ Ad-blocking unavailable + {short && {short}} +
+
+ + + +
+
+ {expanded && ( +

+ {toast.text || 'ARCHIVR_UBLOCK=true but ARCHIVR_UBLOCK_EXT is not set or the path is invalid. The page was captured without ad-blocking. Set ARCHIVR_UBLOCK_EXT to the unpacked uBlock Origin Lite extension directory to enable ad-blocking, or set ARCHIVR_UBLOCK=false to silence this warning.'} +

+ )} +
+ ) + } + return (
@@ -36,7 +81,7 @@ function Toast({ toast, onDismiss }) { {short && {short}}
- {toast.errorText && ( + {toast.text && (
- {expanded && toast.errorText && ( -
{toast.errorText}
+ {expanded && toast.text && ( +
{toast.text}
)} ) diff --git a/frontend/src/styles.css b/frontend/src/styles.css index c8d8ffe..f7bb2b0 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -608,30 +608,86 @@ select { } .capture-actions { display: flex; - gap: 10px; - justify-content: flex-end; - margin-top: 16px; + flex-direction: column; + gap: 8px; + margin-top: 18px; } -.capture-cancel { - border: 1px solid var(--line); - background: none; - color: var(--ink); - padding: 8px 18px; - border-radius: var(--r); - cursor: pointer; -} -.capture-cancel:hover { background: var(--paper-2); } .capture-submit { border: 0; background: var(--ink); color: var(--paper); - padding: 8px 20px; - border-radius: var(--r); + padding: 13px 20px; + border-radius: var(--r2); cursor: pointer; font-weight: 600; + font-size: 15px; + width: 100%; + min-width: 220px; + letter-spacing: 0.01em; } .capture-submit:hover { opacity: 0.85; } .capture-submit:disabled { opacity: 0.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 options ────────────────────────────────────────────── */ +.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 0.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 + multi-row ─────────────────────────────────── */ .capture-dialog-header { @@ -812,6 +868,7 @@ select { to { opacity: 1; transform: translateY(0) scale(1); } } .toast--error { border-left: 3px solid var(--accent); } +.toast--warning { border-left: 3px solid #e8a000; } .toast-top { display: flex; @@ -892,6 +949,84 @@ select { 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); } + +/* ── Extension toggle (pill switch) ─────────────────────────────────────── */ +.ext-toggle { + flex-shrink: 0; + position: relative; + width: 44px; + height: 24px; + border-radius: 12px; + background: var(--line); + border: 0; + cursor: pointer; + transition: background 0.18s ease; + padding: 0; +} +.ext-toggle--sm { width: 36px; height: 20px; border-radius: 10px; } +.ext-toggle--on { background: var(--ink); } +.ext-toggle:disabled { opacity: 0.4; cursor: default; } +.ext-toggle-knob { + position: absolute; + top: 3px; left: 3px; + width: 18px; height: 18px; + border-radius: 50%; + background: var(--paper); + transition: transform 0.18s ease; + display: block; + box-shadow: 0 1px 3px rgba(0,0,0,.2); +} +.ext-toggle--sm .ext-toggle-knob { width: 14px; height: 14px; top: 3px; left: 3px; } +.ext-toggle--on .ext-toggle-knob { transform: translateX(20px); } +.ext-toggle--sm.ext-toggle--on .ext-toggle-knob { transform: translateX(16px); } + +/* ── Extension card (Settings / Extensions tab) ──────────────────────────── */ +.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; } /* ── Utility ─────────────────────────────────────────────────────────────── */ .muted { color: var(--muted); } diff --git a/vendor/readability/Readability.js b/vendor/readability/Readability.js new file mode 100644 index 0000000..5cff454 --- /dev/null +++ b/vendor/readability/Readability.js @@ -0,0 +1,2812 @@ +/* + * Copyright (c) 2010 Arc90 Inc + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * This code is heavily based on Arc90's readability.js (1.7.1) script + * available at: http://code.google.com/p/arc90labs-readability + */ + +/** + * Public constructor. + * @param {HTMLDocument} doc The document to parse. + * @param {Object} options The options object. + */ +function Readability(doc, options) { + // In some older versions, people passed a URI as the first argument. Cope: + if (options && options.documentElement) { + doc = options; + options = arguments[2]; + } else if (!doc || !doc.documentElement) { + throw new Error( + "First argument to Readability constructor should be a document object." + ); + } + options = options || {}; + + this._doc = doc; + this._docJSDOMParser = this._doc.firstChild.__JSDOMParser__; + this._articleTitle = null; + this._articleByline = null; + this._articleDir = null; + this._articleSiteName = null; + this._attempts = []; + this._metadata = {}; + + // Configurable options + this._debug = !!options.debug; + this._maxElemsToParse = + options.maxElemsToParse || this.DEFAULT_MAX_ELEMS_TO_PARSE; + this._nbTopCandidates = + options.nbTopCandidates || this.DEFAULT_N_TOP_CANDIDATES; + this._charThreshold = options.charThreshold || this.DEFAULT_CHAR_THRESHOLD; + this._classesToPreserve = this.CLASSES_TO_PRESERVE.concat( + options.classesToPreserve || [] + ); + this._keepClasses = !!options.keepClasses; + this._serializer = + options.serializer || + function (el) { + return el.innerHTML; + }; + this._disableJSONLD = !!options.disableJSONLD; + this._allowedVideoRegex = options.allowedVideoRegex || this.REGEXPS.videos; + this._linkDensityModifier = options.linkDensityModifier || 0; + + // Start with all flags set + this._flags = + this.FLAG_STRIP_UNLIKELYS | + this.FLAG_WEIGHT_CLASSES | + this.FLAG_CLEAN_CONDITIONALLY; + + // Control whether log messages are sent to the console + if (this._debug) { + let logNode = function (node) { + if (node.nodeType == node.TEXT_NODE) { + return `${node.nodeName} ("${node.textContent}")`; + } + let attrPairs = Array.from(node.attributes || [], function (attr) { + return `${attr.name}="${attr.value}"`; + }).join(" "); + return `<${node.localName} ${attrPairs}>`; + }; + this.log = function () { + if (typeof console !== "undefined") { + let args = Array.from(arguments, arg => { + if (arg && arg.nodeType == this.ELEMENT_NODE) { + return logNode(arg); + } + return arg; + }); + args.unshift("Reader: (Readability)"); + // eslint-disable-next-line no-console + console.log(...args); + } else if (typeof dump !== "undefined") { + /* global dump */ + var msg = Array.prototype.map + .call(arguments, function (x) { + return x && x.nodeName ? logNode(x) : x; + }) + .join(" "); + dump("Reader: (Readability) " + msg + "\n"); + } + }; + } else { + this.log = function () {}; + } +} + +Readability.prototype = { + FLAG_STRIP_UNLIKELYS: 0x1, + FLAG_WEIGHT_CLASSES: 0x2, + FLAG_CLEAN_CONDITIONALLY: 0x4, + + // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType + ELEMENT_NODE: 1, + TEXT_NODE: 3, + + // Max number of nodes supported by this parser. Default: 0 (no limit) + DEFAULT_MAX_ELEMS_TO_PARSE: 0, + + // The number of top candidates to consider when analysing how + // tight the competition is among candidates. + DEFAULT_N_TOP_CANDIDATES: 5, + + // Element tags to score by default. + DEFAULT_TAGS_TO_SCORE: "section,h2,h3,h4,h5,h6,p,td,pre" + .toUpperCase() + .split(","), + + // The default number of chars an article must have in order to return a result + DEFAULT_CHAR_THRESHOLD: 500, + + // All of the regular expressions in use within readability. + // Defined up here so we don't instantiate them repeatedly in loops. + REGEXPS: { + // NOTE: These two regular expressions are duplicated in + // Readability-readerable.js. Please keep both copies in sync. + unlikelyCandidates: + /-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i, + okMaybeItsACandidate: + /and|article|body|column|content|main|mathjax|shadow/i, + + positive: + /article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story/i, + negative: + /-ad-|hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|footer|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|widget/i, + extraneous: + /print|archive|comment|discuss|e[\-]?mail|share|reply|all|login|sign|single|utility/i, + byline: /byline|author|dateline|writtenby|p-author/i, + replaceFonts: /<(\/?)font[^>]*>/gi, + normalize: /\s{2,}/g, + videos: + /\/\/(www\.)?((dailymotion|youtube|youtube-nocookie|player\.vimeo|v\.qq|bilibili|live.bilibili)\.com|(archive|upload\.wikimedia)\.org|player\.twitch\.tv)/i, + shareElements: /(\b|_)(share|sharedaddy)(\b|_)/i, + nextLink: /(next|weiter|continue|>([^\|]|$)|»([^\|]|$))/i, + prevLink: /(prev|earl|old|new|<|«)/i, + tokenize: /\W+/g, + whitespace: /^\s*$/, + hasContent: /\S$/, + hashUrl: /^#.+/, + srcsetUrl: /(\S+)(\s+[\d.]+[xw])?(\s*(?:,|$))/g, + b64DataUrl: /^data:\s*([^\s;,]+)\s*;\s*base64\s*,/i, + // Commas as used in Latin, Sindhi, Chinese and various other scripts. + // see: https://en.wikipedia.org/wiki/Comma#Comma_variants + commas: /\u002C|\u060C|\uFE50|\uFE10|\uFE11|\u2E41|\u2E34|\u2E32|\uFF0C/g, + // See: https://schema.org/Article + jsonLdArticleTypes: + /^Article|AdvertiserContentArticle|NewsArticle|AnalysisNewsArticle|AskPublicNewsArticle|BackgroundNewsArticle|OpinionNewsArticle|ReportageNewsArticle|ReviewNewsArticle|Report|SatiricalArticle|ScholarlyArticle|MedicalScholarlyArticle|SocialMediaPosting|BlogPosting|LiveBlogPosting|DiscussionForumPosting|TechArticle|APIReference$/, + // used to see if a node's content matches words commonly used for ad blocks or loading indicators + adWords: + /^(ad(vertising|vertisement)?|pub(licité)?|werb(ung)?|广告|Реклама|Anuncio)$/iu, + loadingWords: + /^((loading|正在加载|Загрузка|chargement|cargando)(…|\.\.\.)?)$/iu, + }, + + UNLIKELY_ROLES: [ + "menu", + "menubar", + "complementary", + "navigation", + "alert", + "alertdialog", + "dialog", + ], + + DIV_TO_P_ELEMS: new Set([ + "BLOCKQUOTE", + "DL", + "DIV", + "IMG", + "OL", + "P", + "PRE", + "TABLE", + "UL", + ]), + + ALTER_TO_DIV_EXCEPTIONS: ["DIV", "ARTICLE", "SECTION", "P", "OL", "UL"], + + PRESENTATIONAL_ATTRIBUTES: [ + "align", + "background", + "bgcolor", + "border", + "cellpadding", + "cellspacing", + "frame", + "hspace", + "rules", + "style", + "valign", + "vspace", + ], + + DEPRECATED_SIZE_ATTRIBUTE_ELEMS: ["TABLE", "TH", "TD", "HR", "PRE"], + + // The commented out elements qualify as phrasing content but tend to be + // removed by readability when put into paragraphs, so we ignore them here. + PHRASING_ELEMS: [ + // "CANVAS", "IFRAME", "SVG", "VIDEO", + "ABBR", + "AUDIO", + "B", + "BDO", + "BR", + "BUTTON", + "CITE", + "CODE", + "DATA", + "DATALIST", + "DFN", + "EM", + "EMBED", + "I", + "IMG", + "INPUT", + "KBD", + "LABEL", + "MARK", + "MATH", + "METER", + "NOSCRIPT", + "OBJECT", + "OUTPUT", + "PROGRESS", + "Q", + "RUBY", + "SAMP", + "SCRIPT", + "SELECT", + "SMALL", + "SPAN", + "STRONG", + "SUB", + "SUP", + "TEXTAREA", + "TIME", + "VAR", + "WBR", + ], + + // These are the classes that readability sets itself. + CLASSES_TO_PRESERVE: ["page"], + + // These are the list of HTML entities that need to be escaped. + HTML_ESCAPE_MAP: { + lt: "<", + gt: ">", + amp: "&", + quot: '"', + apos: "'", + }, + + /** + * Run any post-process modifications to article content as necessary. + * + * @param Element + * @return void + **/ + _postProcessContent(articleContent) { + // Readability cannot open relative uris so we convert them to absolute uris. + this._fixRelativeUris(articleContent); + + this._simplifyNestedElements(articleContent); + + if (!this._keepClasses) { + // Remove classes. + this._cleanClasses(articleContent); + } + }, + + /** + * Iterates over a NodeList, calls `filterFn` for each node and removes node + * if function returned `true`. + * + * If function is not passed, removes all the nodes in node list. + * + * @param NodeList nodeList The nodes to operate on + * @param Function filterFn the function to use as a filter + * @return void + */ + _removeNodes(nodeList, filterFn) { + // Avoid ever operating on live node lists. + if (this._docJSDOMParser && nodeList._isLiveNodeList) { + throw new Error("Do not pass live node lists to _removeNodes"); + } + for (var i = nodeList.length - 1; i >= 0; i--) { + var node = nodeList[i]; + var parentNode = node.parentNode; + if (parentNode) { + if (!filterFn || filterFn.call(this, node, i, nodeList)) { + parentNode.removeChild(node); + } + } + } + }, + + /** + * Iterates over a NodeList, and calls _setNodeTag for each node. + * + * @param NodeList nodeList The nodes to operate on + * @param String newTagName the new tag name to use + * @return void + */ + _replaceNodeTags(nodeList, newTagName) { + // Avoid ever operating on live node lists. + if (this._docJSDOMParser && nodeList._isLiveNodeList) { + throw new Error("Do not pass live node lists to _replaceNodeTags"); + } + for (const node of nodeList) { + this._setNodeTag(node, newTagName); + } + }, + + /** + * Iterate over a NodeList, which doesn't natively fully implement the Array + * interface. + * + * For convenience, the current object context is applied to the provided + * iterate function. + * + * @param NodeList nodeList The NodeList. + * @param Function fn The iterate function. + * @return void + */ + _forEachNode(nodeList, fn) { + Array.prototype.forEach.call(nodeList, fn, this); + }, + + /** + * Iterate over a NodeList, and return the first node that passes + * the supplied test function + * + * For convenience, the current object context is applied to the provided + * test function. + * + * @param NodeList nodeList The NodeList. + * @param Function fn The test function. + * @return void + */ + _findNode(nodeList, fn) { + return Array.prototype.find.call(nodeList, fn, this); + }, + + /** + * Iterate over a NodeList, return true if any of the provided iterate + * function calls returns true, false otherwise. + * + * For convenience, the current object context is applied to the + * provided iterate function. + * + * @param NodeList nodeList The NodeList. + * @param Function fn The iterate function. + * @return Boolean + */ + _someNode(nodeList, fn) { + return Array.prototype.some.call(nodeList, fn, this); + }, + + /** + * Iterate over a NodeList, return true if all of the provided iterate + * function calls return true, false otherwise. + * + * For convenience, the current object context is applied to the + * provided iterate function. + * + * @param NodeList nodeList The NodeList. + * @param Function fn The iterate function. + * @return Boolean + */ + _everyNode(nodeList, fn) { + return Array.prototype.every.call(nodeList, fn, this); + }, + + _getAllNodesWithTag(node, tagNames) { + if (node.querySelectorAll) { + return node.querySelectorAll(tagNames.join(",")); + } + return [].concat.apply( + [], + tagNames.map(function (tag) { + var collection = node.getElementsByTagName(tag); + return Array.isArray(collection) ? collection : Array.from(collection); + }) + ); + }, + + /** + * Removes the class="" attribute from every element in the given + * subtree, except those that match CLASSES_TO_PRESERVE and + * the classesToPreserve array from the options object. + * + * @param Element + * @return void + */ + _cleanClasses(node) { + var classesToPreserve = this._classesToPreserve; + var className = (node.getAttribute("class") || "") + .split(/\s+/) + .filter(cls => classesToPreserve.includes(cls)) + .join(" "); + + if (className) { + node.setAttribute("class", className); + } else { + node.removeAttribute("class"); + } + + for (node = node.firstElementChild; node; node = node.nextElementSibling) { + this._cleanClasses(node); + } + }, + + /** + * Tests whether a string is a URL or not. + * + * @param {string} str The string to test + * @return {boolean} true if str is a URL, false if not + */ + _isUrl(str) { + try { + new URL(str); + return true; + } catch { + return false; + } + }, + /** + * Converts each and uri in the given element to an absolute URI, + * ignoring #ref URIs. + * + * @param Element + * @return void + */ + _fixRelativeUris(articleContent) { + var baseURI = this._doc.baseURI; + var documentURI = this._doc.documentURI; + function toAbsoluteURI(uri) { + // Leave hash links alone if the base URI matches the document URI: + if (baseURI == documentURI && uri.charAt(0) == "#") { + return uri; + } + + // Otherwise, resolve against base URI: + try { + return new URL(uri, baseURI).href; + } catch (ex) { + // Something went wrong, just return the original: + } + return uri; + } + + var links = this._getAllNodesWithTag(articleContent, ["a"]); + this._forEachNode(links, function (link) { + var href = link.getAttribute("href"); + if (href) { + // Remove links with javascript: URIs, since + // they won't work after scripts have been removed from the page. + if (href.indexOf("javascript:") === 0) { + // if the link only contains simple text content, it can be converted to a text node + if ( + link.childNodes.length === 1 && + link.childNodes[0].nodeType === this.TEXT_NODE + ) { + var text = this._doc.createTextNode(link.textContent); + link.parentNode.replaceChild(text, link); + } else { + // if the link has multiple children, they should all be preserved + var container = this._doc.createElement("span"); + while (link.firstChild) { + container.appendChild(link.firstChild); + } + link.parentNode.replaceChild(container, link); + } + } else { + link.setAttribute("href", toAbsoluteURI(href)); + } + } + }); + + var medias = this._getAllNodesWithTag(articleContent, [ + "img", + "picture", + "figure", + "video", + "audio", + "source", + ]); + + this._forEachNode(medias, function (media) { + var src = media.getAttribute("src"); + var poster = media.getAttribute("poster"); + var srcset = media.getAttribute("srcset"); + + if (src) { + media.setAttribute("src", toAbsoluteURI(src)); + } + + if (poster) { + media.setAttribute("poster", toAbsoluteURI(poster)); + } + + if (srcset) { + var newSrcset = srcset.replace( + this.REGEXPS.srcsetUrl, + function (_, p1, p2, p3) { + return toAbsoluteURI(p1) + (p2 || "") + p3; + } + ); + + media.setAttribute("srcset", newSrcset); + } + }); + }, + + _simplifyNestedElements(articleContent) { + var node = articleContent; + + while (node) { + if ( + node.parentNode && + ["DIV", "SECTION"].includes(node.tagName) && + !(node.id && node.id.startsWith("readability")) + ) { + if (this._isElementWithoutContent(node)) { + node = this._removeAndGetNext(node); + continue; + } else if ( + this._hasSingleTagInsideElement(node, "DIV") || + this._hasSingleTagInsideElement(node, "SECTION") + ) { + var child = node.children[0]; + for (var i = 0; i < node.attributes.length; i++) { + child.setAttributeNode(node.attributes[i].cloneNode()); + } + node.parentNode.replaceChild(child, node); + node = child; + continue; + } + } + + node = this._getNextNode(node); + } + }, + + /** + * Get the article title as an H1. + * + * @return string + **/ + _getArticleTitle() { + var doc = this._doc; + var curTitle = ""; + var origTitle = ""; + + try { + curTitle = origTitle = doc.title.trim(); + + // If they had an element with id "title" in their HTML + if (typeof curTitle !== "string") { + curTitle = origTitle = this._getInnerText( + doc.getElementsByTagName("title")[0] + ); + } + } catch (e) { + /* ignore exceptions setting the title. */ + } + + var titleHadHierarchicalSeparators = false; + function wordCount(str) { + return str.split(/\s+/).length; + } + + // If there's a separator in the title, first remove the final part + const titleSeparators = /\|\-–—\\\/>»/.source; + if (new RegExp(`\\s[${titleSeparators}]\\s`).test(curTitle)) { + titleHadHierarchicalSeparators = /\s[\\\/>»]\s/.test(curTitle); + let allSeparators = Array.from( + origTitle.matchAll(new RegExp(`\\s[${titleSeparators}]\\s`, "gi")) + ); + curTitle = origTitle.substring(0, allSeparators.pop().index); + + // If the resulting title is too short, remove the first part instead: + if (wordCount(curTitle) < 3) { + curTitle = origTitle.replace( + new RegExp(`^[^${titleSeparators}]*[${titleSeparators}]`, "gi"), + "" + ); + } + } else if (curTitle.includes(": ")) { + // Check if we have an heading containing this exact string, so we + // could assume it's the full title. + var headings = this._getAllNodesWithTag(doc, ["h1", "h2"]); + var trimmedTitle = curTitle.trim(); + var match = this._someNode(headings, function (heading) { + return heading.textContent.trim() === trimmedTitle; + }); + + // If we don't, let's extract the title out of the original title string. + if (!match) { + curTitle = origTitle.substring(origTitle.lastIndexOf(":") + 1); + + // If the title is now too short, try the first colon instead: + if (wordCount(curTitle) < 3) { + curTitle = origTitle.substring(origTitle.indexOf(":") + 1); + // But if we have too many words before the colon there's something weird + // with the titles and the H tags so let's just use the original title instead + } else if (wordCount(origTitle.substr(0, origTitle.indexOf(":"))) > 5) { + curTitle = origTitle; + } + } + } else if (curTitle.length > 150 || curTitle.length < 15) { + var hOnes = doc.getElementsByTagName("h1"); + + if (hOnes.length === 1) { + curTitle = this._getInnerText(hOnes[0]); + } + } + + curTitle = curTitle.trim().replace(this.REGEXPS.normalize, " "); + // If we now have 4 words or fewer as our title, and either no + // 'hierarchical' separators (\, /, > or ») were found in the original + // title or we decreased the number of words by more than 1 word, use + // the original title. + var curTitleWordCount = wordCount(curTitle); + if ( + curTitleWordCount <= 4 && + (!titleHadHierarchicalSeparators || + curTitleWordCount != + wordCount( + origTitle.replace(new RegExp(`\\s[${titleSeparators}]\\s`, "g"), "") + ) - + 1) + ) { + curTitle = origTitle; + } + + return curTitle; + }, + + /** + * Prepare the HTML document for readability to scrape it. + * This includes things like stripping javascript, CSS, and handling terrible markup. + * + * @return void + **/ + _prepDocument() { + var doc = this._doc; + + // Remove all style tags in head + this._removeNodes(this._getAllNodesWithTag(doc, ["style"])); + + if (doc.body) { + this._replaceBrs(doc.body); + } + + this._replaceNodeTags(this._getAllNodesWithTag(doc, ["font"]), "SPAN"); + }, + + /** + * Finds the next node, starting from the given node, and ignoring + * whitespace in between. If the given node is an element, the same node is + * returned. + */ + _nextNode(node) { + var next = node; + while ( + next && + next.nodeType != this.ELEMENT_NODE && + this.REGEXPS.whitespace.test(next.textContent) + ) { + next = next.nextSibling; + } + return next; + }, + + /** + * Replaces 2 or more successive
elements with a single

. + * Whitespace between
elements are ignored. For example: + *

foo
bar


abc
+ * will become: + *
foo
bar

abc

+ */ + _replaceBrs(elem) { + this._forEachNode(this._getAllNodesWithTag(elem, ["br"]), function (br) { + var next = br.nextSibling; + + // Whether 2 or more
elements have been found and replaced with a + //

block. + var replaced = false; + + // If we find a
chain, remove the
s until we hit another node + // or non-whitespace. This leaves behind the first
in the chain + // (which will be replaced with a

later). + while ((next = this._nextNode(next)) && next.tagName == "BR") { + replaced = true; + var brSibling = next.nextSibling; + next.remove(); + next = brSibling; + } + + // If we removed a
chain, replace the remaining
with a

. Add + // all sibling nodes as children of the

until we hit another
+ // chain. + if (replaced) { + var p = this._doc.createElement("p"); + br.parentNode.replaceChild(p, br); + + next = p.nextSibling; + while (next) { + // If we've hit another

, we're done adding children to this

. + if (next.tagName == "BR") { + var nextElem = this._nextNode(next.nextSibling); + if (nextElem && nextElem.tagName == "BR") { + break; + } + } + + if (!this._isPhrasingContent(next)) { + break; + } + + // Otherwise, make this node a child of the new

. + var sibling = next.nextSibling; + p.appendChild(next); + next = sibling; + } + + while (p.lastChild && this._isWhitespace(p.lastChild)) { + p.lastChild.remove(); + } + + if (p.parentNode.tagName === "P") { + this._setNodeTag(p.parentNode, "DIV"); + } + } + }); + }, + + _setNodeTag(node, tag) { + this.log("_setNodeTag", node, tag); + if (this._docJSDOMParser) { + node.localName = tag.toLowerCase(); + node.tagName = tag.toUpperCase(); + return node; + } + + var replacement = node.ownerDocument.createElement(tag); + while (node.firstChild) { + replacement.appendChild(node.firstChild); + } + node.parentNode.replaceChild(replacement, node); + if (node.readability) { + replacement.readability = node.readability; + } + + for (var i = 0; i < node.attributes.length; i++) { + replacement.setAttributeNode(node.attributes[i].cloneNode()); + } + return replacement; + }, + + /** + * Prepare the article node for display. Clean out any inline styles, + * iframes, forms, strip extraneous

tags, etc. + * + * @param Element + * @return void + **/ + _prepArticle(articleContent) { + this._cleanStyles(articleContent); + + // Check for data tables before we continue, to avoid removing items in + // those tables, which will often be isolated even though they're + // visually linked to other content-ful elements (text, images, etc.). + this._markDataTables(articleContent); + + this._fixLazyImages(articleContent); + + // Clean out junk from the article content + this._cleanConditionally(articleContent, "form"); + this._cleanConditionally(articleContent, "fieldset"); + this._clean(articleContent, "object"); + this._clean(articleContent, "embed"); + this._clean(articleContent, "footer"); + this._clean(articleContent, "link"); + this._clean(articleContent, "aside"); + + // Clean out elements with little content that have "share" in their id/class combinations from final top candidates, + // which means we don't remove the top candidates even they have "share". + + var shareElementThreshold = this.DEFAULT_CHAR_THRESHOLD; + + this._forEachNode(articleContent.children, function (topCandidate) { + this._cleanMatchedNodes(topCandidate, function (node, matchString) { + return ( + this.REGEXPS.shareElements.test(matchString) && + node.textContent.length < shareElementThreshold + ); + }); + }); + + this._clean(articleContent, "iframe"); + this._clean(articleContent, "input"); + this._clean(articleContent, "textarea"); + this._clean(articleContent, "select"); + this._clean(articleContent, "button"); + this._cleanHeaders(articleContent); + + // Do these last as the previous stuff may have removed junk + // that will affect these + this._cleanConditionally(articleContent, "table"); + this._cleanConditionally(articleContent, "ul"); + this._cleanConditionally(articleContent, "div"); + + // replace H1 with H2 as H1 should be only title that is displayed separately + this._replaceNodeTags( + this._getAllNodesWithTag(articleContent, ["h1"]), + "h2" + ); + + // Remove extra paragraphs + this._removeNodes( + this._getAllNodesWithTag(articleContent, ["p"]), + function (paragraph) { + // At this point, nasty iframes have been removed; only embedded video + // ones remain. + var contentElementCount = this._getAllNodesWithTag(paragraph, [ + "img", + "embed", + "object", + "iframe", + ]).length; + return ( + contentElementCount === 0 && !this._getInnerText(paragraph, false) + ); + } + ); + + this._forEachNode( + this._getAllNodesWithTag(articleContent, ["br"]), + function (br) { + var next = this._nextNode(br.nextSibling); + if (next && next.tagName == "P") { + br.remove(); + } + } + ); + + // Remove single-cell tables + this._forEachNode( + this._getAllNodesWithTag(articleContent, ["table"]), + function (table) { + var tbody = this._hasSingleTagInsideElement(table, "TBODY") + ? table.firstElementChild + : table; + if (this._hasSingleTagInsideElement(tbody, "TR")) { + var row = tbody.firstElementChild; + if (this._hasSingleTagInsideElement(row, "TD")) { + var cell = row.firstElementChild; + cell = this._setNodeTag( + cell, + this._everyNode(cell.childNodes, this._isPhrasingContent) + ? "P" + : "DIV" + ); + table.parentNode.replaceChild(cell, table); + } + } + } + ); + }, + + /** + * Initialize a node with the readability object. Also checks the + * className/id for special names to add to its score. + * + * @param Element + * @return void + **/ + _initializeNode(node) { + node.readability = { contentScore: 0 }; + + switch (node.tagName) { + case "DIV": + node.readability.contentScore += 5; + break; + + case "PRE": + case "TD": + case "BLOCKQUOTE": + node.readability.contentScore += 3; + break; + + case "ADDRESS": + case "OL": + case "UL": + case "DL": + case "DD": + case "DT": + case "LI": + case "FORM": + node.readability.contentScore -= 3; + break; + + case "H1": + case "H2": + case "H3": + case "H4": + case "H5": + case "H6": + case "TH": + node.readability.contentScore -= 5; + break; + } + + node.readability.contentScore += this._getClassWeight(node); + }, + + _removeAndGetNext(node) { + var nextNode = this._getNextNode(node, true); + node.remove(); + return nextNode; + }, + + /** + * Traverse the DOM from node to node, starting at the node passed in. + * Pass true for the second parameter to indicate this node itself + * (and its kids) are going away, and we want the next node over. + * + * Calling this in a loop will traverse the DOM depth-first. + * + * @param {Element} node + * @param {boolean} ignoreSelfAndKids + * @return {Element} + */ + _getNextNode(node, ignoreSelfAndKids) { + // First check for kids if those aren't being ignored + if (!ignoreSelfAndKids && node.firstElementChild) { + return node.firstElementChild; + } + // Then for siblings... + if (node.nextElementSibling) { + return node.nextElementSibling; + } + // And finally, move up the parent chain *and* find a sibling + // (because this is depth-first traversal, we will have already + // seen the parent nodes themselves). + do { + node = node.parentNode; + } while (node && !node.nextElementSibling); + return node && node.nextElementSibling; + }, + + // compares second text to first one + // 1 = same text, 0 = completely different text + // works the way that it splits both texts into words and then finds words that are unique in second text + // the result is given by the lower length of unique parts + _textSimilarity(textA, textB) { + var tokensA = textA + .toLowerCase() + .split(this.REGEXPS.tokenize) + .filter(Boolean); + var tokensB = textB + .toLowerCase() + .split(this.REGEXPS.tokenize) + .filter(Boolean); + if (!tokensA.length || !tokensB.length) { + return 0; + } + var uniqTokensB = tokensB.filter(token => !tokensA.includes(token)); + var distanceB = uniqTokensB.join(" ").length / tokensB.join(" ").length; + return 1 - distanceB; + }, + + /** + * Checks whether an element node contains a valid byline + * + * @param node {Element} + * @param matchString {string} + * @return boolean + */ + _isValidByline(node, matchString) { + var rel = node.getAttribute("rel"); + var itemprop = node.getAttribute("itemprop"); + var bylineLength = node.textContent.trim().length; + + return ( + (rel === "author" || + (itemprop && itemprop.includes("author")) || + this.REGEXPS.byline.test(matchString)) && + !!bylineLength && + bylineLength < 100 + ); + }, + + _getNodeAncestors(node, maxDepth) { + maxDepth = maxDepth || 0; + var i = 0, + ancestors = []; + while (node.parentNode) { + ancestors.push(node.parentNode); + if (maxDepth && ++i === maxDepth) { + break; + } + node = node.parentNode; + } + return ancestors; + }, + + /*** + * grabArticle - Using a variety of metrics (content score, classname, element types), find the content that is + * most likely to be the stuff a user wants to read. Then return it wrapped up in a div. + * + * @param page a document to run upon. Needs to be a full document, complete with body. + * @return Element + **/ + /* eslint-disable-next-line complexity */ + _grabArticle(page) { + this.log("**** grabArticle ****"); + var doc = this._doc; + var isPaging = page !== null; + page = page ? page : this._doc.body; + + // We can't grab an article if we don't have a page! + if (!page) { + this.log("No body found in document. Abort."); + return null; + } + + var pageCacheHtml = page.innerHTML; + + while (true) { + this.log("Starting grabArticle loop"); + var stripUnlikelyCandidates = this._flagIsActive( + this.FLAG_STRIP_UNLIKELYS + ); + + // First, node prepping. Trash nodes that look cruddy (like ones with the + // class name "comment", etc), and turn divs into P tags where they have been + // used inappropriately (as in, where they contain no other block level elements.) + var elementsToScore = []; + var node = this._doc.documentElement; + + let shouldRemoveTitleHeader = true; + + while (node) { + if (node.tagName === "HTML") { + this._articleLang = node.getAttribute("lang"); + } + + var matchString = node.className + " " + node.id; + + if (!this._isProbablyVisible(node)) { + this.log("Removing hidden node - " + matchString); + node = this._removeAndGetNext(node); + continue; + } + + // User is not able to see elements applied with both "aria-modal = true" and "role = dialog" + if ( + node.getAttribute("aria-modal") == "true" && + node.getAttribute("role") == "dialog" + ) { + node = this._removeAndGetNext(node); + continue; + } + + // If we don't have a byline yet check to see if this node is a byline; if it is store the byline and remove the node. + if ( + !this._articleByline && + !this._metadata.byline && + this._isValidByline(node, matchString) + ) { + // Find child node matching [itemprop="name"] and use that if it exists for a more accurate author name byline + var endOfSearchMarkerNode = this._getNextNode(node, true); + var next = this._getNextNode(node); + var itemPropNameNode = null; + while (next && next != endOfSearchMarkerNode) { + var itemprop = next.getAttribute("itemprop"); + if (itemprop && itemprop.includes("name")) { + itemPropNameNode = next; + break; + } else { + next = this._getNextNode(next); + } + } + this._articleByline = (itemPropNameNode ?? node).textContent.trim(); + node = this._removeAndGetNext(node); + continue; + } + + if (shouldRemoveTitleHeader && this._headerDuplicatesTitle(node)) { + this.log( + "Removing header: ", + node.textContent.trim(), + this._articleTitle.trim() + ); + shouldRemoveTitleHeader = false; + node = this._removeAndGetNext(node); + continue; + } + + // Remove unlikely candidates + if (stripUnlikelyCandidates) { + if ( + this.REGEXPS.unlikelyCandidates.test(matchString) && + !this.REGEXPS.okMaybeItsACandidate.test(matchString) && + !this._hasAncestorTag(node, "table") && + !this._hasAncestorTag(node, "code") && + node.tagName !== "BODY" && + node.tagName !== "A" + ) { + this.log("Removing unlikely candidate - " + matchString); + node = this._removeAndGetNext(node); + continue; + } + + if (this.UNLIKELY_ROLES.includes(node.getAttribute("role"))) { + this.log( + "Removing content with role " + + node.getAttribute("role") + + " - " + + matchString + ); + node = this._removeAndGetNext(node); + continue; + } + } + + // Remove DIV, SECTION, and HEADER nodes without any content(e.g. text, image, video, or iframe). + if ( + (node.tagName === "DIV" || + node.tagName === "SECTION" || + node.tagName === "HEADER" || + node.tagName === "H1" || + node.tagName === "H2" || + node.tagName === "H3" || + node.tagName === "H4" || + node.tagName === "H5" || + node.tagName === "H6") && + this._isElementWithoutContent(node) + ) { + node = this._removeAndGetNext(node); + continue; + } + + if (this.DEFAULT_TAGS_TO_SCORE.includes(node.tagName)) { + elementsToScore.push(node); + } + + // Turn all divs that don't have children block level elements into p's + if (node.tagName === "DIV") { + // Put phrasing content into paragraphs. + var childNode = node.firstChild; + while (childNode) { + var nextSibling = childNode.nextSibling; + if (this._isPhrasingContent(childNode)) { + var fragment = doc.createDocumentFragment(); + // Collect all consecutive phrasing content into a fragment. + do { + nextSibling = childNode.nextSibling; + fragment.appendChild(childNode); + childNode = nextSibling; + } while (childNode && this._isPhrasingContent(childNode)); + + // Trim leading and trailing whitespace from the fragment. + while ( + fragment.firstChild && + this._isWhitespace(fragment.firstChild) + ) { + fragment.firstChild.remove(); + } + while ( + fragment.lastChild && + this._isWhitespace(fragment.lastChild) + ) { + fragment.lastChild.remove(); + } + + // If the fragment contains anything, wrap it in a paragraph and + // insert it before the next non-phrasing node. + if (fragment.firstChild) { + var p = doc.createElement("p"); + p.appendChild(fragment); + node.insertBefore(p, nextSibling); + } + } + childNode = nextSibling; + } + + // Sites like http://mobile.slate.com encloses each paragraph with a DIV + // element. DIVs with only a P element inside and no text content can be + // safely converted into plain P elements to avoid confusing the scoring + // algorithm with DIVs with are, in practice, paragraphs. + if ( + this._hasSingleTagInsideElement(node, "P") && + this._getLinkDensity(node) < 0.25 + ) { + var newNode = node.children[0]; + node.parentNode.replaceChild(newNode, node); + node = newNode; + elementsToScore.push(node); + } else if (!this._hasChildBlockElement(node)) { + node = this._setNodeTag(node, "P"); + elementsToScore.push(node); + } + } + node = this._getNextNode(node); + } + + /** + * Loop through all paragraphs, and assign a score to them based on how content-y they look. + * Then add their score to their parent node. + * + * A score is determined by things like number of commas, class names, etc. Maybe eventually link density. + **/ + var candidates = []; + this._forEachNode(elementsToScore, function (elementToScore) { + if ( + !elementToScore.parentNode || + typeof elementToScore.parentNode.tagName === "undefined" + ) { + return; + } + + // If this paragraph is less than 25 characters, don't even count it. + var innerText = this._getInnerText(elementToScore); + if (innerText.length < 25) { + return; + } + + // Exclude nodes with no ancestor. + var ancestors = this._getNodeAncestors(elementToScore, 5); + if (ancestors.length === 0) { + return; + } + + var contentScore = 0; + + // Add a point for the paragraph itself as a base. + contentScore += 1; + + // Add points for any commas within this paragraph. + contentScore += innerText.split(this.REGEXPS.commas).length; + + // For every 100 characters in this paragraph, add another point. Up to 3 points. + contentScore += Math.min(Math.floor(innerText.length / 100), 3); + + // Initialize and score ancestors. + this._forEachNode(ancestors, function (ancestor, level) { + if ( + !ancestor.tagName || + !ancestor.parentNode || + typeof ancestor.parentNode.tagName === "undefined" + ) { + return; + } + + if (typeof ancestor.readability === "undefined") { + this._initializeNode(ancestor); + candidates.push(ancestor); + } + + // Node score divider: + // - parent: 1 (no division) + // - grandparent: 2 + // - great grandparent+: ancestor level * 3 + if (level === 0) { + var scoreDivider = 1; + } else if (level === 1) { + scoreDivider = 2; + } else { + scoreDivider = level * 3; + } + ancestor.readability.contentScore += contentScore / scoreDivider; + }); + }); + + // After we've calculated scores, loop through all of the possible + // candidate nodes we found and find the one with the highest score. + var topCandidates = []; + for (var c = 0, cl = candidates.length; c < cl; c += 1) { + var candidate = candidates[c]; + + // Scale the final candidates score based on link density. Good content + // should have a relatively small link density (5% or less) and be mostly + // unaffected by this operation. + var candidateScore = + candidate.readability.contentScore * + (1 - this._getLinkDensity(candidate)); + candidate.readability.contentScore = candidateScore; + + this.log("Candidate:", candidate, "with score " + candidateScore); + + for (var t = 0; t < this._nbTopCandidates; t++) { + var aTopCandidate = topCandidates[t]; + + if ( + !aTopCandidate || + candidateScore > aTopCandidate.readability.contentScore + ) { + topCandidates.splice(t, 0, candidate); + if (topCandidates.length > this._nbTopCandidates) { + topCandidates.pop(); + } + break; + } + } + } + + var topCandidate = topCandidates[0] || null; + var neededToCreateTopCandidate = false; + var parentOfTopCandidate; + + // If we still have no top candidate, just use the body as a last resort. + // We also have to copy the body node so it is something we can modify. + if (topCandidate === null || topCandidate.tagName === "BODY") { + // Move all of the page's children into topCandidate + topCandidate = doc.createElement("DIV"); + neededToCreateTopCandidate = true; + // Move everything (not just elements, also text nodes etc.) into the container + // so we even include text directly in the body: + while (page.firstChild) { + this.log("Moving child out:", page.firstChild); + topCandidate.appendChild(page.firstChild); + } + + page.appendChild(topCandidate); + + this._initializeNode(topCandidate); + } else if (topCandidate) { + // Find a better top candidate node if it contains (at least three) nodes which belong to `topCandidates` array + // and whose scores are quite closed with current `topCandidate` node. + var alternativeCandidateAncestors = []; + for (var i = 1; i < topCandidates.length; i++) { + if ( + topCandidates[i].readability.contentScore / + topCandidate.readability.contentScore >= + 0.75 + ) { + alternativeCandidateAncestors.push( + this._getNodeAncestors(topCandidates[i]) + ); + } + } + var MINIMUM_TOPCANDIDATES = 3; + if (alternativeCandidateAncestors.length >= MINIMUM_TOPCANDIDATES) { + parentOfTopCandidate = topCandidate.parentNode; + while (parentOfTopCandidate.tagName !== "BODY") { + var listsContainingThisAncestor = 0; + for ( + var ancestorIndex = 0; + ancestorIndex < alternativeCandidateAncestors.length && + listsContainingThisAncestor < MINIMUM_TOPCANDIDATES; + ancestorIndex++ + ) { + listsContainingThisAncestor += Number( + alternativeCandidateAncestors[ancestorIndex].includes( + parentOfTopCandidate + ) + ); + } + if (listsContainingThisAncestor >= MINIMUM_TOPCANDIDATES) { + topCandidate = parentOfTopCandidate; + break; + } + parentOfTopCandidate = parentOfTopCandidate.parentNode; + } + } + if (!topCandidate.readability) { + this._initializeNode(topCandidate); + } + + // Because of our bonus system, parents of candidates might have scores + // themselves. They get half of the node. There won't be nodes with higher + // scores than our topCandidate, but if we see the score going *up* in the first + // few steps up the tree, that's a decent sign that there might be more content + // lurking in other places that we want to unify in. The sibling stuff + // below does some of that - but only if we've looked high enough up the DOM + // tree. + parentOfTopCandidate = topCandidate.parentNode; + var lastScore = topCandidate.readability.contentScore; + // The scores shouldn't get too low. + var scoreThreshold = lastScore / 3; + while (parentOfTopCandidate.tagName !== "BODY") { + if (!parentOfTopCandidate.readability) { + parentOfTopCandidate = parentOfTopCandidate.parentNode; + continue; + } + var parentScore = parentOfTopCandidate.readability.contentScore; + if (parentScore < scoreThreshold) { + break; + } + if (parentScore > lastScore) { + // Alright! We found a better parent to use. + topCandidate = parentOfTopCandidate; + break; + } + lastScore = parentOfTopCandidate.readability.contentScore; + parentOfTopCandidate = parentOfTopCandidate.parentNode; + } + + // If the top candidate is the only child, use parent instead. This will help sibling + // joining logic when adjacent content is actually located in parent's sibling node. + parentOfTopCandidate = topCandidate.parentNode; + while ( + parentOfTopCandidate.tagName != "BODY" && + parentOfTopCandidate.children.length == 1 + ) { + topCandidate = parentOfTopCandidate; + parentOfTopCandidate = topCandidate.parentNode; + } + if (!topCandidate.readability) { + this._initializeNode(topCandidate); + } + } + + // Now that we have the top candidate, look through its siblings for content + // that might also be related. Things like preambles, content split by ads + // that we removed, etc. + var articleContent = doc.createElement("DIV"); + if (isPaging) { + articleContent.id = "readability-content"; + } + + var siblingScoreThreshold = Math.max( + 10, + topCandidate.readability.contentScore * 0.2 + ); + // Keep potential top candidate's parent node to try to get text direction of it later. + parentOfTopCandidate = topCandidate.parentNode; + var siblings = parentOfTopCandidate.children; + + for (var s = 0, sl = siblings.length; s < sl; s++) { + var sibling = siblings[s]; + var append = false; + + this.log( + "Looking at sibling node:", + sibling, + sibling.readability + ? "with score " + sibling.readability.contentScore + : "" + ); + this.log( + "Sibling has score", + sibling.readability ? sibling.readability.contentScore : "Unknown" + ); + + if (sibling === topCandidate) { + append = true; + } else { + var contentBonus = 0; + + // Give a bonus if sibling nodes and top candidates have the example same classname + if ( + sibling.className === topCandidate.className && + topCandidate.className !== "" + ) { + contentBonus += topCandidate.readability.contentScore * 0.2; + } + + if ( + sibling.readability && + sibling.readability.contentScore + contentBonus >= + siblingScoreThreshold + ) { + append = true; + } else if (sibling.nodeName === "P") { + var linkDensity = this._getLinkDensity(sibling); + var nodeContent = this._getInnerText(sibling); + var nodeLength = nodeContent.length; + + if (nodeLength > 80 && linkDensity < 0.25) { + append = true; + } else if ( + nodeLength < 80 && + nodeLength > 0 && + linkDensity === 0 && + nodeContent.search(/\.( |$)/) !== -1 + ) { + append = true; + } + } + } + + if (append) { + this.log("Appending node:", sibling); + + if (!this.ALTER_TO_DIV_EXCEPTIONS.includes(sibling.nodeName)) { + // We have a node that isn't a common block level element, like a form or td tag. + // Turn it into a div so it doesn't get filtered out later by accident. + this.log("Altering sibling:", sibling, "to div."); + + sibling = this._setNodeTag(sibling, "DIV"); + } + + articleContent.appendChild(sibling); + // Fetch children again to make it compatible + // with DOM parsers without live collection support. + siblings = parentOfTopCandidate.children; + // siblings is a reference to the children array, and + // sibling is removed from the array when we call appendChild(). + // As a result, we must revisit this index since the nodes + // have been shifted. + s -= 1; + sl -= 1; + } + } + + if (this._debug) { + this.log("Article content pre-prep: " + articleContent.innerHTML); + } + // So we have all of the content that we need. Now we clean it up for presentation. + this._prepArticle(articleContent); + if (this._debug) { + this.log("Article content post-prep: " + articleContent.innerHTML); + } + + if (neededToCreateTopCandidate) { + // We already created a fake div thing, and there wouldn't have been any siblings left + // for the previous loop, so there's no point trying to create a new div, and then + // move all the children over. Just assign IDs and class names here. No need to append + // because that already happened anyway. + topCandidate.id = "readability-page-1"; + topCandidate.className = "page"; + } else { + var div = doc.createElement("DIV"); + div.id = "readability-page-1"; + div.className = "page"; + while (articleContent.firstChild) { + div.appendChild(articleContent.firstChild); + } + articleContent.appendChild(div); + } + + if (this._debug) { + this.log("Article content after paging: " + articleContent.innerHTML); + } + + var parseSuccessful = true; + + // Now that we've gone through the full algorithm, check to see if + // we got any meaningful content. If we didn't, we may need to re-run + // grabArticle with different flags set. This gives us a higher likelihood of + // finding the content, and the sieve approach gives us a higher likelihood of + // finding the -right- content. + var textLength = this._getInnerText(articleContent, true).length; + if (textLength < this._charThreshold) { + parseSuccessful = false; + // eslint-disable-next-line no-unsanitized/property + page.innerHTML = pageCacheHtml; + + this._attempts.push({ + articleContent, + textLength, + }); + + if (this._flagIsActive(this.FLAG_STRIP_UNLIKELYS)) { + this._removeFlag(this.FLAG_STRIP_UNLIKELYS); + } else if (this._flagIsActive(this.FLAG_WEIGHT_CLASSES)) { + this._removeFlag(this.FLAG_WEIGHT_CLASSES); + } else if (this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)) { + this._removeFlag(this.FLAG_CLEAN_CONDITIONALLY); + } else { + // No luck after removing flags, just return the longest text we found during the different loops + this._attempts.sort(function (a, b) { + return b.textLength - a.textLength; + }); + + // But first check if we actually have something + if (!this._attempts[0].textLength) { + return null; + } + + articleContent = this._attempts[0].articleContent; + parseSuccessful = true; + } + } + + if (parseSuccessful) { + // Find out text direction from ancestors of final top candidate. + var ancestors = [parentOfTopCandidate, topCandidate].concat( + this._getNodeAncestors(parentOfTopCandidate) + ); + this._someNode(ancestors, function (ancestor) { + if (!ancestor.tagName) { + return false; + } + var articleDir = ancestor.getAttribute("dir"); + if (articleDir) { + this._articleDir = articleDir; + return true; + } + return false; + }); + return articleContent; + } + } + }, + + /** + * Converts some of the common HTML entities in string to their corresponding characters. + * + * @param str {string} - a string to unescape. + * @return string without HTML entity. + */ + _unescapeHtmlEntities(str) { + if (!str) { + return str; + } + + var htmlEscapeMap = this.HTML_ESCAPE_MAP; + return str + .replace(/&(quot|amp|apos|lt|gt);/g, function (_, tag) { + return htmlEscapeMap[tag]; + }) + .replace(/&#(?:x([0-9a-f]+)|([0-9]+));/gi, function (_, hex, numStr) { + var num = parseInt(hex || numStr, hex ? 16 : 10); + + // these character references are replaced by a conforming HTML parser + if (num == 0 || num > 0x10ffff || (num >= 0xd800 && num <= 0xdfff)) { + num = 0xfffd; + } + + return String.fromCodePoint(num); + }); + }, + + /** + * Try to extract metadata from JSON-LD object. + * For now, only Schema.org objects of type Article or its subtypes are supported. + * @return Object with any metadata that could be extracted (possibly none) + */ + _getJSONLD(doc) { + var scripts = this._getAllNodesWithTag(doc, ["script"]); + + var metadata; + + this._forEachNode(scripts, function (jsonLdElement) { + if ( + !metadata && + jsonLdElement.getAttribute("type") === "application/ld+json" + ) { + try { + // Strip CDATA markers if present + var content = jsonLdElement.textContent.replace( + /^\s*\s*$/g, + "" + ); + var parsed = JSON.parse(content); + + if (Array.isArray(parsed)) { + parsed = parsed.find(it => { + return ( + it["@type"] && + it["@type"].match(this.REGEXPS.jsonLdArticleTypes) + ); + }); + if (!parsed) { + return; + } + } + + var schemaDotOrgRegex = /^https?\:\/\/schema\.org\/?$/; + var matches = + (typeof parsed["@context"] === "string" && + parsed["@context"].match(schemaDotOrgRegex)) || + (typeof parsed["@context"] === "object" && + typeof parsed["@context"]["@vocab"] == "string" && + parsed["@context"]["@vocab"].match(schemaDotOrgRegex)); + + if (!matches) { + return; + } + + if (!parsed["@type"] && Array.isArray(parsed["@graph"])) { + parsed = parsed["@graph"].find(it => { + return (it["@type"] || "").match(this.REGEXPS.jsonLdArticleTypes); + }); + } + + if ( + !parsed || + !parsed["@type"] || + !parsed["@type"].match(this.REGEXPS.jsonLdArticleTypes) + ) { + return; + } + + metadata = {}; + + if ( + typeof parsed.name === "string" && + typeof parsed.headline === "string" && + parsed.name !== parsed.headline + ) { + // we have both name and headline element in the JSON-LD. They should both be the same but some websites like aktualne.cz + // put their own name into "name" and the article title to "headline" which confuses Readability. So we try to check if either + // "name" or "headline" closely matches the html title, and if so, use that one. If not, then we use "name" by default. + + var title = this._getArticleTitle(); + var nameMatches = this._textSimilarity(parsed.name, title) > 0.75; + var headlineMatches = + this._textSimilarity(parsed.headline, title) > 0.75; + + if (headlineMatches && !nameMatches) { + metadata.title = parsed.headline; + } else { + metadata.title = parsed.name; + } + } else if (typeof parsed.name === "string") { + metadata.title = parsed.name.trim(); + } else if (typeof parsed.headline === "string") { + metadata.title = parsed.headline.trim(); + } + if (parsed.author) { + if (typeof parsed.author.name === "string") { + metadata.byline = parsed.author.name.trim(); + } else if ( + Array.isArray(parsed.author) && + parsed.author[0] && + typeof parsed.author[0].name === "string" + ) { + metadata.byline = parsed.author + .filter(function (author) { + return author && typeof author.name === "string"; + }) + .map(function (author) { + return author.name.trim(); + }) + .join(", "); + } + } + if (typeof parsed.description === "string") { + metadata.excerpt = parsed.description.trim(); + } + if (parsed.publisher && typeof parsed.publisher.name === "string") { + metadata.siteName = parsed.publisher.name.trim(); + } + if (typeof parsed.datePublished === "string") { + metadata.datePublished = parsed.datePublished.trim(); + } + } catch (err) { + this.log(err.message); + } + } + }); + return metadata ? metadata : {}; + }, + + /** + * Attempts to get excerpt and byline metadata for the article. + * + * @param {Object} jsonld — object containing any metadata that + * could be extracted from JSON-LD object. + * + * @return Object with optional "excerpt" and "byline" properties + */ + _getArticleMetadata(jsonld) { + var metadata = {}; + var values = {}; + var metaElements = this._doc.getElementsByTagName("meta"); + + // property is a space-separated list of values + var propertyPattern = + /\s*(article|dc|dcterm|og|twitter)\s*:\s*(author|creator|description|published_time|title|site_name)\s*/gi; + + // name is a single value + var namePattern = + /^\s*(?:(dc|dcterm|og|twitter|parsely|weibo:(article|webpage))\s*[-\.:]\s*)?(author|creator|pub-date|description|title|site_name)\s*$/i; + + // Find description tags. + this._forEachNode(metaElements, function (element) { + var elementName = element.getAttribute("name"); + var elementProperty = element.getAttribute("property"); + var content = element.getAttribute("content"); + if (!content) { + return; + } + var matches = null; + var name = null; + + if (elementProperty) { + matches = elementProperty.match(propertyPattern); + if (matches) { + // Convert to lowercase, and remove any whitespace + // so we can match below. + name = matches[0].toLowerCase().replace(/\s/g, ""); + // multiple authors + values[name] = content.trim(); + } + } + if (!matches && elementName && namePattern.test(elementName)) { + name = elementName; + if (content) { + // Convert to lowercase, remove any whitespace, and convert dots + // to colons so we can match below. + name = name.toLowerCase().replace(/\s/g, "").replace(/\./g, ":"); + values[name] = content.trim(); + } + } + }); + + // get title + metadata.title = + jsonld.title || + values["dc:title"] || + values["dcterm:title"] || + values["og:title"] || + values["weibo:article:title"] || + values["weibo:webpage:title"] || + values.title || + values["twitter:title"] || + values["parsely-title"]; + + if (!metadata.title) { + metadata.title = this._getArticleTitle(); + } + + const articleAuthor = + typeof values["article:author"] === "string" && + !this._isUrl(values["article:author"]) + ? values["article:author"] + : undefined; + + // get author + metadata.byline = + jsonld.byline || + values["dc:creator"] || + values["dcterm:creator"] || + values.author || + values["parsely-author"] || + articleAuthor; + + // get description + metadata.excerpt = + jsonld.excerpt || + values["dc:description"] || + values["dcterm:description"] || + values["og:description"] || + values["weibo:article:description"] || + values["weibo:webpage:description"] || + values.description || + values["twitter:description"]; + + // get site name + metadata.siteName = jsonld.siteName || values["og:site_name"]; + + // get article published time + metadata.publishedTime = + jsonld.datePublished || + values["article:published_time"] || + values["parsely-pub-date"] || + null; + + // in many sites the meta value is escaped with HTML entities, + // so here we need to unescape it + metadata.title = this._unescapeHtmlEntities(metadata.title); + metadata.byline = this._unescapeHtmlEntities(metadata.byline); + metadata.excerpt = this._unescapeHtmlEntities(metadata.excerpt); + metadata.siteName = this._unescapeHtmlEntities(metadata.siteName); + metadata.publishedTime = this._unescapeHtmlEntities(metadata.publishedTime); + + return metadata; + }, + + /** + * Check if node is image, or if node contains exactly only one image + * whether as a direct child or as its descendants. + * + * @param Element + **/ + _isSingleImage(node) { + while (node) { + if (node.tagName === "IMG") { + return true; + } + if (node.children.length !== 1 || node.textContent.trim() !== "") { + return false; + } + node = node.children[0]; + } + return false; + }, + + /** + * Find all